text stringlengths 14 6.51M |
|---|
(*
Name: UfrmOSKCharacterMap
Copyright: Copyright (C) SIL International.
Documentation:
Description:
Create Date: 14 Sep 2006
Modified Date: 25 Sep 2014
Authors: mcdurdin
Related Files:
Dependencies:
Bugs:
Todo:
Notes:
History: 14 Sep 2006 - mcdurdin - Initial version
04 Dec 2006 - mcdurdin - Support inserting characters/codes/names
04 Dec 2006 - mcdurdin - Handle stay-on-top with child dialogs
12 Dec 2006 - mcdurdin - Add product referencing for localized strings
14 Jun 2008 - mcdurdin - I1463 - Cancel focus on double click
16 Jan 2009 - mcdurdin - I1512 - Focus back to original window before stuffing in characters
03 May 2011 - mcdurdin - I2890 - Record diagnostic data when encountering registry errors
18 May 2012 - mcdurdin - I3306 - V9.0 - Remove TntControls + Win9x support
25 Sep 2014 - mcdurdin - I4411 - V9.0 - Character map allows Ctrl+Click to insert character
25 Sep 2014 - mcdurdin - I4412 - V9.0 - Character Map needs to insert characters using SendInput
*)
unit UfrmOSKCharacterMap; // I3306
interface
uses
System.UITypes,
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, UfrmOSKPlugInBase, UfrmCharacterMapNew, CharMapInsertMode, CharacterDragObject,
ComCtrls, UnicodeData, keymanapi_TLB,
UfrmUnicodeDataStatus, StdCtrls;
type
TfrmOSKCharacterMap = class(TfrmOSKPlugInBase, IUnicodeDataUIManager)
lblDesktopLight: TLabel;
lblLightLink: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
private
FUnicodeDataStatus: TfrmUnicodeDataStatus;
procedure CharMapCancelFocus(Sender: TObject);
procedure CharMapCanInsertCode(Sender: TObject; Control: TWinControl;
var Result: Boolean);
procedure CharMapInsertCode(Sender: TObject; Control: TWinControl;
DragObject: TCharacterDragObject);
{ Private declarations }
procedure CharMapFilterEntered(Sender: TObject);
procedure CharMapFilterExited(Sender: TObject);
procedure DoRestoreFocus;
procedure CharMapDialogOpening(Sender: TObject);
procedure CharMapDialogClosing(Sender: TObject);
procedure WMMouseActivate(var Message: TWMMouseActivate); message WM_MOUSEACTIVATE;
public
procedure UDUI_Error(Sender: TUnicodeData; Error: TUnicodeDataError; const Details: WideString);
function UDUI_ShouldStartRebuildOnError(const Msg: WideString): Boolean;
function UDUI_StartRebuild(ACallback: TNotifyEvent; AskFirst: Boolean): Boolean;
procedure UDUI_UpdateStatus(const Msg: WideString; Pos: Integer; Max: Integer);
{ Public declarations }
procedure Deactivating; override;
class function GetUnicodeSourceRootPath: string;
class function IsCharMapAvailable: Boolean;
class function IsCharMapDataInstalled: Boolean;
end;
implementation
uses
custinterfaces,
kmint,
MessageIdentifierConsts,
MessageIdentifiers,
ErrorControlledRegistry,
RegistryKeys,
USendInputString,
UfrmVisualKeyboard;
{$R *.dfm}
class function TfrmOSKCharacterMap.IsCharMapAvailable: Boolean;
begin
Result := True; // TODO REFACTOR
end;
class function TfrmOSKCharacterMap.IsCharMapDataInstalled: Boolean;
begin
Result :=
FileExists(GetUnicodeSourceRootPath + UnicodeDataMdbName) or
FileExists(GetUnicodeSourceRootPath + UnicodeDataTxtName);
end;
class function TfrmOSKCharacterMap.GetUnicodeSourceRootPath: string;
begin
Result := '';
with TRegistryErrorControlled.Create do // I2890
try
RootKey := HKEY_LOCAL_MACHINE;
if OpenKeyReadOnly(SRegKey_KeymanDesktop) and ValueExists(SRegValue_CharMapSourceData)
then Result := IncludeTrailingPathDelimiter(ReadString(SRegValue_CharMapSourceData));
finally
Free;
end;
end;
procedure TfrmOSKCharacterMap.UDUI_Error(Sender: TUnicodeData;
Error: TUnicodeDataError; const Details: WideString);
begin
case Error of
udeCouldNotDeleteDatabaseForRebuild:
ShowMessage(MsgFromIdFormat(SKUnicodeData_DatabaseCouldNotBeDeleted, [Details]));
udeCouldNotCreateDatabase:
ShowMessage(MsgFromIdFormat(SKUnicodeData_CouldNotCreateDatabase, [Details]));
end;
end;
function TfrmOSKCharacterMap.UDUI_ShouldStartRebuildOnError(const Msg: WideString): Boolean;
begin
Result := MessageDlg(MsgFromIdFormat(SKUnicodeData_DatabaseLoadFailedRebuild, [Msg]),
mtConfirmation, [mbYes, mbNo], 0) = mrYes;
end;
function TfrmOSKCharacterMap.UDUI_StartRebuild(ACallback: TNotifyEvent;
AskFirst: Boolean): Boolean;
begin
Result := False;
if AskFirst and (MessageDlg(MsgFromId(SKUnicodeData_Build),
mtConfirmation, [mbYes, mbNo], 0) = mrNo) then
Exit;
FUnicodeDataStatus := TfrmUnicodeDataStatus.Create(Self);
try
FUnicodeDataStatus.Callback := ACallback;
Result := FUnicodeDataStatus.ShowModal = mrOk;
finally
FreeAndNil(FUnicodeDataStatus);
end;
end;
procedure TfrmOSKCharacterMap.UDUI_UpdateStatus(const Msg: WideString; Pos,
Max: Integer);
begin
if Assigned(FUnicodeDataStatus) then
FUnicodeDataStatus.UpdateStatus(msg, pos, max);
end;
procedure TfrmOSKCharacterMap.WMMouseActivate(var Message: TWMMouseActivate);
var
pt: TPoint;
h: Cardinal;
begin
if not Assigned(frmCharacterMapNew) then
inherited
else
begin
GetCursorPos(pt);
h := WindowFromPoint(pt);
if ((h = frmCharacterMapNew.editFilter.Handle) or (h = frmCharacterMapNew.editCharName.Handle))
then Message.Result := MA_ACTIVATE
else inherited;
end;
end;
procedure TfrmOSKCharacterMap.FormCreate(Sender: TObject);
var
s: WideString;
begin
inherited;
s := GetUnicodeSourceRootPath;
CreateUnicodeData(s, Self, s);
frmCharacterMapNew := TfrmCharacterMapNew.Create(Self, SRegKey_KeymanOSK_CharMap);
frmCharacterMapNew.BorderStyle := bsNone;
frmCharacterMapNew.Align := alClient;
frmCharacterMapNew.Parent := Self;
frmCharacterMapNew.Visible := True;
frmCharacterMapNew.InsertMode := cmimCharacter;
frmCharacterMapNew.IgnoreLastActiveControl := True;
frmCharacterMapNew.CharMapDrag := False;
frmCharacterMapNew.CtrlClickIsDblClick := True; // I4411
frmCharacterMapNew.ShouldCancelFocusOnDblClick := True;
frmCharacterMapNew.OnCancelFocus := CharMapCancelFocus;
frmCharacterMapNew.OnInsertCode := CharMapInsertCode;
frmCharacterMapNew.OnCanInsertCode := CharMapCanInsertCode;
frmCharacterMapNew.OnFilterEntered := CharMapFilterEntered;
frmCharacterMapNew.OnFilterExited := CharMapFilterExited;
frmCharacterMapNew.OnDialogOpening := CharMapDialogOpening;
frmCharacterMapNew.OnDialogClosing := CharMapDialogClosing;
end;
procedure TfrmOSKCharacterMap.FormResize(Sender: TObject);
begin
inherited;
if Assigned(frmCharacterMapNew) then
frmCharacterMapNew.CharNameNextToFilter := Width > 250;
lblDesktopLight.SetBounds(
(ClientWidth - lblDesktopLight.Width) div 2,
(ClientHeight - lblDesktopLight.Height - lblLightLink.Height) div 2,
lblDesktopLight.Width,
lblDesktopLight.Height);
lblLightLink.SetBounds(
(ClientWidth - lblLightLink.Width) div 2,
(ClientHeight + lblLightLink.Height) div 2,
lblLightLink.Width,
lblLightLink.Height);
end;
procedure TfrmOSKCharacterMap.CharMapInsertCode(Sender: TObject; Control: TWinControl; DragObject: TCharacterDragObject);
var
ch: WideString;
hwnd: THandle;
begin
ch := DragObject.Text[cmimText];
if ch = '' then
Exit;
hwnd := kmcom.Control.LastFocusWindow;
SendInputString(hwnd, ch); // I4412
end;
procedure TfrmOSKCharacterMap.CharMapCanInsertCode(Sender: TObject; Control: TWinControl; var Result: Boolean);
begin
Result := True;
end;
procedure TfrmOSKCharacterMap.CharMapDialogOpening(Sender: TObject);
var
hwnd: THandle;
frm: TCustomForm;
begin
frm := GetParentForm(Self);
SetWindowPos(frm.Handle, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE or SWP_NOSIZE);
hwnd := kmcom.Control.LastFocusWindow;
AttachThreadInput(GetCurrentThreadId, GetWindowThreadProcessId(hwnd, nil), TRUE);
SetForegroundWindow(frm.Handle);
SetActiveWindow(frm.Handle);
AttachThreadInput(GetCurrentThreadId, GetwindowThreadProcessId(hwnd, nil), FALSE);
end;
procedure TfrmOSKCharacterMap.CharMapDialogClosing(Sender: TObject);
var
frm: TCustomForm;
begin
frm := GetParentForm(Self);
SetWindowPos(frm.Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE or SWP_NOSIZE or SWP_NOACTIVATE);
if GetFocus = 0 then
DoRestoreFocus;
end;
procedure TfrmOSKCharacterMap.CharMapFilterEntered(Sender: TObject);
var
hwnd: THandle;
frm: TCustomForm;
begin
frm := GetParentForm(Self);
hwnd := kmcom.Control.LastFocusWindow;
AttachThreadInput(GetWindowThreadProcessId(hwnd, nil), GetCurrentThreadId, TRUE);
SetForegroundWindow(frm.Handle);
SetActiveWindow(frm.Handle);
AttachThreadInput(GetwindowThreadProcessId(hwnd, nil), GetCurrentThreadId, FALSE);
if Assigned(frmCharacterMapNew) then
frmCharacterMapNew.editFilter.SetFocus;
Windows.SetFocus(frmCharacterMapNew.editFilter.Handle);
end;
procedure TfrmOSKCharacterMap.CharMapFilterExited(Sender: TObject);
begin
end;
procedure TfrmOSKCharacterMap.CharMapCancelFocus(Sender: TObject);
var
frm: TCustomForm;
begin
frm := GetParentForm(Self);
SetWindowPos(frm.Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE or SWP_NOSIZE or SWP_NOACTIVATE);
DoRestoreFocus;
end;
procedure TfrmOSKCharacterMap.Deactivating;
var
frm: TCustomForm;
begin
frm := GetParentForm(Self);
SetWindowPos(frm.Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE or SWP_NOSIZE or SWP_NOACTIVATE);
end;
procedure TfrmOSKCharacterMap.DoRestoreFocus;
var
hwnd: THandle;
begin
hwnd := kmcom.Control.LastFocusWindow;
AttachThreadInput(GetCurrentThreadId, GetWindowThreadProcessId(hwnd, nil), TRUE);
Windows.SetForegroundWindow(hwnd);
Windows.SetFocus(hwnd);
AttachThreadInput(GetCurrentThreadId, GetwindowThreadProcessId(hwnd, nil), FALSE);
end;
end.
|
unit UFrmSobre;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TFrmSobre = class(TForm)
Lb_Sobre: TLabel;
Lb_Versao: TLabel;
Lb_ArquivosExcel: TLabel;
SaveArq: TSaveDialog;
Lb_Manual: TLabel;
procedure Lb_ArquivosExcelClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Lb_ManualClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FrmSobre: TFrmSobre;
implementation
{$R *.dfm}
uses funcoes;
procedure TFrmSobre.FormCreate(Sender: TObject);
begin
Lb_Versao.Caption := 'Versão: ' + VersaoExe;
end;
procedure TFrmSobre.Lb_ArquivosExcelClick(Sender: TObject);
var
Stream: TResourceStream;
begin
SaveArq.FilterIndex := 1;
SaveArq.FileName := 'ArquivosExcel.zip';
if SaveArq.Execute then
begin
Stream := TResourceStream.Create(hInstance, 'ArquivosExcel', RT_RCDATA);
try
Stream.SaveToFile(SaveArq.FileName);
Application.MessageBox(PWideChar('Arquivo "' + ExtractFileName(SaveArq.FileName) + '" gerado com sucesso no caminho "' + ExtractFileDir(SaveArq.FileName) + '".'), 'Informação', MB_ICONINFORMATION + MB_OK);
finally
Stream.Free;
end;
end;
end;
procedure TFrmSobre.Lb_ManualClick(Sender: TObject);
var
Stream: TResourceStream;
begin
SaveArq.FilterIndex := 2;
SaveArq.FileName := 'ManualNFSe_AM.pdf';
if SaveArq.Execute then
begin
Stream := TResourceStream.Create(hInstance, 'ManualNFSe_AM', RT_RCDATA);
try
Stream.SaveToFile(SaveArq.FileName);
Application.MessageBox(PWideChar('Arquivo "' + ExtractFileName(SaveArq.FileName) + '" gerado com sucesso no caminho "' + ExtractFileDir(SaveArq.FileName) + '".'), 'Informação', MB_ICONINFORMATION + MB_OK);
finally
Stream.Free;
end;
end;
end;
end.
|
{**********************************************}
{ TErrorBarSeries Component Editor Dialog }
{ Copyright (c) 1996-2004 by David Berneda }
{**********************************************}
unit TeeErrBarEd;
{$I TeeDefs.inc}
interface
uses {$IFNDEF LINUX}
Windows, Messages,
{$ENDIF}
SysUtils, Classes,
{$IFDEF CLX}
QGraphics, QControls, QForms, QDialogs, QStdCtrls, QExtCtrls, QComCtrls,
{$ELSE}
Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls,
{$ENDIF}
Chart, Series, ErrorBar, TeCanvas, TeePenDlg, TeeProcs;
type
TErrorSeriesEditor = class(TForm)
SEBarwidth: TEdit;
Label1: TLabel;
BPen: TButtonPen;
RGWidthUnit: TRadioGroup;
UDBarWidth: TUpDown;
RGStyle: TRadioGroup;
CBColorEach: TCheckBox;
procedure FormShow(Sender: TObject);
procedure SEBarwidthChange(Sender: TObject);
procedure BPenClick(Sender: TObject);
procedure RGWidthUnitClick(Sender: TObject);
procedure RGStyleClick(Sender: TObject);
procedure CBColorEachClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
ErrorSeries : TCustomErrorSeries;
FBarForm : TCustomForm;
public
{ Public declarations }
end;
implementation
{$IFNDEF CLX}
{$R *.DFM}
{$ELSE}
{$R *.xfm}
{$ENDIF}
Uses TeeBrushDlg, TeeBarEdit, TeeConst, TeeEdiSeri;
procedure TErrorSeriesEditor.FormShow(Sender: TObject);
begin
ErrorSeries:=TCustomErrorSeries(Tag);
if Assigned(ErrorSeries) then
With ErrorSeries do
begin
UDBarWidth.Position:=ErrorWidth;
if ErrorWidthUnits=ewuPercent then RGWidthUnit.ItemIndex:=0
else RGWidthUnit.ItemIndex:=1;
RGStyle.Visible:=ErrorSeries is TErrorSeries;
if RGStyle.Visible then RGStyle.ItemIndex:=Ord(ErrorStyle);
CBColorEach.Checked:=ColorEachPoint;
BPen.LinkPen(ErrorPen);
end;
if (ErrorSeries is TErrorBarSeries) and (not Assigned(FBarForm)) then
FBarForm:=TFormTeeSeries(Parent.Owner).InsertSeriesForm( TBarSeriesEditor,
1,TeeMsg_GalleryBar,
ErrorSeries);
end;
procedure TErrorSeriesEditor.SEBarwidthChange(Sender: TObject);
begin
if Showing then ErrorSeries.ErrorWidth:=UDBarWidth.Position;
end;
procedure TErrorSeriesEditor.BPenClick(Sender: TObject);
begin
With ErrorSeries do
if not (ErrorSeries is TErrorBarSeries) then SeriesColor:=ErrorPen.Color;
end;
procedure TErrorSeriesEditor.RGWidthUnitClick(Sender: TObject);
begin
ErrorSeries.ErrorWidthUnits:=TErrorWidthUnits(RGWidthUnit.ItemIndex);
end;
procedure TErrorSeriesEditor.RGStyleClick(Sender: TObject);
begin
if Showing then ErrorSeries.ErrorStyle:=TErrorSeriesStyle(RGStyle.ItemIndex);
end;
procedure TErrorSeriesEditor.CBColorEachClick(Sender: TObject);
begin
ErrorSeries.ColorEachPoint:=CBColorEach.Checked;
end;
procedure TErrorSeriesEditor.FormCreate(Sender: TObject);
begin
BorderStyle:=TeeBorderStyle;
end;
initialization
RegisterClass(TErrorSeriesEditor);
end.
|
unit FrmRangePoints;
{$mode objfpc}{$H+}
interface
uses
Forms, StdCtrls, Spin, OriEditors;
type
TRangePointsFrm = class(TFrame)
fedStep: TOriFloatEdit;
rbPoints: TRadioButton;
rbStep: TRadioButton;
sePoints: TSpinEdit;
procedure fedStepChange(Sender: TObject);
procedure rbPointsChange(Sender: TObject);
procedure rbStepChange(Sender: TObject);
procedure sePointsChange(Sender: TObject);
private
procedure SetStep(const Value: Double);
procedure SetPoints(Value: Integer);
procedure SetUseStep(Value: Boolean);
function GetStep: Double;
function GetPoints: Integer;
function GetUseStep: Boolean;
public
property Step: Double read GetStep write SetStep;
property Points: Integer read GetPoints write SetPoints;
property UseStep: Boolean read GetUseStep write SetUseStep;
end;
implementation
{$R *.lfm}
procedure TRangePointsFrm.rbStepChange(Sender: TObject);
begin
try
if rbStep.Checked and fedStep.CanFocus then fedStep.SetFocus;
except
// On FormCreate CanFocus = True but SetFocus raises 'Can not focus'
end;
end;
procedure TRangePointsFrm.fedStepChange(Sender: TObject);
begin
rbStep.Checked := True;
end;
procedure TRangePointsFrm.rbPointsChange(Sender: TObject);
begin
try
if rbPoints.Checked and sePoints.CanFocus then sePoints.SetFocus;
except
// On FormCreate CanFocus = True but SetFocus raises 'Can not focus'
end;
end;
procedure TRangePointsFrm.sePointsChange(Sender: TObject);
begin
rbPoints.Checked := True;
end;
procedure TRangePointsFrm.SetStep(const Value: Double);
begin
fedStep.Value := Value;
end;
procedure TRangePointsFrm.SetPoints(Value: Integer);
begin
sePoints.Value := Value;
end;
procedure TRangePointsFrm.SetUseStep(Value: Boolean);
begin
rbStep.Checked := Value;
rbPoints.Checked := not Value;
end;
function TRangePointsFrm.GetStep: Double;
begin
Result := fedStep.Value;
end;
function TRangePointsFrm.GetPoints: Integer;
begin
Result := sePoints.Value;
end;
function TRangePointsFrm.GetUseStep: Boolean;
begin
Result := rbStep.Checked;
end;
end.
|
{
Double Commander
-------------------------------------------------------------------------
Keyboard options page
Copyright (C) 2006-2011 Koblov Alexander (Alexx2000@mail.ru)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
}
unit fOptionsKeyboard;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, StdCtrls,
fOptionsFrame;
type
{ TfrmOptionsKeyboard }
TfrmOptionsKeyboard = class(TOptionsEditor)
cbLynxLike: TCheckBox;
cbNoModifier: TComboBox;
cbAlt: TComboBox;
cbCtrlAlt: TComboBox;
gbTyping: TGroupBox;
lblNoModifier: TLabel;
lblAlt: TLabel;
lblCtrlAlt: TLabel;
protected
procedure Init; override;
procedure Load; override;
function Save: TOptionsEditorSaveFlags; override;
public
class function GetIconIndex: Integer; override;
class function GetTitle: String; override;
end;
implementation
{$R *.lfm}
uses
DCStrUtils, uGlobs, uLng;
const
KeyAction_None = 0;
KeyAction_CommandLine = 1;
KeyAction_QuickSearch = 2;
KeyAction_QuickFilter = 3;
{ TfrmOptionsKeyboard }
procedure TfrmOptionsKeyboard.Init;
begin
// Copy localized strings to each combo box.
ParseLineToList(rsOptLetters, cbNoModifier.Items);
cbAlt.Items.Assign(cbNoModifier.Items);
cbCtrlAlt.Items.Assign(cbNoModifier.Items);
end;
procedure TfrmOptionsKeyboard.Load;
procedure SetAction(ComboBox: TComboBox; KeyTypingAction: TKeyTypingAction);
begin
case KeyTypingAction of
ktaNone:
ComboBox.ItemIndex := KeyAction_None;
ktaCommandLine:
ComboBox.ItemIndex := KeyAction_CommandLine;
ktaQuickSearch:
ComboBox.ItemIndex := KeyAction_QuickSearch;
ktaQuickFilter:
ComboBox.ItemIndex := KeyAction_QuickFilter;
else
raise Exception.Create('Unknown TKeyTypingMode');
end;
end;
begin
SetAction(cbNoModifier, gKeyTyping[ktmNone]);
SetAction(cbAlt, gKeyTyping[ktmAlt]);
SetAction(cbCtrlAlt, gKeyTyping[ktmCtrlAlt]);
cbLynxLike.Checked := gLynxLike;
end;
function TfrmOptionsKeyboard.Save: TOptionsEditorSaveFlags;
function GetAction(ComboBox: TComboBox): TKeyTypingAction;
begin
case ComboBox.ItemIndex of
KeyAction_None:
Result := ktaNone;
KeyAction_CommandLine:
Result := ktaCommandLine;
KeyAction_QuickSearch:
Result := ktaQuickSearch;
KeyAction_QuickFilter:
Result := ktaQuickFilter;
else
raise Exception.Create('Unknown action selected');
end;
end;
begin
gKeyTyping[ktmNone] := GetAction(cbNoModifier);
gKeyTyping[ktmAlt] := GetAction(cbAlt);
gKeyTyping[ktmCtrlAlt] := GetAction(cbCtrlAlt);
gLynxLike := cbLynxLike.Checked;
Result := [];
end;
class function TfrmOptionsKeyboard.GetIconIndex: Integer;
begin
Result := 26;
end;
class function TfrmOptionsKeyboard.GetTitle: String;
begin
Result := rsOptionsEditorKeyboard;
end;
end.
|
unit ltr11api;
interface
uses SysUtils, ltrapi, ltrapitypes;
const
LTR11_CLOCK =15000; // тактовая частота модуля в кГц
LTR11_MAX_CHANNEL =32; // Максимальное число физических каналов
LTR11_MAX_LCHANNEL =128; // Максимальное число логических каналов
LTR11_ADC_RANGEQNT =4; // количество входных диапазонов АЦП
// Коды ошибок, возвращаемые функциями библиотеки
LTR11_ERR_INVALID_DESCR =-1000; // указатель на описатель модуля равен NULL
LTR11_ERR_INVALID_ADCMODE =-1001; // недопустимый режим запуска АЦП
LTR11_ERR_INVALID_ADCLCHQNT =-1002; // недопустимое количество логических каналов
LTR11_ERR_INVALID_ADCRATE =-1003; // недопустимое значение частоты дискретизации АЦП модуля
LTR11_ERR_INVALID_ADCSTROBE =-1004; // недопустимый источник тактовой частоты для АЦП
LTR11_ERR_GETFRAME =-1005; // ошибка получения кадра данных с АЦП
LTR11_ERR_GETCFG =-1006; // ошибка чтения конфигурации
LTR11_ERR_CFGDATA =-1007; // ошибка при получении конфигурации модуля
LTR11_ERR_CFGSIGNATURE =-1008; // неверное значение первого байта конфигурационной записи модуля
LTR11_ERR_CFGCRC =-1009; // неверная контрольная сумма конфигурационной записи
LTR11_ERR_INVALID_ARRPOINTER =-1010; // указатель на массив равен NULL
LTR11_ERR_ADCDATA_CHNUM =-1011; // неверный номер канала в массиве данных от АЦП
LTR11_ERR_INVALID_CRATESN =-1012; // указатель на строку с серийным номером крейта равен NULL
LTR11_ERR_INVALID_SLOTNUM =-1013; // недопустимый номер слота в крейте
LTR11_ERR_NOACK =-1014; // нет подтверждения от модуля
LTR11_ERR_MODULEID =-1015; // попытка открытия модуля, отличного от LTR11
LTR11_ERR_INVALIDACK =-1016; // неверное подтверждение от модуля
LTR11_ERR_ADCDATA_SLOTNUM =-1017; // неверный номер слота в данных от АЦП
LTR11_ERR_ADCDATA_CNT =-1018; // неверный счетчик пакетов в данных от АЦП
LTR11_ERR_INVALID_STARTADCMODE =-1019; // неверный режим старта сбора данных
// Режимы запуска АЦП
LTR11_ADCMODE_ACQ =$00; // сбор данных
LTR11_ADCMODE_TEST_U1P =$04; // подача тестового напряжения +U1
LTR11_ADCMODE_TEST_U1N =$05; // подача тестового напряжения -U1
LTR11_ADCMODE_TEST_U2N =$06; // подача тестового напряжения -U2
LTR11_ADCMODE_TEST_U2P =$07; // подача тестового напряжения +U2
// Режим начала сбора данных модулем
LTR11_STARTADCMODE_INT =0; // внутренний старт =по команде хоста;
LTR11_STARTADCMODE_EXTRISE =1; // по фронту внешнего сигнала;
LTR11_STARTADCMODE_EXTFALL =2; // по спаду внешнего сигнала.
// Источник тактирования АЦП
LTR11_INPMODE_EXTRISE =0; // запуск преобразования по фронту внешнего сигнала
LTR11_INPMODE_EXTFALL =1; // запуск преобразования по спаду внешнего сигнала
LTR11_INPMODE_INT =2; // внутренний запуск АЦП
// Входные дипазоны каналов
LTR11_CHRANGE_10000MV = 0; // +-10 В (10000 мВ)
LTR11_CHRANGE_2500MV = 1; // +-2.5 В (2500 мВ)
LTR11_CHRANGE_625MV = 2; // +-0.625 В (625 мВ)
LTR11_CHRANGE_156MV = 3; // +-0.156 В (156 мВ)
// Режимы работы каналов
LTR11_CHMODE_DIFF =0; // диф. подкл., 16 каналов
LTR11_CHMODE_COMM =1; // общая земля, 32 каналов
LTR11_CHMODE_ZERO =2; // измерение нуля
// Константы, оставленные для совместимости
LTR11_CHGANE_10000MV =LTR11_CHRANGE_10000MV;
LTR11_CHGANE_2500MV =LTR11_CHRANGE_2500MV;
LTR11_CHGANE_625MV =LTR11_CHRANGE_625MV;
LTR11_CHGANE_156MV =LTR11_CHRANGE_625MV;
LTR11_CHMODE_16CH =LTR11_CHMODE_DIFF;
LTR11_CHMODE_32CH =LTR11_CHMODE_COMM;
//================================================================================================
type
{$A4}
LTR11_GainSet = record
Offset:double; // смещение нуля
Gain :double; // масштабный коэффициент
end;
TINFO_LTR11 = record // информация о модуле
Name :array[0..15]of AnsiChar; // название модуля (строка)
Serial:array[0..23]of AnsiChar; // серийный номер модуля (строка)
Ver :word; // версия ПО модуля (младший байт - минорная,старший - мажорная
Date:array[0..13]of AnsiChar; // дата создания ПО (строка)
CbrCoef:array[0..LTR11_ADC_RANGEQNT-1]of LTR11_GainSet ; // калибровочные коэффициенты для каждого диапазона
end;
ADC_SET = record
divider:integer; // делитель тактовой частоты модуля, значения:
// 2..65535
//
prescaler:integer; // пределитель тактовой частоты модуля:
// 1, 8, 64, 256, 1024
//
end;
TLTR11 = record // информация о модуле LTR11
size:integer; // размер структуры в байтах
Channel:TLTR; // описатель канала связи с модулем
StartADCMode:integer; // режим начала сбора данных:
// LTR11_STARTADCMODE_INT - внутренний старт (по
// команде хоста);
// LTR11_STARTADCMODE_EXTRISE - по фронту внешнего
// сигнала;
// LTR11_STARTADCMODE_EXTFALL - по спаду внешнего
// сигнала.
//
InpMode:integer; // режим ввода данных с АЦП
// LTR11_INPMODE_INT - внутренний запуск АЦП
// (частота задается AdcRate)
// LTR11_INPMODE_EXTRISE - по фронту внешнего сигнала
// LTR11_INPMODE_EXTFALL - по спаду внешнего сигнала
//
LChQnt:integer; // число активных логических каналов (размер кадра)
LChTbl:array[0..LTR11_MAX_LCHANNEL-1]of byte;
// управляющая таблица с активными логическими каналами
// структура одного байта таблицы: MsbGGMMCCCCLsb
// GG - входной диапазон:
// 0 - +-10 В;
// 1 - +-2.5 В;
// 2 - +-0.625 В;
// 3 - +-0.156В;
// MM - режим:
// 0 - 16-канальный, каналы 1-16;
// 1 - измерение собственного напряжения
// смещения нуля;
// 2 - 32-канальный, каналы 1-16;
// 3 - 32-канальный, каналы 17-32;
// CCCC - номер физического канала:
// 0 - канал 1 (17);
// . . .
// 15 - канал 16 (32).
//
ADCMode:integer; // режим сбора данных или тип тестового режима
ADCRate:ADC_SET; // параметры для задания частоты дискретизации АЦП
// частота рассчитывается по формуле:
// F = LTR11_CLOCK/(prescaler*(divider+1)
// ВНИМАНИЕ!!! Частота 400 кГц является особым случаем:
// для ее установки пределитель и делитель должны иметь
// следующие значения:
// prescaler = 1
// divider = 36
//
ChRate:double; // частота одного канала в кГц (период кадра) при
//внутреннем запуске АЦП
//
ModuleInfo:TINFO_LTR11;
end;
//================================================================================================
pTLTR11=^TLTR11;
//================================================================================================
{$A+}
{ Вариант реализации через var/out}
Function LTR11_Init(var hnd: TLTR11):integer; overload;
Function LTR11_Open(var hnd: TLTR11; net_addr : LongWord; net_port : Word;
csn: string; slot: integer): Integer; overload;
Function LTR11_IsOpened(var hnd: TLTR11):integer;
Function LTR11_Close(var hnd: TLTR11) : Integer; overload;
Function LTR11_GetConfig(var hnd: TLTR11):integer; overload;
Function LTR11_SetADC(var hnd: TLTR11):integer; overload;
Function LTR11_Start(var hnd: TLTR11):integer; overload;
Function LTR11_Stop(var hnd: TLTR11):integer; overload;
Function LTR11_Recv(var hnd: TLTR11; out data : array of LongWord; out tmark : array of LongWord; size: LongWord; tout : LongWord): Integer; overload;
Function LTR11_Recv(var hnd: TLTR11; out data : array of LongWord; size: LongWord; tout : LongWord): Integer; overload;
Function LTR11_ProcessData(var hnd: TLTR11; var src : array of LongWord;
out dest : array of Double; var size: Integer;
calibr : Boolean; volt : boolean) : Integer; overload;
Function LTR11_GetFrame(var hnd: TLTR11; out buf: array of LongWord):integer; overload;
Function LTR11_FindAdcFreqParams(adcFreq:Double; out prescaler : Integer; out divider : Integer; out resultAdcFreq : double):Integer;
Function LTR11_GetErrorString(err:integer):string;
Function LTR11_CreateLChannel(phy_ch: byte; mode: byte; gain : byte) : byte;
Function LTR11_SearchFirstFrame(var hnd : TLTR11; var data : array of LongWord;
size : LongWord; out index : LongWord) : Integer;
{ старый вариант, оставленный только для совместимости }
{$IFNDEF LTRAPI_DISABLE_COMPAT_DEFS}
Function LTR11_Init(module:pTLTR11):integer; {$I ltrapi_callconvention}; overload;
Function LTR11_Open(module:pTLTR11; net_addrDWORD:LongWord; net_portWORD:word; crate_snCHAR:Pointer;
slot_numINT:integer):integer; {$I ltrapi_callconvention};overload;
Function LTR11_Close(module:pTLTR11):integer; {$I ltrapi_callconvention}; overload;
Function LTR11_GetConfig(module:pTLTR11):integer; {$I ltrapi_callconvention}; overload;
Function LTR11_SetADC(module:pTLTR11):integer; {$I ltrapi_callconvention}; overload;
Function LTR11_Start(module:pTLTR11):integer; {$I ltrapi_callconvention}; overload;
Function LTR11_Stop(module:pTLTR11):integer; {$I ltrapi_callconvention}; overload;
Function LTR11_Recv(module:pTLTR11; dataDWORD : Pointer; tmarkDWORD : Pointer; size : LongWord; timeout : LongWord):integer; {$I ltrapi_callconvention}; overload;
Function LTR11_ProcessData(module:pTLTR11; srcDWORD:Pointer; destDOUBLE:Pointer; sizeINT:Pointer;
calibrBOOL:boolean; voltBOOL:boolean):integer; {$I ltrapi_callconvention}; overload;
Function LTR11_GetFrame(module:pTLTR11; bufDWORD:Pointer):integer; {$I ltrapi_callconvention}; overload;
{$ENDIF}
//================================================================================================
implementation
Function _init(var hnd: TLTR11):integer; {$I ltrapi_callconvention}; overload; external 'ltr11api' name 'LTR11_Init';
Function _open(var hnd: TLTR11; net_addr : LongWord; net_port : Word; csn: PAnsiChar; slot: integer) : Integer; {$I ltrapi_callconvention}; external 'ltr11api' name 'LTR11_Open';
Function _is_opened(var hnd: TLTR11) : Integer; {$I ltrapi_callconvention}; external 'ltr11api' name 'LTR11_IsOpened';
Function _close(var hnd: TLTR11) : Integer; {$I ltrapi_callconvention}; overload; external 'ltr11api' name 'LTR11_Close';
Function _get_config(var hnd: TLTR11):integer; {$I ltrapi_callconvention}; overload; external 'ltr11api' name 'LTR11_GetConfig';
Function _set_adc(var hnd: TLTR11):integer; {$I ltrapi_callconvention}; overload; external 'ltr11api' name 'LTR11_SetADC';
Function _start(var hnd: TLTR11):integer; {$I ltrapi_callconvention}; overload; external 'ltr11api' name 'LTR11_Start';
Function _stop(var hnd: TLTR11):integer; {$I ltrapi_callconvention}; overload; external 'ltr11api' name 'LTR11_Stop';
Function _recv(var hnd: TLTR11; out data; out tmark; size: LongWord; tout : LongWord): Integer; {$I ltrapi_callconvention}; external 'ltr11api' name 'LTR11_Recv';
Function _process_data(var hnd: TLTR11; var src; out dest; var size: integer; calibr : Integer; volt : Integer): Integer; {$I ltrapi_callconvention}; external 'ltr11api' name 'LTR11_ProcessData';
Function _get_frame(var hnd: TLTR11; out buf):integer; {$I ltrapi_callconvention}; external 'ltr11api' name 'LTR11_GetFrame';
Function _find_adc_freq_params(adcFreq:Double; out prescaler : Integer; out divider : Integer; out resultAdcFreq : double):Integer; {$I ltrapi_callconvention}; external 'ltr11api' name 'LTR11_FindAdcFreqParams';
Function _get_err_str(err : integer) : PAnsiChar; {$I ltrapi_callconvention}; external 'ltr11api' name 'LTR11_GetErrorString';
Function _create_lchannel(phy_ch: byte; mode: byte; gain : byte) : byte; {$I ltrapi_callconvention}; external 'ltr11api' name 'LTR11_CreateLChannel';
Function _search_first_frame(var hnd : TLTR11; var data; size : LongWord; out index : LongWord) : Integer; {$I ltrapi_callconvention}; external 'ltr11api' name 'LTR11_SearchFirstFrame';
{$IFNDEF LTRAPI_DISABLE_COMPAT_DEFS}
Function LTR11_Init(module:pTLTR11):integer; {$I ltrapi_callconvention}; overload; external 'ltr11api';
Function LTR11_Open(module:pTLTR11; net_addrDWORD:LongWord; net_portWORD:word; crate_snCHAR:Pointer;
slot_numINT:integer):integer; {$I ltrapi_callconvention}; overload;external 'ltr11api';
Function LTR11_Close(module:pTLTR11):integer; {$I ltrapi_callconvention}; overload; external 'ltr11api';
Function LTR11_GetConfig(module:pTLTR11):integer;{$I ltrapi_callconvention}; external 'ltr11api';
Function LTR11_GetFrame(module:pTLTR11; bufDWORD:Pointer):integer; {$I ltrapi_callconvention}; external 'ltr11api';
Function LTR11_ProcessData(module:pTLTR11; srcDWORD:Pointer; destDOUBLE:Pointer; sizeINT:Pointer;
calibrBOOL:boolean; voltBOOL:boolean):integer; {$I ltrapi_callconvention}; external 'ltr11api';
Function LTR11_SetADC(module:pTLTR11):integer; {$I ltrapi_callconvention}; external 'ltr11api';
Function LTR11_Start(module:pTLTR11):integer; {$I ltrapi_callconvention}; external 'ltr11api';
Function LTR11_Stop(module:pTLTR11):integer; {$I ltrapi_callconvention}; external 'ltr11api';
Function LTR11_Recv(module:pTLTR11; dataDWORD : Pointer; tmarkDWORD : Pointer; size : LongWord; timeout : LongWord):integer; {$I ltrapi_callconvention}; external 'ltr11api';
{$ENDIF}
Function LTR11_Init(var hnd: TLTR11):integer; overload;
begin
LTR11_Init:=_init(hnd);
end;
Function LTR11_Open(var hnd: TLTR11; net_addr : LongWord; net_port : Word; csn: string; slot: integer): Integer; overload;
begin
LTR11_Open:=_open(hnd, net_addr, net_port, PAnsiChar(AnsiString(csn)), slot);
end;
Function LTR11_IsOpened(var hnd: TLTR11):integer;
begin
LTR11_IsOpened:=_is_opened(hnd);
end;
Function LTR11_Close(var hnd: TLTR11) : Integer; overload;
begin
LTR11_Close:=_close(hnd);
end;
Function LTR11_GetConfig(var hnd: TLTR11):integer; overload;
begin
LTR11_GetConfig:=_get_config(hnd);
end;
Function LTR11_SetADC(var hnd: TLTR11):integer; overload;
begin
LTR11_SetADC:=_set_adc(hnd);
end;
Function LTR11_Start(var hnd: TLTR11):integer; overload;
begin
LTR11_Start:=_start(hnd);
end;
Function LTR11_Stop(var hnd: TLTR11):integer; overload;
begin
LTR11_Stop:=_stop(hnd);
end;
Function LTR11_Recv(var hnd: TLTR11; out data : array of LongWord; out tmark : array of LongWord; size: LongWord; tout : LongWord): Integer;
begin
LTR11_Recv:=_recv(hnd, data, tmark, size, tout);
end;
Function LTR11_Recv(var hnd: TLTR11; out data : array of LongWord; size: LongWord; tout : LongWord): Integer;
begin
LTR11_Recv:=_recv(hnd, data, PLongWord(nil)^, size, tout);
end;
Function LTR11_ProcessData(var hnd: TLTR11; var src : array of LongWord;
out dest : array of Double; var size: Integer;
calibr : Boolean; volt : Boolean) : Integer; overload;
begin
LTR11_ProcessData:=_process_data(hnd, src, dest, size, Integer(calibr) , Integer(volt));
end;
Function LTR11_GetFrame(var hnd: TLTR11; out buf: array of LongWord):integer; overload;
begin
LTR11_GetFrame:=_get_frame(hnd, buf);
end;
Function LTR11_GetErrorString(err: Integer) : string;
begin
LTR11_GetErrorString:=string(_get_err_str(err));
end;
Function LTR11_SearchFirstFrame(var hnd : TLTR11; var data : array of LongWord;
size : LongWord; out index : LongWord) : Integer;
begin
LTR11_SearchFirstFrame:= _search_first_frame(hnd, data, size, index);
end;
Function LTR11_FindAdcFreqParams(adcFreq:Double; out prescaler : Integer; out divider : Integer; out resultAdcFreq : double):Integer;
begin
LTR11_FindAdcFreqParams:=_find_adc_freq_params(adcFreq, prescaler, divider, resultAdcFreq);
end;
Function LTR11_CreateLChannel(phy_ch: byte; mode: byte; gain : byte) : byte;
begin
LTR11_CreateLChannel:=_create_lchannel(phy_ch, mode, gain);
end;
end.
|
{*******************************************************}
{ }
{ Delphi REST Client Framework }
{ }
{ Copyright(c) 2014-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit REST.Backend.ServiceComponents;
interface
uses
System.Classes, System.SysUtils, System.JSON, System.Generics.Collections,
REST.Client, REST.BindSource,
Data.Bind.Components, Data.Bind.ObjectScope,
REST.Backend.Providers, REST.Backend.ServiceTypes,
REST.Backend.BindSource,
REST.Backend.PushTypes, REST.Backend.Consts,
REST.Backend.MetaTypes;
type
TCustomBackendUsers = class(TBackendServiceComponentAuth<IBackendUsersService, TBackendUsersApi>)
private
function GetUsers: TBackendUsersApi;
function GetProviderService: IBackendUsersService;
protected
function InternalCreateBackendServiceAPI: TBackendUsersApi; override;
function InternalCreateIndependentBackendServiceAPI: TBackendUsersApi; override;
function CreateAuthAccess: IAuthAccess; override;
public
property Users: TBackendUsersApi read GetUsers;
property ProviderService: IBackendUsersService read GetProviderService;
function CreateUserAPI: TBackendUsersApi;
end;
TBackendUsers = class(TCustomBackendUsers)
published
property Provider;
property Auth;
end;
TCustomBackendGroups = class(TBackendServiceComponentAuth<IBackendGroupsService, TBackendGroupsApi>)
private
function GetGroups: TBackendGroupsApi;
function GetProviderService: IBackendGroupsService;
protected
function InternalCreateBackendServiceAPI: TBackendGroupsApi; override;
function InternalCreateIndependentBackendServiceAPI: TBackendGroupsApi; override;
function CreateAuthAccess: IAuthAccess; override;
public
property Groups: TBackendGroupsApi read GetGroups;
property ProviderService: IBackendGroupsService read GetProviderService;
function CreateGroupsAPI: TBackendGroupsApi;
end;
TBackendGroups = class(TCustomBackendGroups)
published
property Provider;
property Auth;
end;
TCustomBackendStorage = class(TBackendServiceComponentAuth<IBackendStorageService, TBackendStorageApi>)
private
function GetStorage: TBackendStorageApi;
function GetProviderService: IBackendStorageService;
protected
function InternalCreateBackendServiceAPI: TBackendStorageApi; override;
function InternalCreateIndependentBackendServiceAPI: TBackendStorageApi; override;
function CreateAuthAccess: IAuthAccess; override;
public
property Storage: TBackendStorageApi read GetStorage;
property ProviderService: IBackendStorageService read GetProviderService;
function CreateStorageAPI: TBackendStorageApi;
end;
TBackendStorage = class(TCustomBackendStorage)
published
property Provider;
property Auth;
end;
TCustomBackendFiles = class(TBackendServiceComponentAuth<IBackendFilesService, TBackendFilesApi>)
private
function GetFiles: TBackendFilesApi;
function GetProviderService: IBackendFilesService;
protected
function InternalCreateBackendServiceAPI: TBackendFilesApi; override;
function InternalCreateIndependentBackendServiceAPI: TBackendFilesApi; override;
function CreateAuthAccess: IAuthAccess; override;
public
property Files: TBackendFilesApi read GetFiles;
property ProviderService: IBackendFilesService read GetProviderService;
function CreateFilesAPI: TBackendFilesApi;
end;
TBackendFiles = class(TCustomBackendFiles)
published
property Provider;
property Auth;
end;
TSubBackendQueryBindSource = class;
TCustomBackendQuery = class(TBackendBindSourceComponentAuth<IBackendQueryService, TBackendQueryApi>, IRESTResponseJSON)
private type
TNotify = TRESTComponentNotify;
TNotifyList = TRESTComponentNotifyList<TNotify>;
private
FNotifyList: TNotifyList;
FJSONNotifyList: TList<TNotifyEvent>;
FBackendClassName: string;
FQueryLines: TStrings;
FJSONResult: TJSONArray;
FBindSource: TSubBackendQueryBindSource;
FBackendService: string;
function GetQueryApi: TBackendQueryApi;
procedure SetQueryLines(const Value: TStrings);
procedure SetBackendClassName(const Value: string);
procedure PropertyValueChanged;
procedure JSONValueChanged;
function GetProviderService: IBackendQueryService;
procedure SetBackendService(const Value: string);
protected
function CreateAuthAccess: IAuthAccess; override;
function CreateBindSource: TBaseObjectBindSource; override;
function InternalCreateBackendServiceAPI: TBackendQueryApi; override;
function InternalCreateIndependentBackendServiceAPI: TBackendQueryApi; override;
{ IRESTResponseJSON } // Support ResponseAdapter
procedure AddJSONChangedEvent(const ANotify: TNotifyEvent);
procedure RemoveJSONChangedEvent(const ANotify: TNotifyEvent);
procedure GetJSONResponse(out AJSONValue: TJSONValue; out AHasOwner: Boolean);
function HasJSONResponse: Boolean;
function HasResponseContent: Boolean;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Execute;
procedure ClearResult;
procedure SetJSONResult(const AJSONResult: TJSONArray);
function CreateQueryAPI: TBackendQueryApi;
property QueryLines: TStrings read FQueryLines write SetQueryLines;
property BackendClassName: string read FBackendClassName write SetBackendClassName;
property BackendService: string read FBackendService write SetBackendService;
property JSONResult: TJSONArray read FJSONResult;
property BindSource: TSubBackendQueryBindSource read FBindSource;
property QueryApi: TBackendQueryApi read GetQueryApi;
property ProviderService: IBackendQueryService read GetProviderService;
end;
TBackendQuery = class(TCustomBackendQuery)
published
property Provider;
property Auth;
property BackendClassName;
property BackendService;
property QueryLines;
property BindSource;
end;
/// <summary>
/// LiveBindings adapter for TCustomBackendQuery. Create bindable members
/// </summary>
TBackendQueryAdapter = class(TRESTComponentAdapter)
public type
TNotify = class(TRESTComponentNotify)
private
FAdapter: TBackendQueryAdapter;
constructor Create(const AAdapter: TBackendQueryAdapter);
public
procedure PropertyValueChanged(Sender: TObject); override;
end;
private
FQuery: TCustomBackendQuery;
FNotify: TNotify;
procedure SetQuery(const AQuery: TCustomBackendQuery);
procedure AddPropertyFields;
protected
procedure DoChangePosting; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
function GetCanActivate: Boolean; override;
procedure AddFields; override;
function GetSource: TBaseLinkingBindSource; override;
public
constructor Create(AComponent: TComponent); override;
destructor Destroy; override;
procedure GetMemberNames(AList: TStrings); override;
property Query: TCustomBackendQuery read FQuery write SetQuery;
end;
/// <summary>
/// LiveBindings bindsource for TCustomBackendQuery. Creates adapter
/// </summary>
TCustomBackendQueryBindSource = class(TRESTComponentBindSource)
private
FAdapter: TBackendQueryAdapter;
function GetQuery: TCustomBackendQuery;
procedure SetQuery(const AValue: TCustomBackendQuery);
protected
function CreateAdapter: TRESTComponentAdapter; override;
public
property Query: TCustomBackendQuery read GetQuery write SetQuery;
property Adapter: TBackendQueryAdapter read FAdapter;
end;
/// <summary>
/// LiveBindings bindsource for TCustomRESTRequest. Publishes subcomponent properties
/// </summary>
TSubBackendQueryBindSource = class(TCustomBackendQueryBindSource)
published
property AutoActivate;
property AutoEdit;
property AutoPost;
end;
TSubPushSenderBindSource = class;
[HPPGEN(HPPGenAttribute.mkFriend, 'TPushSenderAdapter')]
TCustomBackendPush = class(TBackendBindSourceComponentAuth<IBackendPushService, TBackendPushApi>)
public type
TSendEvent = TNotifyEvent;
TSendingEvent = TNotifyEvent;
TExtrasItem = class;
TExtrasCollection = class(TOwnedCollection)
private type
TEnumerator = class(TCollectionEnumerator)
public
function GetCurrent: TExtrasItem; inline;
property Current: TExtrasItem read GetCurrent;
end;
protected
function GetItem(AIndex: integer): TExtrasItem;
procedure SetItem(AIndex: integer; const AValue: TExtrasItem);
function GetAttrCount: integer; override;
function GetAttr(Index: integer): string; override;
function GetItemAttr(Index, ItemIndex: integer): string; override;
procedure Update(AItem: TCollectionItem); override;
public
constructor Create(const AOwner: TComponent);
procedure UpdateExtras(const AExtras: TPushData.TExtras);
function GetEnumerator: TEnumerator;
property Items[AIndex: Integer]: TExtrasItem read GetItem write SetItem; default;
end;
TExtrasItem = class(TCollectionItem)
private
FName: string;
FValue: string;
protected
procedure SetName(const AValue: string);
procedure SetValue(const AValue: string);
public
procedure Assign(ASource: TPersistent); override;
function ToString: string; override;
function GetDisplayName: string; override;
published
property Name: string read FName write SetName;
property Value: string read FValue write SetValue;
end;
private type
TNotify = class(TRESTComponentNotify)
public
procedure ExtrasListChanged(Sender: TObject); virtual;
end;
TNotifyList = TRESTComponentNotifyList<TNotify>;
private
FNotifyList: TNotifyList;
FPushData: TPushData;
FExtras: TExtrasCollection;
FBindSource: TSubPushSenderBindSource;
FOnSending: TSendingEvent;
FOnSend: TSendEvent;
FTarget: TStrings;
function GetProviderService: IBackendPushService;
procedure PropertyValueChanged;
procedure ExtrasListChanged;
function GetPushAPI: TBackendPushAPI;
procedure SetAPS(const Value: TPushData.TAPS);
procedure SetMessage(const Value: string);
function GetAPS: TPushData.TAPS;
function GetMessage: string;
function GetGCM: TPushData.TGCM;
procedure SetGCM(const Value: TPushData.TGCM);
procedure SetExtras(const Value: TExtrasCollection);
procedure SetTarget(const Value: TStrings);
protected
function InternalCreateBackendServiceAPI: TBackendPushApi; override;
function InternalCreateIndependentBackendServiceAPI: TBackendPushApi; override;
function CreateBindSource: TBaseObjectBindSource; override;
procedure DoSend; virtual;
procedure DoSending; virtual;
function CreateAuthAccess: IAuthAccess; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
/// <summary>Broadcasts a push notification to all installations</summary>
procedure PushData(const AData: TPushData); overload;
/// <summary>Sends push notifications to the installations that match a target</summary>
procedure PushData(const AData: TPushData; const ATarget: TJSONObject); overload;
/// <summary>Sends a push notification to installations that match the Target property.
/// The APS, GCM, Extras, and Message properties will be used to build a push notification. If the Target property
/// is empty then the push notification is broadcast to all installations.
/// </summary>
procedure Push; overload;
/// <summary>Data sent to apple devices when use the Push() procedure.</summary>
property APS: TPushData.TAPS read GetAPS write SetAPS;
/// <summary>Data sent to android devices when use the Push() procedure.</summary>
property GCM: TPushData.TGCM read GetGCM write SetGCM;
/// <summary>Custom data sent when use the Push() procedure.</summary>
property Extras: TExtrasCollection read FExtras write SetExtras;
/// <summary>Message to send to all devices when use the Push() procedure. Use this property as an alternative to setting APS.Alert and GCM.Message.</summary>
property Message: string read GetMessage write SetMessage;
property BindSource: TSubPushSenderBindSource read FBindSource;
property OnSending: TSendingEvent read FOnSending write FOnSending;
property OnSend: TSendEvent read FOnSend write FOnSend;
property PushAPI: TBackendPushAPI read GetPushAPI;
/// <summary>Specify where to send push. Example: {"where":{"devicetype":"ios"}}.
/// Target must be text that can be parsed into a JSON object. The member names are provider-specific.
/// "where" is a typical member name. Some providers also support "channels", such as {"channels":["a", "b"]}
/// </summary>
property Target: TStrings read FTarget write SetTarget;
property ProviderService: IBackendPushService read GetProviderService;
end;
TBackendPush = class(TCustomBackendPush)
published
property Provider;
property Auth;
property Message;
property APS;
property GCM;
property Extras;
property BindSource;
property Target;
end;
/// <summary>
/// LiveBindings adapter for TCustomBackendPush. Create bindable members
/// </summary>
TPushSenderAdapter = class(TRESTComponentAdapter)
public type
TNotify = class(TCustomBackendPush.TNotify)
private
FAdapter: TPushSenderAdapter;
constructor Create(const AAdapter: TPushSenderAdapter);
public
procedure PropertyValueChanged(Sender: TObject); override;
procedure ExtrasListChanged(Sender: TObject); override;
end;
private
FComponent: TCustomBackendPush;
FNotify: TNotify;
procedure SetPushSender(const APushSender: TCustomBackendPush);
procedure AddPropertyFields;
procedure AddParameterFields;
procedure ExtrasListChanged;
protected
procedure DoChangePosting; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
function GetCanActivate: Boolean; override;
procedure AddFields; override;
function GetSource: TBaseLinkingBindSource; override;
public
constructor Create(AComponent: TComponent); override;
destructor Destroy; override;
procedure GetMemberNames(AList: TStrings); override;
property PushSender: TCustomBackendPush read FComponent write SetPushSender;
end;
/// <summary>
/// LiveBindings bindsource for TCustomBackendPush. Creates adapter
/// </summary>
TCustomPushSenderBindSource = class(TRESTComponentBindSource)
private
FAdapter: TPushSenderAdapter;
function GetComponent: TCustomBackendPush;
procedure SetComponent(const AValue: TCustomBackendPush);
protected
function CreateAdapter: TRESTComponentAdapter; override;
public
property Component: TCustomBackendPush read GetComponent write SetComponent;
property Adapter: TPushSenderAdapter read FAdapter;
end;
/// <summary>
/// LiveBindings bindsource for TCustomBackendPush. Publishes subcomponent properties
/// </summary>
TSubPushSenderBindSource = class(TCustomPushSenderBindSource)
published
property AutoActivate;
property AutoEdit;
property AutoPost;
end;
TSubLoginBindSource = class;
TCustomBackendAuth = class(TBackendBindSourceComponent<IBackendAuthService, TBackendAuthApi>, IBackendAuthReg)
public type
TSendEvent = TNotifyEvent;
TSendingEvent = TNotifyEvent;
TUserDetailsItem = class;
TUserDetailsCollection = class(TOwnedCollection)
private type
TEnumerator = class(TCollectionEnumerator)
public
function GetCurrent: TUserDetailsItem; inline;
property Current: TUserDetailsItem read GetCurrent;
end;
protected
function GetItem(AIndex: integer): TUserDetailsItem;
procedure SetItem(AIndex: integer; const AValue: TUserDetailsItem);
function GetAttrCount: integer; override;
function GetAttr(Index: integer): string; override;
function GetItemAttr(Index, ItemIndex: integer): string; override;
procedure Update(AItem: TCollectionItem); override;
public
constructor Create(const AOwner: TComponent);
procedure ClearValues;
function GetEnumerator: TEnumerator;
property Items[AIndex: Integer]: TUserDetailsItem read GetItem write SetItem; default;
end;
TUserDetailsItem = class(TCollectionItem)
private
FName: string;
FValue: string;
protected
procedure SetName(const AValue: string);
procedure SetValue(const AValue: string);
public
procedure Assign(ASource: TPersistent); override;
function ToString: string; override;
function GetDisplayName: string; override;
published
property Name: string read FName write SetName;
property Value: string read FValue write SetValue;
end;
public type
TNotify = class(TRESTComponentNotify)
public
procedure UserDetailsChanged(Sender: TObject); virtual;
end;
TNotifyList = TRESTComponentNotifyList<TNotify>;
TLoginPromptEvent = procedure(Sender: TObject; var AUserName, APassword: string) of object;
private
FLoggedInValue: TBackendEntityValue;
FNotifyList: TNotifyList;
FUserDetails: TUserDetailsCollection;
FBindSource: TSubLoginBindSource;
FPassword: string;
FUserName: string;
FLoginPrompt: Boolean;
FAuthAccess: TList<IAuthAccess>;
FAuthentication: TBackendAuthentication;
FDefaultAuthentication: TBackendDefaultAuthentication;
FOnLoggedIn: TNotifyEvent;
FOnLoggingIn: TNotifyEvent;
FOnSigningUp: TNotifyEvent;
FOnSignedUp: TNotifyEvent;
FOnLoggedOut: TNotifyEvent;
FOnLoginPrompt: TLoginPromptEvent;
function GetProviderService: IBackendAuthService;
procedure PropertyValueChanged;
procedure UserDetailsChanged;
function GetAuthApi: TBackendAuthApi;
procedure SetUserDetails(const Value: TUserDetailsCollection);
procedure SetPassword(const Value: string);
procedure SetUserName(const Value: string);
procedure DoAuthAccess(const AProc: TProc<IAuthAccess>);
procedure ValidateAuthAccess;
function GetLoggedIn: Boolean;
function GetLoggedInToken: string;
function GetLoggedInUserName: string;
procedure CheckLoggedIn;
protected
{ IBackendAuthReg }
procedure RegisterForAuth(const AAuthAccess: IAuthAccess);
procedure UnregisterForAuth(const AAuthAccess: IAuthAccess);
function InternalCreateBackendServiceAPI: TBackendAuthApi; override;
function InternalCreateIndependentBackendServiceAPI: TBackendAuthApi; override;
function CreateBindSource: TBaseObjectBindSource; override;
procedure SetAuthentication(const Value: TBackendAuthentication);
procedure SetDefaultAuthentication(
const Value: TBackendDefaultAuthentication);
function LoginDialog(out AUserName, APassword: string): Boolean; virtual;
procedure DoLoggedIn; virtual;
procedure DoLoggingIn; virtual;
procedure DoLoggedOut; virtual;
function DoLogInPrompt(out AUserName, APassword: string): Boolean; virtual;
procedure DoSignedUp; virtual;
procedure DoSigningUp; virtual;
procedure ProviderChanged; override;
procedure Loaded; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Login; overload;
procedure Login(const ALogin: TBackendEntityValue; const AJSON: TJSONObject); overload;
procedure Signup;
procedure Logout;
procedure UpdateUserDetails;
procedure UserDetailsToJSON(const AJSON: TJSONObject);
procedure JSONToUserDetails(const AJSON: TJSONObject);
procedure ClearFieldValues;
// procedure RetrieveUserDetails;
// procedure GetDetails; overload;
// procedure GetDetails(const ALogin: TBackendEntityValue); overload;
// procedure ClearDetails;
property UserDetails: TUserDetailsCollection read FUserDetails write SetUserDetails;
property UserName: string read FUserName write SetUserName;
property Password: string read FPassword write SetPassword;
property LoginPrompt: Boolean read FLoginPrompt write FLoginPrompt;
property BindSource: TSubLoginBindSource read FBindSource;
property AuthAPI: TBackendAuthApi read GetAuthApi;
property ProviderService: IBackendAuthService read GetProviderService;
property Authentication: TBackendAuthentication read FAuthentication write SetAuthentication
default TBackendAuthentication.Default;
property DefaultAuthentication: TBackendDefaultAuthentication read FDefaultAuthentication write SetDefaultAuthentication
default TBackendDefaultAuthentication.None;
property LoggedIn: Boolean read GetLoggedIn;
property LoggedInToken: string read GetLoggedInToken;
property LoggedInUserName: string read GetLoggedInUserName;
property OnLoginPrompt: TLoginPromptEvent read FOnLoginPrompt write FOnLoginPrompt;
property OnLoggingIn: TNotifyEvent read FOnLoggingIn write FOnLoggingIn;
property OnLoggedIn: TNotifyEvent read FOnLoggedIn write FOnLoggedIn;
property OnSigningUp: TNotifyEvent read FOnSigningUp write FOnSigningUp;
property OnSignedUp: TNotifyEvent read FOnSignedUp write FOnSignedUp;
property OnLoggedOut: TNotifyEvent read FOnLoggedOut write FOnLoggedOut;
property LoggedInValue: TBackendEntityValue read FLoggedInValue;
end;
TBackendAuth = class(TCustomBackendAuth)
published
property Provider;
property UserName;
property Password;
property LoginPrompt;
property UserDetails;
property BindSource;
property Authentication;
property DefaultAuthentication;
property OnLoginPrompt;
property OnLoggingIn;
property OnLoggedIn;
property OnSigningUp;
property OnSignedUp;
property OnLoggedOut;
end;
/// <summary>
/// LiveBindings adapter for TCustomBackendAuth. Create bindable members
/// </summary>
TBackendAuthAdapter = class(TRESTComponentAdapter)
public type
TNotify = class(TCustomBackendAuth.TNotify)
private
FAdapter: TBackendAuthAdapter;
constructor Create(const AAdapter: TBackendAuthAdapter);
public
procedure PropertyValueChanged(Sender: TObject); override;
procedure UserDetailsChanged(Sender: TObject); override;
end;
private
FComponent: TCustomBackendAuth;
FNotify: TNotify;
procedure SetBackendAuth(const ALogin: TCustomBackendAuth);
procedure AddPropertyFields;
procedure AddParameterFields;
procedure UserDetailsChanged;
protected
procedure DoChangePosting; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
function GetCanActivate: Boolean; override;
procedure AddFields; override;
function GetSource: TBaseLinkingBindSource; override;
public
constructor Create(AComponent: TComponent); override;
destructor Destroy; override;
procedure GetMemberNames(AList: TStrings); override;
property BackendAuth: TCustomBackendAuth read FComponent write SetBackendAuth;
end;
/// <summary>
/// LiveBindings bindsource for TCustomBackendAuth. Creates adapter
/// </summary>
TCustomLoginBindSource = class(TRESTComponentBindSource)
private
FAdapter: TBackendAuthAdapter;
function GetComponent: TCustomBackendAuth;
procedure SetComponent(const AValue: TCustomBackendAuth);
protected
function CreateAdapter: TRESTComponentAdapter; override;
public
property Component: TCustomBackendAuth read GetComponent write SetComponent;
property Adapter: TBackendAuthAdapter read FAdapter;
end;
/// <summary>
/// LiveBindings bindsource for TCustomBackendAuth. Publishes subcomponent properties
/// </summary>
TSubLoginBindSource = class(TCustomLoginBindSource)
published
property AutoActivate;
property AutoEdit;
property AutoPost;
end;
TAuthAccess = class(TInterfacedObject, IAuthAccess)
private
FAuthentication: TFunc<IBackendAuthenticationApi>;
FComponent: IBackendServiceComponent;
private
procedure Login(const ALogin: TBackendEntityValue);
procedure Logout;
procedure SetAuthentication(const Value: TBackendAuthentication);
procedure SetDefaultAuthentication(
const Value: TBackendDefaultAuthentication);
function GetProvider: IBackendProvider;
public
constructor Create(const AComponent: IBackendServiceComponent;
const AAuthentication: TFunc<IBackendAuthenticationApi>);
end;
implementation
uses
REST.JSON, REST.Backend.Exception;
{ TCustomBackendQuery }
constructor TCustomBackendQuery.Create(AOwner: TComponent);
begin
/// it is important to create the notify-list before
/// calling the inherited constructor
FNotifyList := TNotifyList.Create;
FJSONNotifyList := TList<TNotifyEvent>.Create;
inherited;
FQueryLines := TStringList.Create;
end;
function TCustomBackendQuery.CreateAuthAccess: IAuthAccess;
begin
Result := TAuthAccess.Create(Self,
function: IBackendAuthenticationApi
begin
Result := Self.GetQueryApi.AuthenticationApi;
end);
end;
function TCustomBackendQuery.CreateBindSource: TBaseObjectBindSource;
begin
FBindSource := TSubBackendQueryBindSource.Create(self);
FBindSource.Name := 'BindSource'; { Do not localize }
FBindSource.SetSubComponent(true);
FBindSource.Query := self;
Result := FBindSource;
end;
function TCustomBackendQuery.CreateQueryAPI: TBackendQueryApi;
begin
Result := InternalCreateIndependentBackendServiceAPI;
end;
destructor TCustomBackendQuery.Destroy;
begin
FreeAndNil(FNotifyList);
FreeAndNil(FJSONNotifyList);
FQueryLines.Free;
inherited;
end;
procedure TCustomBackendQuery.AddJSONChangedEvent(const ANotify: TNotifyEvent);
begin
Assert(not FJSONNotifyList.Contains(ANotify));
if not FJSONNotifyList.Contains(ANotify) then
FJSONNotifyList.Add(ANotify);
end;
procedure TCustomBackendQuery.ClearResult;
begin
if FJSONResult <> nil then
begin
FreeAndNil(FJSONResult);
JSONValueChanged;
end;
end;
procedure TCustomBackendQuery.Execute;
var
LQuery: TArray<string>;
LResult: TJSONArray;
begin
// Clear
LResult := TJSONArray.Create;
try
FreeAndNil(FJSONResult);
LQuery := QueryLines.ToStringArray;
GetBackendServiceApi.Query(BackendService, BackendClassName, LQuery, LResult);
except
LResult.Free;
raise;
end;
SetJSONResult(LResult);
end;
procedure TCustomBackendQuery.SetJSONResult(const AJSONResult: TJSONArray);
begin
FreeAndNil(FJSONResult);
FJSONResult := AJSONResult;
JSONValueChanged;
end;
procedure TCustomBackendQuery.GetJSONResponse(out AJSONValue: TJSONValue;
out AHasOwner: Boolean);
begin
if FJSONResult <> nil then
begin
AJSONValue := FJSONResult;
AHasOwner := True;
end
else
begin
AJSONValue := nil;
AHasOwner := False;
end;
end;
function TCustomBackendQuery.GetProviderService: IBackendQueryService;
begin
Result := GetBackendService;
end;
function TCustomBackendQuery.GetQueryApi: TBackendQueryApi;
begin
Result := GetBackendServiceAPI;
end;
function TCustomBackendQuery.HasJSONResponse: Boolean;
begin
Result := FJSONResult <> nil;
end;
function TCustomBackendQuery.HasResponseContent: Boolean;
begin
Result := HasJSONResponse;
end;
function TCustomBackendQuery.InternalCreateBackendServiceAPI: TBackendQueryApi;
begin
Result := TBackendQueryApi.Create(GetBackendService); // Service.CreateStorageApi);
end;
function TCustomBackendQuery.InternalCreateIndependentBackendServiceAPI: TBackendQueryApi;
begin
Result := TBackendQueryApi.Create(GetBackendService.CreateQueryApi); // Service.CreateStorageApi);
end;
procedure TCustomBackendQuery.PropertyValueChanged;
begin
if (FNotifyList <> nil) then
begin
FNotifyList.notify(
procedure(ANotify: TNotify)
begin
ANotify.PropertyValueChanged(self);
end);
end;
end;
procedure TCustomBackendQuery.JSONValueChanged;
var
LNotifyEvent: TNotifyEvent;
begin
PropertyValueChanged;
for LNotifyEvent in FJSONNotifyList do
LNotifyEvent(Self);
end;
procedure TCustomBackendQuery.RemoveJSONChangedEvent(const ANotify: TNotifyEvent);
begin
Assert(FJSONNotifyList.Contains(ANotify));
FJSONNotifyList.Remove(ANotify);
end;
procedure TCustomBackendQuery.SetBackendClassName(const Value: string);
begin
if FBackendClassName <> Value then
begin
FBackendClassName := Value;
PropertyValueChanged;
end;
end;
procedure TCustomBackendQuery.SetBackendService(const Value: string);
begin
if FBackendService <> Value then
begin
FBackendService := Value;
PropertyValueChanged;
end;
end;
procedure TCustomBackendQuery.SetQueryLines(const Value: TStrings);
begin
FQueryLines.Assign(Value);
PropertyValueChanged;
end;
{ TCustomBackendQueryBindSource }
function TCustomBackendQueryBindSource.CreateAdapter: TRESTComponentAdapter;
begin
FAdapter := TBackendQueryAdapter.Create(self);
result := FAdapter;
end;
function TCustomBackendQueryBindSource.GetQuery: TCustomBackendQuery;
begin
result := FAdapter.Query;
end;
procedure TCustomBackendQueryBindSource.SetQuery(const AValue: TCustomBackendQuery);
begin
FAdapter.Query := AValue;
end;
{ TBackendQueryAdapter }
procedure TBackendQueryAdapter.SetQuery(const AQuery: TCustomBackendQuery);
var
LActive: Boolean;
begin
if FQuery <> AQuery then
begin
if FQuery <> nil then
begin
if FQuery.FNotifyList <> nil then
FQuery.FNotifyList.RemoveNotify(FNotify);
FQuery.RemoveFreeNotification(self);
end;
LActive := Active;
Active := False;
FQuery := AQuery;
if FQuery <> nil then
begin
if FQuery.FNotifyList <> nil then
FQuery.FNotifyList.AddNotify(FNotify);
FQuery.FreeNotification(self);
end;
if LActive and CanActivate then
Active := true;
end;
end;
procedure TBackendQueryAdapter.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
/// clean up component-references
if Operation = opRemove then
begin
if AComponent = FQuery then
Query := nil
end;
end;
constructor TBackendQueryAdapter.Create(AComponent: TComponent);
begin
inherited;
FNotify := TNotify.Create(self);
end;
destructor TBackendQueryAdapter.Destroy;
begin
inherited;
if (FQuery <> nil) then
begin
if FQuery.FNotifyList <> nil then
FQuery.FNotifyList.RemoveNotify(FNotify);
end;
FNotify.Free;
end;
procedure TBackendQueryAdapter.DoChangePosting;
begin
inherited;
end;
procedure TBackendQueryAdapter.AddFields;
begin
AddPropertyFields;
end;
procedure TBackendQueryAdapter.AddPropertyFields;
const
sJSONResult = 'JSONResult';
sBackendClassName = 'BackendClassName';
sBackendService = 'BackendService';
sQueryStrings = 'QueryStrings';
var
LGetMemberObject: IGetMemberObject;
begin
CheckInactive;
ClearFields;
if FQuery <> nil then
begin
LGetMemberObject := TBindSourceAdapterGetMemberObject.Create(self);
CreateReadOnlyField<string>(sJSONResult, LGetMemberObject, TScopeMemberType.mtText,
function: string
begin
if FQuery.JSONResult <> nil then
result := FQuery.JSONResult.Format
else
Result := '';
end);
CreateReadWriteField<string>(sBackendClassName, LGetMemberObject, TScopeMemberType.mtText,
function: string
begin
result := FQuery.BackendClassName
end,
procedure(AValue: string)
begin
FQuery.BackendClassName := AValue;
end);
CreateReadWriteField<string>(sBackendService, LGetMemberObject, TScopeMemberType.mtText,
function: string
begin
result := FQuery.BackendService
end,
procedure(AValue: string)
begin
FQuery.BackendService := AValue;
end);
CreateReadWriteField<string>(sQueryStrings, LGetMemberObject, TScopeMemberType.mtText,
function: string
begin
result := FQuery.QueryLines.Text
end,
procedure(AValue: string)
begin
FQuery.QueryLines.Text := AValue
end);
end;
end;
function TBackendQueryAdapter.GetCanActivate: Boolean;
begin
result := (FQuery <> nil);
end;
procedure TBackendQueryAdapter.GetMemberNames(AList: TStrings);
var
LField: TBindSourceAdapterField;
begin
for LField in Fields do
begin
if (LField is TReadWriteField<string>) then
// Provide object so that LiveBindings designer can select in designer when member is clicked
AList.AddObject(LField.MemberName, TReadWriteField<string>(LField).Persistent)
else
AList.Add(LField.MemberName);
end;
end;
function TBackendQueryAdapter.GetSource: TBaseLinkingBindSource;
begin
result := FQuery;
end;
{ TBackendQueryAdapter.TNotify }
constructor TBackendQueryAdapter.TNotify.Create(
const AAdapter: TBackendQueryAdapter);
begin
FAdapter := AAdapter
end;
procedure TBackendQueryAdapter.TNotify.PropertyValueChanged(Sender: TObject);
begin
if Assigned(FAdapter) then
FAdapter.RefreshFields;
end;
{ TCustomPushSender }
constructor TCustomBackendPush.Create(AOwner: TComponent);
begin
/// it is important to create the notify-list before
/// calling the inherited constructor
FNotifyList := TNotifyList.Create;
FPushData := TPushData.Create;
FPushData.OnChange :=
procedure
begin
PropertyValueChanged;
end;
FExtras := TExtrasCollection.Create(Self);
FTarget := TStringList.Create;
inherited;
end;
destructor TCustomBackendPush.Destroy;
begin
FreeAndNil(FNotifyList);
inherited;
FExtras.Free;
FPushData.Free;
FTarget.Free;
end;
procedure TCustomBackendPush.DoSend;
begin
end;
procedure TCustomBackendPush.DoSending;
begin
end;
function TCustomBackendPush.GetAPS: TPushData.TAPS;
begin
Result := FPushData.APS;
end;
function TCustomBackendPush.GetGCM: TPushData.TGCM;
begin
Result := FPushData.GCM;
end;
function TCustomBackendPush.GetMessage: string;
begin
Result := FPushData.Message;
end;
function TCustomBackendPush.GetProviderService: IBackendPushService;
begin
Result := GetBackendService;
end;
function TCustomBackendPush.GetPushAPI: TBackendPushAPI;
begin
Result := GetBackendServiceAPI;
end;
function TCustomBackendPush.InternalCreateBackendServiceAPI: TBackendPushApi;
begin
Result := TBackendPushApi.Create(GetBackendService); // Service.CreateStorageApi);
end;
function TCustomBackendPush.InternalCreateIndependentBackendServiceAPI: TBackendPushApi;
begin
Result := TBackendPushApi.Create(GetBackendService.CreatePushApi); // Service.CreateStorageApi);
end;
procedure TCustomBackendPush.PropertyValueChanged;
begin
if (FNotifyList <> nil) then
begin
FNotifyList.notify(
procedure(ANotify: TNotify)
begin
ANotify.PropertyValueChanged(self);
end);
end;
end;
procedure TCustomBackendPush.ExtrasListChanged;
begin
if (FNotifyList <> nil) then
begin
FNotifyList.notify(
procedure(ANotify: TNotify)
begin
ANotify.ExtrasListChanged(self);
end);
end;
end;
procedure TCustomBackendPush.PushData(const AData: TPushData);
begin
PushData(AData, nil);
end;
procedure TCustomBackendPush.PushData(const AData: TPushData; const ATarget: TJSONObject);
begin
GetBackendServiceApi.PushToTarget(AData, ATarget);
end;
procedure TCustomBackendPush.Push;
var
LTargetString: string;
LTargetJSON: TJSONValue;
begin
LTargetJSON := nil;
try
FExtras.UpdateExtras(FPushData.Extras);
LTargetString := Target.Text;
if Trim(LTargetString) <> '' then
LTargetJSON := TJSONObject.ParseJSONValue(LTargetString);
if LTargetJSON is TJSONObject then
PushData(FPushData, TJSONObject(LTargetJSON))
else
PushData(FPushData);
finally
LTargetJSON.Free;
end;
end;
procedure TCustomBackendPush.SetAPS(const Value: TPushData.TAPS);
begin
FPushData.APS := Value;
end;
procedure TCustomBackendPush.SetExtras(const Value: TExtrasCollection);
begin
FExtras.Assign(Value);
end;
procedure TCustomBackendPush.SetTarget(const Value: TStrings);
begin
FTarget.Assign(Value);
PropertyValueChanged;
end;
procedure TCustomBackendPush.SetGCM(const Value: TPushData.TGCM);
begin
FPushData.GCM := Value;
end;
procedure TCustomBackendPush.SetMessage(const Value: string);
begin
FPushData.Message := Value;
end;
function TCustomBackendPush.CreateAuthAccess: IAuthAccess;
begin
Result := TAuthAccess.Create(Self,
function: IBackendAuthenticationApi
begin
Result := Self.GetPushAPI.AuthenticationApi;
end);
end;
function TCustomBackendPush.CreateBindSource: TBaseObjectBindSource;
begin
FBindSource := TSubPushSenderBindSource.Create(self);
FBindSource.Name := 'BindSource'; { Do not localize }
FBindSource.SetSubComponent(true);
FBindSource.Component := self;
Result := FBindSource;
end;
{ TCustomPushSenderBindSource }
function TCustomPushSenderBindSource.CreateAdapter: TRESTComponentAdapter;
begin
FAdapter := TPushSenderAdapter.Create(self);
result := FAdapter;
end;
function TCustomPushSenderBindSource.GetComponent: TCustomBackendPush;
begin
result := FAdapter.PushSender;
end;
procedure TCustomPushSenderBindSource.SetComponent(const AValue: TCustomBackendPush);
begin
FAdapter.PushSender := AValue;
end;
{ TPushSenderAdapter }
procedure TPushSenderAdapter.SetPushSender(const APushSender: TCustomBackendPush);
var
LActive: Boolean;
begin
if FComponent <> APushSender then
begin
if FComponent <> nil then
begin
if FComponent.FNotifyList <> nil then
FComponent.FNotifyList.RemoveNotify(FNotify);
FComponent.RemoveFreeNotification(self);
end;
LActive := Active;
Active := False;
FComponent := APushSender;
if FComponent <> nil then
begin
if FComponent.FNotifyList <> nil then
FComponent.FNotifyList.AddNotify(FNotify);
FComponent.FreeNotification(self);
end;
if LActive and CanActivate then
Active := true;
end;
end;
procedure TPushSenderAdapter.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
/// clean up component-references
if Operation = opRemove then
begin
if AComponent = FComponent then
PushSender := nil
end;
end;
procedure TPushSenderAdapter.ExtrasListChanged;
begin
if (FComponent <> nil) and not(csLoading in FComponent.ComponentState) then
begin
if Active and not Posting then
begin
// Force extras to be recreated
Active := False;
Active := True;
end;
end;
end;
constructor TPushSenderAdapter.Create(AComponent: TComponent);
begin
inherited;
FNotify := TNotify.Create(self);
end;
destructor TPushSenderAdapter.Destroy;
begin
inherited;
if (FComponent <> nil) then
begin
if FComponent.FNotifyList <> nil then
FComponent.FNotifyList.RemoveNotify(FNotify);
end;
FNotify.Free;
end;
procedure TPushSenderAdapter.DoChangePosting;
begin
inherited;
end;
procedure TPushSenderAdapter.AddFields;
begin
AddPropertyFields;
AddParameterFields;
end;
procedure TPushSenderAdapter.AddPropertyFields;
const
sMessage = 'Message';
sAPSAlert = 'APS.Alert';
sAPSBadge = 'APS.Badge';
sAPSSound = 'APS.Sound';
sGCMTitle = 'GCM.Title';
sGCMMsg = 'GCM.Msg';
sGCMMessage = 'GCM.Message';
sGCMAction = 'GCM.Action';
sTarget = 'Target';
var
LGetMemberObject: IGetMemberObject;
begin
CheckInactive;
ClearFields;
if FComponent <> nil then
begin
LGetMemberObject := TBindSourceAdapterGetMemberObject.Create(self);
CreateReadWriteField<string>(sMessage, LGetMemberObject, TScopeMemberType.mtText,
function: string
begin
Result := FComponent.Message
end,
procedure(AValue: string)
begin
FComponent.Message := AValue;
end);
CreateReadWriteField<string>(sAPSAlert, LGetMemberObject, TScopeMemberType.mtText,
function: string
begin
Result := FComponent.APS.Alert;
end,
procedure(AValue: string)
begin
FComponent.APS.Alert := AValue;
end);
CreateReadWriteField<string>(sAPSBadge, LGetMemberObject, TScopeMemberType.mtText,
function: string
begin
Result := FComponent.APS.Badge
end,
procedure(AValue: string)
begin
FComponent.APS.Badge := AValue;
end);
CreateReadWriteField<string>(sAPSSound, LGetMemberObject, TScopeMemberType.mtText,
function: string
begin
Result := FComponent.APS.Sound
end,
procedure(AValue: string)
begin
FComponent.APS.Sound := AValue;
end);
CreateReadWriteField<string>(sGCMAction, LGetMemberObject, TScopeMemberType.mtText,
function: string
begin
Result := FComponent.GCM.Action
end,
procedure(AValue: string)
begin
FComponent.GCM.Action := AValue;
end);
CreateReadWriteField<string>(sGCMTitle, LGetMemberObject, TScopeMemberType.mtText,
function: string
begin
Result := FComponent.GCM.Title
end,
procedure(AValue: string)
begin
FComponent.GCM.Title := AValue;
end);
CreateReadWriteField<string>(sGCMMessage, LGetMemberObject, TScopeMemberType.mtText,
function: string
begin
Result := FComponent.GCM.Message
end,
procedure(AValue: string)
begin
FComponent.GCM.Message := AValue;
end);
CreateReadWriteField<string>(sGCMMsg, LGetMemberObject, TScopeMemberType.mtText,
function: string
begin
Result := FComponent.GCM.Msg
end,
procedure(AValue: string)
begin
FComponent.GCM.Msg := AValue;
end);
CreateReadWriteField<string>(sTarget, LGetMemberObject, TScopeMemberType.mtText,
function: string
begin
result := FComponent.Target.Text
end,
procedure(AValue: string)
begin
FComponent.Target.Text := AValue
end);
end;
end;
procedure TPushSenderAdapter.AddParameterFields;
procedure ClearExtrasFields;
var
I: integer;
begin
for I := Fields.Count - 1 downto 0 do
if (Fields[I] is TReadWriteField<string>) and (TReadWriteField<string>(Fields[I]).Persistent <> nil) then
Fields.Delete(I);
end;
procedure MakeExtrasFieldNames(const ADictionary: TDictionary<string, TCustomBackendPush.TExtrasItem>);
const
sPrefix = 'Extras.';
var
I: integer;
LExtrasCollection: TCustomBackendPush.TExtrasCollection;
LExtrasItem: TCustomBackendPush.TExtrasItem;
LName: string;
LIndex: integer;
LSuffix: string;
begin
Assert(ADictionary.Count = 0);
LExtrasCollection := FComponent.Extras;
for I := 0 to LExtrasCollection.Count - 1 do
begin
LExtrasItem := LExtrasCollection[I];
LName := LExtrasItem.Name;
if LName = '' then
LName := IntToStr(LExtrasItem.Index);
LName := sPrefix + LName;
LIndex := 1;
LSuffix := '';
while ADictionary.ContainsKey(LName + LSuffix) do
begin
LSuffix := IntToStr(LIndex);
inc(LIndex);
end;
ADictionary.Add(LName + LSuffix, LExtrasItem);
end;
end;
procedure MakeExrasField(const AExtrasItem: TCustomBackendPush.TExtrasItem; const AFieldName: string;
const AGetMemberObject: IGetMemberObject);
begin
CreateReadWriteField<string>(AFieldName, AGetMemberObject, TScopeMemberType.mtText,
function: string
begin
result := AExtrasItem.Value;
end,
procedure(AValue: string)
begin
AExtrasItem.Value := AValue;
end, AExtrasItem); // is member of field
end;
var
LDictionary: TDictionary<string, TCustomBackendPush.TExtrasItem>;
LPair: TPair<string, TCustomBackendPush.TExtrasItem>;
LGetMemberObject: IGetMemberObject;
begin
ClearExtrasFields;
if FComponent <> nil then
begin
LDictionary := TDictionary<string, TCustomBackendPush.TExtrasItem>.Create;
try
MakeExtrasFieldNames(LDictionary);
LGetMemberObject := TBindSourceAdapterGetMemberObject.Create(self);
for LPair in LDictionary do
MakeExrasField(LPair.Value, LPair.Key, LGetMemberObject);
finally
LDictionary.Free;
end;
end;
end;
function TPushSenderAdapter.GetCanActivate: Boolean;
begin
result := (FComponent <> nil);
end;
procedure TPushSenderAdapter.GetMemberNames(AList: TStrings);
var
LField: TBindSourceAdapterField;
begin
for LField in Fields do
begin
if (LField is TReadWriteField<string>) then
// Provide object so that LiveBindings designer can select in designer when member is clicked
AList.AddObject(LField.MemberName, TReadWriteField<string>(LField).Persistent)
else
AList.Add(LField.MemberName);
end;
end;
function TPushSenderAdapter.GetSource: TBaseLinkingBindSource;
begin
result := FComponent;
end;
{ TPushSenderAdapter.TNotify }
constructor TPushSenderAdapter.TNotify.Create(
const AAdapter: TPushSenderAdapter);
begin
FAdapter := AAdapter
end;
procedure TPushSenderAdapter.TNotify.ExtrasListChanged(Sender: TObject);
begin
if Assigned(FAdapter) then
FAdapter.ExtrasListChanged;
end;
procedure TPushSenderAdapter.TNotify.PropertyValueChanged(Sender: TObject);
begin
if Assigned(FAdapter) then
FAdapter.RefreshFields;
end;
{ TCustomBackendStorage }
function TCustomBackendStorage.CreateAuthAccess: IAuthAccess;
begin
Result := TAuthAccess.Create(Self,
function: IBackendAuthenticationApi
begin
Result := Self.GetStorage.AuthenticationApi;
end);
end;
function TCustomBackendStorage.CreateStorageAPI: TBackendStorageApi;
begin
Result := InternalCreateIndependentBackendServiceAPI;
end;
function TCustomBackendStorage.GetProviderService: IBackendStorageService;
begin
Result := GetBackendService;
end;
function TCustomBackendStorage.GetStorage: TBackendStorageApi;
begin
Result := GetBackendServiceAPI;
end;
function TCustomBackendStorage.InternalCreateBackendServiceAPI: TBackendStorageApi;
begin
Result := TBackendStorageApi.Create(GetBackendService); // Service.CreateStorageApi);
end;
function TCustomBackendStorage.InternalCreateIndependentBackendServiceAPI: TBackendStorageApi;
begin
Result := TBackendStorageApi.Create(GetBackendService.CreateStorageApi); // Service.CreateStorageApi);
end;
{ TCustomBackendUsers }
function TCustomBackendUsers.CreateUserAPI: TBackendUsersApi;
begin
Result := InternalCreateIndependentBackendServiceAPI;
end;
function TCustomBackendUsers.GetProviderService: IBackendUsersService;
begin
Result := GetBackendService;
end;
function TCustomBackendUsers.GetUsers: TBackendUsersApi;
begin
Result := GetBackendServiceAPI;
end;
function TCustomBackendUsers.InternalCreateBackendServiceAPI: TBackendUsersApi;
begin
Result := TBackendUsersApi.Create(GetBackendService); // Service.CreateStorageApi);
end;
function TCustomBackendUsers.InternalCreateIndependentBackendServiceAPI: TBackendUsersApi;
begin
Result := TBackendUsersApi.Create(GetBackendService.CreateUsersApi); // Service.CreateStorageApi);
end;
function TCustomBackendUsers.CreateAuthAccess: IAuthAccess;
begin
Result := TAuthAccess.Create(Self,
function: IBackendAuthenticationApi
begin
Result := Self.GetUsers.AuthenticationApi;
end);
end;
{ TCustomBackendGroups }
function TCustomBackendGroups.CreateGroupsAPI: TBackendGroupsApi;
begin
Result := InternalCreateIndependentBackendServiceAPI;
end;
function TCustomBackendGroups.GetProviderService: IBackendGroupsService;
begin
Result := GetBackendService;
end;
function TCustomBackendGroups.GetGroups: TBackendGroupsApi;
begin
Result := GetBackendServiceAPI;
end;
function TCustomBackendGroups.InternalCreateBackendServiceAPI: TBackendGroupsApi;
begin
Result := TBackendGroupsApi.Create(GetBackendService); // Service.CreateStorageApi);
end;
function TCustomBackendGroups.InternalCreateIndependentBackendServiceAPI: TBackendGroupsApi;
begin
Result := TBackendGroupsApi.Create(GetBackendService.CreateGroupsApi); // Service.CreateStorageApi);
end;
function TCustomBackendGroups.CreateAuthAccess: IAuthAccess;
begin
Result := TAuthAccess.Create(Self,
function: IBackendAuthenticationApi
begin
Result := Self.GetGroups.AuthenticationApi;
end);
end;
{ TCustomBackendFiles }
function TCustomBackendFiles.CreateFilesAPI: TBackendFilesApi;
begin
Result := InternalCreateIndependentBackendServiceAPI;
end;
function TCustomBackendFiles.GetFiles: TBackendFilesApi;
begin
Result := GetBackendServiceAPI;
end;
function TCustomBackendFiles.GetProviderService: IBackendFilesService;
begin
Result := GetBackendService;
end;
function TCustomBackendFiles.InternalCreateBackendServiceAPI: TBackendFilesApi;
begin
Result := TBackendFilesApi.Create(GetBackendService); // Service.CreateStorageApi);
end;
function TCustomBackendFiles.InternalCreateIndependentBackendServiceAPI: TBackendFilesApi;
begin
Result := TBackendFilesApi.Create(GetBackendService.CreateFilesApi); // Service.CreateStorageApi);
end;
function TCustomBackendFiles.CreateAuthAccess: IAuthAccess;
begin
Result := TAuthAccess.Create(Self,
function: IBackendAuthenticationApi
begin
Result := Self.GetFiles.AuthenticationApi;
end);
end;
{ TCustomBackendPush.TExtrasCollection.TEnumerator }
function TCustomBackendPush.TExtrasCollection.TEnumerator.GetCurrent: TExtrasItem;
begin
Result := TExtrasItem(inherited GetCurrent);
end;
{ TCustomBackendPush.TExtrasCollection }
constructor TCustomBackendPush.TExtrasCollection.Create(const AOwner: TComponent);
begin
inherited Create(AOwner, TExtrasItem);
end;
function TCustomBackendPush.TExtrasCollection.GetAttr(Index: integer): string;
begin
case index of
0:
Result := sExtrasName;
1:
Result := sExtrasValue;
else
Result := ''; { do not localize }
end;
end;
function TCustomBackendPush.TExtrasCollection.GetAttrCount: integer;
begin
Result := 2;
end;
function TCustomBackendPush.TExtrasCollection.GetEnumerator: TEnumerator;
begin
Result := TEnumerator.Create(self);
end;
function TCustomBackendPush.TExtrasCollection.GetItem(AIndex: integer): TExtrasItem;
begin
Result := TExtrasItem(inherited Items[AIndex]);
end;
function TCustomBackendPush.TExtrasCollection.GetItemAttr(Index, ItemIndex: integer): string;
begin
case index of
0:
begin
Result := Items[ItemIndex].Name;
if Result = '' then
Result := IntToStr(ItemIndex);
end;
1:
Result := Items[ItemIndex].Value;
else
Result := '';
end;
end;
procedure TCustomBackendPush.TExtrasCollection.SetItem(AIndex: integer; const AValue: TExtrasItem);
begin
inherited SetItem(AIndex, TCollectionItem(AValue));
end;
procedure TCustomBackendPush.TExtrasCollection.Update(AItem: TCollectionItem);
begin
inherited;
if Self.Owner <> nil then
begin
if AItem = nil then // Entire list changed
if Self.Owner is TCustomBackendPush then
TCustomBackendPush(Self.Owner).ExtrasListChanged;
end;
end;
procedure TCustomBackendPush.TExtrasCollection.UpdateExtras(
const AExtras: TPushData.TExtras);
var
LItem: TCustomBackendPush.TExtrasItem;
begin
AExtras.Clear;
for LItem in Self do
AExtras.Add(LItem.Name, LItem.Value);
end;
//function TCustomBackendPush.CreateAuthAccess: IAuthAccess;
//begin
// Result := TAuthAccess.Create(Self,
// function: IBackendAuthenticationApi
// begin
// Result := Self.GetPushApi.AuthenticationApi;
// end);
//end;
{ TCustomBackendPush.TExtrasItem }
procedure TCustomBackendPush.TExtrasItem.Assign(ASource: TPersistent);
var
LExtra: TExtrasItem;
begin
if (ASource is TExtrasItem) then
begin
LExtra := TExtrasItem(ASource);
FName := LExtra.Name;
FValue := LExtra.Value;
end
else
inherited;
end;
function TCustomBackendPush.TExtrasItem.GetDisplayName: string;
begin
result := FName;
end;
procedure TCustomBackendPush.TExtrasItem.SetName(const AValue: string);
begin
if FName <> AValue then
begin
FName := AValue;
Changed(False);
if Self.Collection.Owner is TCustomBackendPush then
TCustomBackendPush(Self.Collection.Owner).ExtrasListChanged;
end;
end;
procedure TCustomBackendPush.TExtrasItem.SetValue(const AValue: string);
begin
if FValue <> AValue then
begin
FValue := AValue;
Changed(False);
if (Self.Collection is TExtrasCollection) and (Self.Collection.Owner <> nil) then
if Self.Collection.Owner is TCustomBackendPush then
TCustomBackendPush(Self.Collection.Owner).PropertyValueChanged;
end;
end;
function TCustomBackendPush.TExtrasItem.ToString: string;
begin
result := Format('%s=%s', [FName, FValue])
end;
{ TCustomBackendPush.TNotify }
procedure TCustomBackendPush.TNotify.ExtrasListChanged(Sender: TObject);
begin
//
end;
{ TCustomBackendLogin }
procedure TCustomBackendAuth.ClearFieldValues;
begin
UserName := '';
Password := '';
UserDetails.ClearValues;
end;
constructor TCustomBackendAuth.Create(AOwner: TComponent);
begin
/// it is important to create the notify-list before
/// calling the inherited constructor
FNotifyList := TNotifyList.Create;
FUserDetails := TUserDetailsCollection.Create(Self);
FAuthAccess := TList<IAuthAccess>.Create;
FDefaultAuthentication := TBackendDefaultAuthentication.None;
inherited;
end;
destructor TCustomBackendAuth.Destroy;
begin
FreeAndNil(FNotifyList);
inherited;
FUserDetails.Free;
FAuthAccess.Free;
end;
procedure TCustomBackendAuth.ValidateAuthAccess;
var
LProvider: IBackendProvider;
begin
LProvider := nil;
DoAuthAccess(
procedure(AAuthAccess: IAuthAccess)
begin
if (AAuthAccess.Provider <> nil) and (LProvider <> nil) then
begin
if AAuthAccess.Provider <> LProvider then
begin
raise EBackendServiceError.Create(sBackendAuthMultipleProviders);
end;
end
else if LProvider <> nil then
LProvider := AAuthAccess.Provider;
end);
if (Self.Provider <> nil) and (LProvider <> nil) then
if LProvider <> Self.Provider then
raise EBackendServiceError.Create(sBackendAuthMultipleProviders);
end;
function TCustomBackendAuth.GetProviderService: IBackendAuthService;
begin
Result := GetBackendService;
end;
function TCustomBackendAuth.GetAuthApi: TBackendAuthApi;
begin
Result := GetBackendServiceAPI;
end;
function TCustomBackendAuth.GetLoggedIn: Boolean;
begin
Result := LoggedInToken <> '';
end;
function TCustomBackendAuth.InternalCreateBackendServiceAPI: TBackendAuthApi;
begin
Result := TBackendAuthApi.Create(GetBackendService); // Service.CreateStorageApi);
end;
function TCustomBackendAuth.InternalCreateIndependentBackendServiceAPI: TBackendAuthApi;
begin
Result := TBackendAuthApi.Create(GetBackendService.CreateAuthApi); // Service.CreateStorageApi);
end;
procedure TCustomBackendAuth.JSONToUserDetails(const AJSON: TJSONObject);
var
LItem: TUserDetailsItem;
S: string;
begin
for LItem in Self.UserDetails do
begin
if AJSON.TryGetValue<string>(LItem.Name, S) then
LItem.Value := S
else
LItem.Value := '';
end;
end;
procedure TCustomBackendAuth.UserDetailsToJSON(const AJSON: TJSONObject);
var
LItem: TUserDetailsItem;
begin
for LItem in Self.UserDetails do
begin
if LItem.Name <> '' then
AJSON.AddPair(LItem.Name, LItem.Value)
end;
end;
procedure TCustomBackendAuth.Loaded;
begin
inherited;
if Provider <> nil then
begin
Self.GetAuthApi.Authentication := FAuthentication;
Self.GetAuthApi.DefaultAuthentication := FDefaultAuthentication;
end;
DoAuthAccess(
procedure(AAuth: IAuthAccess)
begin
AAuth.SetAuthentication(FAuthentication);
AAuth.SetDefaultAuthentication(FDefaultAuthentication);
end);
end;
procedure TCustomBackendAuth.Login(const ALogin: TBackendEntityValue; const AJSON: TJSONObject);
var
LLogin: TBackendEntityValue;
begin
FLoggedInValue := ALogin;
FAuthentication := TBackendAuthentication.Session; // Do not set property. Property setter calls DoAuthAccess
if AJSON <> nil then
JSONToUserDetails(AJSON);
Self.GetAuthApi.Login(ALogin);
LLogin := ALogin;
DoAuthAccess(
procedure(AAuth: IAuthAccess)
begin
AAuth.Login(LLogin);
end);
DoLoggedin;
end;
procedure TCustomBackendAuth.Login;
var
LLogin: TBackendEntityValue;
LUserName: string;
LPassword: string;
LJSON: TJSONObject;
begin
LJSON := nil;
try
ValidateAuthAccess;
DoLoggingIn;
LUserName := FUserName;
LPassword := FPassword;
if LoginPrompt then
begin
DoLoginPrompt(LUserName, LPassword);
if LUserName = '' then
Exit; // EXIT
end;
GetBackendServiceApi.LoginUser(LUserName, LPassword,
procedure(const AObject: TBackendEntityValue; const AJSON: TJSONObject)
begin
LLogin := AObject;
if AJSON <> nil then
LJSON := AJSON.Clone as TJSONObject;
end);
Login(LLogin, LJSON);
finally
LJSON.Free;
end;
end;
procedure TCustomBackendAuth.Signup;
var
LJSON: TJSONObject;
LLogin: TBackendEntityValue;
begin
LJSON := TJSONObject.Create;
try
ValidateAuthAccess;
DoSigningUp;
UserDetailsToJSON(LJSON);
GetBackendServiceApi.SignupUser(FUserName, FPassword, LJSON, LLogin);
Login(LLogin, LJSON);
DoSignedUp;
finally
LJSON.Free;
end;
end;
procedure TCustomBackendAuth.DoLoggedIn;
begin
if Assigned(FOnLoggedIn) then
FOnLoggedIn(Self);
end;
procedure TCustomBackendAuth.DoLoggedOut;
begin
if Assigned(FOnLoggedOut) then
FOnLoggedOut(Self);
end;
function TCustomBackendAuth.DoLogInPrompt(out AUserName, APassword: string): Boolean;
begin
if Assigned(FOnLoginPrompt) then
begin
FOnLoginPrompt(Self, AUserName, APassword);
Result := AUserName <> '';
end
else
Result := LoginDialog(AUserName, APassword);
end;
procedure TCustomBackendAuth.DoLoggingIn;
begin
if Assigned(FOnLoggingIn) then
FOnLoggingIn(Self);
end;
procedure TCustomBackendAuth.DoSignedUp;
begin
if Assigned(FOnSignedUp) then
FOnSignedUp(Self);
end;
procedure TCustomBackendAuth.DoSigningUp;
begin
if Assigned(FOnSigningUp) then
FOnSigningUp(Self);
end;
function TCustomBackendAuth.LoginDialog(out AUserName, APassword: string): Boolean;
var
LUserName, LPassword: string;
begin
LUserName := FUserName;
LPassword := FPassword;
Result := TLoginCredentialService.GetLoginCredentials('', LUserName, LPassword);
if Result then
begin
AUserName := LUserName;
APassword := LPassword;
end;
end;
function TCustomBackendAuth.GetLoggedInToken: string;
begin
if not FLoggedInValue.TryGetAuthToken(Result) then
Result := '';
end;
function TCustomBackendAuth.GetLoggedInUserName: string;
begin
if not FLoggedInValue.TryGetUserName(Result) then
Result := '';
end;
procedure TCustomBackendAuth.DoAuthAccess(const AProc: TProc<IAuthAccess>);
var
LItem: IAuthAccess;
begin
for LItem in FAuthAccess do
AProc(LItem);
end;
procedure TCustomBackendAuth.Logout;
begin
FLoggedInValue := TBackendEntityValue.Empty;
FAuthentication := TBackendAuthentication.Default; // Do not set property. Property setter calls DoAuthAccess
try
GetBackendServiceApi.LogoutUser;
finally
Self.GetAuthApi.Logout;
DoAuthAccess(
procedure(AAuth: IAuthAccess)
begin
AAuth.Logout;
end);
DoLoggedOut;
end;
end;
procedure TCustomBackendAuth.PropertyValueChanged;
begin
if (FNotifyList <> nil) then
begin
FNotifyList.notify(
procedure(ANotify: TNotify)
begin
ANotify.PropertyValueChanged(self);
end);
end;
end;
procedure TCustomBackendAuth.ProviderChanged;
begin
inherited;
if not (csLoading in ComponentState) then
if Provider <> nil then
DefaultAuthentication := Self.GetAuthApi.DefaultAuthentication;
end;
procedure TCustomBackendAuth.RegisterForAuth(const AAuthAccess: IAuthAccess);
var
LProvider: IBackendProvider;
begin
if not FAuthAccess.Contains(AAuthAccess) then
begin
LProvider := Self.Provider;
if (LProvider <> nil) and (AAuthAccess.Provider <> nil) and (AAuthAccess.Provider <> LProvider) then
begin
raise EBackendServiceError.Create(sBackendAuthMismatchedProvider);
end;
FAuthAccess.Add(AAuthAccess);
// Synchronize component
if not (csLoading in ComponentState) then
begin
if LoggedIn then
begin
AAuthAccess.Login(FLoggedInValue);
AAuthAccess.SetDefaultAuthentication(Self.DefaultAuthentication);
end
else
begin
AAuthAccess.SetDefaultAuthentication(Self.DefaultAuthentication);
AAuthAccess.Logout;
AAuthAccess.SetAuthentication(Self.Authentication);
end;
end;
end;
end;
procedure TCustomBackendAuth.UserDetailsChanged;
begin
if (FNotifyList <> nil) then
begin
FNotifyList.notify(
procedure(ANotify: TNotify)
begin
ANotify.UserDetailsChanged(self);
end);
end;
end;
procedure TCustomBackendAuth.SetAuthentication(
const Value: TBackendAuthentication);
begin
// Do not check if FAuthentication <> Value then
FAuthentication := Value;
if not (csLoading in ComponentState) then
begin
if Provider <> nil then
Self.GetAuthApi.Authentication := Value;
DoAuthAccess(
procedure(AAuth: IAuthAccess)
begin
AAuth.SetAuthentication(FAuthentication);
end);
end;
end;
procedure TCustomBackendAuth.SetDefaultAuthentication(
const Value: TBackendDefaultAuthentication);
begin
// Do not check if FAuthentication <> Value then
FDefaultAuthentication := Value;
if not (csLoading in ComponentState) then
begin
if Provider <> nil then
Self.GetAuthApi.DefaultAuthentication := Value;
DoAuthAccess(
procedure(AAuth: IAuthAccess)
begin
AAuth.SetDefaultAuthentication(FDefaultAuthentication);
end);
end;
end;
procedure TCustomBackendAuth.SetUserDetails(const Value: TUserDetailsCollection);
begin
FUserDetails.Assign(Value);
end;
procedure TCustomBackendAuth.SetPassword(const Value: string);
begin
FPassword := Value;
PropertyValueChanged;
end;
procedure TCustomBackendAuth.SetUserName(const Value: string);
begin
FUserName := Value;
PropertyValueChanged;
end;
procedure TCustomBackendAuth.UnregisterForAuth(const AAuthAccess: IAuthAccess);
begin
FAuthAccess.Remove(AAuthAccess);
end;
//procedure TCustomBackendAuth.RetrieveUserDetails;
//begin
//
//end;
procedure TCustomBackendAuth.CheckLoggedIn;
begin
if not LoggedIn then
raise EBackendServiceError.Create(sLoginRequired);
end;
procedure TCustomBackendAuth.UpdateUserDetails;
var
LJSON: TJSONObject;
LUpdated: TBackendEntityValue;
begin
CheckLoggedIn;
LJSON := TJSONObject.Create;
try
UserDetailsToJSON(LJSON);
GetBackendServiceApi.UpdateUser(FLoggedInValue, LJSON, LUpdated);
finally
LJSON.Free;
end;
end;
function TCustomBackendAuth.CreateBindSource: TBaseObjectBindSource;
begin
FBindSource := TSubLoginBindSource.Create(self);
FBindSource.Name := 'BindSource'; { Do not localize }
FBindSource.SetSubComponent(true);
FBindSource.Component := self;
Result := FBindSource;
end;
{ TCustomLoginBindSource }
function TCustomLoginBindSource.CreateAdapter: TRESTComponentAdapter;
begin
FAdapter := TBackendAuthAdapter.Create(self);
result := FAdapter;
end;
function TCustomLoginBindSource.GetComponent: TCustomBackendAuth;
begin
result := FAdapter.BackendAuth;
end;
procedure TCustomLoginBindSource.SetComponent(const AValue: TCustomBackendAuth);
begin
FAdapter.BackendAuth := AValue;
end;
{ TLoginAdapter }
procedure TBackendAuthAdapter.SetBackendAuth(const ALogin: TCustomBackendAuth);
var
LActive: Boolean;
begin
if FComponent <> ALogin then
begin
if FComponent <> nil then
begin
if FComponent.FNotifyList <> nil then
FComponent.FNotifyList.RemoveNotify(FNotify);
FComponent.RemoveFreeNotification(self);
end;
LActive := Active;
Active := False;
FComponent := ALogin;
if FComponent <> nil then
begin
if FComponent.FNotifyList <> nil then
FComponent.FNotifyList.AddNotify(FNotify);
FComponent.FreeNotification(self);
end;
if LActive and CanActivate then
Active := true;
end;
end;
procedure TBackendAuthAdapter.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
/// clean up component-references
if Operation = opRemove then
begin
if AComponent = FComponent then
BackendAuth := nil
end;
end;
procedure TBackendAuthAdapter.UserDetailsChanged;
begin
if (FComponent <> nil) and not(csLoading in FComponent.ComponentState) then
begin
if Active and not Posting then
begin
// Force to be recreated
Active := False;
Active := True;
end;
end;
end;
constructor TBackendAuthAdapter.Create(AComponent: TComponent);
begin
inherited;
FNotify := TNotify.Create(self);
end;
destructor TBackendAuthAdapter.Destroy;
begin
inherited;
if (FComponent <> nil) then
begin
if FComponent.FNotifyList <> nil then
FComponent.FNotifyList.RemoveNotify(FNotify);
end;
FNotify.Free;
end;
procedure TBackendAuthAdapter.DoChangePosting;
begin
inherited;
end;
procedure TBackendAuthAdapter.AddFields;
begin
AddPropertyFields;
AddParameterFields;
end;
procedure TBackendAuthAdapter.AddPropertyFields;
const
sUserName = 'UserName';
sPassword = 'Password';
var
LGetMemberObject: IGetMemberObject;
begin
CheckInactive;
ClearFields;
if FComponent <> nil then
begin
LGetMemberObject := TBindSourceAdapterGetMemberObject.Create(self);
CreateReadWriteField<string>(sUserName, LGetMemberObject, TScopeMemberType.mtText,
function: string
begin
Result := FComponent.UserName
end,
procedure(AValue: string)
begin
FComponent.UserName := AValue;
end);
CreateReadWriteField<string>(sPassword, LGetMemberObject, TScopeMemberType.mtText,
function: string
begin
Result := FComponent.Password;
end,
procedure(AValue: string)
begin
FComponent.Password := AValue;
end);
end;
end;
procedure TBackendAuthAdapter.AddParameterFields;
procedure ClearUserDetailFields;
var
I: integer;
begin
for I := Fields.Count - 1 downto 0 do
if (Fields[I] is TReadWriteField<string>) and (TReadWriteField<string>(Fields[I]).Persistent <> nil) then
Fields.Delete(I);
end;
procedure MakeUserDetailFieldNames(const ADictionary: TDictionary<string, TCustomBackendAuth.TUserDetailsItem>);
const
sPrefix = 'UserDetail.';
var
I: integer;
LUserDetailsCollection: TCustomBackendAuth.TUserDetailsCollection;
LUserDetailItem: TCustomBackendAuth.TUserDetailsItem;
LName: string;
LIndex: integer;
LSuffix: string;
begin
Assert(ADictionary.Count = 0);
LUserDetailsCollection := FComponent.UserDetails;
for I := 0 to LUserDetailsCollection.Count - 1 do
begin
LUserDetailItem := LUserDetailsCollection[I];
LName := LUserDetailItem.Name;
if LName = '' then
LName := IntToStr(LUserDetailItem.Index);
LName := sPrefix + LName;
LIndex := 1;
LSuffix := '';
while ADictionary.ContainsKey(LName + LSuffix) do
begin
LSuffix := IntToStr(LIndex);
inc(LIndex);
end;
ADictionary.Add(LName + LSuffix, LUserDetailItem);
end;
end;
procedure MakeUserDetailsField(const AExtrasItem: TCustomBackendAuth.TUserDetailsItem; const AFieldName: string;
const AGetMemberObject: IGetMemberObject);
begin
CreateReadWriteField<string>(AFieldName, AGetMemberObject, TScopeMemberType.mtText,
function: string
begin
result := AExtrasItem.Value;
end,
procedure(AValue: string)
begin
AExtrasItem.Value := AValue;
end, AExtrasItem); // is member of field
end;
var
LDictionary: TDictionary<string, TCustomBackendAuth.TUserDetailsItem>;
LPair: TPair<string, TCustomBackendAuth.TUserDetailsItem>;
LGetMemberObject: IGetMemberObject;
begin
ClearUserDetailFields;
if FComponent <> nil then
begin
LDictionary := TDictionary<string, TCustomBackendAuth.TUserDetailsItem>.Create;
try
MakeUserDetailFieldNames(LDictionary);
LGetMemberObject := TBindSourceAdapterGetMemberObject.Create(self);
for LPair in LDictionary do
MakeUserDetailsField(LPair.Value, LPair.Key, LGetMemberObject);
finally
LDictionary.Free;
end;
end;
end;
function TBackendAuthAdapter.GetCanActivate: Boolean;
begin
result := (FComponent <> nil);
end;
procedure TBackendAuthAdapter.GetMemberNames(AList: TStrings);
var
LField: TBindSourceAdapterField;
begin
for LField in Fields do
begin
if (LField is TReadWriteField<string>) then
// Provide object so that LiveBindings designer can select in designer when member is clicked
AList.AddObject(LField.MemberName, TReadWriteField<string>(LField).Persistent)
else
AList.Add(LField.MemberName);
end;
end;
function TBackendAuthAdapter.GetSource: TBaseLinkingBindSource;
begin
result := FComponent;
end;
{ TLoginAdapter.TNotify }
constructor TBackendAuthAdapter.TNotify.Create(
const AAdapter: TBackendAuthAdapter);
begin
FAdapter := AAdapter
end;
procedure TBackendAuthAdapter.TNotify.UserDetailsChanged(Sender: TObject);
begin
if Assigned(FAdapter) then
FAdapter.UserDetailsChanged;
end;
procedure TBackendAuthAdapter.TNotify.PropertyValueChanged(Sender: TObject);
begin
if Assigned(FAdapter) then
FAdapter.RefreshFields;
end;
{ TCustomBackendLogin.TUserDetailsCollection.TEnumerator }
function TCustomBackendAuth.TUserDetailsCollection.TEnumerator.GetCurrent: TUserDetailsItem;
begin
Result := TUserDetailsItem(inherited GetCurrent);
end;
{ TCustomBackendLogin.TUserDetailsCollection }
procedure TCustomBackendAuth.TUserDetailsCollection.ClearValues;
var
LItem: TUserDetailsItem;
begin
for LItem in Self do
LItem.Value := '';
end;
constructor TCustomBackendAuth.TUserDetailsCollection.Create(const AOwner: TComponent);
begin
inherited Create(AOwner, TUserDetailsItem);
end;
function TCustomBackendAuth.TUserDetailsCollection.GetAttr(Index: integer): string;
begin
case index of
0:
Result := sExtrasName;
1:
Result := sExtrasValue;
else
Result := ''; { do not localize }
end;
end;
function TCustomBackendAuth.TUserDetailsCollection.GetAttrCount: integer;
begin
Result := 2;
end;
function TCustomBackendAuth.TUserDetailsCollection.GetEnumerator: TEnumerator;
begin
Result := TEnumerator.Create(self);
end;
function TCustomBackendAuth.TUserDetailsCollection.GetItem(AIndex: integer): TUserDetailsItem;
begin
Result := TUserDetailsItem(inherited Items[AIndex]);
end;
function TCustomBackendAuth.TUserDetailsCollection.GetItemAttr(Index, ItemIndex: integer): string;
begin
case index of
0:
begin
Result := Items[ItemIndex].Name;
if Result = '' then
Result := IntToStr(ItemIndex);
end;
1:
Result := Items[ItemIndex].Value;
else
Result := '';
end;
end;
procedure TCustomBackendAuth.TUserDetailsCollection.SetItem(AIndex: integer; const AValue: TUserDetailsItem);
begin
inherited SetItem(AIndex, TCollectionItem(AValue));
end;
procedure TCustomBackendAuth.TUserDetailsCollection.Update(AItem: TCollectionItem);
begin
inherited;
if Self.Owner <> nil then
begin
if AItem = nil then // Entire list changed
if Self.Owner is TCustomBackendAuth then
TCustomBackendAuth(Self.Owner).UserDetailsChanged;
end;
end;
{ TCustomBackendLogin.TUserDetailsItem }
procedure TCustomBackendAuth.TUserDetailsItem.Assign(ASource: TPersistent);
var
LExtra: TUserDetailsItem;
begin
if (ASource is TUserDetailsItem) then
begin
LExtra := TUserDetailsItem(ASource);
FName := LExtra.Name;
FValue := LExtra.Value;
end
else
inherited;
end;
function TCustomBackendAuth.TUserDetailsItem.GetDisplayName: string;
begin
result := FName;
end;
procedure TCustomBackendAuth.TUserDetailsItem.SetName(const AValue: string);
begin
if FName <> AValue then
begin
FName := AValue;
Changed(False);
if Self.Collection.Owner is TCustomBackendAuth then
TCustomBackendAuth(Self.Collection.Owner).UserDetailsChanged;
end;
end;
procedure TCustomBackendAuth.TUserDetailsItem.SetValue(const AValue: string);
begin
if FValue <> AValue then
begin
FValue := AValue;
Changed(False);
if (Self.Collection is TUserDetailsCollection) and (Self.Collection.Owner <> nil) then
if Self.Collection.Owner is TCustomBackendAuth then
TCustomBackendAuth(Self.Collection.Owner).PropertyValueChanged;
end;
end;
function TCustomBackendAuth.TUserDetailsItem.ToString: string;
begin
result := Format('%s=%s', [FName, FValue])
end;
{ TCustomBackendLogin.TNotify }
procedure TCustomBackendAuth.TNotify.UserDetailsChanged(Sender: TObject);
begin
//
end;
{ TAuthAccess }
constructor TAuthAccess.Create(const AComponent: IBackendServiceComponent;
const AAuthentication: TFunc<IBackendAuthenticationApi>);
begin
FAuthentication := AAuthentication;
FComponent := AComponent;
end;
function TAuthAccess.GetProvider: IBackendProvider;
begin
Result := FComponent.Provider;
end;
procedure TAuthAccess.Login(const ALogin: TBackendEntityValue);
begin
FAuthentication.Login(ALogin);
end;
procedure TAuthAccess.Logout;
begin
FAuthentication.Logout;
end;
procedure TAuthAccess.SetAuthentication(const Value: TBackendAuthentication);
begin
FAuthentication.Authentication := Value;
end;
procedure TAuthAccess.SetDefaultAuthentication(
const Value: TBackendDefaultAuthentication);
begin
FAuthentication.DefaultAuthentication := Value;
end;
end.
|
constructor CalcException.create(code: Integer);
begin
self.code := code;
end;
function CalcException.getCode: Integer;
begin
Result := code;
end;
class procedure CalcException.checkException(status: Status);
var
code: Integer;
begin
code := status.getCode();
if (code <> 0) then
raise CalcException.create(code);
end;
class procedure CalcException.catchException(status: Status; e: Exception);
begin
if (e.inheritsFrom(CalcException)) then
status.setCode(CalcException(e).code)
else
status.setCode(-1);
end;
class procedure CalcException.setVersionError(status: Status; interfaceName: string;
currentVersion, expectedVersion: NativeInt);
begin
status.setCode(Status.ERROR_1);
end;
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLFileO3TC<p>
<b>History : </b><font size=-1><ul>
<li>23/08/10 - Yar - Replaced OpenGL1x to OpenGLTokens
<li>31/05/10 - Yar - Fixes for Linux x64
<li>08/05/10 - Yar - Removed check for residency in AssignFromTexture
<li>22/04/10 - Yar - Fixes after GLState revision
<li>27/01/10 - Yar - Bugfix in BlockOffset with negative result
<li>23/11/10 - DaStr - Added $I GLScene.inc
<li>23/01/10 - Yar - Added to AssignFromTexture CurrentFormat parameter
Fixed cube map loading bug
<li>20/01/10 - Yar - Creation
</ul><p>
}
unit GLFileO3TC;
interface
{$I GLScene.inc}
uses
System.Classes,
System.SysUtils,
//GLS
GLCrossPlatform,
OpenGLTokens,
GLContext,
GLGraphics,
GLTextureFormat,
GLApplicationFileIO;
type
TGLO3TCImage = class(TGLBaseImage)
public
class function Capabilities: TDataFileCapabilities; override;
procedure LoadFromFile(const filename: string); override;
procedure SaveToFile(const filename: string); override;
procedure LoadFromStream(stream: TStream); override;
procedure SaveToStream(stream: TStream); override;
procedure AssignFromTexture(textureContext: TGLContext;
const textureHandle: TGLuint;
textureTarget: TGLTextureTarget;
const CurrentFormat: Boolean;
const intFormat: TGLInternalFormat); reintroduce;
end;
implementation
uses
GLVectorGeometry;
const
O3_TC_RGB_S3TC_DXT1 = 1;
O3_TC_RGBA_S3TC_DXT5 = 4;
O3_TC_ATI3DC_ATI2N = 16;
const
O3_TC_CUBE_MAP = $0001;
O3_TC_ARRAY = $0002;
type
TO3TC_Header = record
Useless: Cardinal;
Magic: Cardinal; // Magic number: Must be O3TC.
Size: Cardinal; // Must be filled with sizeof(TO3TC_Header).
Version: Cardinal; // Version.
end;
TO3TC_ChunkHeader = record
// Must be filled with sizeof(TO3TC_Chunk_Header):
ChunkHeaderSize: Cardinal;
// Reserved in JeGX's version 1.0
Extension: Cardinal;
// The size of the data chunk that follows this one.
Size: Cardinal;
// Reserved
reserved2: Cardinal;
// Pixel format:
// - O3_TC_RGB_S3TC_DXT1 = 1
// - O3_TC_RGBA_S3TC_DXT5 = 4
// - O3_TC_ATI3DC_ATI2N = 16
InternalPixelFormat: Cardinal;
// Texture width.
Width: Cardinal;
// Texture height.
Height: Cardinal;
// Texture depth.
Depth: Cardinal;
// Number of mipmaps.
NumMipmaps: Cardinal;
// The texture name (optional).
TextureName: array[0..127] of AnsiChar;
// The texture id (optional).
TextureId: Cardinal;
end;
// ------------------
// ------------------ TGLO3TCImage ------------------
// ------------------
// LoadFromFile
//
procedure TGLO3TCImage.LoadFromFile(const filename: string);
var
fs: TStream;
begin
if FileStreamExists(fileName) then
begin
fs := CreateFileStream(fileName, fmOpenRead);
try
LoadFromStream(fs);
finally
fs.Free;
ResourceName := filename;
end;
end
else
raise EInvalidRasterFile.CreateFmt('File %s not found.', [filename]);
end;
// SaveToFile
//
procedure TGLO3TCImage.SaveToFile(const filename: string);
var
fs: TStream;
begin
fs := CreateFileStream(fileName, fmOpenWrite or fmCreate);
try
SaveToStream(fs);
finally
fs.Free;
end;
ResourceName := filename;
end;
// LoadFromStream
//
procedure TGLO3TCImage.LoadFromStream(stream: TStream);
type
TFOURCC = array[0..3] of AnsiChar;
var
Header: TO3TC_Header;
ChunkHeader: TO3TC_ChunkHeader;
begin
// Get the O3TC_Header.
stream.Read(Header, Sizeof(TO3TC_Header));
// Check for O3TC magic number...
if TFOURCC(Header.Magic) <> 'O3TC' then
raise EInvalidRasterFile.Create('Invalid O3TC file.');
// Get the O3TC_Chunk_Header
stream.Read(ChunkHeader, Sizeof(TO3TC_ChunkHeader));
FLOD[0].Width := ChunkHeader.Width;
FLOD[0].Height := ChunkHeader.Height;
FLOD[0].Depth := ChunkHeader.Depth;
// Get the number of mipmaps
if ChunkHeader.NumMipmaps <> 0 then
fLevelCount := MaxInteger(ChunkHeader.NumMipmaps, 1)
else
fLevelCount := 1;
if Header.Version > 1 then
begin
fCubeMap := (ChunkHeader.Extension and O3_TC_CUBE_MAP) <> 0;
fTextureArray := (ChunkHeader.Extension and O3_TC_ARRAY) <> 0;
end
else
begin
fCubeMap := false;
fTextureArray := false;
end;
// Set format properties
case ChunkHeader.InternalPixelFormat of
O3_TC_RGB_S3TC_DXT1:
begin
fColorFormat := GL_COMPRESSED_RGB_S3TC_DXT1_EXT;
fInternalFormat := tfCOMPRESSED_RGB_S3TC_DXT1;
fDataType := GL_COMPRESSED_RGB_S3TC_DXT1_EXT;
fElementSize := 8;
end;
O3_TC_RGBA_S3TC_DXT5:
begin
fColorFormat := GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
fInternalFormat := tfCOMPRESSED_RGBA_S3TC_DXT5;
fDataType := GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
fElementSize := 16;
end;
O3_TC_ATI3DC_ATI2N:
begin
fColorFormat := GL_COMPRESSED_LUMINANCE_ALPHA_3DC_ATI;
fInternalFormat := tfCOMPRESSED_LUMINANCE_ALPHA_3DC;
fDataType := GL_COMPRESSED_LUMINANCE_ALPHA_3DC_ATI;
fElementSize := 16;
end;
else
raise EInvalidRasterFile.Create('Unsupported O3TC format.')
end;
if ChunkHeader.Size <> DataSize then
EInvalidRasterFile.Create('O3TC erroneous image data size.');
ReallocMem(fData, ChunkHeader.Size);
// Read raw data
stream.Read(fData^, ChunkHeader.Size);
end;
// SaveFromStream
//
procedure TGLO3TCImage.SaveToStream(stream: TStream);
const
Magic: array[0..3] of AnsiChar = 'O3TC';
var
Header: TO3TC_Header;
ChunkHeader: TO3TC_ChunkHeader;
begin
if not ((fColorFormat = GL_COMPRESSED_RGB_S3TC_DXT1_EXT)
or (fColorFormat = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT)
or (fColorFormat = GL_COMPRESSED_LUMINANCE_ALPHA_3DC_ATI)) then
raise
EInvalidRasterFile.Create('These image format do not match the O3TC format specification.');
// Setup Header
Header.Magic := Cardinal(Magic);
Header.Size := SizeOf(TO3TC_Header) - SizeOf(Cardinal);
ChunkHeader.Extension := 0;
if not (fCubeMap or fTextureArray) then
begin
Header.Version := 1;
end
else
begin
Header.Version := 2;
if fCubeMap then
ChunkHeader.Extension := ChunkHeader.Extension or O3_TC_CUBE_MAP;
if fTextureArray then
ChunkHeader.Extension := ChunkHeader.Extension or O3_TC_ARRAY;
end;
ChunkHeader.ChunkHeaderSize := SizeOf(TO3TC_ChunkHeader);
ChunkHeader.Width := GetWidth;
ChunkHeader.Height := GetHeight;
ChunkHeader.Depth := GetDepth;
ChunkHeader.NumMipmaps := fLevelCount;
ChunkHeader.reserved2 := 1;
FillChar(ChunkHeader.TextureName, 128, 0);
ChunkHeader.TextureId := 0;
case fColorFormat of
GL_COMPRESSED_RGB_S3TC_DXT1_EXT: ChunkHeader.InternalPixelFormat :=
O3_TC_RGB_S3TC_DXT1;
GL_COMPRESSED_RGBA_S3TC_DXT5_EXT: ChunkHeader.InternalPixelFormat :=
O3_TC_RGBA_S3TC_DXT5;
GL_COMPRESSED_LUMINANCE_ALPHA_3DC_ATI: ChunkHeader.InternalPixelFormat :=
O3_TC_ATI3DC_ATI2N;
end;
ChunkHeader.Size := DataSize;
stream.Write(Header, Sizeof(TO3TC_Header));
stream.Write(ChunkHeader, Sizeof(TO3TC_ChunkHeader));
stream.Write(fData[0], ChunkHeader.Size);
end;
// AssignFromTexture
//
procedure TGLO3TCImage.AssignFromTexture(textureContext: TGLContext;
const textureHandle: TGLuint;
textureTarget: TGLTextureTarget;
const CurrentFormat: Boolean;
const intFormat: TGLInternalFormat);
var
oldContext: TGLContext;
contextActivate: Boolean;
texFormat, texLod, optLod: Cardinal;
level, faceCount, face: Integer;
residentFormat: TGLInternalFormat;
bCompressed: Boolean;
vtcBuffer, top, bottom: PByte;
i, j, k: Integer;
cw, ch: Integer;
glTarget: TGLEnum;
function blockOffset(x, y, z: Integer): Integer;
begin
if z >= (FLOD[level].Depth and -4) then
Result := fElementSize * (cw * ch * (FLOD[level].Depth and -4) + x +
cw * (y + ch * (z - 4 * ch)))
else
Result := fElementSize * (4 * (x + cw * (y + ch * floor(z / 4))) + (z and
3));
if Result < 0 then
Result := 0;
end;
begin
oldContext := CurrentGLContext;
contextActivate := (oldContext <> textureContext);
if contextActivate then
begin
if Assigned(oldContext) then
oldContext.Deactivate;
textureContext.Activate;
end;
glTarget := DecodeGLTextureTarget(textureTarget);
try
textureContext.GLStates.TextureBinding[0, textureTarget] := textureHandle;
fLevelCount := 0;
GL.GetTexParameteriv(glTarget, GL_TEXTURE_MAX_LEVEL, @texLod);
if glTarget = GL_TEXTURE_CUBE_MAP then
begin
fCubeMap := true;
faceCount := 6;
glTarget := GL_TEXTURE_CUBE_MAP_POSITIVE_X;
end
else
begin
fCubeMap := false;
faceCount := 1;
end;
fTextureArray := (glTarget = GL_TEXTURE_1D_ARRAY)
or (glTarget = GL_TEXTURE_2D_ARRAY)
or (glTarget = GL_TEXTURE_CUBE_MAP_ARRAY);
repeat
// Check level existence
GL.GetTexLevelParameteriv(glTarget, fLevelCount, GL_TEXTURE_INTERNAL_FORMAT,
@texFormat);
if texFormat = 1 then
Break;
Inc(fLevelCount);
if fLevelCount = 1 then
begin
GL.GetTexLevelParameteriv(glTarget, 0, GL_TEXTURE_WIDTH, @FLOD[0].Width);
GL.GetTexLevelParameteriv(glTarget, 0, GL_TEXTURE_HEIGHT, @FLOD[0].Height);
FLOD[0].Depth := 0;
if (glTarget = GL_TEXTURE_3D)
or (glTarget = GL_TEXTURE_2D_ARRAY)
or (glTarget = GL_TEXTURE_CUBE_MAP_ARRAY) then
GL.GetTexLevelParameteriv(glTarget, 0, GL_TEXTURE_DEPTH, @FLOD[0].Depth);
residentFormat := OpenGLFormatToInternalFormat(texFormat);
if CurrentFormat then
fInternalFormat := residentFormat
else
fInternalFormat := intFormat;
FindCompatibleDataFormat(fInternalFormat, fColorFormat, fDataType);
// Get optimal number or MipMap levels
optLod := GetImageLodNumber(GetWidth, GetHeight, GetDepth, IsVolume);
if texLod > optLod then
texLod := optLod;
// Check for MipMap posibility
if ((fInternalFormat >= tfFLOAT_R16)
and (fInternalFormat <= tfFLOAT_RGBA32)) then
texLod := 1;
end;
until fLevelCount = Integer(texLod);
if fLevelCount > 0 then
begin
fElementSize := GetTextureElementSize(fColorFormat, fDataType);
ReallocMem(FData, DataSize);
bCompressed := IsCompressed;
vtcBuffer := nil;
for face := 0 to faceCount - 1 do
begin
if fCubeMap then
glTarget := face + GL_TEXTURE_CUBE_MAP_POSITIVE_X;
for level := 0 to fLevelCount - 1 do
begin
if bCompressed then
begin
if GL.NV_texture_compression_vtc and IsVolume then
begin
if level = 0 then
GetMem(vtcBuffer, GetLevelSizeInByte(0));
GL.GetCompressedTexImage(glTarget, level, vtcBuffer);
// Shufle blocks from VTC to S3TC
cw := (FLOD[level].Width + 3) div 4;
ch := (FLOD[level].Height + 3) div 4;
top := GetLevelAddress(level);
for k := 0 to FLOD[level].Depth - 1 do
for i := 0 to ch - 1 do
for j := 0 to cw - 1 do
begin
bottom := vtcBuffer;
Inc(bottom, blockOffset(j, i, k));
Move(bottom^, top^, fElementSize);
Inc(top, fElementSize);
end;
end
else
GL.GetCompressedTexImage(glTarget, level, GetLevelAddress(level));
end
else
GL.GetTexImage(glTarget, level, fColorFormat, fDataType, GetLevelAddress(level));
end; // for level
end; // for face
if Assigned(vtcBuffer) then
FreeMem(vtcBuffer);
// Check memory corruption
ReallocMem(FData, DataSize);
if fLevelCount = 0 then
fLevelCount := 1;
GL.CheckError;
end;
finally
if contextActivate then
begin
textureContext.Deactivate;
if Assigned(oldContext) then
oldContext.Activate;
end;
end;
end;
// Capabilities
//
class function TGLO3TCImage.Capabilities: TDataFileCapabilities;
begin
Result := [dfcRead, dfcWrite];
end;
initialization
{ Register this Fileformat-Handler with GLScene }
RegisterRasterFormat('o3tc', 'oZone3D Texture Compression', TGLO3TCImage);
end.
|
{**********************************************}
{ TOBVFunction (On Balance Volume) }
{ Copyright (c) 2002-2004 by David Berneda }
{**********************************************}
unit TeeOBVFunction;
{$I TeeDefs.inc}
interface
uses
{$IFNDEF LINUX}
Windows, Messages,
{$ENDIF}
SysUtils, Classes,
{$IFDEF CLX}
QGraphics, QControls, QForms, QDialogs, QStdCtrls,
{$ELSE}
Graphics, Controls, Forms, Dialogs, StdCtrls,
{$ENDIF}
OHLChart, TeEngine, TeCanvas, Chart, TeeBaseFuncEdit;
type
TOBVFunction=class(TTeeFunction)
private
FVolume : TChartSeries;
procedure SetVolume(const Value: TChartSeries);
protected
class Function GetEditorClass:String; override;
Function IsValidSource(Value:TChartSeries):Boolean; override;
procedure Notification( AComponent: TComponent;
Operation: TOperation); override;
public
Constructor Create(AOwner:TComponent); override;
procedure AddPoints(Source:TChartSeries); override;
published
property Volume:TChartSeries read FVolume write SetVolume;
end;
TOBVFuncEditor = class(TBaseFunctionEditor)
Label1: TLabel;
CBVolume: TComboFlat;
procedure CBVolumeChange(Sender: TObject);
private
{ Private declarations }
protected
procedure ApplyFormChanges; override;
Procedure SetFunction; override;
public
{ Public declarations }
end;
implementation
{$IFNDEF CLX}
{$R *.DFM}
{$ELSE}
{$R *.xfm}
{$ENDIF}
uses TeeProCo, TeeConst;
{ TOBVFunction }
constructor TOBVFunction.Create(AOwner: TComponent);
begin
inherited;
InternalSetPeriod(1);
CanUsePeriod:=False;
SingleSource:=True;
HideSourceList:=True;
end;
procedure TOBVFunction.AddPoints(Source: TChartSeries);
var t : Integer;
tmp : Double;
begin
ParentSeries.Clear;
if Assigned(FVolume) then
with Source as TOHLCSeries do
for t:=0 to Count-1 do
if FVolume.Count>t then
begin
tmp:=FVolume.MandatoryValueList.Value[t];
if CloseValues.Value[t]>OpenValues.Value[t] then
begin
if t>0 then tmp:=tmp+ParentSeries.MandatoryValueList.Last
end
else
if t>0 then tmp:=ParentSeries.MandatoryValueList.Last-tmp;
ParentSeries.AddXY(DateValues.Value[t],tmp);
end
else break;
end;
class function TOBVFunction.GetEditorClass: String;
begin
result:='TOBVFuncEditor';
end;
function TOBVFunction.IsValidSource(Value: TChartSeries): Boolean;
begin
result:=Value is TOHLCSeries;
end;
procedure TOBVFunction.SetVolume(const Value: TChartSeries);
begin
if FVolume<>Value then
begin
{$IFDEF D5}
if Assigned(FVolume) then
FVolume.RemoveFreeNotification(Self);
{$ENDIF}
FVolume:=Value;
if Assigned(FVolume) then
FVolume.FreeNotification(Self);
ReCalculate;
end;
end;
procedure TOBVFunction.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (Operation=opRemove) and (AComponent=FVolume) then
Volume:=nil;
end;
procedure TOBVFuncEditor.ApplyFormChanges;
begin
inherited;
with TOBVFunction(IFunction) do
Volume:=TChartSeries(CBVolume.Items.Objects[CBVolume.ItemIndex]);
end;
procedure TOBVFuncEditor.SetFunction;
begin
inherited;
with TOBVFunction(IFunction) do
CBVolume.ItemIndex:=CBVolume.Items.IndexOfObject(Volume);
with CBVolume do
begin
FillSeriesItems(Items,IFunction.ParentSeries.ParentChart.SeriesList);
Items.InsertObject(0,TeeMsg_None,nil);
Items.Delete(Items.IndexOfObject(IFunction.ParentSeries));
ItemIndex:=Items.IndexOfObject(TOBVFunction(IFunction).Volume);
end;
end;
procedure TOBVFuncEditor.CBVolumeChange(Sender: TObject);
begin
EnableApply;
end;
initialization
RegisterClass(TOBVFuncEditor);
RegisterTeeFunction( TOBVFunction,
{$IFNDEF CLR}@{$ENDIF}TeeMsg_FunctionOBV,
{$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryFinancial );
finalization
UnRegisterTeeFunctions([ TOBVFunction ]);
end.
|
unit Command.Button1;
interface
uses
System.Classes,
System.SysUtils,
Vcl.StdCtrls,
Pattern.Command;
type
TButon1Command = class (TCommand)
private
FMemo: TMemo;
protected
procedure DoGuard; override;
procedure DoExecute; override;
published
property Memo: Vcl.StdCtrls.TMemo read FMemo write FMemo;
end;
implementation
procedure TButon1Command.DoGuard;
begin
Assert(Memo<>nil);
end;
procedure TButon1Command.DoExecute;
begin
Memo.Lines.Add('[1] Simple message from command 1');
Memo.Lines.Add('--- ---');
end;
end.
|
unit VM_Canvas;
interface
uses SysUtils, VM.Invoke, Graphics, Forms, Classes, Types;
var _Canvas: TCanvas = nil;
implementation
function _GetCanvas: TCanvas;
begin
Result := _Canvas;
end;
type
TCanvasColor = (
ccNone,
ccBlack,
ccMaroon
);
function GetColor(CColor: TCanvasColor): TColor;
begin
case CColor of
ccNone: Result := clBtnFace;
ccBlack: Result := clBlack;
ccMaroon: Result := clMaroon;
else
Result := clNone;
end;
end;
procedure _ClearCanvas;
begin
_Canvas.Brush.Color := clWindow;
_Canvas.FillRect(TRect.Create(0, 0, 1200, 1200));
end;
procedure _ProcessMessages;
begin
Application.ProcessMessages;
end;
procedure _DrawCircle(X, Y: Integer; CColor: TCanvasColor);
var
c: TColor;
begin
c := GetColor(CColor);
_Canvas.Pen.Color := c;
_Canvas.Brush.Color := c;
_Canvas.Ellipse(X, Y, X+15, Y+15);
end;
procedure RegisterVM_Canvas;
begin
//RegisterType('Canvas', 'TCanvas', nil);
RegisterProc('Canvas', 'GetCanvas', @_GetCanvas);
RegisterProc('Canvas', 'DrawCircle', @_DrawCircle);
RegisterProc('Canvas', 'ProcessMessages', @_ProcessMessages);
RegisterProc('Canvas', 'ClearCanvas', @_ClearCanvas);
end;
initialization
RegisterVM_Canvas;
end.
|
unit StdStyleActnCtrls;
interface
uses ActnMan, ActnMenus, ActnCtrls;
type
{ TStandardStyleActionBars }
TStandardStyleActionBars = class(TActionBarStyleEx)
public
function GetColorMapClass(ActionBar: TCustomActionBar): TCustomColorMapClass; override;
function GetControlClass(ActionBar: TCustomActionBar;
AnItem: TActionClientItem): TCustomActionControlClass; override;
function GetPopupClass(ActionBar: TCustomActionBar): TCustomPopupClass; override;
function GetAddRemoveItemClass(ActionBar: TCustomActionBar): TCustomAddRemoveItemClass; override;
function GetStyleName: string; override;
function GetScrollBtnClass: TCustomToolScrollBtnClass; override;
end;
var
StandardStyle: TStandardStyleActionBars;
implementation
uses ListActns, ActnColorMaps, StdActnMenus, Consts;
{ TStandardActionBandStyle }
function TStandardStyleActionBars.GetAddRemoveItemClass(ActionBar: TCustomActionBar): TCustomAddRemoveItemClass;
begin
Result := TStandardAddRemoveItem;
end;
function TStandardStyleActionBars.GetColorMapClass(
ActionBar: TCustomActionBar): TCustomColorMapClass;
begin
Result := TStandardColorMap;
end;
function TStandardStyleActionBars.GetControlClass(ActionBar: TCustomActionBar;
AnItem: TActionClientItem): TCustomActionControlClass;
begin
if ActionBar is TCustomActionToolBar then
begin
if AnItem.HasItems then
Result := TCustomDropDownButton
else
if (AnItem.Action is TStaticListAction) or
(AnItem.Action is TVirtualListAction) then
Result := TCustomComboControl
else
Result := TStandardButtonControl;
end
else if ActionBar is TCustomActionMainMenuBar then
Result := TStandardMenuButton
else if ActionBar is TCustomizeActionToolBar then
begin
with ActionBar as TCustomizeActionToolbar do
if not Assigned(RootMenu) or (AnItem.ParentItem <> TCustomizeActionToolBar(RootMenu).AdditionalItem) then
Result := TStandardMenuItem
else
Result := TStandardAddRemoveItem;
end
else if ActionBar is TCustomActionPopupMenu then
Result := TStandardMenuItem
else
// TODO: This should probably be an exception since there is no suitable alternative
Result := TStandardButtonControl;
end;
function TStandardStyleActionBars.GetPopupClass(
ActionBar: TCustomActionBar): TCustomPopupClass;
begin
if ActionBar is TCustomActionToolBar then
Result := TStandardCustomizePopup
else
Result := TStandardMenuPopup;
end;
function TStandardStyleActionBars.GetScrollBtnClass: TCustomToolScrollBtnClass;
begin
Result := TStandardToolScrollBtn;
end;
function TStandardStyleActionBars.GetStyleName: string;
begin
Result := 'Standard'; { Do not localize }
end;
initialization
StandardStyle := TStandardStyleActionBars.Create;
RegisterActnBarStyle(StandardStyle);
finalization
UnregisterActnBarStyle(StandardStyle);
StandardStyle.Free;
end.
|
namespace RemObjects.Elements.System;
interface
type
SeekOrigin = public enum (&Begin, Current, &End);
Stream = public abstract class
protected
method GetLength: Int64; virtual;
method SetLength(value: Int64); virtual;
method SetPosition(value: Int64); virtual;
method GetPosition: Int64; virtual;
method IsValid: Boolean; abstract;
public
method CanRead: Boolean; abstract;
method CanSeek: Boolean; abstract;
method CanWrite: Boolean;abstract;
method Seek(Offset: Int64; Origin: SeekOrigin): Int64; abstract;
method Close; virtual;
method &Read(const buf: ^Void; Count: UInt32): UInt32; abstract;
method &Write(const buf: ^Void; Count: UInt32): UInt32; abstract;
method CopyTo(Destination: Stream);
property Length: Int64 read GetLength write SetLength;
property Position: Int64 read GetPosition write SetPosition;
end;
implementation
method Stream.GetLength: Int64;
begin
if not CanSeek then raise new NotSupportedException();
var pos := Seek(0, SeekOrigin.Current);
var temp := Seek(0, SeekOrigin.End);
Seek(pos, SeekOrigin.Begin);
exit temp;
end;
method Stream.GetPosition: Int64;
begin
exit Seek(0, SeekOrigin.Current);
end;
method Stream.SetPosition(value: Int64);
begin
Seek(value, SeekOrigin.Begin);
end;
method Stream.SetLength(value: Int64);
begin
raise new NotSupportedException;
end;
method Stream.Close;
begin
// empty
end;
method Stream.CopyTo(Destination: Stream);
const
bufsize = 4*1024; //4 kb
begin
if Destination = nil then raise new Exception('Destination is null');
if not self.CanRead() then raise new NotSupportedException;
if not Destination.CanWrite() then raise new NotSupportedException;
var buf: array [bufsize] of Byte := InternalCalls.Undefined<array [bufsize] of Byte>();
while true do begin
var rest := &Read(@buf[0],bufsize);
if rest > 0 then rest := Destination.Write(@buf[0],rest);
if rest <> bufsize then break;
end;
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLAsyncHDS<p>
Implements a HDS Filter that generates HeightData tiles in a seperate thread.<p>
This component is a THeightDataSourceFilter, which uses a THeightDataSourceThread,
to asyncronously search the HeightData cache for any queued tiles.
When found, it then prepares the queued tile in its own THeightDataThread.
This allows the GUI to remain responsive, and prevents freezes when new tiles are
being prepared. Although this keeps the framerate up, it may cause holes in the
terrain to show, if the HeightDataThreads cant keep up with the TerrainRenderer's
requests for new tiles.
<p>
<b>History : </b><font size=-1><ul>
<li>22/04/10 - Yar - Fixes after GLState revision
<li>11/10/07 - DaStr - Added $I GLScene.inc, removed unused dependancy
<li>25/03/07 - DaStr - Replaced Dialogs with GLCrossPlatform for Delphi5 compatibility
<li>22/03/07 - LIN - Added UseDirtyTiles property - Specifies how dirty tiles are replaced.
<li>22/03/07 - LIN - Data is now prepared in 3 stages:
BeforePreparingData : (Main Thread)
PreparingData : (Sub-Thread) (Main Thread if MaxThreads=0)
AfterPreparingData : (Main Thread)
<li>05/03/07 - LIN - Added ThreadCount and WaitFor
<li>12/02/07 - LIN - Creation
</ul></font>
}
unit GLAsyncHDS;
interface
{$I GLScene.inc}
uses Classes, GLHeightData, GLCrossPlatform;
type
TGLAsyncHDS = class;
TIdleEvent = procedure(Sender:TGLAsyncHDS;TilesUpdated:boolean) of object;
TNewTilePreparedEvent = procedure (Sender : TGLAsyncHDS; heightData : THeightData) of object; //a tile was updated (called INSIDE the sub-thread?)
// TUseDirtyTiles
//
{: TUseDirtyTiles determines if/how dirty tiles are displayed and when they are released.
<ul>
<li>TUseDirtyTiles
<li>
<li> When a tile is maked as dirty, a replacement is queued immediately.
<li> However, the replacement cant be used until the HDThread has finished preparing it.
<li> Dirty tiles can be deleted as soon as they are no longer used/displayed.
Possible states for a TUseDirtyTiles.<p>
<li>hdsNever : Dirty tiles get released immediately, leaving a hole in the terrain, until the replacement is hdsReady.
<li>hdsUntilReplaced : Dirty tiles are used, until the HDThread has finished preparing the queued replacement.
<li>hdsUntilAllReplaced : Waits until the HDSThread has finished preparing ALL queued tiles,
<li> before allowing the renderer to switch over to the new set of tiles.
<li> (This prevents a fading checkerbox effect.)
</ul> }
TUseDirtyTiles=(dtNever,dtUntilReplaced,dtUntilAllReplaced);
TGLAsyncHDS = class (THeightDataSourceFilter)
private
{ Private Declarations }
FOnIdleEvent :TIdleEvent;
FOnNewTilePrepared : TNewTilePreparedEvent;
FUseDirtyTiles:TUseDirtyTiles;
FTilesUpdated:boolean;
protected
{ Protected Declarations }
public
//TilesUpdated:boolean;
{ Public Declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure BeforePreparingData(heightData : THeightData); override;
procedure StartPreparingData(heightData : THeightData); override;
procedure ThreadIsIdle; override;
procedure NewTilePrepared(heightData:THeightData);
function ThreadCount:integer;
procedure WaitFor(TimeOut:integer=2000);
//procedure NotifyChange(Sender : TObject); override;
function TilesUpdated:boolean; //Returns true if tiles have been updated since the flag was last reset
procedure TilesUpdatedFlagReset; //sets the TilesUpdatedFlag to false; (is ThreadSafe)
published
{ Published Declarations }
property OnIdle : TIdleEvent read FOnIdleEvent write FOnIdleEvent;
property OnNewTilePrepared : TNewTilePreparedEvent read FOnNewTilePrepared write FOnNewTilePrepared;
property UseDirtyTiles :TUseDirtyTiles read FUseDirtyTiles write FUseDirtyTiles;
property MaxThreads; //sets the maximum number of simultaineous threads that will prepare tiles.(>1 is rarely needed)
property Active; //set to false, to ignore new queued tiles.(Partially processed tiles will still be completed)
end;
TGLAsyncHDThread = class(THeightDataThread)
public
Owner : TGLAsyncHDS;
HDS : THeightDataSource;
Procedure Execute; override;
Procedure Sync;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
uses SysUtils;
// ------------------
// ------------------ TGLAsyncHDS ------------------
// ------------------
// Create
//
constructor TGLAsyncHDS.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
MaxThreads:=1;
FUseDirtyTiles:=dtNever;
FTilesUpdated:=true;
end;
// Destroy
//
destructor TGLAsyncHDS.Destroy;
begin
inherited Destroy;
end;
// BeforePreparingData
//
procedure TGLAsyncHDS.BeforePreparingData(heightData : THeightData);
begin
if FUseDirtyTiles=dtNever then begin
if heightData.OldVersion<>nil then begin
heightData.OldVersion.DontUse:=true;
heightData.DontUse:=false;
end;
end;
if assigned(HeightDataSource) then HeightDataSource.BeforePreparingData(heightData);
end;
// StartPreparingData
//
procedure TGLAsyncHDS.StartPreparingData(heightData : THeightData);
var HDThread : TGLAsyncHDThread;
HDS:THeightDataSource;
begin
HDS:=HeightDataSource;
//---if there is no linked HDS then return an empty tile--
if not Assigned(HDS) then begin
heightData.DataState:=hdsNone;
exit;
end;
if (Active=false) then exit;
//---If not using threads then prepare the HD tile directly--- (everything else freezes until done)
if MaxThreads=0 then begin
HDS.StartPreparingData(HeightData);
if heightData.DataState=hdsPreparing
then heightData.DataState:=hdsReady
else heightData.DataState:=hdsNone;
end else begin //--MaxThreads>0 : start the thread and go back to start the next one--
heightData.DataState:=hdsPreparing; //prevent other threads from preparing this HD.
HDThread:=TGLAsyncHDThread.Create(true);
HDThread.Owner:=self;
HDThread.HDS:=self.HeightDataSource;
HDThread.HeightData:=HeightData;
heightData.Thread:=HDThread;
HDThread.FreeOnTerminate:=false;
HDThread.Start;
end;
end;
//OnIdle event
//
procedure TGLAsyncHDS.ThreadIsIdle;
var i:integer;
lst:TList;
HD:THeightData;
begin
//----------- dtUntilAllReplaced -------------
//Switch to the new version of ALL dirty tiles
lst:=self.Data.LockList;
try
if FUseDirtyTiles=dtUntilAllReplaced then begin
i:=lst.Count;
while(i>0) do begin
dec(i);
HD:=THeightData(lst.Items[i]);
if (HD.DataState in [hdsReady,hdsNone])
and(Hd.DontUse)and(HD.OldVersion<>nil) then begin
HD.DontUse:=false;
HD.OldVersion.DontUse:=true;
FTilesUpdated:=true;
end;
end;
end;//Until All Replaced
if Assigned(FOnIdleEvent) then FOnIdleEvent(Self,FTilesUpdated);
finally
self.Data.UnlockList;
end;
//--------------------------------------------
end;
//OnNewTilePrepared event
//
procedure TGLAsyncHDS.NewTilePrepared(heightData:THeightData);
var HD:THeightData;
begin
if assigned(HeightDataSource) then HeightDataSource.AfterPreparingData(HeightData);
with self.Data.LockList do begin
try
HD:=heightdata;
//--------------- dtUntilReplaced -------------
//Tell terrain renderer to display the new tile
if (FUseDirtyTiles=dtUntilReplaced)and(HD.DontUse)and(HD.OldVersion<>nil) then begin
HD.DontUse:=false; //No longer ignore the new tile
HD.OldVersion.DontUse:=true; //Start ignoring the old tile
end;
//---------------------------------------------
if HD.DontUse=false then FTilesUpdated:=true;
if Assigned(FOnNewTilePrepared) then FOnNewTilePrepared(Self,HeightData); //OnNewTilePrepared Event
finally
self.Data.UnlockList;
end;
end;
end;
//ThreadCount
// Count the active threads
//
function TGLAsyncHDS.ThreadCount:integer;
var lst: Tlist;
i,TdCtr:integer;
HD:THeightData;
begin
lst:=self.Data.LockList;
i:=0;TdCtr:=0;
while(i<lst.Count)and(TdCtr<self.MaxThreads) do begin
HD:=THeightData(lst.Items[i]);
if HD.Thread<>nil then Inc(TdCtr);
inc(i);
end;
self.Data.UnlockList;
result:=TdCtr;
end;
//WaitFor
// Wait for all running threads to finish.
// Should only be called after setting Active to false,
// to prevent new threads from starting.
procedure TGLAsyncHDS.WaitFor(TimeOut:Integer=2000);
var OutTime:TDateTime;
begin
Assert(self.active=false);
OutTime:=now+TimeOut;
While ((now<OutTime)and(ThreadCount>0)) do begin
sleep(0);
end;
Assert(ThreadCount=0);
end;
{
procedure TGLAsyncHDS.NotifyChange(Sender : TObject);
begin
TilesChanged:=true;
end;
}
// This function prevents the user from trying to write directly to this variable.
// FTilesUpdated if NOT threadsafe and should only be reset with TilesUpdatedFlagReset.
function TGLAsyncHDS.TilesUpdated:boolean;
begin
result:=FTilesUpdated;
end;
// Set the TilesUpdatedFlag to false. (is Threadsafe)
procedure TGLAsyncHDS.TilesUpdatedFlagReset;
begin
if not assigned(self) then exit; //prevents AV on Application termination.
with Data.LockList do try
FTilesUpdated:=False;
finally Data.UnlockList; end;
end;
//-------------------HD Thread----------------
Procedure TGLAsyncHDThread.Execute;
Begin
HDS.StartPreparingData(HeightData);
HeightData.Thread:=nil;
Synchronize(sync);
end;
Procedure TGLAsyncHDThread.Sync;
begin
Owner.NewTilePrepared(heightData);
if heightData.DataState=hdsPreparing then heightData.DataState:=hdsReady;
end;
//--------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// class registrations
RegisterClass(TGLAsyncHDS);
end.
|
{
This unit is part of the Lua4Delphi Source Code
Copyright (C) 2009-2012, LaKraven Studios Ltd.
Copyright Protection Packet(s): L4D014
www.Lua4Delphi.com
www.LaKraven.com
--------------------------------------------------------------------
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.
--------------------------------------------------------------------
Unit: L4D.Lua.StaticLua51.pas
Released: 5th February 2012
Changelog:
22nd February 2012:
- Added method "lua_pushliteral" (initially forgotten)
- Added support for "direct-to-file" API call logging!
5th February 2012:
- Released
}
unit L4D.Lua.StaticLua51;
interface
{$I Lua4Delphi.inc}
{$WEAKPACKAGEUNIT ON}
uses
L4D.Lua.Intf, L4D.Lua.Lua51, L4D.Lua.Constants{$IFDEF L4D_API_LOGGING}, L4D.Debug.Logging{$ENDIF};
type
{
TLua51Static
- Lua 5.1 Static Link
}
{$REGION 'TLua51Static'}
TLua51Static = class(TLua51Common)
protected
procedure SetLuaLibRefs; override;
{$REGION 'ILuaLibCommon'}
function lua_atpanic(L: PLuaState; panicf: TLuaDelphiFunction): TLuaDelphiFunction; override;
function lua_checkstack(L: PLuaState; sz: Integer): LongBool; override;
procedure lua_close(L: PLuaState); override;
procedure lua_concat(L: PLuaState; n: Integer); override;
procedure lua_createtable(L: PLuaState; narr, nrec: Integer); override;
function lua_dump(L: PLuaState; writer: TLuaWriterFunction; data: Pointer): Integer; override;
function lua_error(L: PLuaState): Integer; override;
function lua_gc(L: PLuaState; what, data: Integer): Integer; override;
function lua_getallocf(L: PLuaState; ud: PPointer): TLuaAllocFunction; override;
procedure lua_getfield(L: PLuaState; idx: Integer; k: PAnsiChar); override;
function lua_gethook(L: PLuaState): TLuaHookFunction; override;
function lua_gethookcount(L: PLuaState): Integer; override;
function lua_gethookmask(L: PLuaState): Integer; override;
function lua_getinfo(L: PLuaState; const what: PAnsiChar; ar: PLuaDebug): Integer; override;
function lua_getlocal(L: PLuaState; ar: PLuaDebug; n: Integer): PAnsiChar; override;
function lua_getmetatable(L: PLuaState; objindex: Integer): LongBool; override;
function lua_getstack(L: PLuaState; level: Integer; ar: PLuaDebug): Integer; override;
procedure lua_gettable(L: PLuaState ; idx: Integer); override;
function lua_gettop(L: PLuaState): Integer; override;
function lua_getupvalue(L: PLuaState; funcindex, n: Integer): PAnsiChar; override;
procedure lua_insert(L: PLuaState; idx: Integer); override;
function lua_iscfunction(L: PLuaState; idx: Integer): LongBool; override;
function lua_isnumber(L: PLuaState; idx: Integer): LongBool; override;
function lua_isstring(L: PLuaState; idx: Integer): LongBool; override;
function lua_isuserdata(L: PLuaState; idx: Integer): LongBool; override;
function lua_newthread(L: PLuaState): PLuaState; override;
public
function lua_newstate(f: TLuaAllocFunction; ud: Pointer): PLuaState; override;
protected
function lua_newuserdata(L: PLuaState; sz: Cardinal): Pointer; override;
function lua_next(L: PLuaState; idx: Integer): Integer; override;
procedure lua_pushboolean(L: PLuaState; b: LongBool); override;
procedure lua_pushcclosure(L: PLuaState; fn: TLuaDelphiFunction; n: Integer); override;
function lua_pushfstring(L: PLuaState; const fmt: PAnsiChar): PAnsiChar; {varargs;} override;
procedure lua_pushinteger(L: PLuaState; n: Integer); override;
procedure lua_pushlightuserdata(L: PLuaState; p: Pointer); override;
procedure lua_pushnil(L: PLuaState); override;
procedure lua_pushnumber(L: PLuaState; n: Double); override;
function lua_pushstring(L: PLuaState; const s: PAnsiChar): PAnsiChar; override;
function lua_pushthread(L: PLuaState): LongBool; override;
procedure lua_pushvalue(L: PLuaState; idx: Integer); override;
function lua_pushvfstring(L: PLuaState; const fmt: PAnsiChar; argp: Pointer): PAnsiChar; override;
function lua_rawequal(L: PLuaState; idx1, idx2: Integer): LongBool; override;
procedure lua_rawget(L: PLuaState; idx: Integer); override;
procedure lua_rawgeti(L: PLuaState; idx, n: Integer); override;
procedure lua_rawset(L: PLuaState; idx: Integer); override;
procedure lua_rawseti(L: PLuaState; idx , n: Integer); override;
procedure lua_remove(L: PLuaState; idx: Integer); override;
procedure lua_replace(L: PLuaState; idx: Integer); override;
procedure lua_setallocf(L: PLuaState; f: TLuaAllocFunction; ud: Pointer); override;
procedure lua_setfield(L: PLuaState; idx: Integer; const k: PAnsiChar); override;
function lua_sethook(L: PLuaState; func: TLuaHookFunction; mask, count: Integer): Integer; override;
function lua_setlocal(L: PLuaState; ar: PLuaDebug; n: Integer): PAnsiChar; override;
procedure lua_settable(L: PLuaState; idx: Integer); override;
procedure lua_settop(L: PLuaState; idx: Integer); override;
function lua_setupvalue(L: PLuaState; funcindex, n: Integer): PAnsiChar; override;
function lua_status(L: PLuaState): Integer; override;
function lua_toboolean(L: PLuaState; idx: Integer): LongBool; override;
function lua_tocfunction(L: PLuaState; idx: Integer): TLuaDelphiFunction; override;
function lua_tolstring(L: PLuaState; idx: Integer; len: PCardinal): PAnsiChar; override;
function lua_topointer(L: PLuaState; idx: Integer): Pointer; override;
function lua_tothread(L: PLuaState; idx: Integer): PLuaState; override;
function lua_touserdata(L: PLuaState; idx: Integer): Pointer; override;
function lua_type(L: PLuaState; idx: Integer): Integer; override;
function lua_typename(L: PLuaState; tp: Integer): PAnsiChar; override;
procedure lua_xmove(src, dest: PLuaState; n: Integer); override;
function luaopen_base(L: PLuaState): Integer; override;
function luaopen_debug(L: PLuaState): Integer; override;
function luaopen_io(L: PLuaState): Integer; override;
function luaopen_math(L: PLuaState): Integer; override;
function luaopen_os(L: PLuaState): Integer; override;
function luaopen_package(L: PLuaState): Integer; override;
function luaopen_string(L: PLuaState): Integer; override;
function luaopen_table(L: PLuaState): Integer; override;
{$ENDREGION}
{$REGION 'ILuaAuxCommon'}
procedure luaL_addlstring(B: PLuaLBuffer; const s: PAnsiChar; ls: Cardinal); override;
procedure luaL_addstring(B: PLuaLBuffer; const s: PAnsiChar); override;
procedure luaL_addvalue(B: PLuaLBuffer); override;
function luaL_argerror(L: PLuaState; numarg: Integer; const extramsg: PAnsiChar): Integer; override;
procedure luaL_buffinit(L: PLuaState; B: PLuaLBuffer); override;
function luaL_callmeta(L: PLuaState; obj: Integer; const e: PAnsiChar): Integer; override;
procedure luaL_checkany(L: PLuaState; narg: Integer); override;
function luaL_checkinteger(L: PLuaState; numArg: Integer): Integer; override;
function luaL_checklstring(L: PLuaState; numArg: Integer; ls: PCardinal): PAnsiChar; override;
function luaL_checknumber(L: PLuaState; numArg: Integer): Double; override;
function luaL_checkoption(L: PLuaState; narg: Integer; const def: PAnsiChar; const lst: array of PAnsiChar): Integer; override;
procedure luaL_checkstack(L: PLuaState; sz: Integer; const msg: PAnsiChar); override;
procedure luaL_checktype(L: PLuaState; narg, t: Integer); override;
function luaL_checkudata(L: PLuaState; ud: Integer; const tname: PAnsiChar): Pointer; override;
function luaL_error(L: PLuaState; const fmt: PAnsiChar): Integer; {varargs;} override;
function luaL_getmetafield(L: PLuaState; obj: Integer; const e: PAnsiChar): Integer; override;
function luaL_gsub(L: PLuaState; const s, p, r: PAnsiChar): PAnsiChar; override;
function luaL_loadstring(L: PLuaState; const s: PAnsiChar): Integer; override;
function luaL_newmetatable(L: PLuaState; const tname: PAnsiChar): Integer; override;
function luaL_newstate: PLuaState; override;
procedure luaL_openlibs(L: PLuaState); override;
function luaL_optinteger(L: PLuaState; nArg: Integer; def: Integer): Integer; override;
function luaL_optlstring(L: PLuaState; numArg: Integer; const def: PAnsiChar; ls: PCardinal): PAnsiChar; override;
function luaL_optnumber(L: PLuaState; nArg: Integer; def: Double): Double; override;
procedure luaL_pushresult(B: PLuaLBuffer); override;
function luaL_ref(L: PLuaState; t: Integer): Integer; override;
procedure luaL_unref(L: PLuaState; t, ref: Integer); override;
procedure luaL_where(L: PLuaState; lvl: Integer); override;
{$ENDREGION}
{$REGION 'IluaInterchange'}
procedure lua_call(L: PLuaState; nargs, nresults: Integer); override; // External "lua_call" in 5.1, External "lua_callk" in 5.2
function lua_cpcall(L: PLuaState; func: TLuaDelphiFunction; ud: Pointer): Integer; override; // External in 5.1, "lua_pcall" in 5.2
function lua_equal(L: PLuaState; idx1, idx2: Integer): LongBool; override; // External in 5.1, "lua_compare" in 5.2
procedure lua_getfenv(L: PLuaState; idx: Integer); override; // External in 5.1, "lua_getuservalue" in 5.2
function lua_lessthan(L: PLuaState; idx1, idx2: Integer): LongBool; override; // External in 5.1, "lua_compare" in 5.2
function lua_load(L: PLuaState; reader: TLuaReaderFunction; dt: Pointer; const chunkname: PAnsiChar): Integer; overload; override; // Extra parameter in 5.2 (mode)... 5.1 to pass "nil" to operate normally
function lua_objlen(L: PLuaState; idx: Integer): Cardinal; override; // External in 5.1, "lua_rawlen" in 5.2
function lua_pcall(L: PLuaState; nargs, nresults, errfunc: Integer): Integer; override; // External in 5.1, "lua_pcallk" in 5.2
function lua_pushlstring(L: PLuaState; const s: PAnsiChar; ls: Cardinal): PAnsiChar; overload; override;
function lua_resume(L: PLuaState; narg: Integer): Integer; override; // 5.1 version // Commonized Externals
function lua_setfenv(L: PLuaState; idx: Integer): LongBool; override; // External in 5.1, "lua_setuservalue" in 5.2
function lua_setmetatable(L: PLuaState; objindex: Integer): LongBool; override; // Function in 5.1, Procedure in 5.2... using a Function for both (saves hardship)
function lua_tointeger(L: PLuaState; idx: Integer): Integer; override; // In 5.1
function lua_tonumber(L: PLuaState; idx: Integer): Double; override; // In 5.1
function lua_yield(L: PLuaState; nresults: Integer): Integer; override; // "lua_yield" in 5.1, "lua_yieldk" in 5.2
{$ENDREGION}
{$REGION 'ILuaAuxInterchange'}
function luaL_loadbuffer(L: PLuaState; buff: PAnsiChar; sz: Cardinal; name: PAnsiChar): Integer; override;
function luaL_loadfile(L: PLuaState; filename: PAnsiChar): Integer; override;
function luaL_prepbuffer(B: TLuaLBuffer): PAnsiChar; override;
procedure luaL_register(L: PLuaState; libname: PAnsiChar; lib: PluaLReg); override;
{$ENDREGION}
{$REGION 'ILua51Aux'}
procedure luaL_openlib(L: PLuaState; const libname: PAnsiChar; const lr: PLuaLReg; nup: Integer); overload; override;
{$ENDREGION}
end;
{$ENDREGION}
implementation
const
{$IFDEF MSWINDOWS}
LUA_lua_cpcall = 'lua_cpcall';
LUA_lua_equal = 'lua_equal';
LUA_luaL_findtable = 'luaL_findtable';
LUA_lua_getfenv = 'lua_getfenv';
LUA_lua_lessthan = 'lua_lessthan';
LUA_lua_objlen = 'lua_objlen';
LUA_lua_setfenv = 'lua_setfenv';
{$ELSE}
LUA_lua_cpcall = '_lua_cpcall';
LUA_lua_equal = '_lua_equal';
LUA_luaL_findtable = '_luaL_findtable';
LUA_lua_getfenv = '_lua_getfenv';
LUA_lua_lessthan = '_lua_lessthan';
LUA_lua_objlen = '_lua_objlen';
LUA_lua_setfenv = '_lua_setfenv';
{$ENDIF}
{$REGION 'Lua Lib Common External Methods'}
function EXT_lua_atpanic(L: PLuaState; panicf: TLuaDelphiFunction): TLuaDelphiFunction; cdecl; external LUA_DLL name LUA_lua_atpanic;
function EXT_lua_checkstack(L: PLuaState; sz: Integer): LongBool; cdecl; external LUA_DLL name LUA_lua_checkstack;
procedure EXT_lua_close(L: PLuaState); cdecl; external LUA_DLL name LUA_lua_close;
procedure EXT_lua_concat(L: PLuaState; n: Integer); cdecl; external LUA_DLL name LUA_lua_concat;
procedure EXT_lua_createtable(L: PLuaState; narr, nrec: Integer); cdecl; external LUA_DLL name LUA_lua_createtable;
function EXT_lua_dump(L: PLuaState; writer: TLuaWriterFunction; data: Pointer): Integer; cdecl; external LUA_DLL name LUA_lua_dump;
function EXT_lua_error(L: PLuaState): Integer; cdecl; external LUA_DLL name LUA_lua_error;
function EXT_lua_gc(L: PLuaState; what, data: Integer): Integer; cdecl; external LUA_DLL name LUA_lua_gc;
function EXT_lua_getallocf(L: PLuaState; ud: PPointer): TLuaAllocFunction; cdecl; external LUA_DLL name LUA_lua_getallocf;
procedure EXT_lua_getfield(L: PLuaState; idx: Integer; k: PAnsiChar); cdecl; external LUA_DLL name LUA_lua_getfield;
function EXT_lua_gethook(L: PLuaState): TLuaHookFunction; cdecl; external LUA_DLL name LUA_lua_gethook;
function EXT_lua_gethookcount(L: PLuaState): Integer; cdecl; external LUA_DLL name LUA_lua_gethookcount;
function EXT_lua_gethookmask(L: PLuaState): Integer; cdecl; external LUA_DLL name LUA_lua_gethookmask;
function EXT_lua_getinfo(L: PLuaState; const what: PAnsiChar; ar: PLuaDebug): Integer; cdecl; external LUA_DLL name LUA_lua_getinfo;
function EXT_lua_getlocal(L: PLuaState; ar: PLuaDebug; n: Integer): PAnsiChar; cdecl; external LUA_DLL name LUA_lua_getlocal;
function EXT_lua_getmetatable(L: PLuaState; objindex: Integer): LongBool; cdecl; external LUA_DLL name LUA_lua_getmetatable;
function EXT_lua_getstack(L: PLuaState; level: Integer; ar: PLuaDebug): Integer; cdecl; external LUA_DLL name LUA_lua_getstack;
procedure EXT_lua_gettable(L: PLuaState ; idx: Integer); cdecl; external LUA_DLL name LUA_lua_gettable;
function EXT_lua_gettop(L: PLuaState): Integer; cdecl; external LUA_DLL name LUA_lua_gettop;
function EXT_lua_getupvalue(L: PLuaState; funcindex, n: Integer): PAnsiChar; cdecl; external LUA_DLL name LUA_lua_getupvalue;
procedure EXT_lua_insert(L: PLuaState; idx: Integer); cdecl; external LUA_DLL name LUA_lua_insert;
function EXT_lua_iscfunction(L: PLuaState; idx: Integer): LongBool; cdecl; external LUA_DLL name LUA_lua_iscfunction;
function EXT_lua_isnumber(L: PLuaState; idx: Integer): LongBool; cdecl; external LUA_DLL name LUA_lua_isnumber;
function EXT_lua_isstring(L: PLuaState; idx: Integer): LongBool; cdecl; external LUA_DLL name LUA_lua_isstring;
function EXT_lua_isuserdata(L: PLuaState; idx: Integer): LongBool; cdecl; external LUA_DLL name LUA_lua_isuserdata;
function EXT_lua_newthread(L: PLuaState): PLuaState; cdecl; external LUA_DLL name LUA_lua_newthread;
function EXT_lua_newstate(f: TLuaAllocFunction; ud: Pointer): PLuaState; cdecl; external LUA_DLL name LUA_lua_newstate;
function EXT_lua_newuserdata(L: PLuaState; sz: Cardinal): Pointer; cdecl; external LUA_DLL name LUA_lua_newuserdata;
function EXT_lua_next(L: PLuaState; idx: Integer): Integer; cdecl; external LUA_DLL name LUA_lua_next;
procedure EXT_lua_pushboolean(L: PLuaState; b: LongBool); cdecl; external LUA_DLL name LUA_lua_pushboolean;
procedure EXT_lua_pushcclosure(L: PLuaState; fn: TLuaDelphiFunction; n: Integer); cdecl; external LUA_DLL name LUA_lua_pushcclosure;
function EXT_lua_pushfstring(L: PLuaState; const fmt: PAnsiChar): PAnsiChar; {varargs;} cdecl; external LUA_DLL name LUA_lua_pushfstring;
procedure EXT_lua_pushinteger(L: PLuaState; n: Integer); cdecl; external LUA_DLL name LUA_lua_pushinteger;
procedure EXT_lua_pushlightuserdata(L: PLuaState; p: Pointer); cdecl; external LUA_DLL name LUA_lua_pushlightuserdata;
procedure EXT_lua_pushlstring(L: PLuaState; s: PAnsiChar; len: Cardinal); cdecl; external Lua_DLL name LUA_lua_pushlstring;
procedure EXT_lua_pushnil(L: PLuaState); cdecl; external LUA_DLL name LUA_lua_pushnil;
procedure EXT_lua_pushnumber(L: PLuaState; n: Double); cdecl; external LUA_DLL name LUA_lua_pushnumber;
procedure EXT_lua_pushstring(L: PLuaState; const s: PAnsiChar); cdecl; external LUA_DLL name LUA_lua_pushstring;
function EXT_lua_pushthread(L: PLuaState): LongBool; cdecl; external LUA_DLL name LUA_lua_pushthread;
procedure EXT_lua_pushvalue(L: PLuaState; idx: Integer); cdecl; external LUA_DLL name LUA_lua_pushvalue;
function EXT_lua_pushvfstring(L: PLuaState; const fmt: PAnsiChar; argp: Pointer): PAnsiChar; cdecl; external LUA_DLL name LUA_lua_pushvfstring;
function EXT_lua_rawequal(L: PLuaState; idx1, idx2: Integer): LongBool; cdecl; external LUA_DLL name LUA_lua_rawequal;
procedure EXT_lua_rawget(L: PLuaState; idx: Integer); cdecl; external LUA_DLL name LUA_lua_rawget;
procedure EXT_lua_rawgeti(L: PLuaState; idx, n: Integer); cdecl; external LUA_DLL name LUA_lua_rawgeti;
procedure EXT_lua_rawset(L: PLuaState; idx: Integer); cdecl; external LUA_DLL name LUA_lua_rawset;
procedure EXT_lua_rawseti(L: PLuaState; idx , n: Integer); cdecl; external LUA_DLL name LUA_lua_rawseti;
procedure EXT_lua_remove(L: PLuaState; idx: Integer); cdecl; external LUA_DLL name LUA_lua_remove;
procedure EXT_lua_replace(L: PLuaState; idx: Integer); cdecl; external LUA_DLL name LUA_lua_replace;
procedure EXT_lua_setallocf(L: PLuaState; f: TLuaAllocFunction; ud: Pointer); cdecl; external LUA_DLL name LUA_lua_setallocf;
procedure EXT_lua_setfield(L: PLuaState; idx: Integer; const k: PAnsiChar); cdecl; external LUA_DLL name LUA_lua_setfield;
function EXT_lua_sethook(L: PLuaState; func: TLuaHookFunction; mask, count: Integer): Integer; cdecl; external LUA_DLL name LUA_lua_sethook;
function EXT_lua_setlocal(L: PLuaState; ar: PLuaDebug; n: Integer): PAnsiChar; cdecl; external LUA_DLL name LUA_lua_setlocal;
procedure EXT_lua_settable(L: PLuaState; idx: Integer); cdecl; external LUA_DLL name LUA_lua_settable;
procedure EXT_lua_settop(L: PLuaState; idx: Integer); cdecl; external LUA_DLL name LUA_lua_settop;
function EXT_lua_setupvalue(L: PLuaState; funcindex, n: Integer): PAnsiChar; cdecl; external LUA_DLL name LUA_lua_setupvalue;
function EXT_lua_status(L: PLuaState): Integer; cdecl; external LUA_DLL name LUA_lua_status;
function EXT_lua_toboolean(L: PLuaState; idx: Integer): LongBool; cdecl; external LUA_DLL name LUA_lua_toboolean;
function EXT_lua_tocfunction(L: PLuaState; idx: Integer): TLuaDelphiFunction; cdecl; external LUA_DLL name LUA_lua_tocfunction;
function EXT_lua_tolstring(L: PLuaState; idx: Integer; len: PCardinal): PAnsiChar; cdecl; external LUA_DLL name LUA_lua_tolstring;
function EXT_lua_topointer(L: PLuaState; idx: Integer): Pointer; cdecl; external LUA_DLL name LUA_lua_topointer;
function EXT_lua_tothread(L: PLuaState; idx: Integer): PLuaState; cdecl; external LUA_DLL name LUA_lua_tothread;
function EXT_lua_touserdata(L: PLuaState; idx: Integer): Pointer; cdecl; external LUA_DLL name LUA_lua_touserdata;
function EXT_lua_type(L: PLuaState; idx: Integer): Integer; cdecl; external LUA_DLL name LUA_lua_type;
function EXT_lua_typename(L: PLuaState; tp: Integer): PAnsiChar; cdecl; external LUA_DLL name LUA_lua_typename;
procedure EXT_lua_xmove(src, dest: PLuaState; n: Integer); cdecl; external LUA_DLL name LUA_lua_xmove;
function EXT_luaopen_base(L: PLuaState): Integer; cdecl; external LUA_DLL name LUA_luaopen_base;
function EXT_luaopen_debug(L: PLuaState): Integer; cdecl; external LUA_DLL name LUA_luaopen_debug;
function EXT_luaopen_io(L: PLuaState): Integer; cdecl; external LUA_DLL name LUA_luaopen_io;
function EXT_luaopen_math(L: PLuaState): Integer; cdecl; external LUA_DLL name LUA_luaopen_math;
function EXT_luaopen_os(L: PLuaState): Integer; cdecl; external LUA_DLL name LUA_luaopen_os;
function EXT_luaopen_package(L: PLuaState): Integer; cdecl; external LUA_DLL name LUA_luaopen_package;
function EXT_luaopen_string(L: PLuaState): Integer; cdecl; external LUA_DLL name LUA_luaopen_string;
function EXT_luaopen_table(L: PLuaState): Integer; cdecl; external LUA_DLL name LUA_luaopen_table;
{$ENDREGION}
{$REGION 'Lua Auxiliary Common External Methods'}
procedure EXT_luaL_addlstring(B: PLuaLBuffer; const s: PAnsiChar; ls: Cardinal); cdecl; external LUA_DLL name LUA_luaL_addlstring;
procedure EXT_luaL_addstring(B: PLuaLBuffer; const s: PAnsiChar); cdecl; external LUA_DLL name LUA_luaL_addstring;
procedure EXT_luaL_addvalue(B: PLuaLBuffer); cdecl; external LUA_DLL name LUA_luaL_addvalue;
function EXT_luaL_argerror(L: PLuaState; numarg: Integer; const extramsg: PAnsiChar): Integer; cdecl; external LUA_DLL name LUA_luaL_argerror;
procedure EXT_luaL_buffinit(L: PLuaState; B: PLuaLBuffer); cdecl; external LUA_DLL name LUA_luaL_buffinit;
function EXT_luaL_callmeta(L: PLuaState; obj: Integer; const e: PAnsiChar): Integer; cdecl; external LUA_DLL name LUA_luaL_callmeta;
procedure EXT_luaL_checkany(L: PLuaState; narg: Integer); cdecl; external LUA_DLL name LUA_luaL_checkany;
function EXT_luaL_checkinteger(L: PLuaState; numArg: Integer): Integer; cdecl; external LUA_DLL name LUA_luaL_checkinteger;
function EXT_luaL_checklstring(L: PLuaState; numArg: Integer; ls: PCardinal): PAnsiChar; cdecl; external LUA_DLL name LUA_luaL_checklstring;
function EXT_luaL_checknumber(L: PLuaState; numArg: Integer): Double; cdecl; external LUA_DLL name LUA_luaL_checknumber;
function EXT_luaL_checkoption(L: PLuaState; narg: Integer; const def: PAnsiChar; const lst: array of PAnsiChar): Integer; cdecl; external LUA_DLL name LUA_luaL_checkoption;
procedure EXT_luaL_checkstack(L: PLuaState; sz: Integer; const msg: PAnsiChar); cdecl; external LUA_DLL name LUA_luaL_checkstack;
procedure EXT_luaL_checktype(L: PLuaState; narg, t: Integer); cdecl; external LUA_DLL name LUA_luaL_checktype;
function EXT_luaL_checkudata(L: PLuaState; ud: Integer; const tname: PAnsiChar): Pointer; cdecl; external LUA_DLL name LUA_luaL_checkudata;
function EXT_luaL_error(L: PLuaState; const fmt: PAnsiChar): Integer; varargs; cdecl; external LUA_DLL name LUA_luaL_error;
function EXT_luaL_findtable(L: PLuaState; idx: Integer; fname: PAnsiChar; szhint: Integer): PAnsiChar; cdecl; external LUA_DLL name LUA_luaL_findtable;
function EXT_luaL_getmetafield(L: PLuaState; obj: Integer; const e: PAnsiChar): Integer; cdecl; external LUA_DLL name LUA_luaL_getmetafield;
function EXT_luaL_gsub(L: PLuaState; const s, p, r: PAnsiChar): PAnsiChar; cdecl; external LUA_DLL name LUA_luaL_gsub;
function EXT_luaL_loadstring(L: PLuaState; const s: PAnsiChar): Integer; cdecl; external LUA_DLL name LUA_luaL_loadstring;
function EXT_luaL_newmetatable(L: PLuaState; const tname: PAnsiChar): Integer; cdecl; external LUA_DLL name LUA_luaL_newmetatable;
function EXT_luaL_newstate: PLuaState; cdecl; external LUA_DLL name LUA_luaL_newstate;
procedure EXT_luaL_openlib(L: PLuaState; libname: PAnsiChar; lr: PLuaLReg; nup: Integer); cdecl; external LUA_DLL name LUA_luaL_openlib;
procedure EXT_luaL_openlibs(L: PLuaState); cdecl; external LUA_DLL name LUA_luaL_openlibs;
function EXT_luaL_optinteger(L: PLuaState; nArg: Integer; def: Integer): Integer; cdecl; external LUA_DLL name LUA_luaL_optinteger;
function EXT_luaL_optlstring(L: PLuaState; numArg: Integer; const def: PAnsiChar; ls: PCardinal): PAnsiChar; cdecl; external LUA_DLL name LUA_luaL_optlstring;
function EXT_luaL_optnumber(L: PLuaState; nArg: Integer; def: Double): Double; cdecl; external LUA_DLL name LUA_luaL_optnumber;
procedure EXT_luaL_pushresult(B: PLuaLBuffer); cdecl; external LUA_DLL name LUA_luaL_pushresult;
function EXT_luaL_ref(L: PLuaState; t: Integer): Integer; cdecl; external LUA_DLL name LUA_luaL_ref;
procedure EXT_luaL_unref(L: PLuaState; t, ref: Integer); cdecl; external LUA_DLL name LUA_luaL_unref;
procedure EXT_luaL_where(L: PLuaState; lvl: Integer); cdecl; external LUA_DLL name LUA_luaL_where;
{$ENDREGION}
{$REGION 'Lua 5.1 Specific External Methods'}
procedure EXT_lua_call(L: PLuaState; nargs, nresults: Integer); cdecl; external LUA_DLL name LUA_lua_call;
function EXT_lua_cpcall(L: PLuaState; func: TLuaDelphiFunction; ud: Pointer): Integer; cdecl; external LUA_DLL name LUA_lua_cpcall;
function EXT_lua_equal(L: PLuaState; idx1, idx2: Integer): LongBool; cdecl; external LUA_DLL name LUA_lua_equal;
procedure EXT_lua_getfenv(L: PLuaState; idx: Integer); cdecl; external LUA_DLL name LUA_lua_getfenv;
function EXT_lua_lessthan(L: PLuaState; idx1, idx2: Integer): LongBool; cdecl; external LUA_DLL name LUA_lua_lessthan;
function EXT_lua_load(L: PLuaState; reader: TLuaReaderFunction; dt: Pointer; const chunkname: PAnsiChar): Integer; cdecl; external LUA_DLL name LUA_lua_load;
function ext_lua_objlen(L: PLuaState; idx: Integer): Cardinal; cdecl; external LUA_DLL name LUA_lua_objlen;
function EXT_lua_pcall(L: PLuaState; nargs, nresults, errfunc: Integer): Integer; cdecl; external LUA_DLL name LUA_lua_pcall;
function EXT_lua_resume(L: PLuaState; narg: Integer): Integer; cdecl; external LUA_DLL name LUA_lua_resume;
function EXT_lua_setfenv(L: PLuaState; idx: Integer): LongBool; cdecl; external LUA_DLL name LUA_lua_setfenv;
function EXT_lua_setmetatable(L: PLuaState; objindex: Integer): LongBool; cdecl; external LUA_DLL name LUA_lua_setmetatable;
function EXT_lua_tointeger(L: PLuaState; idx: Integer): TLuaInteger; cdecl; external LUA_DLL name LUA_lua_tointeger;
function EXT_lua_tonumber(L: PLuaState; idx: Integer): TLuaNumber; cdecl; external LUA_DLL name LUA_lua_tonumber;
function EXT_lua_yield(L: PLuaState; nresults: Integer): Integer; cdecl; external LUA_DLL name LUA_lua_yield;
{$ENDREGION}
{$REGION 'Lua 5.1 Auxiliary Specific External Methods'}
function EXT_luaL_loadbuffer(L: PLuaState; buff: PAnsiChar; sz: Cardinal; name: PAnsiChar): Integer; cdecl; external LUA_DLL name LUA_luaL_loadbuffer;
function EXT_luaL_loadfile(L: PLuaState; filename: PAnsiChar): Integer; cdecl; external LUA_DLL name LUA_luaL_loadfile;
function EXT_luaL_prepbuffer(B: TLuaLBuffer): PAnsiChar; cdecl; external LUA_DLL name LUA_luaL_prepbuffer;
procedure EXT_luaL_register(L: PLuaState; libname: PAnsiChar; lib: PluaLReg); cdecl; external LUA_DLL name LUA_luaL_register;
{$ENDREGION}
{$REGION 'TLua51Static - Lua 5.1 Static Link'}
{ TLua51Static }
procedure TLua51Static.luaL_addlstring(B: PLuaLBuffer; const s: PAnsiChar; ls: Cardinal);
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_luaL_addlstring, nil, '%p, "%s", %n', [B, s, ls]);{$ENDIF}
EXT_luaL_addlstring(B, s, ls);
end;
procedure TLua51Static.luaL_addstring(B: PLuaLBuffer; const s: PAnsiChar);
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_luaL_addstring, nil, '%p, "%s"', [B, s]);{$ENDIF}
EXT_luaL_addstring(B, s);
end;
procedure TLua51Static.luaL_addvalue(B: PLuaLBuffer);
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_luaL_addvalue, nil, '%p', [B]);{$ENDIF}
EXT_luaL_addvalue(B);
end;
function TLua51Static.luaL_argerror(L: PLuaState; numarg: Integer; const extramsg: PAnsiChar): Integer;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_luaL_argerror, L, ', %d, "%s"', [numarg, extramsg]);{$ENDIF}
Result := EXT_luaL_argerror(L, numarg, extramsg);
end;
procedure TLua51Static.luaL_buffinit(L: PLuaState; B: PLuaLBuffer);
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_luaL_buffinit, L, ', %p', [B]);{$ENDIF}
EXT_luaL_buffinit(L, B);
end;
function TLua51Static.luaL_callmeta(L: PLuaState; obj: Integer; const e: PAnsiChar): Integer;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_luaL_callmeta, L, ', %d, "%s"', [obj, e]);{$ENDIF}
Result := EXT_luaL_callmeta(L, obj, e);
end;
procedure TLua51Static.luaL_checkany(L: PLuaState; narg: Integer);
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_luaL_checkany, L, ', %d', [narg]);{$ENDIF}
EXT_luaL_checkany(L, narg);
end;
function TLua51Static.luaL_checkinteger(L: PLuaState; numArg: Integer): Integer;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_luaL_checkinteger, L, ', %d', [numArg]);{$ENDIF}
Result := EXT_luaL_checkinteger(L, numArg);
end;
function TLua51Static.luaL_checklstring(L: PLuaState; numArg: Integer; ls: PCardinal): PAnsiChar;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_luaL_checklstring, L, ', %d, %d', [numArg, ls]);{$ENDIF}
Result := EXT_luaL_checklstring(L, numArg, ls);
end;
function TLua51Static.luaL_checknumber(L: PLuaState; numArg: Integer): Double;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_luaL_checknumber, L, ', %d', [numArg]);{$ENDIF}
Result := EXT_luaL_checknumber(L, numArg);
end;
function TLua51Static.luaL_checkoption(L: PLuaState; narg: Integer; const def: PAnsiChar; const lst: array of PAnsiChar): Integer;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_luaL_checkoption, L, ', %d, "%s", %d', [narg, def, Length(lst)]);{$ENDIF}
Result := EXT_luaL_checkoption(L, narg, def, lst);
end;
procedure TLua51Static.luaL_checkstack(L: PLuaState; sz: Integer; const msg: PAnsiChar);
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_luaL_checkstack, L, ', %d, "%s"', [sz, msg]);{$ENDIF}
EXT_luaL_checkstack(L, sz, msg);
end;
procedure TLua51Static.luaL_checktype(L: PLuaState; narg, t: Integer);
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_luaL_checktype, L, ', %d, %d', [narg, t]);{$ENDIF}
EXT_luaL_checktype(L, narg, t);
end;
function TLua51Static.luaL_checkudata(L: PLuaState; ud: Integer; const tname: PAnsiChar): Pointer;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_luaL_checkudata, L, ', %d, "%s"', [ud, tname]);{$ENDIF}
Result := EXT_luaL_checkudata(L, ud, tname);
end;
function TLua51Static.luaL_error(L: PLuaState; const fmt: PAnsiChar): Integer;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_luaL_error, L, ', "%s"', [fmt]);{$ENDIF}
Result := EXT_luaL_error(L, fmt);
end;
function TLua51Static.luaL_getmetafield(L: PLuaState; obj: Integer; const e: PAnsiChar): Integer;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_luaL_getmetafield, L, ', %d, "%s"', [obj, e]);{$ENDIF}
Result := EXT_luaL_getmetafield(L, obj, e);
end;
function TLua51Static.luaL_gsub(L: PLuaState; const s, p, r: PAnsiChar): PAnsiChar;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_luaL_gsub, L, ', "%s", "%s", "%s"', [s, p, r]);{$ENDIF}
Result := EXT_luaL_gsub(L, s, p, r);
end;
function TLua51Static.luaL_loadbuffer(L: PLuaState; buff: PAnsiChar; sz: Cardinal; name: PAnsiChar): Integer;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_luaL_loadbuffer, L, ', "%s", %d, "%s"', [buff, sz, name]);{$ENDIF}
Result := EXT_luaL_loadbuffer(L, buff, sz, name);
end;
function TLua51Static.luaL_loadfile(L: PLuaState; filename: PAnsiChar): Integer;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_luaL_loadfile, L, ', "%s"', [filename]);{$ENDIF}
Result := EXT_luaL_loadfile(L, filename);
end;
function TLua51Static.luaL_loadstring(L: PLuaState; const s: PAnsiChar): Integer;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_luaL_loadstring, L, ', "%s"', [s]);{$ENDIF}
Result := EXT_luaL_loadstring(L, s);
end;
function TLua51Static.luaL_newmetatable(L: PLuaState; const tname: PAnsiChar): Integer;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_luaL_newmetatable, L, ', "%s"', [tname]);{$ENDIF}
Result := EXT_luaL_newmetatable(L, tname);
end;
function TLua51Static.luaL_newstate: PLuaState;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_luaL_newstate, nil, '', []);{$ENDIF}
Result := EXT_luaL_newstate;
end;
procedure TLua51Static.luaL_openlib(L: PLuaState; const libname: PAnsiChar; const lr: PLuaLReg; nup: Integer);
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_luaL_openlib, L, ', "%s", %p, %d', [libname, lr, nup]);{$ENDIF}
EXT_luaL_openlib(L, libname, lr, nup);
end;
procedure TLua51Static.luaL_openlibs(L: PLuaState);
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_luaL_openlibs, L, '', []);{$ENDIF}
EXT_luaL_openlibs(L);
end;
function TLua51Static.luaL_optinteger(L: PLuaState; nArg, def: Integer): Integer;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_luaL_optinteger, L, ', %d, %d', [nArg, def]);{$ENDIF}
Result := EXT_luaL_optinteger(L, nArg, def);
end;
function TLua51Static.luaL_optlstring(L: PLuaState; numArg: Integer; const def: PAnsiChar; ls: PCardinal): PAnsiChar;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_luaL_optlstring, L, ', %d, "%s", %p', [numArg, def, ls]);{$ENDIF}
Result := EXT_luaL_optlstring(L, numArg, def, ls);
end;
function TLua51Static.luaL_optnumber(L: PLuaState; nArg: Integer; def: Double): Double;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_luaL_optnumber, L, ', %d, %n', [nArg, def]);{$ENDIF}
Result := EXT_luaL_optnumber(L, nArg, def);
end;
function TLua51Static.luaL_prepbuffer(B: TLuaLBuffer): PAnsiChar;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_luaL_prepbuffer, nil, '%p', [@B]);{$ENDIF}
Result := EXT_luaL_prepbuffer(B);
end;
procedure TLua51Static.luaL_pushresult(B: PLuaLBuffer);
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_luaL_pushresult, nil, '%p', [B]);{$ENDIF}
EXT_luaL_pushresult(B);
end;
function TLua51Static.luaL_ref(L: PLuaState; t: Integer): Integer;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_luaL_ref, L, ', %d', [t]);{$ENDIF}
Result := EXT_luaL_ref(L, t);
end;
procedure TLua51Static.luaL_register(L: PLuaState; libname: PAnsiChar; lib: PluaLReg);
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_luaL_register, L, ', "%s", %p', [libname, lib]);{$ENDIF}
EXT_luaL_register(L, libname, lib);
end;
procedure TLua51Static.luaL_unref(L: PLuaState; t, ref: Integer);
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_luaL_unref, L, ', %d, %d', [t, ref]);{$ENDIF}
EXT_luaL_unref(L, t, ref);
end;
procedure TLua51Static.luaL_where(L: PLuaState; lvl: Integer);
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_luaL_where, L, ', %d', [lvl]);{$ENDIF}
EXT_luaL_where(L, lvl);
end;
function TLua51Static.luaopen_base(L: PLuaState): Integer;
begin
Result := LoadLuaLibrary(L, LUA_COLIBNAME, EXT_luaopen_base);
end;
function TLua51Static.luaopen_debug(L: PLuaState): Integer;
begin
Result := LoadLuaLibrary(L, LUA_DBLIBNAME, EXT_luaopen_debug);
end;
function TLua51Static.luaopen_io(L: PLuaState): Integer;
begin
Result := LoadLuaLibrary(L, LUA_IOLIBNAME, EXT_luaopen_io);
end;
function TLua51Static.luaopen_math(L: PLuaState): Integer;
begin
Result := LoadLuaLibrary(L, LUA_MATHLIBNAME, EXT_luaopen_math);
end;
function TLua51Static.luaopen_os(L: PLuaState): Integer;
begin
Result := LoadLuaLibrary(L, LUA_OSLIBNAME, EXT_luaopen_os);
end;
function TLua51Static.luaopen_package(L: PLuaState): Integer;
begin
Result := LoadLuaLibrary(L, LUA_LOADLIBNAME, EXT_luaopen_package);
end;
function TLua51Static.luaopen_string(L: PLuaState): Integer;
begin
Result := LoadLuaLibrary(L, LUA_STRLIBNAME, EXT_luaopen_string);
end;
function TLua51Static.luaopen_table(L: PLuaState): Integer;
begin
Result := LoadLuaLibrary(L, LUA_TABLIBNAME, EXT_luaopen_table);
end;
function TLua51Static.lua_atpanic(L: PLuaState; panicf: TLuaDelphiFunction): TLuaDelphiFunction;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_atpanic, L, ', %s', ['<TLuaDelphiFunction value>']);{$ENDIF}
Result := EXT_lua_atpanic(L, panicf);
end;
procedure TLua51Static.lua_call(L: PLuaState; nargs, nresults: Integer);
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_call, L, ', %d, %d', [nargs, nresults]);{$ENDIF}
EXT_lua_call(L, nargs, nresults);
end;
function TLua51Static.lua_checkstack(L: PLuaState; sz: Integer): LongBool;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_checkstack, L, ', %d', [sz]);{$ENDIF}
Result := EXT_lua_checkstack(L, sz);
end;
procedure TLua51Static.lua_close(L: PLuaState);
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_close, L, '', []);{$ENDIF}
EXT_lua_close(L);
end;
procedure TLua51Static.lua_concat(L: PLuaState; n: Integer);
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_concat, L, ', %d', [n]);{$ENDIF}
EXT_lua_concat(L, n);
end;
function TLua51Static.lua_cpcall(L: PLuaState; func: TLuaDelphiFunction; ud: Pointer): Integer;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_cpcall, L, ', %s, %p', ['<TLuaDelphiFunction value>', ud]);{$ENDIF}
Result := EXT_lua_cpcall(L, func, ud);
end;
procedure TLua51Static.lua_createtable(L: PLuaState; narr, nrec: Integer);
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_createtable, L, ', %d, %d', [narr, nrec]);{$ENDIF}
EXT_lua_createtable(L, narr, nrec);
end;
function TLua51Static.lua_dump(L: PLuaState; writer: TLuaWriterFunction; data: Pointer): Integer;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_dump, L, ', %s, %d', ['<TLuaWriterFunction value>', data]);{$ENDIF}
Result := EXT_lua_dump(L, writer, data);
end;
function TLua51Static.lua_equal(L: PLuaState; idx1, idx2: Integer): LongBool;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_equal, L, ', %d, %d', [idx1, idx2]);{$ENDIF}
Result := EXT_lua_equal(L, idx1, idx2);
end;
function TLua51Static.lua_error(L: PLuaState): Integer;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_error, L, '', []);{$ENDIF}
Result := EXT_lua_error(L);
end;
function TLua51Static.lua_gc(L: PLuaState; what, data: Integer): Integer;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_gc, L, ', %d, %d', [what, data]);{$ENDIF}
Result := EXT_lua_gc(L, what, data);
end;
function TLua51Static.lua_getallocf(L: PLuaState; ud: PPointer): TLuaAllocFunction;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_getallocf, L, ', %p', [ud]);{$ENDIF}
Result := EXT_lua_getallocf(L, ud);
end;
procedure TLua51Static.lua_getfenv(L: PLuaState; idx: Integer);
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_getfenv, L, ', %d', [idx]);{$ENDIF}
EXT_lua_getfenv(L, idx);
end;
procedure TLua51Static.lua_getfield(L: PLuaState; idx: Integer; k: PAnsiChar);
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_getfield, L, ', %d, "%s"', [idx, k]);{$ENDIF}
EXT_lua_getfield(L, idx, k);
end;
function TLua51Static.lua_gethook(L: PLuaState): TLuaHookFunction;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_gethook, L, '', []);{$ENDIF}
Result := EXT_lua_gethook(L);
end;
function TLua51Static.lua_gethookcount(L: PLuaState): Integer;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_gethookcount, L, '', []);{$ENDIF}
Result := EXT_lua_gethookcount(L);
end;
function TLua51Static.lua_gethookmask(L: PLuaState): Integer;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_gethookmask, L, '', []);{$ENDIF}
Result := EXT_lua_gethookmask(L);
end;
function TLua51Static.lua_getinfo(L: PLuaState; const what: PAnsiChar; ar: PLuaDebug): Integer;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_getinfo, L, ', "%s", %p', [what, ar]);{$ENDIF}
Result := EXT_lua_getinfo(L, what, ar);
end;
function TLua51Static.lua_getlocal(L: PLuaState; ar: PLuaDebug; n: Integer): PAnsiChar;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_getlocal, L, ', %p, %d', [ar, n]);{$ENDIF}
Result := EXT_lua_getlocal(L, ar, n);
end;
function TLua51Static.lua_getmetatable(L: PLuaState; objindex: Integer): LongBool;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_getmetatable, L, ', %d', [objindex]);{$ENDIF}
Result := EXT_lua_getmetatable(L, objindex);
end;
function TLua51Static.lua_getstack(L: PLuaState; level: Integer; ar: PLuaDebug): Integer;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_getstack, L, ', %d, %p', [level, ar]);{$ENDIF}
Result := EXT_lua_getstack(L, level, ar);
end;
procedure TLua51Static.lua_gettable(L: PLuaState; idx: Integer);
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_gettable, L, ', %d', [idx]);{$ENDIF}
EXT_lua_gettable(L, idx);
end;
function TLua51Static.lua_gettop(L: PLuaState): Integer;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_gettop, L, '', []);{$ENDIF}
Result := EXT_lua_gettop(L);
end;
function TLua51Static.lua_getupvalue(L: PLuaState; funcindex, n: Integer): PAnsiChar;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_getupvalue, L, ', %d, %d', [funcindex, n]);{$ENDIF}
Result := EXT_lua_getupvalue(L, funcindex, n);
end;
procedure TLua51Static.lua_insert(L: PLuaState; idx: Integer);
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_insert, L, ', %d', [idx]);{$ENDIF}
EXT_lua_insert(L, idx);
end;
function TLua51Static.lua_iscfunction(L: PLuaState; idx: Integer): LongBool;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_iscfunction, L, ', %d', [idx]);{$ENDIF}
Result := EXT_lua_iscfunction(L, idx);
end;
function TLua51Static.lua_isnumber(L: PLuaState; idx: Integer): LongBool;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_isnumber, L, ', %d', [idx]);{$ENDIF}
Result := EXT_lua_isnumber(L, idx);
end;
function TLua51Static.lua_isstring(L: PLuaState; idx: Integer): LongBool;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_isstring, L, ', %d', [idx]);{$ENDIF}
Result := EXT_lua_isstring(L, idx);
end;
function TLua51Static.lua_isuserdata(L: PLuaState; idx: Integer): LongBool;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_isuserdata, L, ', %d', [idx]);{$ENDIF}
Result := EXT_lua_isuserdata(L, idx);
end;
function TLua51Static.lua_lessthan(L: PLuaState; idx1, idx2: Integer): LongBool;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_lessthan, L, ', %d, %d', [idx1, idx2]);{$ENDIF}
Result := EXT_lua_lessthan(L, idx1, idx2);
end;
function TLua51Static.lua_load(L: PLuaState; reader: TLuaReaderFunction; dt: Pointer; const chunkname: PAnsiChar): Integer;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_load, L, ', %s, %p, "%s"', ['<TLuaReaderFunction value>', dt, chunkname]);{$ENDIF}
Result := EXT_lua_load(L, reader, dt, chunkname);
end;
function TLua51Static.lua_newstate(f: TLuaAllocFunction; ud: Pointer): PLuaState;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_newstate, nil, '%s, %p', ['<TLuaAllocFunction value>', ud]);{$ENDIF}
Result := EXT_lua_newstate(f, ud);
end;
function TLua51Static.lua_newthread(L: PLuaState): PLuaState;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_newthread, L, '', []);{$ENDIF}
Result := EXT_lua_newthread(L);
end;
function TLua51Static.lua_newuserdata(L: PLuaState; sz: Cardinal): Pointer;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_newuserdata, L, ', %d', [sz]);{$ENDIF}
Result := EXT_lua_newuserdata(L, sz);
end;
function TLua51Static.lua_next(L: PLuaState; idx: Integer): Integer;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_next, L, ', %d', [idx]);{$ENDIF}
Result := EXT_lua_next(L, idx);
end;
function TLua51Static.lua_objlen(L: PLuaState; idx: Integer): Cardinal;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_objlen, L, ', %d', [idx]);{$ENDIF}
Result := EXT_lua_objlen(L, idx);
end;
function TLua51Static.lua_pcall(L: PLuaState; nargs, nresults, errfunc: Integer): Integer;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_pcall, L, ', %d, %d, %d', [nargs, nresults, errfunc]);{$ENDIF}
Result := EXT_lua_pcall(L, nargs, nresults, errfunc);
end;
procedure TLua51Static.lua_pushboolean(L: PLuaState; b: LongBool);
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_pushboolean, L, ', "%s"', [L4DBoolStrings[b]]);{$ENDIF}
EXT_lua_pushboolean(L, b);
end;
procedure TLua51Static.lua_pushcclosure(L: PLuaState; fn: TLuaDelphiFunction; n: Integer);
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_pushcclosure, L, ', %s', ['<TLuaDelphiFunction value>']);{$ENDIF}
EXT_lua_pushcclosure(L, fn, n);
end;
function TLua51Static.lua_pushfstring(L: PLuaState; const fmt: PAnsiChar): PAnsiChar;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_pushfstring, L, ', "%s"', [fmt]);{$ENDIF}
Result := EXT_lua_pushfstring(L, fmt);
end;
procedure TLua51Static.lua_pushinteger(L: PLuaState; n: Integer);
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_pushinteger, L, ', %d', [n]);{$ENDIF}
EXT_lua_pushinteger(L, n);
end;
procedure TLua51Static.lua_pushlightuserdata(L: PLuaState; p: Pointer);
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_pushlightuserdata, L, ', %p', [p]);{$ENDIF}
EXT_lua_pushlightuserdata(L, p);
end;
function TLua51Static.lua_pushlstring(L: PLuaState; const s: PAnsiChar; ls: Cardinal): PAnsiChar;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_pushlstring, L, ', "%s", %d', [s, ls]);{$ENDIF}
EXT_lua_pushlstring(L, s, ls);
Result := s;
end;
procedure TLua51Static.lua_pushnil(L: PLuaState);
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_pushnil, L, '', []);{$ENDIF}
EXT_lua_pushnil(L);
end;
procedure TLua51Static.lua_pushnumber(L: PLuaState; n: Double);
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_pushnumber, L, ', %g', [n]);{$ENDIF}
EXT_lua_pushnumber(L, n);
end;
function TLua51Static.lua_pushstring(L: PLuaState; const s: PAnsiChar): PAnsiChar;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_pushstring, L, ', "%s"', [s]);{$ENDIF}
EXT_lua_pushstring(L, s);
Result := s;
end;
function TLua51Static.lua_pushthread(L: PLuaState): LongBool;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_pushthread, L, '', []);{$ENDIF}
Result := EXT_lua_pushthread(L);
end;
procedure TLua51Static.lua_pushvalue(L: PLuaState; idx: Integer);
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_pushvalue, L, ', %d', [idx]);{$ENDIF}
EXT_lua_pushvalue(L, idx);
end;
function TLua51Static.lua_pushvfstring(L: PLuaState; const fmt: PAnsiChar; argp: Pointer): PAnsiChar;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_pushvfstring, L, ', "%s", %p', [fmt, argp]);{$ENDIF}
Result := EXT_lua_pushvfstring(L, fmt, argp);
end;
function TLua51Static.lua_rawequal(L: PLuaState; idx1, idx2: Integer): LongBool;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_rawequal, L, ', %d, %d', [idx1, idx2]);{$ENDIF}
Result := EXT_lua_rawequal(L, idx1, idx2);
end;
procedure TLua51Static.lua_rawget(L: PLuaState; idx: Integer);
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_rawget, L, ', %d', [idx]);{$ENDIF}
EXT_lua_rawget(L, idx);
end;
procedure TLua51Static.lua_rawgeti(L: PLuaState; idx, n: Integer);
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_rawgeti, L, ', %d, %d', [idx, n]);{$ENDIF}
EXT_lua_rawgeti(L, idx, n);
end;
procedure TLua51Static.lua_rawset(L: PLuaState; idx: Integer);
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_rawset, L, ', %d', [idx]);{$ENDIF}
EXT_lua_rawset(L, idx);
end;
procedure TLua51Static.lua_rawseti(L: PLuaState; idx, n: Integer);
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_rawseti, L, ', %d, %d', [idx, n]);{$ENDIF}
EXT_lua_rawseti(L, idx, n);
end;
procedure TLua51Static.lua_remove(L: PLuaState; idx: Integer);
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_remove, L, ', %d', [idx]);{$ENDIF}
EXT_lua_remove(L, idx);
end;
procedure TLua51Static.lua_replace(L: PLuaState; idx: Integer);
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_replace, L, ', %d', [idx]);{$ENDIF}
EXT_lua_replace(L, idx);
end;
function TLua51Static.lua_resume(L: PLuaState; narg: Integer): Integer;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_resume, L, ', %d', [narg]);{$ENDIF}
Result := EXT_lua_resume(L, narg);
end;
procedure TLua51Static.lua_setallocf(L: PLuaState; f: TLuaAllocFunction; ud: Pointer);
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_setallocf, L, ', %s, %p', ['<TLuaAllocFunction value>', ud]);{$ENDIF}
EXT_lua_setallocf(L, f, ud);
end;
function TLua51Static.lua_setfenv(L: PLuaState; idx: Integer): LongBool;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_setfenv, L, ', %d', [idx]);{$ENDIF}
Result := EXT_lua_setfenv(L, idx);
end;
procedure TLua51Static.lua_setfield(L: PLuaState; idx: Integer; const k: PAnsiChar);
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_setfield, L, ', %d, "%s"', [idx, k]);{$ENDIF}
EXT_lua_setfield(L, idx, k);
end;
function TLua51Static.lua_sethook(L: PLuaState; func: TLuaHookFunction; mask, count: Integer): Integer;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_sethook, L, ', %s, %d, %d', ['<TLuaHookFunction value>', mask, count]);{$ENDIF}
Result := EXT_lua_sethook(L, func, mask, count);
end;
function TLua51Static.lua_setlocal(L: PLuaState; ar: PLuaDebug; n: Integer): PAnsiChar;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_setlocal, L, ', %p, %d', [ar, n]);{$ENDIF}
Result := EXT_lua_setlocal(L, ar, n);
end;
function TLua51Static.lua_setmetatable(L: PLuaState; objindex: Integer): LongBool;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_setmetatable, L, ', %d', [objindex]);{$ENDIF}
Result := EXT_lua_setmetatable(L, objindex);
end;
procedure TLua51Static.lua_settable(L: PLuaState; idx: Integer);
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_settable, L, ', %d', [idx]);{$ENDIF}
EXT_lua_settable(L, idx);
end;
procedure TLua51Static.lua_settop(L: PLuaState; idx: Integer);
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_settop, L, ', %d', [idx]);{$ENDIF}
EXT_lua_settop(L, idx);
end;
function TLua51Static.lua_setupvalue(L: PLuaState; funcindex, n: Integer): PAnsiChar;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_setupvalue, L, ', %d, %d', [funcindex, n]);{$ENDIF}
Result := EXT_lua_setupvalue(L, funcindex, n);
end;
function TLua51Static.lua_status(L: PLuaState): Integer;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_status, L, '', []);{$ENDIF}
Result := EXT_lua_status(L);
end;
function TLua51Static.lua_toboolean(L: PLuaState; idx: Integer): LongBool;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_toboolean, L, ', %d', [idx]);{$ENDIF}
Result := EXT_lua_toboolean(L, idx);
end;
function TLua51Static.lua_tocfunction(L: PLuaState; idx: Integer): TLuaDelphiFunction;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_tocfunction, L, ', %d', [idx]);{$ENDIF}
Result := EXT_lua_tocfunction(L, idx);
end;
function TLua51Static.lua_tointeger(L: PLuaState; idx: Integer): Integer;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_tointeger, L, ', %d', [idx]);{$ENDIF}
Result := EXT_lua_tointeger(L, idx);
end;
function TLua51Static.lua_tolstring(L: PLuaState; idx: Integer; len: PCardinal): PAnsiChar;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_tolstring, L, ', %d, %p', [idx, len]);{$ENDIF}
Result := EXT_lua_tolstring(L, idx, len);
end;
function TLua51Static.lua_tonumber(L: PLuaState; idx: Integer): Double;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_tonumber, L, ', %d', [idx]);{$ENDIF}
Result := EXT_lua_tonumber(L, idx);
end;
function TLua51Static.lua_topointer(L: PLuaState; idx: Integer): Pointer;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_topointer, L, ', %d', [idx]);{$ENDIF}
Result := EXT_lua_topointer(L, idx);
end;
function TLua51Static.lua_tothread(L: PLuaState; idx: Integer): PLuaState;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_tothread, L, ', %d', [idx]);{$ENDIF}
Result := EXT_lua_tothread(L, idx);
end;
function TLua51Static.lua_touserdata(L: PLuaState; idx: Integer): Pointer;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_touserdata, L, ', %d', [idx]);{$ENDIF}
Result := EXT_lua_touserdata(L, idx);
end;
function TLua51Static.lua_type(L: PLuaState; idx: Integer): Integer;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_type, L, ', %d', [idx]);{$ENDIF}
Result := EXT_lua_type(L, idx);
end;
function TLua51Static.lua_typename(L: PLuaState; tp: Integer): PAnsiChar;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_typename, L, ', %d', [tp]);{$ENDIF}
Result := EXT_lua_typename(L, tp);
end;
procedure TLua51Static.lua_xmove(src, dest: PLuaState; n: Integer);
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_xmove, src, ', $%p, %d', [dest, n]);{$ENDIF}
EXT_lua_xmove(src, dest, n);
end;
function TLua51Static.lua_yield(L: PLuaState; nresults: Integer): Integer;
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.AddAPICall(LUA_lua_yield, L, ', %d', [nresults]);{$ENDIF}
Result := EXT_lua_yield(L, nresults);
end;
procedure TLua51Static.SetLuaLibRefs;
begin
inherited;
FLibBase := EXT_luaopen_base;
FLibDebug := EXT_luaopen_debug;
FLibIO := EXT_luaopen_io;
FLibMath := EXT_luaopen_math;
FLibOS := EXT_luaopen_os;
FLibPackage := EXT_luaopen_package;
FLibString := EXT_luaopen_string;
FLibTable := EXT_luaopen_table;
end;
{$ENDREGION}
end.
|
program MyProgram;
uses MyUnit;
const
myConst = 'my''string';
myValueConst : real = 12.0;
//myArrayConst : array [1..100] of integer; //TODO
type
tMyEnum = (Jan, Feb, Mar);
tMyRange = 10..20;
tMyArray = array[tMyRange,1..10] of real;
tMyRecord = record
val1 : real;
val2, val3 : tMyEnum;
end;
tMyObject = object
val1 : integer;
function GetVal1 : integer;
procedure SetVal1(val1 : integer);
end;
tMyClass = class
private
val1 : string[100];
public
function GetVal1 : integer;
procedure SetVal1(val1 : integer);
published
property Value1 : integer read GetVal1 write SetVal1;
end;
var
instance : tMyClass;
function tMyClass.GetVal1 : integer;
begin
result := self.val1;
end;
procedure tMyClass.SetVal1(val1 : integer);
var
a : real;
begin
self.val1 := val1;
end;
begin
instance := tMyClass.Create;
instance.Value1 := 10;
tMyClass(instance).Value1 := 9;
tAny(tMyClass(instance).Value1).val := 9;
for index := tMinValue to 10 do
begin
if indexer < (8-instance.Value1) then
begin
with instance do
begin
Value1 := indexer;
end;
end;
end;
end |
{
AD.A.P.T. Library
Copyright (C) 2014-2018, Simon J Stuart, All Rights Reserved
Original Source Location: https://github.com/LaKraven/ADAPT
Subject to original License: https://github.com/LaKraven/ADAPT/blob/master/LICENSE.md
}
unit ADAPT.Threads.Intf;
{$I ADAPT.inc}
interface
uses
{$IFDEF ADAPT_USE_EXPLICIT_UNIT_NAMES}
System.Classes,
{$ELSE}
Classes,
{$ENDIF ADAPT_USE_EXPLICIT_UNIT_NAMES}
ADAPT, ADAPT.Intf;
{$I ADAPT_RTTI.inc}
type
{ Enums }
TADThreadState = (tsRunning, tsPaused);
/// <summary><c>Common Interface for ADAPT Thread Types.</c></summary>
IADThread = interface(IADInterface)
['{021D276B-6619-4489-ABD1-56787D0FBF2D}']
function GetLock: IADReadWriteLock;
property Lock: IADReadWriteLock read GetLock;
end;
/// <summary><c>Common Interface for ADAPT Precision Thread Types.</c></summary>
IADPrecisionThread = interface(IADThread)
['{3668FFD2-45E4-4EA7-948F-75A698C90480}']
/// <summary><c>Forces the "Next Tick Time" to be bumped to RIGHT NOW. This will trigger the next Tick immediately regardless of any Rate Limit setting.</c></summary>
procedure Bump;
/// <summary><c>Places the Thread in an Inactive state, waiting for the signal to </c><see DisplayName="Wake" cref="ADAPT.Threads|IADPrecisionThread.Wake"/><c> the Thread.</c></summary>
procedure Rest;
/// <summary><c>Wakes the Thread if it is an Inactive state (see </c><see DisplayName="Rest" cref="ADAPT.Threads|IADPrecisionThread.Rest"/><c> for details)</c></summary>
procedure Wake;
{ Property Getters }
function GetNextTickTime: ADFloat;
function GetThreadState: TADThreadState;
function GetTickRate: ADFloat;
function GetTickRateAverage: ADFloat;
function GetTickRateAverageOver: Cardinal;
function GetTickRateDesired: ADFloat;
function GetTickRateLimit: ADFloat;
function GetThrottleInterval: Cardinal;
{ Property Setters }
procedure SetThreadState(const AThreadState: TADThreadState);
procedure SetTickRateAverageOver(const AAverageOver: Cardinal);
procedure SetTickRateDesired(const ADesiredRate: ADFloat);
procedure SetTickRateLimit(const ATickRateLimit: ADFloat);
procedure SetThrottleInterval(const AThrottleInterval: Cardinal);
/// <summary><c>The Absolute Reference Time at which the next Tick will occur.</c></summary>
property NextTickTime: ADFloat read GetNextTickTime;
/// <summary><c>The current State of the Thread (running or paused).</c></summary>
property ThreadState: TADThreadState read GetThreadState write SetThreadState;
/// <summary><c>The Absolute Rate (in Ticks Per Second [T/s]) at which the Thread is executing its Tick method.</c></summary>
property TickRate: ADFloat read GetTickRate;
/// <summary><c>The Running Average Rate (in Ticks Per Second [T/s]) at which the Thread is executing its Tick method.</c></summary>
property TickRateAverage: ADFloat read GetTickRateAverage;
/// <summary><c>The Time (in Seconds) over which to calculate the Running Average.</c></summary>
property TickRateAverageOver: Cardinal read GetTickRateAverageOver write SetTickRateAverageOver;
/// <summary><c>The number of Ticks Per Second [T/s] you would LIKE the Thread to operate at.</c></summary>
/// <remarks><c>This value is used to calculate how much "Extra Time" (if any) is available on the current Tick.</c></remarks>
property TickRateDesired: ADFloat read GetTickRateDesired write SetTickRateDesired;
/// <summary><c>The Absolute Tick Rate (in Ticks Per Second [T/s]) at which you wish the Thread to operate.</c></summary>
/// <remarks><c>There is no guarantee that the rate you specify here will be achievable. Slow hardware or an overloaded running environment may mean the thread operates below the specified rate.</c></remarks>
property TickRateLimit: ADFloat read GetTickRateLimit write SetTickRateLimit;
/// <summary><c>The minimum amount of time that must be available between Ticks in order to Rest the Thread.</c></summary>
/// <remarks>
/// <para><c>Value is in </c>MILLISECONDS<c> (1 = 0.001 seconds)</c></para>
/// <para><c>Minimum value = </c>1</para>
/// </remarks>
property ThrottleInterval: Cardinal read GetThrottleInterval write SetThrottleInterval;
end;
implementation
end.
|
unit NETAtoms;
{
This Unit contains all the _NET atoms from the freedesktop 1.4 spec
}
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, X, XLib;
type
TNETAtom = (
//WM_ Atoms
// _NET Atoms
//Root Window Properties
_SUPPORTED, // array of cardinal (_NET atoms that are supported)
_CLIENT_LIST, // array of TWindow
_CLIENT_LIST_STACKING, // array of TWindow (bottom to top)
_NUMBER_OF_DESKTOPS, // cardinal
_DESKTOP_GEOMETRY, // array [0..1] of cardinal (width height)
_DESKTOP_VIEWPORT, // array of cardinal array [0..1] viewports (top left position)
_CURRENT_DESKTOP, // cardinal (index of desktop)
_DESKTOP_NAMES, // array of null terminated UTF8 Strings
_ACTIVE_WINDOW, // TWindow
_WORKAREA, // array [0..3] of cardinal (x, y, width, height)
_SUPPORTING_WM_CHECK, // TWindow
_VIRTUAL_ROOTS, // array of TWindow
_DESKTOP_LAYOUT, // array [0..3] of cardinal (orientation, columns, rows, starting_corner)
_SHOWING_DESKTOP, // cardinal (1 = Showing Desktop 0 = not Showing Desktop) boolean
//Root Window Messages
_CLOSE_WINDOW,
_MOVERESIZE_WINDOW,
_WM_MOVERESIZE,
_RESTACK_WINDOW,
_REQUEST_FRAME_EXTENTS,
//Application Window Properties
_WM_NAME, // UTF8 String
_WM_VISIBLE_NAME, //UTF8 String
_WM_ICON_NAME, // UTF8 String
_WM_VISIBLE_ICON_NAME, // UTF8 String
_WM_DESKTOP, // cardinal (index of the desktop of the window) $FFFFFFFF for all desktops
_WM_WINDOW_TYPE, // TAtom of the different types below
_WM_WINDOW_TYPE_DESKTOP,
_WM_WINDOW_TYPE_DOCK,
_WM_WINDOW_TYPE_TOOLBAR,
_WM_WINDOW_TYPE_MENU,
_WM_WINDOW_TYPE_UTILITY,
_WM_WINDOW_TYPE_SPLASH,
_WM_WINDOW_TYPE_DIALOG,
_WM_WINDOW_TYPE_NORMAL,
_WM_STATE, // array of TAtoms. Possible members are listed below. others should be ignored
_WM_STATE_MODAL,
_WM_STATE_STICKY,
_WM_STATE_MAXIMIZED_VERT,
_WM_STATE_MAXIMIZED_HORZ,
_WM_STATE_SHADED,
_WM_STATE_SKIP_TASKBAR,
_WM_STATE_SKIP_PAGER,
_WM_STATE_HIDDEN,
_WM_STATE_FULLSCREEN,
_WM_STATE_ABOVE,
_WM_STATE_BELOW,
_WM_STATE_DEMANDS_ATTENTION,
_WM_ALLOWED_ACTIONS, //array of TAtoms below. unknown atoms are ignored
_WM_ACTION_MOVE,
_WM_ACTION_RESIZE,
_WM_ACTION_MINIMIZE,
_WM_ACTION_SHADE,
_WM_ACTION_STICK,
_WM_ACTION_MAXIMIZE_HORZ,
_WM_ACTION_MAXIMIZE_VERT,
_WM_ACTION_FULLSCREEN,
_WM_ACTION_CHANGE_DESKTOP,
_WM_ACTION_CLOSE,
_WM_STRUT, // array [0..3] of cardinal (left right top bottom)
_WM_STRUT_PARTIAL, // array [0..11] of cardinal (left, right, top, bottom,
// left_start_y, left_end_y, right_start_y, right_end_y,
// top_start_x, top_end_x, bottom_start_x, bottom_end_x )
_WM_ICON_GEOMETRY, // array [0..3] of cardinal (x, y, width, height)
_WM_ICON, // array of cardinal the first two in the array are the width height
// and the rest of the array is the icon data in BGRA order
_WM_PID, // cardinal (process id of the window)
_WM_HANDLED_ICONS,
_WM_USER_TIME, // cardinal (XServer time of last user activity)
_FRAME_EXTENTS, // array [0..3] of cardinal (left, right, top ,bottom)
//Window Manager Protocols
_WM_PING,
_WM_SYNC_REQUEST
);
const
_NET_WM_ORIENTATION_HORZ = 0;
_NET_WM_ORIENTATION_VERT = 1;
_NET_WM_TOPLEFT = 0;
_NET_WM_TOPRIGHT = 1;
_NET_WM_BOTTOMRIGHT = 2;
_NET_WM_BOTTOMLEFT = 3;
_NET_WM_MOVERESIZE_SIZE_TOPLEFT = 0;
_NET_WM_MOVERESIZE_SIZE_TOP = 1;
_NET_WM_MOVERESIZE_SIZE_TOPRIGHT = 2;
_NET_WM_MOVERESIZE_SIZE_RIGHT = 3;
_NET_WM_MOVERESIZE_SIZE_BOTTOMRIGHT = 4;
_NET_WM_MOVERESIZE_SIZE_BOTTOM = 5;
_NET_WM_MOVERESIZE_SIZE_BOTTOMLEFT = 6;
_NET_WM_MOVERESIZE_SIZE_LEFT = 7;
_NET_WM_MOVERESIZE_MOVE = 8; // movement only
_NET_WM_MOVERESIZE_SIZE_KEYBOARD = 9; // size via keyboard
_NET_WM_MOVERESIZE_MOVE_KEYBOARD = 10; // move via keyboard
_NET_WM_MOVERESIZE_CANCEL = 11; // cancel operation
_NET_WM_STATE_REMOVE = 0; // remove/unset property
_NET_WM_STATE_ADD = 1; // add/set property
_NET_WM_STATE_TOGGLE = 2; // toggle property
type
TNetMoveResizeSource = Integer; // see the _NET_WM_MOVERESIZE_* consts above
TNetAtoms = array [TNETAtom] of X.TAtom;
procedure Init_NETAtoms(const ADisplay: PXDisplay; out AAtoms: TNetAtoms);
function _NETAtomToString(Atom: TNetAtom): String;
implementation
procedure Init_NETAtoms(const ADisplay: PXDisplay; out AAtoms: TNetAtoms);
var
NetAtom: TNetAtom;
AtomStr: String;
begin
for NetAtom := Low(TNetAtom) to High(TNetAtom) do begin
AtomStr := _NETAtomToString(NetAtom);
AAtoms[NetAtom] := XInternAtom(ADisplay, PChar(AtomStr), False);
end;
end;
function _NETAtomToString(Atom: TNetAtom): String;
begin
Result := '';
case Atom of
_SUPPORTED : Result := '_NET_SUPPORTED';
_CLIENT_LIST : Result := '_NET_CLIENT_LIST';
_CLIENT_LIST_STACKING : Result := '_NET_CLIENT_LIST_STACKING';
_NUMBER_OF_DESKTOPS : Result := '_NET_NUMBER_OF_DESKTOPS';
_DESKTOP_GEOMETRY : Result := '_NET_DESKTOP_GEOMETRY';
_DESKTOP_VIEWPORT : Result := '_NET_DESKTOP_VIEWPORT';
_CURRENT_DESKTOP : Result := '_NET_CURRENT_DESKTOP';
_DESKTOP_NAMES : Result := '_NET_DESKTOP_NAMES';
_ACTIVE_WINDOW : Result := '_NET_ACTIVE_WINDOW';
_WORKAREA : Result := '_NET_WORKAREA';
_SUPPORTING_WM_CHECK : Result := '_NET_SUPPORTING_WM_CHECK';
_VIRTUAL_ROOTS : Result := '_NET_VIRTUAL_ROOTS';
_DESKTOP_LAYOUT : Result := '_NET_DESKTOP_LAYOUT';
_SHOWING_DESKTOP : Result := '_NET_SHOWING_DESKTOP';
_CLOSE_WINDOW : Result := '_NET_CLOSE_WINDOW';
_MOVERESIZE_WINDOW : Result := '_NET_MOVERESIZE_WINDOW';
_WM_MOVERESIZE : Result := '_NET_WM_MOVERESIZE';
_RESTACK_WINDOW : Result := '_NET_RESTACK_WINDOW';
_REQUEST_FRAME_EXTENTS : Result := '_NET_REQUEST_FRAME_EXTENTS';
_WM_NAME : Result := '_NET_WM_NAME';
_WM_VISIBLE_NAME : Result := '_NET_WM_VISIBLE_NAME';
_WM_ICON_NAME : Result := '_NET_WM_ICON_NAME';
_WM_VISIBLE_ICON_NAME : Result := '_NET_WM_VISIBLE_ICON_NAME';
_WM_DESKTOP : Result := '_NET_WM_DESKTOP';
_WM_WINDOW_TYPE : Result := '_NET_WM_WINDOW_TYPE';
_WM_WINDOW_TYPE_DESKTOP: Result := '_NET_WM_WINDOW_TYPE_DESKTOP';
_WM_WINDOW_TYPE_DOCK : Result := '_NET_WM_WINDOW_TYPE_DOCK';
_WM_WINDOW_TYPE_TOOLBAR: Result := '_NET_WM_WINDOW_TYPE_TOOLBAR';
_WM_WINDOW_TYPE_MENU : Result := '_NET_WM_WINDOW_TYPE_MENU';
_WM_WINDOW_TYPE_UTILITY: Result := '_NET_WM_WINDOW_TYPE_UTILITY';
_WM_WINDOW_TYPE_SPLASH : Result := '_NET_WM_WINDOW_TYPE_SPLASH';
_WM_WINDOW_TYPE_DIALOG : Result := '_NET_WM_WINDOW_TYPE_DIALOG';
_WM_WINDOW_TYPE_NORMAL : Result := '_NET_WM_WINDOW_TYPE_NORMAL';
_WM_STATE : Result := '_NET_WM_STATE';
_WM_STATE_MODAL : Result := '_NET_WM_STATE_MODAL';
_WM_STATE_STICKY : Result := '_NET_WM_STATE_STICKY';
_WM_STATE_MAXIMIZED_VERT:Result := '_NET_WM_STATE_MAXIMIZED_VERT';
_WM_STATE_MAXIMIZED_HORZ:Result := '_NET_WM_STATE_MAXIMIZED_HORZ';
_WM_STATE_SHADED : Result := '_NET_WM_STATE_SHADED';
_WM_STATE_SKIP_TASKBAR : Result := '_NET_WM_STATE_SKIP_TASKBAR';
_WM_STATE_SKIP_PAGER : Result := '_NET_WM_STATE_SKIP_PAGER';
_WM_STATE_HIDDEN : Result := '_NET_WM_STATE_HIDDEN';
_WM_STATE_FULLSCREEN : Result := '_NET_WM_STATE_FULLSCREEN';
_WM_STATE_ABOVE : Result := '_NET_WM_STATE_ABOVE';
_WM_STATE_BELOW : Result := '_NET_WM_STATE_BELOW';
_WM_STATE_DEMANDS_ATTENTION: Result := '_NET_WM_STATE_DEMANDS_ATTENTION';
_WM_ALLOWED_ACTIONS : Result := '_NET_WM_ALLOWED_ACTIONS';
_WM_ACTION_MOVE : Result := '_NET_WM_ACTION_MOVE';
_WM_ACTION_RESIZE : Result := '_NET_WM_ACTION_RESIZE';
_WM_ACTION_MINIMIZE : Result := '_NET_WM_ACTION_MINIMIZE';
_WM_ACTION_SHADE : Result := '_NET_WM_ACTION_SHADE';
_WM_ACTION_STICK : Result := '_NET_WM_ACTION_STICK';
_WM_ACTION_MAXIMIZE_HORZ:Result := '_NET_WM_ACTION_MAXIMIZE_HORZ';
_WM_ACTION_MAXIMIZE_VERT:Result := '_NET_WM_ACTION_MAXIMIZE_VERT';
_WM_ACTION_FULLSCREEN : Result := '_NET_WM_ACTION_FULLSCREEN';
_WM_ACTION_CHANGE_DESKTOP:Result:= '_NET_WM_ACTION_CHANGE_DESKTOP';
_WM_ACTION_CLOSE : Result := '_NET_WM_ACTION_CLOSE';
_WM_STRUT : Result := '_NET_WM_STRUT';
_WM_STRUT_PARTIAL : Result := '_NET_WM_STRUT_PARTIAL';
_WM_ICON_GEOMETRY : Result := '_NET_WM_ICON_GEOMETRY';
_WM_ICON : Result := '_NET_WM_ICON';
_WM_PID : Result := '_NET_WM_PID';
_WM_HANDLED_ICONS : Result := '_NET_WM_HANDLED_ICONS';
_WM_USER_TIME : Result := '_NET_WM_USER_TIME';
_FRAME_EXTENTS : Result := '_NET_FRAME_EXTENTS';
_WM_PING : Result := '_NET_WM_PING';
_WM_SYNC_REQUEST : Result := '_NET_WM_SYNC_REQUEST';
end;
end;
end.
|
unit uViewConfiguracoes;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls, Grids, Buttons,
MVCInterfaces, uEmpresa, USped, UI010;
// A View somente conhece o Modelo para exibir os atributos dele mas não pode alterar ou interagir com o Modelo
type
TListaEvent = procedure of object; // Aqui é uma grande sacada pois a variável abaixo
// FDOLista recebe um procedimento do Controle sem na verdade
// conhecer o controle
// para ententer melhor veja a inicialização ( TControle.Initialize)
// do controle
TViewConfiguracoes = class(TForm)
pEmpresa: TPanel;
cbEmpresa: TComboBox;
bPesquisar: TButton;
pRodape: TPanel;
pCentral: TPanel;
Label1: TLabel;
PBlocoI010: TPanel;
Label2: TLabel;
sbIncluiI010: TSpeedButton;
sbExclui010: TSpeedButton;
sgI010: TStringGrid;
PBlocoI100: TPanel;
sgI100: TStringGrid;
Label3: TLabel;
sbIncluirI100: TSpeedButton;
sbExcluirI100: TSpeedButton;
lSpedID: TLabel;
PBI200: TPanel;
Label4: TLabel;
sbIncluirI200: TSpeedButton;
sbExcluiI200: TSpeedButton;
sgI200: TStringGrid;
procedure bPesquisarClick(Sender: TObject);
procedure sbIncluiI010Click(Sender: TObject);
procedure sgI010SelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
procedure sgI010Click(Sender: TObject);
procedure sbIncluirI100Click(Sender: TObject);
procedure sgI100Click(Sender: TObject);
procedure sgI100SelectCell(Sender: TObject; ACol, ARow: Integer;
var CanSelect: Boolean);
procedure sbIncluirI200Click(Sender: TObject);
private
FModelo : TEmpresa;
FModeloI010 : TI010;
FDoLista : TListaEvent;
FIncluiI010 : TListaEvent;
FDoListaI100 : TListaEvent;
FIncluiI100 : TListaEvent;
FDoListaI200 : TListaEvent;
procedure SetModel(const Value: TEmpresa);
procedure SetDoLista(const Value: TListaEvent);
procedure SetIncluiI010(const Value: TListaEvent);
procedure SetDoListaI100(const Value: TListaEvent);
procedure SetModeloI010(const Value: TI010);
procedure SetIncluiI100(const Value: TListaEvent);
procedure SetDoListaI200(const Value: TListaEvent);
public
fLinhaSg010 : Integer;
fLinhasgI100 : Integer;
IncluiI200 : TListaEvent;
procedure Initialize;
procedure ModeloMudou;
property Modelo : TEmpresa read FModelo write SetModel;
property ModeloI010 : TI010 read fModeloI010 write SetModeloI010;
property DoLista : TListaEvent read FDoLista write SetDoLista;
property IncluiI010 : TListaEvent read FIncluiI010 write SetIncluiI010;
property DoListaI100 : TListaEvent read FDoListaI100 write SetDoListaI100;
property DOListaI200 : TListaEvent read FDoListaI200 write SetDoListaI200;
property IncluiI100 : TListaEvent read FIncluiI100 write SetIncluiI100;
end;
//var // Programador bom comenta estas linha, como eu comentei logo...
// ViewConfiguracoes: TViewConfiguracoes;
implementation
{$R *.dfm}
{ TViewConfiguracoes }
procedure TViewConfiguracoes.Initialize;
begin
end;
procedure TViewConfiguracoes.ModeloMudou;
begin
end;
procedure TViewConfiguracoes.SetDoLista(const Value: TListaEvent);
begin
FDoLista := Value;
end;
procedure TViewConfiguracoes.SetModel(const Value: TEmpresa);
begin
FModelo := Value;
end;
procedure TViewConfiguracoes.bPesquisarClick(Sender: TObject);
begin
DoLista;
end;
procedure TViewConfiguracoes.sbIncluiI010Click(Sender: TObject);
begin
IncluiI010;
end;
procedure TViewConfiguracoes.SetIncluiI010(const Value: TListaEvent);
begin
FIncluiI010 := Value;
end;
procedure TViewConfiguracoes.SetDoListaI100(const Value: TListaEvent);
begin
FDoListaI100 := Value;
end;
procedure TViewConfiguracoes.sgI010SelectCell(Sender: TObject; ACol,
ARow: Integer; var CanSelect: Boolean);
begin
fLinhaSg010 := ARow;
end;
procedure TViewConfiguracoes.SetModeloI010(const Value: TI010);
begin
fModeloI010 := Value;
end;
procedure TViewConfiguracoes.sgI010Click(Sender: TObject);
begin
DoListaI100;
end;
procedure TViewConfiguracoes.sbIncluirI100Click(Sender: TObject);
begin
IncluiI100;
end;
procedure TViewConfiguracoes.SetIncluiI100(const Value: TListaEvent);
begin
FIncluiI100 := Value;
end;
procedure TViewConfiguracoes.sgI100Click(Sender: TObject);
begin
DoListaI200;
end;
procedure TViewConfiguracoes.sgI100SelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
begin
fLinhasgI100 := Arow;
end;
procedure TViewConfiguracoes.SetDoListaI200(const Value: TListaEvent);
begin
FDoListaI200 := Value;
end;
procedure TViewConfiguracoes.sbIncluirI200Click(Sender: TObject);
begin
IncluiI200;
end;
end.
|
unit uSpeechesArray;
interface
uses uSpeechesClass, ADODB, DB, SysUtils, Classes, Dialogs;
type TSpeechesArray = class
private
conn : TADOConnection;
dbName : String;
public
constructor Create(db : String);
function getAllSpeeches : TStringList;
function getAllSpeechesByMeeting(meetingID : integer) : TStringList;
function deleteSpeech(speechID : integer) : TStringList;
function addSpeech(speech : TSpeeches) : integer;
procedure updateSpeech(speech : TSpeeches);
function getSpeechByMeetingAndSlot(meetingID, slot : integer;
speechType : String) : TSpeeches;
function getSpeakerHistory(memID : integer) : TStringList;
procedure closeDB;
end;
implementation
{ TSpeechesArray }
{A procedure for adding a new speech to the database. A speeches object is
provided by the user. The functions of the speech object are used to extract
the data stored in its attributes. This data is used to construct an SQL
statement that deletes any existing speech with the same type, meeting, and
slot key that already exists in the database. This prevents erronoeous data
and conflicting elements. Another SQL statement is then constructed, using the
functions of the speech object, to add a the new speech to the speeches table
in the database. The latestID is determined and once the query has completed
the connection to the database is closed.}
function TSpeechesArray.addSpeech(speech: TSpeeches) : integer;
var
sqlQ : string;
query :TADOQuery;
begin
{Execute a delete for that type, meeting, slot}
sqlQ := 'DELETE * FROM tblSpeeches WHERE type = ''' +
speech.getType + ''' AND MeetingID = ' +
IntToStr(speech.getMeetingID) + ' AND Slot = ' +
IntToStr(speech.getSlot);
// InputBox(sqlQ, sqlQ, sqlQ);
query := TADOQuery.Create(NIL);
query.Connection := conn;
query.Sql.Add(sqlQ);
query.ExecSQL;
query.Close;
sqlQ := 'INSERT INTO tblSpeeches (MemberID, Type, Best, ' +
'MeetingID, ConjugateSpeechID, Slot) VALUES (';
sqlQ := sqlQ + IntToStr(speech.getMemberID) + ',';
sqlQ := sqlQ + '''' +speech.getType;
sqlQ := sqlQ + ''', ''' +BoolToStr(speech.getBest);
sqlQ := sqlQ + ''', ''' +IntToStr(speech.getMeetingID);
sqlQ := sqlQ + ''', '''+IntToStr(speech.getConjugateSpeech)+''', '+
IntToStr(speech.getSlot)+')';
// InputBox(sqlQ, sqlQ, sqlQ);
query := TADOQuery.Create(NIL);
query.Connection := conn;
query.Sql.Add(sqlQ);
query.ExecSQL;
query.Close;
query := TADOQuery.Create(NIL);
query.Connection := conn;
sqlq := 'SELECT @@Identity AS LatestID';
query.Sql.Add(sqlQ);
query.Active := true;
if NOT query.EOF then
begin
Result := query.FieldValues['LatestID'];
end;
query.Active := false;
query.Close;
end;
{Code with the specific purpose of closing the database connection to prevent
errors, overflows, slow response, etc.}
procedure TSpeechesArray.closeDB;
begin
conn.Close;
end;
{The constructor for the speeches array class. Specifies how it connects to the
database and takes in the name of a database to which it then connects.}
constructor TSpeechesArray.Create(db: String);
begin
conn := TADOConnection.Create(NIL);
conn.ConnectionString := 'Provider=MSDASQL.1;' +
'Persist Security Info=False;Extended Properties="DBQ=' + db + ';' +
'Driver={Driver do Microsoft Access (*.mdb)};DriverId=25;FIL=MS Access;' +
'FILEDSN=C:\Program Files\Common Files\ODBC\Data Sources\Test.dsn;' +
'MaxBufferSize=2048;MaxScanRows=8;PageTimeout=5;SafeTransactions=0;' +
'Threads=3;UID=admin;UserCommitSync=Yes;"';
end;
{A function to query the speeches table of the database
and delete a selected speech. A speechID is provided by the user (or system)
and is used to specifically select a speech in the database. The SQL statement
executes a query to delete all fields relating to this speech. The database
conection is then closed.}
function TSpeechesArray.deleteSpeech(speechID: integer): TStringList;
var
sqlQ : String;
query :TADOQuery;
begin
sqlQ := 'DELETE * FROM tblSpeeches WHERE SpeechID = ' + IntToStr(speechID);
// InputBox(sqlQ, sqlQ, sqlQ);
query := TADOQuery.Create(NIL);
query.Connection := conn;
query.Sql.Add(sqlQ);
query.ExecSQL;
query.Close;
end;
{A function to query the speeches table of the database and return all fields.
This function simply returns all the data about all the speeches found in the
database as a stringlist. This is done through a hardcoded SQL statement. A
stringlist is created and the results of the SQL are fed in as the toString
expressions from speech objects which are generated in the following script.
The database connection is then closed.}
function TSpeechesArray.getAllSpeeches: TStringList;
var
sqlQ : String;
query : TADOQuery;
s : TSpeeches;
sl : TStringList;
begin
sqlQ := 'SELECT tblMembers.Surname AS MemberSurname, + ' +
'tblMembers.Name AS MemberName, tblSpeeches.* FROM tblSpeeches, ' +
'tblMembers WHERE tblSpeeches.MemberID = tblMembers.MemberID';
query := TADOQuery.Create(NIL);
query.Connection := conn;
query.Sql.Add(sqlQ);
query.Active := true;
sl := TStringList.Create;
while NOT query.EOF do
begin
s := TSpeeches.Create(query.FieldValues['SpeechID'],
query.FieldValues['MemberID'],
query.FieldValues['MemberName']+' '+
query.FieldValues['MemberSurname'],
query.FieldValues['Type'],
query.FieldValues['Best'],
query.FieldValues['MeetingID'],
query.FieldValues['ConjugateSpeechID'],
query.FieldValues['Slot']);
sl.AddObject(s.toString, s);
query.Next;
end;
query.Active := false;
query.Close;
Result := sl;
end;
{A function to query the speeches table of the database and return all fields
from all speeches that ocurred at a specific meeting, based on an inputted
meetinID.
This function simply returns all the data about all the speeches found in the
database as a stringlist. This is done through a hardcoded SQL statement. A
stringlist is created and the results of the SQL are fed in as the toString
expressions from speech objects which are generated in the following script.
The database connection is then closed.}
function TSpeechesArray.getAllSpeechesByMeeting(
meetingID: integer): TStringList;
var
sqlQ : String;
query : TADOQuery;
s : TSpeeches;
sl : TStringList;
begin
sqlQ := 'SELECT tblMembers.Surname AS MemberSurname, ' +
'tblMembers.Name AS MemberName, tblSpeeches.* FROM tblSpeeches, ' +
'tblMembers WHERE tblSpeeches.MemberID = tblMembers.MemberID ' +
'AND MeetingID = ' + IntToStr(meetingID);
query := TADOQuery.Create(NIL);
query.Connection := conn;
query.Sql.Add(sqlQ);
query.Active := true;
sl := TStringList.Create;
while NOT query.EOF do
begin
s := TSpeeches.Create(query.FieldValues['SpeechID'],
query.FieldValues['MemberID'],
query.FieldValues['MemberName']+' '+
query.FieldValues['MemberSurname'],
query.FieldValues['Type'],
query.FieldValues['Best'],
query.FieldValues['MeetingID'],
query.FieldValues['ConjugateSpeechID'],
query.FieldValues['Slot']);
sl.AddObject(s.toString, s);
query.Next;
end;
query.Active := false;
query.Close;
Result := sl;
end;
{A function which, when given a memberID, creates an SQL statement which
executes a query to return all the data from all the speeches in the
database which have that memberID - i.e. all the speeches by the specific
member. The speeches are formed into speeches objects and the toShortString
function's output for each of them is added to a stringlist. The database
connection is then closed.}
function TSpeechesArray.getSpeakerHistory(memID: integer): TStringList;
var
sqlQ : String;
query : TADOQuery;
s : TSpeeches;
sl : TStringList;
begin
sqlQ := 'SELECT * FROM tblSpeeches WHERE MemberID = ' + IntToStr(memID);
query := TADOQuery.Create(NIL);
query.Connection := conn;
query.Sql.Add(sqlQ);
query.Active := true;
sl := TStringList.Create;
while NOT query.EOF do
begin
s := TSpeeches.Create(query.FieldValues['SpeechID'],
query.FieldValues['MemberID'],
'',
query.FieldValues['Type'],
query.FieldValues['Best'],
query.FieldValues['MeetingID'],
query.FieldValues['ConjugateSpeechID'],
query.FieldValues['Slot']);
sl.AddObject(s.toShortString, s);
query.Next;
end;
query.Active := false;
query.Close;
Result := sl;
end;
{A function to query the speeches table of the database and return a speech
object based on a speech with a specific type that ocurred at a specific
meeting, in a specific slot, based on an inputted meetinID, slot,
and speechtype.
This function simply returns all the data about the speech found in the
database as a speeches object. This is done through an SQL statement.
The resulting data of the SQL is fed into a newly created Speeches object.
The database connection is then closed.}
function TSpeechesArray.getSpeechByMeetingAndSlot(meetingID,
slot: integer; speechType : String): TSpeeches;
var
sqlQ : String;
query : TADOQuery;
s : TSpeeches;
sl : TStringList;
begin
sqlQ := 'SELECT tblMembers.Surname AS MemberSurname, ' +
'tblMembers.Name AS MemberName, tblSpeeches.* FROM tblSpeeches, ' +
'tblMembers WHERE tblSpeeches.MemberID = tblMembers.MemberID ' +
'AND MeetingID = ' + IntToStr(meetingID) + ' AND Slot = ' +
IntToStr(slot) + ' AND Type = ''' + speechType + '''';
query := TADOQuery.Create(NIL);
query.Connection := conn;
query.Sql.Add(sqlQ);
query.Active := true;
sl := TStringList.Create;
s := nil;
if NOT query.EOF then
begin
s := TSpeeches.Create(query.FieldValues['SpeechID'],
query.FieldValues['MemberID'],
query.FieldValues['MemberName']+' '+
query.FieldValues['MemberSurname'],
query.FieldValues['Type'],
query.FieldValues['Best'],
query.FieldValues['MeetingID'],
query.FieldValues['ConjugateSpeechID'],
query.FieldValues['Slot']);
end;
query.Active := false;
query.Close;
Result := s;
end;
{A function to query the speeches table of the database and
update a selected speech. A speech object is provided to the procedure. The
data from the object is accessed through its various functions and used
to construct an SQL statement to update the details of a specific speech in
the database. Once the query has been executed the connection
to the database is closed.}
procedure TSpeechesArray.updateSpeech(speech: TSpeeches);
var
sqlQ : string;
query :TADOQuery;
begin
sqlQ := 'UPDATE tblSpeeches SET '
+'MemberID = '+IntToStr(speech.getMemberID)
+', Type = '+''''+speech.getType+''''
+', Best = '+BoolToStr(speech.getBest)
+', MeetingID = '+IntToStr(speech.getMeetingID)
+', ConjugateSpeechID = '+IntToStr(speech.getConjugateSpeech)
+' WHERE SpeechID = '+IntToStr(speech.getID);
// InputBox(sqlQ, sqlQ, sqlQ);
query := TADOQuery.Create(NIL);
query.Connection := conn;
query.Sql.Add(sqlQ);
query.ExecSQL;
query.Close;
end;
end.
|
{
Ultibo Configure RTL Tool.
Copyright (C) 2022 - SoftOz Pty Ltd.
Arch
====
<All>
Boards
======
<All>
Licence
=======
LGPLv2.1 with static linking exception (See COPYING.modifiedLGPL.txt)
Credits
=======
Information for this unit was obtained from:
References
==========
Configure RTL
=============
The Configure RTL tool is used by the Ultibo core installer to update the configuration
files used by FPC to determine unit locations etc and the environment options file for
Lazarus.
The tool only runs once at the end of the install and is not required again, the
files updated are:
FP.CFG
FPC.CFG
RPI.CFG
RPI2.CFG
RPI3.CFG
RPI4.CFG
QEMUVPB.CFG
environmentoptions.xml
lazarus.cfg
BuildRTL.ini
QEMULauncher.ini
}
program ConfigureRTL;
{$MODE Delphi}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Interfaces,
SysUtils,
FileCtrl,
Main in 'Main.pas';
{$R *.res}
var
InstallPath:String;
CompilerPath:String;
CompilerVersion:String;
LazarusVersion:String;
LazarusVersionNo:String;
ConfigurationPath:String;
LazarusProfilePath:String;
begin
{Install will pass 4 parameters:
1. The APP directory where the files were installed
2. The FPC version which is defined in the script
3. The Lazarus version which is defined in the script
4. The Lazarus version no which is defined in the script}
{Check Parameters}
if ParamCount >=4 then
begin
{Get Install Path}
InstallPath:=StripTrailingSlash(ParamStr(1));
{Check Install Path}
if DirectoryExists(InstallPath) then
begin
{Get FPC Version}
CompilerVersion:=ParamStr(2);
{Get Lazarus Version}
LazarusVersion:=ParamStr(3);
{Get Lazarus Version No}
LazarusVersionNo:=ParamStr(4);
{Get Compiler Path}
{$IFDEF WINDOWS}
CompilerPath:=InstallPath + '\fpc\' + CompilerVersion;
{$ENDIF}
{$IFDEF LINUX}
CompilerPath:=InstallPath + '/fpc';
{$ENDIF}
{Get Configuration Path}
{$IFDEF WINDOWS}
ConfigurationPath:=InstallPath + '\fpc\' + CompilerVersion + '\bin\i386-win32';
{$ENDIF}
{$IFDEF LINUX}
ConfigurationPath:=InstallPath + '/fpc/bin';
{$ENDIF}
{Get Lazarus Profile (Optional)}
LazarusProfilePath:=ParamStr(5);
{Check Configuration Path}
if DirectoryExists(ConfigurationPath) then
begin
{$IFDEF WINDOWS}
{Edit FP.CFG}
EditConfiguration('FP.CFG',AddTrailingSlash(ConfigurationPath),'%INSTALLDIRECTORY%',CompilerPath);
{Edit FPC.CFG}
EditConfiguration('FPC.CFG',AddTrailingSlash(ConfigurationPath),'%INSTALLDIRECTORY%',CompilerPath);
{Edit RPI.CFG}
EditConfiguration('RPI.CFG',AddTrailingSlash(ConfigurationPath),'%INSTALLDIRECTORY%',CompilerPath);
{Edit RPI2.CFG}
EditConfiguration('RPI2.CFG',AddTrailingSlash(ConfigurationPath),'%INSTALLDIRECTORY%',CompilerPath);
{Edit RPI3.CFG}
EditConfiguration('RPI3.CFG',AddTrailingSlash(ConfigurationPath),'%INSTALLDIRECTORY%',CompilerPath);
{Edit RPI4.CFG}
EditConfiguration('RPI4.CFG',AddTrailingSlash(ConfigurationPath),'%INSTALLDIRECTORY%',CompilerPath);
{Edit QEMUVPB.CFG}
EditConfiguration('QEMUVPB.CFG',AddTrailingSlash(ConfigurationPath),'%INSTALLDIRECTORY%',CompilerPath);
{Create environmentoptions.xml}
CreateOptions('environmentoptions.xml',AddTrailingSlash(InstallPath),AddTrailingSlash(CompilerPath),LazarusVersion,LazarusVersionNo);
{Create lazarus.cfg}
CreateConfig('lazarus.cfg',AddTrailingSlash(InstallPath),LazarusProfilePath);
{Create BuildRTL.ini}
CreateBuildRTL('tools\BuildRTL.ini',AddTrailingSlash(InstallPath),CompilerVersion);
{Create QEMULauncher.ini}
CreateQEMULauncher('tools\QEMULauncher.ini',AddTrailingSlash(InstallPath));
{$ENDIF}
{$IFDEF LINUX}
{Don't Edit FP.CFG or FPC.CFG}
{Edit RPI.CFG}
EditConfiguration('RPI.CFG',AddTrailingSlash(ConfigurationPath),'%INSTALLDIRECTORY%',CompilerPath);
{Edit RPI2.CFG}
EditConfiguration('RPI2.CFG',AddTrailingSlash(ConfigurationPath),'%INSTALLDIRECTORY%',CompilerPath);
{Edit RPI3.CFG}
EditConfiguration('RPI3.CFG',AddTrailingSlash(ConfigurationPath),'%INSTALLDIRECTORY%',CompilerPath);
{Edit RPI4.CFG}
EditConfiguration('RPI4.CFG',AddTrailingSlash(ConfigurationPath),'%INSTALLDIRECTORY%',CompilerPath);
{Edit QEMUVPB.CFG}
EditConfiguration('QEMUVPB.CFG',AddTrailingSlash(ConfigurationPath),'%INSTALLDIRECTORY%',CompilerPath);
{Create environmentoptions.xml}
CreateOptions('environmentoptions.xml',AddTrailingSlash(InstallPath),AddTrailingSlash(CompilerPath),LazarusVersion,LazarusVersionNo);
{Create lazarus.cfg}
CreateConfig('lazarus.cfg',AddTrailingSlash(InstallPath),LazarusProfilePath);
{Create BuildRTL.ini}
CreateBuildRTL('tools/BuildRTL.ini',AddTrailingSlash(InstallPath),CompilerVersion);
{Create QEMULauncher.ini}
CreateQEMULauncher('tools/QEMULauncher.ini',AddTrailingSlash(InstallPath));
{$ENDIF}
end;
end;
end;
end.
|
unit Un_Registro_Servico;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, DB, ExtCtrls, DBCtrls, Grids, DBGrids, StdCtrls, Buttons, StdConvs;
type
T_Registro_Servico = class(TForm)
dsServ: TDataSource;
gbOS: TGroupBox;
dbgOS: TDBGrid;
DBNavigator1: TDBNavigator;
gbCliente: TGroupBox;
lblCliente: TLabel;
cbClientes: TComboBox;
edtEndereco: TLabeledEdit;
edtBairro: TLabeledEdit;
edtCidade: TLabeledEdit;
edtCEP: TLabeledEdit;
edtFone1: TLabeledEdit;
edtFone2: TLabeledEdit;
edtFax: TLabeledEdit;
edtCelular: TLabeledEdit;
edtEmail: TLabeledEdit;
gbEquipamento: TGroupBox;
lblEquipamento: TLabel;
cbEquipamento: TComboBox;
edtDefeito: TLabeledEdit;
edtSerie: TLabeledEdit;
edtComplemento: TLabeledEdit;
lblArea: TLabel;
cbArea: TComboBox;
gbServico: TGroupBox;
lblSituacao: TLabel;
cbSituacao: TComboBox;
lblTecnicos: TLabel;
cbTecnico: TComboBox;
lblExecutante: TLabel;
cbExecutante: TComboBox;
Label1: TLabel;
edtObs: TMemo;
edtDataEntrada: TLabeledEdit;
edtDataSaida: TLabeledEdit;
chkPago: TCheckBox;
edtOrcamento: TLabeledEdit;
edtDataPrevisto: TLabeledEdit;
edtPago: TLabeledEdit;
sbNovaOS: TSpeedButton;
sbSair: TSpeedButton;
sbClientes: TSpeedButton;
pnlOS: TPanel;
sbExcluirOs: TSpeedButton;
sbAlterarOS: TSpeedButton;
btnSalvar: TBitBtn;
btnCancelar: TBitBtn;
lblNOs: TLabel;
edtServico: TLabeledEdit;
edtOs: TLabeledEdit;
lblRetorno: TLabel;
lblRetornoTexto: TLabel;
TempoRetorno: TTimer;
sbImprimir: TSpeedButton;
procedure lblClienteClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure dsServDataChange(Sender: TObject; Field: TField);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure dbgOSKeyPress(Sender: TObject; var Key: Char);
procedure lblEquipamentoClick(Sender: TObject);
procedure lblAreaClick(Sender: TObject);
procedure lblSituacaoClick(Sender: TObject);
procedure lblTecnicosClick(Sender: TObject);
procedure sbNovaOSClick(Sender: TObject);
procedure sbSairClick(Sender: TObject);
procedure sbExcluirOsClick(Sender: TObject);
procedure sbAlterarOSClick(Sender: TObject);
procedure btnCancelarClick(Sender: TObject);
procedure btnSalvarClick(Sender: TObject);
procedure cbClientesExit(Sender: TObject);
procedure edtEmailExit(Sender: TObject);
procedure edtCEPExit(Sender: TObject);
procedure edtFone1Exit(Sender: TObject);
procedure edtCelularExit(Sender: TObject);
procedure lblClienteMouseLeave(Sender: TObject);
procedure lblClienteMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure cbExecutanteExit(Sender: TObject);
procedure edtDataEntradaExit(Sender: TObject);
procedure edtOrcamentoExit(Sender: TObject);
procedure edtDataSaidaExit(Sender: TObject);
procedure edtDataPrevistoExit(Sender: TObject);
procedure chkPagoExit(Sender: TObject);
procedure TempoRetornoTimer(Sender: TObject);
procedure sbImprimirClick(Sender: TObject);
procedure dbgOSDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
private { Private declarations }
cFlg, cBusca, cNova : String;
cNovoCliente : String;
cRetorno : String;
nOs : Integer;
Procedure Controle( x : Boolean );
Procedure LimpaDados;
Procedure DadosCliente;
Procedure Apoio( x : Boolean );
Procedure RetornoOS( cNumero : String );
public { Public declarations }
end;
var
_Registro_Servico: T_Registro_Servico;
implementation
uses
Un_dm, Un_UDF, Un_Clientes, Un_Funcionarios, Un_Main, Un_Areas, Un_Equipamentos, Un_Situacoes, Un_Imprimir_OS;
{$R *.dfm}
procedure T_Registro_Servico.lblClienteMouseLeave(Sender: TObject);
begin
(Sender as TLabel).Font.Color := clWindowText;
(Sender as TLabel).Font.Size := 8;
end;
procedure T_Registro_Servico.lblClienteMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
var
I : Integer;
begin
(Sender as TLabel).Font.Color := clHotLight;
(Sender as TLabel).Font.Size := 10;
for I := 0 to _Registro_Servico.ControlCount -1 do
begin
if (_Registro_Servico.Controls[I] is TLabel) then
begin
if (_Registro_Servico.Controls[I].Name <> (Sender as TLabel).Name) then
begin
(_Registro_Servico.Controls[I] as TLabel).Font.Color := clWindowText;
(_Registro_Servico.Controls[I] as TLabel).Font.Size := 8;
end;
end;
end;
end;
procedure T_Registro_Servico.Controle( x: Boolean );
begin //
sbNovaOS.Enabled := x;
sbAlterarOS.Enabled := x;
sbExcluirOs.Enabled := x;
sbSair.Enabled := x;
gbCliente.Enabled := Not x;
gbEquipamento.Enabled := Not x;
gbServico.Enabled := Not x;
btnSalvar.Visible := Not x;
btnCancelar.Visible := Not x;
end;
procedure T_Registro_Servico.FormCreate(Sender: TObject);
begin
cFlg := '';
cBusca := '';
nOs := 0;
edtDefeito.Hint := 'Dados do defeito informado pelo cliente'#13'e/ou dados opicionais do equipamento.';
end;
procedure T_Registro_Servico.FormShow(Sender: TObject);
begin
Application.ProcessMessages;
lblRetorno.Visible := False;
lblRetorno.Caption := '';
lblRetornoTexto.Visible := False;
_Main.stlClientes.Clear; // Clientes
_dm.qr11.Close;
_dm.qr11.SQL.Text := 'select * from CLIENTES order by NomeCliente';
_dm.qr11.Open;
cbClientes.Text := '';
cbClientes.Clear;
While Not _dm.qr11.Eof Do
Begin
cbClientes.Items.Add( _dm.qr11.FieldByName( 'NomeCliente' ).AsString );
_Main.stlClientes.Add( _dm.qr11.FieldByName( 'CodCliente' ).AsString );
_dm.qr11.Next;
End;
_Main.stlEquip.Clear; // Equipamentos
_dm.qr11.Close;
_dm.qr11.SQL.Text := 'select * from [Tipo de equipamento] order by Descricao';
_dm.qr11.Open;
cbEquipamento.Text := '';
cbEquipamento.Clear;
While Not _dm.qr11.Eof Do
Begin
cbEquipamento.Items.Add( _dm.qr11.FieldByName( 'Descricao' ).AsString );
_Main.stlEquip.Add( _dm.qr11.FieldByName( 'CodEquipamento' ).AsString );
_dm.qr11.Next;
End;
_Main.stlArea.Clear; // Áreas
_dm.qr11.Close;
_dm.qr11.SQL.Text := 'select * from Area order by Descricao';
_dm.qr11.Open;
cbArea.Text := '';
cbArea.Clear;
While Not _dm.qr11.Eof Do
Begin
cbArea.Items.Add( _dm.qr11.FieldByName( 'Descricao' ).AsString );
_Main.stlArea.Add( _dm.qr11.FieldByName( 'CodArea' ).AsString );
_dm.qr11.Next;
End;
_Main.stlSit.Clear; // Situações
_dm.qr11.Close;
_dm.qr11.SQL.Text := 'select * from Situacao order by Descricao';
_dm.qr11.Open;
cbSituacao.Text := '';
cbSituacao.Clear;
While Not _dm.qr11.Eof Do
Begin
cbSituacao.Items.Add( _dm.qr11.FieldByName( 'Descricao' ).AsString );
_Main.stlSit.Add( _dm.qr11.FieldByName( 'CodSituacao' ).AsString );
_dm.qr11.Next;
End;
_Main.stlFunc.Clear; // Técnicos e Executantes
_dm.qr11.Close;
_dm.qr11.SQL.Text := 'select * from Funcionarios Where Funcão = 1 order by Apelido';
_dm.qr11.Open;
cbTecnico.Text := '';
cbTecnico.Clear;
cbExecutante.Text := '';
cbExecutante.Clear;
While Not _dm.qr11.Eof Do
Begin
cbTecnico.Items.Add( _dm.qr11.FieldByName( 'Apelido' ).AsString );
cbExecutante.Items.Add( _dm.qr11.FieldByName( 'Apelido' ).AsString );
_Main.stlFunc.Add( _dm.qr11.FieldByName( 'CodTecnicos' ).AsString );
_dm.qr11.Next;
End;
Controle( True );
_dm.qr06.Close;
_dm.qr06.SQL.Text := 'select * from Servicos order by OS';
_dm.qr06.Open;
_dm.qr06.Last;
// nOs := _dm.qr06.FieldByName( 'OS' ).AsInteger;
// pnlOS.Caption := FormatFloat( '###,##0', nOs );
_dm.qr06.First;
Application.ProcessMessages;
dbgOS.SetFocus;
end;
procedure T_Registro_Servico.lblClienteClick(Sender: TObject);
Var
cPorta : String;
begin // Clientes
_Clientes := T_Clientes.Create( Self );
Try
_Clientes.cPorta := 'A';
_Clientes.ShowModal;
Finally
cPorta := _Clientes.cPorta;
_Clientes.Release;
_Clientes := Nil;
End;
If cPorta = '' Then
Begin
_Main.stlClientes.Clear;
_dm.qr11.Close;
_dm.qr11.SQL.Text := 'select * from CLIENTES order by NomeCliente';
_dm.qr11.Open;
cbClientes.Text := '';
cbClientes.Clear;
While Not _dm.qr11.Eof Do
Begin
cbClientes.Items.Add( _dm.qr11.FieldByName( 'NomeCliente' ).AsString );
_Main.stlClientes.Add( _dm.qr11.FieldByName( 'CodCliente' ).AsString );
_dm.qr11.Next;
End;
End;
end;
procedure T_Registro_Servico.lblEquipamentoClick(Sender: TObject);
Var
cPorta : String;
begin // Equipamentos
_Equipamentos := T_Equipamentos.Create( Self );
Try
_Equipamentos.cPorta := 'A';
_Equipamentos.ShowModal;
Finally
cPorta := _Equipamentos.cPorta;
_Equipamentos.Release;
_Equipamentos := Nil;
End;
If cPorta = '' Then
Begin
_Main.stlEquip.Clear;
_dm.qr11.Close;
_dm.qr11.SQL.Text := 'select * from [Tipo de equipamento] order by Descricao';
_dm.qr11.Open;
cbEquipamento.Text := '';
cbEquipamento.Clear;
While Not _dm.qr11.Eof Do
Begin
cbEquipamento.Items.Add( _dm.qr11.FieldByName( 'Descricao' ).AsString );
_Main.stlEquip.Add( _dm.qr11.FieldByName( 'CodEquipamento' ).AsString );
_dm.qr11.Next;
End;
End;
end;
procedure T_Registro_Servico.lblAreaClick(Sender: TObject);
Var
cPorta : String;
begin // Áreas
_Areas := T_Areas.Create( Self );
Try
_Areas.cPorta := 'A';
_Areas.ShowModal;
Finally
cPorta := _Areas.cPorta;
_Areas.Release;
_Areas := Nil;
End;
If cPorta = '' Then
Begin
_Main.stlArea.Clear;
_dm.qr11.Close;
_dm.qr11.SQL.Text := 'select * from Area order by Descricao';
_dm.qr11.Open;
cbArea.Text := '';
cbArea.Clear;
While Not _dm.qr11.Eof Do
Begin
cbArea.Items.Add( _dm.qr11.FieldByName( 'Descricao' ).AsString );
_Main.stlArea.Add( _dm.qr11.FieldByName( 'CodArea' ).AsString );
_dm.qr11.Next;
End;
End;
end;
procedure T_Registro_Servico.lblSituacaoClick(Sender: TObject);
Var
cPorta : String;
begin // Situações
_Situacoes := T_Situacoes.Create( Self );
Try
_Situacoes.cPorta := 'A';
_Situacoes.ShowModal;
Finally
cPorta := _Situacoes.cPorta;
_Situacoes.Release;
_Situacoes := Nil;
End;
If cPorta = '' Then
Begin
_Main.stlSit.Clear;
_dm.qr11.Close;
_dm.qr11.SQL.Text := 'select * from Situacao order by Descricao';
_dm.qr11.Open;
cbSituacao.Text := '';
cbSituacao.Clear;
While Not _dm.qr11.Eof Do
Begin
cbSituacao.Items.Add( _dm.qr11.FieldByName( 'Descricao' ).AsString );
_Main.stlSit.Add( _dm.qr11.FieldByName( 'CodSituacao' ).AsString );
_dm.qr11.Next;
End;
End;
end;
procedure T_Registro_Servico.lblTecnicosClick(Sender: TObject);
Var
cPorta : String;
begin // Técnicos e Executantes
_Funcionarios := T_Funcionarios.Create( Self );
Try
_Funcionarios.cPorta := 'A';
_Funcionarios.ShowModal;
Finally
_Funcionarios.Release;
_Funcionarios := Nil;
End;
If cPorta = '' Then
Begin
_Main.stlFunc.Clear;
_dm.qr11.Close;
_dm.qr11.SQL.Text := 'select * from Funcionarios Where Funcão = 1 order by Apelido';
_dm.qr11.Open;
If (Sender as TLabel).Caption = 'Técnico' Then
Begin
cbTecnico.Text := '';
cbTecnico.Clear;
End;
If (Sender as TLabel).Caption = 'Executante' Then
Begin
cbExecutante.Text := '';
cbExecutante.Clear;
End;
While Not _dm.qr11.Eof Do
Begin
If (Sender as TLabel).Caption = 'Técnico' Then cbTecnico.Items.Add( _dm.qr11.FieldByName( 'Apelido' ).AsString );
If (Sender as TLabel).Caption = 'Executante' Then cbExecutante.Items.Add( _dm.qr11.FieldByName( 'Apelido' ).AsString );
_Main.stlSit.Add( _dm.qr11.FieldByName( 'CodTecnicos' ).AsString );
_dm.qr11.Next;
End;
End;
end;
procedure T_Registro_Servico.dbgOSDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin // nOs :=
// nOs := _dm.qr06.FieldByName( 'OS' ).AsInteger;
// pnlOS.Caption := FormatFloat( '###,##0', nOs );
end;
procedure T_Registro_Servico.dbgOSKeyPress(Sender: TObject; var Key: Char);
begin
If ( Key <> #13 ) and ( Key <> #27 ) Then
Begin
If ( Key = #37 ) or ( Key = #38 ) or ( Key = #39 ) or ( Key = #40 ) Then
Begin
cBusca := '';
End;
If Key <> #8 Then
Begin
cBusca := cBusca + Key;
End
Else
Begin
cBusca := Copy( cBusca, 1, Length( cBusca ) - 1 );
End;
_dm.qr06.Locate( 'OS', cBusca, [loPartialKey, loCaseInsensitive] );
// nOs := _dm.qr06.FieldByName( 'OS' ).AsInteger;
End;
end;
procedure T_Registro_Servico.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
Case Key Of
VK_ESCAPE :
Begin
If ( cFlg = 'N' ) or ( cFlg = 'A' ) Then
Begin
lblRetorno.Visible := False;
lblRetornoTexto.Visible := False;
TempoRetorno.Enabled := False;
Controle( True );
Apoio( True );
cFlg := '';
_dm.qr06.Close;
_dm.qr06.Open;
dbgOS.SetFocus;
End
Else
Close;
End;
VK_RETURN :
Begin
Perform( WM_NEXTDLGCTL, 0, 0 );
Key := 0;
End;
End;
If ( Key = VK_END ) or ( Key = VK_HOME ) or
( Key = VK_LEFT ) or ( Key = VK_UP ) or ( Key = VK_RIGHT ) or ( Key = VK_DOWN ) Then
Begin
cBusca := '';
End;
end;
procedure T_Registro_Servico.sbSairClick(Sender: TObject);
begin
Close;
end;
procedure T_Registro_Servico.sbExcluirOsClick(Sender: TObject);
begin
If MessageDlg( 'Confirma Exclusão da O.S. ?', mtConfirmation, [ mbYes, mbNo ], 0 ) = mrYes Then
Begin
_dm.qr12.Close;
_dm.qr12.SQL.Text := 'delete from Servicos where OS = ' + _dm.qr06.FieldByName( 'OS' ).AsString + '';
_dm.qr12.ExecSQL;
_dm.qr06.Close;
_dm.qr06.Open;
_dm.qr06.Last;
//nOs := _dm.qr06.FieldByName( 'OS' ).AsInteger;
//pnlOS.Caption := FormatFloat( '###,##0', nOs );
cBusca := '';
Application.ProcessMessages;
_dm.qr06.Close;
_dm.qr06.Open;
End;
end;
procedure T_Registro_Servico.dsServDataChange(Sender: TObject; Field: TField);
begin // Mostra de Serviços.
lblNOs.Caption := 'O.S. atual:'#13'' + _dm.qr06.FieldByName( 'OS' ).AsString;
nOs := _dm.qr06.FieldByName( 'OS' ).AsInteger;
pnlOS.Caption := FormatFloat( '###,##0', nOs );
DadosCliente;
edtOs.Text := _dm.qr06.FieldByName( 'OS' ).AsString;
If _dm.qr06.FieldByName( 'Equipamento' ).AsString <> '' Then
Begin
cbEquipamento.Color := clWindow;
cbEquipamento.ItemIndex := _Main.stlEquip.IndexOf( _dm.qr06.FieldByName( 'Equipamento' ).AsString );
End
Else
Begin
cbEquipamento.Color := clRed;
cbEquipamento.ItemIndex := -1;
End;
edtComplemento.Text := _dm.qr06.FieldByName( 'Complemento' ).AsString;
edtDefeito.Text := _dm.qr06.FieldByName( 'Defeito' ).AsString;
edtSerie.Text := _dm.qr06.FieldByName( 'NSerie' ).AsString;
If _dm.qr06.FieldByName( 'Area' ).AsString <> '' Then
Begin
cbArea.Color := clWindow;
cbArea.ItemIndex := _Main.stlArea.IndexOf( _dm.qr06.FieldByName( 'Area' ).AsString );
End
Else
Begin
cbArea.Color := clRed;
cbArea.ItemIndex := -1;
End;
edtDataEntrada.Text := _dm.qr06.FieldByName( 'DataEntrada' ).AsString;
edtOrcamento.Text := _dm.qr06.FieldByName( 'ValorOrcamento' ).AsString;
edtDataSaida.Text := _dm.qr06.FieldByName( 'DataSaida' ).AsString;
chkPago.Checked := _dm.qr06.FieldByName( 'Pago' ).AsBoolean;
edtDataPrevisto.Text := _dm.qr06.FieldByName( 'PrevisaoPagamento' ).AsString;
edtPago.Text := FormatFloat( '##,##0.00', _dm.qr06.FieldByName( 'Valor' ).AsFloat );
// **
If _dm.qr06.FieldByName( 'Situacao' ).AsString <> '' Then
Begin
cbSituacao.Color := clWindow;
cbSituacao.ItemIndex := _Main.stlSit.IndexOf( _dm.qr06.FieldByName( 'Situacao' ).AsString );
End
Else
Begin
cbSituacao.Color := clRed;
cbSituacao.ItemIndex := -1;
End;
If ( _dm.qr06.FieldByName( 'Tecnico' ).AsString <> '' ) and ( _dm.qr06.FieldByName( 'Tecnico' ).AsString <> '0' ) Then
Begin
cbTecnico.Color := clWindow;
cbTecnico.ItemIndex := _Main.stlFunc.IndexOf( _dm.qr06.FieldByName( 'Tecnico' ).AsString );
End
Else
Begin
cbTecnico.Color := clRed;
cbTecnico.ItemIndex := -1;
End;
If ( _dm.qr06.FieldByName( 'Executante' ).AsString <> '' ) and ( _dm.qr06.FieldByName( 'Executante' ).AsString <> '0' )Then
Begin
cbExecutante.Color := clWindow;
cbExecutante.ItemIndex := _Main.stlFunc.IndexOf( _dm.qr06.FieldByName( 'Executante' ).AsString );
End
Else
Begin
cbExecutante.Color := clRed;
cbExecutante.ItemIndex := -1;
End;
edtServico.Text := ControlaCampoTexto( _dm.qr06.FieldByName( 'ServicoExecutado' ).AsString );
edtObs.Text := _dm.qr06.FieldByName( 'Obs' ).AsString;
end;
procedure T_Registro_Servico.DadosCliente;
begin
cbClientes.Color := clWindow;
cbClientes.ItemIndex := _Main.stlClientes.IndexOf( _dm.qr06.FieldByName( 'CodCliente' ).AsString );
_dm.qr11.Close;
_dm.qr11.SQL.Text := 'select * from Clientes';
_dm.qr11.Open;
If _dm.qr06.FieldByName( 'CodCliente' ).AsString <> '' Then
Begin
If _dm.qr11.Locate( 'CodCliente', _dm.qr06.FieldByName( 'CodCliente' ).AsString, [] ) Then
Begin
edtEndereco.Color := clWindow;
edtEndereco.Text := ControlaCampoTexto( _dm.qr11.FieldByName( 'Endereco' ).AsString );
edtBairro.Text := ControlaCampoTexto( _dm.qr11.FieldByName( 'Bairro' ).AsString );
edtCidade.Text := ControlaCampoTexto( _dm.qr11.FieldByName( 'Cidade' ).AsString );
edtCEP.Text := ControlaCampoTexto( _dm.qr11.FieldByName( 'CEP' ).AsString );
edtFone1.Text := ControlaCampoTexto( _dm.qr11.FieldByName( 'Fone1' ).AsString );
edtFone2.Text := ControlaCampoTexto( _dm.qr11.FieldByName( 'Fone2' ).AsString );
edtFax.Text := ControlaCampoTexto( _dm.qr11.FieldByName( 'Fax' ).AsString );
edtCelular.Text := ControlaCampoTexto( _dm.qr11.FieldByName( 'Celular' ).AsString );
edtEmail.Text := ControlaCampoTexto( _dm.qr11.FieldByName( 'e-mail' ).AsString );
End
Else
Begin
edtEndereco.Color := clAqua;
edtEndereco.Text := 'Dados incorretos no Cadastro';
edtBairro.Text := '';
edtCidade.Text := '';
edtCEP.Text := '';
edtFone1.Text := '';
edtFone2.Text := '';
edtFax.Text := '';
edtCelular.Text := '';
edtEmail.Text := '';
End;
End
Else
Begin
cbClientes.Color := clLime;
cbClientes.Text := 'Cliente não informado. Dados incorretos no Cadastro';
edtEndereco.Color := clLime;
edtEndereco.Text := 'Cliente não informado. Dados incorretos no Cadastro';
edtBairro.Text := '';
edtCidade.Text := '';
edtCEP.Text := '';
edtFone1.Text := '';
edtFone2.Text := '';
edtFax.Text := '';
edtCelular.Text := '';
edtEmail.Text := '';
End;
end;
procedure T_Registro_Servico.sbNovaOSClick(Sender: TObject);
Var
lCtrl : Boolean;
begin
cFlg := 'N';
cRetorno := '';
lCtrl := True;
Controle( False );
LimpaDados;
lblNOs.Caption := ''; // 'O.S. nova:'#13'' + cNova;
If MessageDlg( 'O.S. em Retorno ?'#13'(Garantia interna)', mtConfirmation, [ mbYes, mbNo ], 0 ) = mrYes Then
Begin
While lCtrl Do
Begin
cRetorno := InputBox( 'O.S. Anterior', 'Número:', '0' );
If cRetorno <> '0' Then
Begin //
lblRetorno.Caption := cRetorno;
lblRetornoTexto.Visible := True;
TempoRetorno.Enabled := True;
RetornoOS( cRetorno );
lCtrl := False;
End
Else
Begin
lblRetorno.Caption := '';
lblRetornoTexto.Visible := False;
lCtrl := False;
End;
End;
End;
cbClientes.SetFocus;
end;
procedure T_Registro_Servico.sbAlterarOSClick(Sender: TObject);
begin
cFlg := 'A';
cNova := _dm.qr06.FieldByName( 'OS' ).AsString;
Controle( False );
cbClientes.SetFocus;
end;
procedure T_Registro_Servico.LimpaDados;
begin
cNova := '';
cbClientes.Text := '';
cbClientes.ItemIndex := -1;
edtEndereco.Text := '';
edtBairro.Text := '';
edtCidade.Text := '';
edtCEP.Text := '';
edtFone1.Text := '';
edtFone2.Text := '';
edtFax.Text := '';
edtCelular.Text := '';
edtEmail.Text := '';
cbEquipamento.Text := '';
cbEquipamento.ItemIndex := -1;
edtComplemento.Text := '';
edtDefeito.Text := '';
edtSerie.Text := '';
cbArea.Text := '';
cbArea.ItemIndex := -1;
edtObs.Text := '';
edtDataEntrada.Text := DateToStr( Now );
edtOrcamento.Text := '';
edtDataSaida.Text := '';
chkPago.Checked := False;
edtDataPrevisto.Text := '';
edtPago.Text := '';
cbSituacao.Text := '';
cbSituacao.ItemIndex := -1;
cbTecnico.Text := '';
cbTecnico.ItemIndex := -1;
cbExecutante.Text := '';
cbExecutante.ItemIndex := -1;
edtObs.Text := '';
edtServico.Text := '';
cbClientes.Color := clWindow;
cbEquipamento.Color := clWindow;
cbArea.Color := clWindow;
cbSituacao.Color := clWindow;
cbTecnico.Color := clWindow;
cbExecutante.Color := clWindow;
end;
procedure T_Registro_Servico.cbClientesExit(Sender: TObject);
begin
If cbClientes.Text <> '' Then
Begin
If cbClientes.ItemIndex < 0 Then
Begin
ShowMessage( 'Nome de Cliente não localizado no Cadastro.'#13'Será registrado.' );
cNovoCliente := 'N';
Exit;
End
Else
Begin
_dm.qr11.Close;
_dm.qr11.SQL.Text := 'select * from Clientes';
_dm.qr11.Open;
If _dm.qr11.Locate( 'CodCliente', _Main.stlClientes.Strings[ cbClientes.ItemIndex ], [] ) Then
Begin
edtEndereco.Text := ControlaCampoTexto( _dm.qr11.FieldByName( 'Endereco' ).AsString );
edtBairro.Text := ControlaCampoTexto( _dm.qr11.FieldByName( 'Bairro' ).AsString );
edtCidade.Text := ControlaCampoTexto( _dm.qr11.FieldByName( 'Cidade' ).AsString );
edtCEP.Text := ControlaCampoTexto( _dm.qr11.FieldByName( 'CEP' ).AsString );
edtFone1.Text := ControlaCampoTexto( _dm.qr11.FieldByName( 'Fone1' ).AsString) ;
edtFone2.Text := ControlaCampoTexto( _dm.qr11.FieldByName( 'Fone2' ).AsString );
edtFax.Text := ControlaCampoTexto( _dm.qr11.FieldByName( 'Fax' ).AsString );
edtCelular.Text := ControlaCampoTexto( _dm.qr11.FieldByName( 'Celular' ).AsString );
edtEmail.Text := ControlaCampoTexto( _dm.qr11.FieldByName( 'e-mail' ).AsString );
cbEquipamento.SetFocus;
End;
End;
End;
end;
procedure T_Registro_Servico.edtCEPExit(Sender: TObject);
begin
If edtCEP.Text <> '' Then edtCEP.Text := FormataCEP( edtCEP.Text );
end;
procedure T_Registro_Servico.edtFone1Exit(Sender: TObject);
begin
If edtFone1.Text <> '' Then edtFone1.Text := FormataFone( edtFone1.Text );
end;
procedure T_Registro_Servico.edtCelularExit(Sender: TObject);
begin
If edtCelular.Text <> '' Then edtCelular.Text := FormataFone( edtCelular.Text );
end;
procedure T_Registro_Servico.edtEmailExit(Sender: TObject);
begin
If cNovoCliente = 'N' Then
Begin
If MessageDlg( 'Confirma registro deste Novo Cliente ?', mtConfirmation, [ mbYes, mbNo ], 0 ) = mrYes Then
Begin
edtEndereco.Text := ControlaCampoTexto( edtEndereco.Text );
edtBairro.Text := ControlaCampoTexto( edtBairro.Text );
edtCidade.Text := ControlaCampoTexto( edtCidade.Text );
If edtCEP.Text = '' Then edtCEP.Text := '50.000-000';
edtFone1.Text := ControlaCampoTexto( edtFone1.Text );
edtFone2.Text := ControlaCampoTexto( edtFone2.Text );
edtFax.Text := ControlaCampoTexto( edtFax.Text );
edtCelular.Text := ControlaCampoTexto( edtCelular.Text );
edtEmail.Text := ControlaCampoTexto( edtEmail.Text );
_dm.qr12.Close;
_dm.qr12.SQL.Text := 'select * from CLIENTES';
_dm.qr12.Open;
_dm.qr12.Insert;
_dm.qr12.FieldByName( 'NomeCliente' ).AsString := cbClientes.Text;
_dm.qr12.FieldByName( 'ENDERECO' ).AsString := edtEndereco.Text;
_dm.qr12.FieldByName( 'BAIRRO' ).AsString := edtBairro.Text;
_dm.qr12.FieldByName( 'CIDADE' ).AsString := edtCidade.Text;
_dm.qr12.FieldByName( 'CEP' ).AsString := edtCEP.Text;
_dm.qr12.FieldByName( 'FONE1' ).AsString := edtFone1.Text;
_dm.qr12.FieldByName( 'FONE2' ).AsString := edtFone2.Text;
_dm.qr12.FieldByName( 'FAX' ).AsString := edtFax.Text;
_dm.qr12.FieldByName( 'CELULAR' ).AsString := edtCelular.Text;
_dm.qr12.FieldByName( 'OBS' ).AsString := 'Registrado em ' + DateTimeToStr( Now ) + '.';
_dm.qr12.FieldByName( 'e-mail' ).AsString := edtEmail.Text;
_dm.qr12.Post;
_dm.qr12.Close;
End;
End;
end;
procedure T_Registro_Servico.Apoio( x: Boolean );
begin
edtOrcamento.Visible := x;
edtDataSaida.Visible := x;
chkPago.Visible := x;
edtDataPrevisto.Visible := x;
edtPago.Visible := x;
lblExecutante.Visible := x;
edtServico.Visible := x;
cbExecutante.Visible := x;
end;
procedure T_Registro_Servico.btnCancelarClick(Sender: TObject);
begin
lblRetorno.Caption := '';
lblRetornoTexto.Visible := False;
Controle( True );
Apoio( True );
cFlg := '';
_dm.qr06.Close;
_dm.qr06.Open;
dbgOS.SetFocus;
end;
procedure T_Registro_Servico.btnSalvarClick(Sender: TObject); // Registro de dados do Serviço:
begin
If cNovoCliente = 'N' Then
Begin
_Main.stlClientes.Clear;
_dm.qr11.Close;
_dm.qr11.SQL.Text := 'select * from CLIENTES order by NomeCliente';
_dm.qr11.Open;
cbClientes.Clear;
While Not _dm.qr11.Eof Do
Begin
cbClientes.Items.Add( _dm.qr11.FieldByName( 'NomeCliente' ).AsString );
_Main.stlClientes.Add( _dm.qr11.FieldByName( 'CodCliente' ).AsString );
_dm.qr11.Next;
End;
End;
If cbEquipamento.Text = '' Then
Begin
MessageDlg( 'Favor informar a Situação', mtWarning, [ mbOk ], 0 );
cbEquipamento.SetFocus;
Exit;
End;
If cbArea.Text = '' Then
Begin
MessageDlg( 'Favor informar a Área', mtWarning, [ mbOk ], 0 );
cbArea.SetFocus;
Exit;
End;
If cbSituacao.Text = '' Then
Begin
MessageDlg( 'Favor informar a Situação', mtWarning, [ mbOk ], 0 );
cbSituacao.SetFocus;
Exit;
End;
If cbTecnico.Text = '' Then
Begin
MessageDlg( 'Favor informar o Técnico', mtWarning, [ mbOk ], 0 );
cbTecnico.SetFocus;
Exit;
End;
If ( cbExecutante.Text = '' ) and ( edtOrcamento.Text <> '' ) and ( edtOrcamento.Text <> '0' ) Then
Begin
MessageDlg( 'Favor informar o Técnico Executante', mtWarning, [ mbOk ], 0 );
cbExecutante.SetFocus;
Exit;
End;
If cFlg = 'N' Then
Begin
_dm.qr12.Close;
_dm.qr12.SQL.Text := 'select * from Servicos order by OS';
_dm.qr12.Open;
_dm.qr12.Last;
cNova := IntToStr( _dm.qr12.FieldByName( 'OS' ).AsInteger + 1 );
lblNOs.Caption := 'O.S. nova:'#13'' + cNova;
edtOs.Text := cNova;
_dm.qr12.Close;
_dm.qr12.SQL.Text := 'select * from Servicos';
_dm.qr12.Open;
_dm.qr12.Insert;
_dm.qr12.FieldByName( 'OS' ).AsString := cNova;
_dm.qr12.FieldByName( 'CodCliente' ).AsString := _Main.stlClientes.Strings[ cbClientes.ItemIndex ];
_dm.qr12.FieldByName( 'Situacao' ).AsString := _Main.stlSit.Strings[ cbSituacao.ItemIndex ];
_dm.qr12.FieldByName( 'Equipamento' ).AsString := _Main.stlEquip.Strings[ cbEquipamento.ItemIndex ];
_dm.qr12.FieldByName( 'Complemento' ).AsString := edtComplemento.Text;
_dm.qr12.FieldByName( 'NSerie' ).AsString := edtSerie.Text;
_dm.qr12.FieldByName( 'Defeito' ).AsString := edtDefeito.Text;
_dm.qr12.FieldByName( 'DataEntrada' ).AsString := edtDataEntrada.Text;
// _dm.qr12.FieldByName( 'Executante' ).AsString := _Main.stlFunc.Strings[ cbExecutante.ItemIndex ];
_dm.qr12.FieldByName( 'Tecnico' ).AsString := _Main.stlFunc.Strings[ cbTecnico.ItemIndex ];
// _dm.qr12.FieldByName( 'Pago' ).AsBoolean := chkPago.Checked;
// _dm.qr12.FieldByName( 'DataSaida' ).AsString := edtDataSaida.Text;
// _dm.qr12.FieldByName( 'ValorOrcamento' ).AsString := edtOrcamento.Text;
// _dm.qr12.FieldByName( 'Valor' ).AsString := edtPago.Text;
// _dm.qr12.FieldByName( 'PrevisaoPagamento' ).AsString := edtDataPrevisto.Text;
_dm.qr12.FieldByName( 'ServicoExecutado' ).AsString := ControlaCampoTexto( edtServico.Text );
_dm.qr12.FieldByName( 'Area' ).AsString := _Main.stlArea.Strings[ cbArea.ItemIndex ];
_dm.qr12.FieldByName( 'Obs' ).AsString := edtObs.Text;
_dm.qr12.FieldByName( 'Anterior' ).AsString := cRetorno;
_dm.qr12.Post;
_dm.qr12.Close;
Apoio( True );
GravarIni( _Main.cLocal + 'GS.INI', 'Numeracao', 'OS', cNova );
pnlOS.Caption := cNova;
End;
If cFlg = 'A' Then
Begin
_dm.qr12.Close;
_dm.qr12.SQL.Text := 'select * from Servicos';
_dm.qr12.Open;
_dm.qr12.Locate( 'OS', cNova, [] );
_dm.qr12.Edit;
_dm.qr12.FieldByName( 'OS' ).AsString := edtOs.Text;
_dm.qr12.FieldByName( 'CodCliente' ).AsString := _Main.stlClientes.Strings[ cbClientes.ItemIndex ];
_dm.qr12.FieldByName( 'Situacao' ).AsString := _Main.stlSit.Strings[ cbSituacao.ItemIndex ];
_dm.qr12.FieldByName( 'Equipamento' ).AsString := _Main.stlEquip.Strings[ cbEquipamento.ItemIndex ];
_dm.qr12.FieldByName( 'Complemento' ).AsString := edtComplemento.Text;
_dm.qr12.FieldByName( 'NSerie' ).AsString := edtSerie.Text;
_dm.qr12.FieldByName( 'Defeito' ).AsString := edtDefeito.Text;
_dm.qr12.FieldByName( 'DataEntrada' ).AsString := edtDataEntrada.Text;
If cbExecutante.Text <> '' Then
_dm.qr12.FieldByName( 'Executante' ).AsString := _Main.stlFunc.Strings[ cbExecutante.ItemIndex ];
_dm.qr12.FieldByName( 'Tecnico' ).AsString := _Main.stlFunc.Strings[ cbTecnico.ItemIndex ];
_dm.qr12.FieldByName( 'Pago' ).AsBoolean := chkPago.Checked;
_dm.qr12.FieldByName( 'DataSaida' ).AsString := edtDataSaida.Text;
_dm.qr12.FieldByName( 'ValorOrcamento' ).AsString := edtOrcamento.Text;
_dm.qr12.FieldByName( 'Valor' ).AsString := edtPago.Text;
_dm.qr12.FieldByName( 'PrevisaoPagamento' ).AsString := edtDataPrevisto.Text;
_dm.qr12.FieldByName( 'ServicoExecutado' ).AsString := ControlaCampoTexto( edtServico.Text );
_dm.qr12.FieldByName( 'Area' ).AsString := _Main.stlArea.Strings[ cbArea.ItemIndex ];
_dm.qr12.FieldByName( 'Obs' ).AsString := edtObs.Text;
_dm.qr12.FieldByName( 'Anterior' ).AsString := cRetorno;
_dm.qr12.Post;
_dm.qr12.Close;
End;
If MessageDlg( Iif( cFlg, 'N', '', 'Re-' ) + 'Imprimir O.S. Nº ' + cNova + ' ?', mtConfirmation, [ mbYes, mbNo ], 0 ) = mrYes Then
Begin
_Imprimir_OS := T_Imprimir_OS.Create( Self );
Try
_Imprimir_OS.lblNOs.Caption := cNova;
_Imprimir_OS.Print;
Finally
_Imprimir_OS.Free;
_Imprimir_OS := Nil;
End;
End;
lblRetorno.Caption := '';
lblRetornoTexto.Visible := False;
cNovoCliente := '';
Controle( True );
cFlg := '';
_dm.qr06.Close;
_dm.qr06.Open;
_dm.qr06.Last;
nOs := _dm.qr06.FieldByName( 'OS' ).AsInteger;
pnlOS.Caption := FormatFloat( '###,##0', nOs );
_dm.qr06.First;
dbgOS.SetFocus;
end;
procedure T_Registro_Servico.cbExecutanteExit(Sender: TObject);
begin
If cbExecutante.Text <> '' Then cbExecutante.Color := clWindow;
end;
procedure T_Registro_Servico.edtDataEntradaExit(Sender: TObject);
begin
If edtDataEntrada.Text <> '' Then edtDataEntrada.Text := FormataDATA( edtDataEntrada.Text );
end;
procedure T_Registro_Servico.edtOrcamentoExit(Sender: TObject);
begin
// If edtOrcamento.Text <> '' Then edtOrcamento.Text := FormataDATA( edtOrcamento.Text );
end;
procedure T_Registro_Servico.edtDataSaidaExit(Sender: TObject);
begin
If edtDataSaida.Text <> '' Then edtDataSaida.Text := FormataDATA( edtDataSaida.Text );
end;
procedure T_Registro_Servico.edtDataPrevistoExit(Sender: TObject);
begin
If edtDataPrevisto.Text <> '' Then edtDataPrevisto.Text := FormataDATA( edtDataPrevisto.Text );
end;
procedure T_Registro_Servico.chkPagoExit(Sender: TObject);
begin
If chkPago.Checked Then edtPago.SetFocus;
end;
procedure T_Registro_Servico.RetornoOS( cNumero : String );
begin
_dm.qrAux.Close;
_dm.qrAux.SQL.Text := 'select * from Servicos';
_dm.qrAux.Open;
If _dm.qrAux.Locate( 'OS', cNumero, [] ) Then
Begin
cbClientes.ItemIndex := _main.stlClientes.IndexOf( _dm.qrAux.FieldByName( 'CodCliente' ).AsString );
_dm.qr12.Close;
_dm.qr12.SQL.Text := 'select * from CLIENTES';
_dm.qr12.Open;
_dm.qr12.Locate( 'CodCliente', _dm.qrAux.FieldByName( 'CodCliente' ).AsString, [] );
edtEndereco.Text := _dm.qr12.FieldByName( 'ENDERECO' ).AsString;
edtBairro.Text := _dm.qr12.FieldByName( 'BAIRRO' ).AsString;
edtCidade.Text := _dm.qr12.FieldByName( 'CIDADE' ).AsString;
edtCEP.Text := _dm.qr12.FieldByName( 'CEP' ).AsString;
edtFone1.Text := _dm.qr12.FieldByName( 'FONE1' ).AsString;
edtFone2.Text := _dm.qr12.FieldByName( 'FONE2' ).AsString;
edtFax.Text := _dm.qr12.FieldByName( 'FAX' ).AsString;
edtCelular.Text := _dm.qr12.FieldByName( 'CELULAR' ).AsString;
edtEmail.Text := _dm.qr12.FieldByName( 'e-mail' ).AsString;
cbEquipamento.ItemIndex := _main.stlEquip.IndexOf( _dm.qrAux.FieldByName( 'Equipamento' ).AsString );
edtComplemento.Text := _dm.qrAux.FieldByName( 'Complemento' ).AsString;
edtDefeito.Text := _dm.qrAux.FieldByName( 'Defeito' ).AsString;
edtSerie.Text := _dm.qrAux.FieldByName( 'NSerie' ).AsString;
cbArea.ItemIndex := _main.stlArea.IndexOf( _dm.qrAux.FieldByName( 'Area' ).AsString );
edtObs.Text := _dm.qrAux.FieldByName( 'Obs' ).AsString;
edtDataEntrada.Text := _dm.qrAux.FieldByName( 'DataEntrada' ).AsString;
// edtOrcamento.Text := _dm.qrAux.FieldByName( 'x' ).AsString;
// edtDataSaida.Text := _dm.qrAux.FieldByName( 'x' ).AsString;
chkPago.Checked := False;
// edtDataPrevisto.Text := _dm.qrAux.FieldByName( 'x' ).AsString;
// edtPago.Text := _dm.qrAux.FieldByName( 'x' ).AsString;
cbSituacao.ItemIndex := _main.stlSit.IndexOf( _dm.qrAux.FieldByName( 'Situacao' ).AsString );
cbTecnico.ItemIndex := _main.stlFunc.IndexOf( _dm.qrAux.FieldByName( 'Tecnico' ).AsString );
// cbExecutante.ItemIndex := _dm.qrAux.FieldByName( 'x' ).AsInteger;
edtObs.Text := _dm.qrAux.FieldByName( 'Obs' ).AsString;
edtServico.Text := _dm.qrAux.FieldByName( 'ServicoExecutado' ).AsString;
End
Else
Begin
ShowMessage( 'Número de O.S. informado não'#13'localizado na Tabela de Serviços.' );
cRetorno := '';
End;
end;
procedure T_Registro_Servico.TempoRetornoTimer(Sender: TObject);
begin
If lblRetorno.visible = False Then
Begin
lblRetorno.visible := True;
End
Else
lblRetorno.visible := False;
end;
procedure T_Registro_Servico.sbImprimirClick(Sender: TObject);
begin//
_Imprimir_OS := T_Imprimir_OS.Create( Self );
Try
_Imprimir_OS.nOs := IntToStr( nOs );
_Imprimir_OS.lblNOs.Caption := IntToStr( nOs );
_Imprimir_OS.Preview;
Finally
_Imprimir_OS.Free;
_Imprimir_OS := Nil;
End;
end;
end.
|
unit ElegirCuenta;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, UnitUsuario, UnitCuentaDebito, UnitCuentaCredito,
Vcl.ExtCtrls, Vcl.WinXPanels;
type
TFormElegirCuenta = class(TForm)
btnVerCuentaDebito: TButton;
btnVerCuentaCredito: TButton;
Label1: TLabel;
txtNombre: TEdit;
btnAtras: TButton;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure changeButtonVisibility();
procedure btnVerCuentaDebitoClick(Sender: TObject);
procedure btnVerCuentaCreditoClick(Sender: TObject);
procedure btnAtrasClick(Sender: TObject);
private
{ Private declarations }
public
usuario : TUsuario;
cuentaDebito : TCuentaDebito;
cuentaCredito : TCuentaCredito;
end;
var
FormElegirCuenta: TFormElegirCuenta;
implementation
{$R *.dfm}
uses BuscarCliente, CuentaDebito, CuentaCredito;
procedure TFormElegirCuenta.FormShow(Sender: TObject);
begin
usuario := BuscarCliente.FormBuscarCliente.usuario;
cuentaDebito := BuscarCliente.FormBuscarCliente.cuentaDebito;
cuentaCredito := BuscarCliente.FormBuscarCliente.cuentaCredito;
changeButtonVisibility();
txtNombre.Text := usuario.getNombreCompleto;
end;
procedure TFormElegirCuenta.changeButtonVisibility;
begin
btnVerCuentaDebito.Visible := true;
btnVerCuentaCredito.Visible := true;
if not (cuentaDebito.estadoCuenta = 'activa') then
begin
btnVerCuentaDebito.Hide;
end;
if not (cuentaCredito.estadoCuenta = 'activa') then
begin
btnVerCuentaCredito.Hide;
end;
end;
procedure TFormElegirCuenta.btnAtrasClick(Sender: TObject);
begin
FormElegirCuenta.Visible := false;
FormBuscarCliente.Show;
end;
procedure TFormElegirCuenta.btnVerCuentaCreditoClick(Sender: TObject);
begin
FormCuentaCredito.Show;
FormElegirCuenta.Visible := False;
end;
procedure TFormElegirCuenta.btnVerCuentaDebitoClick(Sender: TObject);
begin
FormCuentaDebito.Show;
FormElegirCuenta.Visible := False;
end;
procedure TFormElegirCuenta.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Application.Terminate;
end;
end.
|
{$MODE OBJFPC}
{$INLINE ON}
program LongestCommonSubsequence;
const
InputFile = 'LCS.INP';
OutputFile = 'LCS.OUT';
max = 1000;
var
x, y, z: AnsiString;
m, n: Integer;
f: array[0..max, 0..max] of Integer;
procedure Enter;
var
f: TextFile;
begin
AssignFile(f, InputFile); Reset(f);
try
ReadLn(f, x);
ReadLn(f, y);
m := Length(x);
n := Length(y);
finally
CloseFile(f);
end;
end;
function GetMax(p, q: Integer): Integer; inline;
begin
if p > q then Result := p else Result := q;
end;
procedure Optimize;
var
i, j: Integer;
begin
FillChar(f[0], (n + 1) * SizeOf(Char), 0);
for i := 1 to m do f[i, 0] := 0;
for i := 1 to m do
for j := 1 to n do
begin
f[i, j] := 0;
if x[i] = y[j] then
f[i, j] := f[i - 1, j - 1] + 1
else
f[i, j] := GetMax(f[i - 1, j], f[i, j - 1]);
end;
end;
procedure Trace;
var
i, j, k: Integer;
begin
SetLength(z, f[m, n]);
i := m; j := n;
k := Length(z);
while (i <> 0) and (j <> 0) do
begin
if x[i] = y[j] then
begin
z[k] := x[i];
Dec(k);
Dec(i); Dec(j);
end
else
if f[i, j] = f[i - 1, j] then Dec(i)
else Dec(j);
end;
end;
procedure PrintResult;
var
f: TextFile;
begin
AssignFile(f, OutputFile); Rewrite(f);
try
WriteLn(f, z);
finally
CloseFile(f);
end;
end;
begin
Enter;
Optimize;
Trace;
PrintResult;
end.
abc1def2ghi3
abcdefghi123
|
(* MPL: SWa, MM, 2020-05-20 *)
(* ------ *)
(* MidiPascal scanner. *)
(* ========================================================================= *)
UNIT MPL;
INTERFACE
TYPE
Symbol = (errSy, eofSy,
programSy, varSy, beginSy, endSy,
readSy, writeSy, integerSy,
semicolonSy, colonSy, commaSy, dotSy,
assignSy,
plusSy, minusSy, timesSy, divSy,
leftParSy, rightParSy,
ifSy, thenSy, elseSy, whileSy, doSy,
ident, number);
VAR
sy: Symbol; (* current symbol *)
syLineNr, syColNr: INTEGER; (* line/column number of current symbol *)
numberVal: INTEGER; (* value if sy = number *)
identStr: STRING; (* name if sy = ident *)
PROCEDURE InitLex(inputFilePath: STRING);
PROCEDURE NewSy;
IMPLEMENTATION
CONST
EOF_CH = Chr(26);
TAB_CH = Chr(9);
VAR
inputFile: TEXT;
line: STRING;
lineNr, linePos: INTEGER;
ch: CHAR;
PROCEDURE NewCh; FORWARD;
PROCEDURE InitLex(inputFilePath: STRING);
BEGIN (* InitLex *)
Assign(inputFile, inputFilePath);
Reset(inputFile);
line := '';
lineNr := 0;
linePos := 0;
NewCh;
NewSy;
END; (* InitLex *)
PROCEDURE NewSy;
BEGIN (* NewSy *)
WHILE ((ch = ' ') OR (ch = TAB_CH)) DO BEGIN (* skip whitespaces *)
NewCh;
END; (* WHILE *)
syLineNr := lineNr;
syColNr := linePos;
CASE ch OF
EOF_CH: BEGIN sy := eofSy; END;
'+': BEGIN sy := plusSy; NewCh; END;
'*': BEGIN sy := timesSy; NewCh; END;
'-': BEGIN sy := minusSy; NewCh; END;
'/': BEGIN sy := divSy; NewCh; END;
'(': BEGIN sy := leftParSy; NewCh; END;
')': BEGIN sy := rightParSy; NewCh; END;
';': BEGIN sy := semicolonSy; NewCh; END;
',': BEGIN sy := commaSy; NewCh; END;
'.': BEGIN sy := dotSy; NewCh; END;
':': BEGIN (* colonSy / assignSy *)
NewCh;
IF (ch = '=') THEN BEGIN
sy := assignSy;
NewCh;
END ELSE BEGIN
sy := colonSy;
END; (* IF *)
END; (* colonSy / assignSy *)
'0'..'9': BEGIN (* number *)
sy := number;
numberVal := 0;
WHILE (ch >= '0') AND (ch <= '9') DO BEGIN
numberVal := numberVal * 10 + Ord(ch) - Ord('0');
NewCh;
END; (* WHILE *)
END; (* number *)
'a'..'z',
'A'..'Z',
'_' : BEGIN (* keyword / ident *)
identStr := '';
WHILE (ch IN ['a'..'z', 'A'..'Z', '_', '0'..'9']) DO BEGIN
identStr := identStr + ch;
NewCh;
END; (* WHILE *)
identStr := UpCase(identStr);
IF (identStr = 'PROGRAM') THEN BEGIN
sy := programSy;
END ELSE IF (identStr = 'BEGIN') THEN BEGIN
sy := beginSy;
END ELSE IF (identStr = 'END') THEN BEGIN
sy := endSy;
END ELSE IF (identStr = 'VAR') THEN BEGIN
sy := varSy;
END ELSE IF (identStr = 'INTEGER') THEN BEGIN
sy := integerSy;
END ELSE IF (identStr = 'READ') THEN BEGIN
sy := readSy;
END ELSE IF (identStr = 'WRITE') THEN BEGIN
sy := writeSy;
END ELSE IF (identStr = 'IF') THEN BEGIN
sy := ifSy;
END ELSE IF (identStr = 'THEN') THEN BEGIN
sy := thenSy;
END ELSE IF (identStr = 'ELSE') THEN BEGIN
sy := elseSy;
END ELSE IF (identStr = 'WHILE') THEN BEGIN
sy := whileSy;
END ELSE IF (identStr = 'DO') THEN BEGIN
sy := doSy;
END ELSE BEGIN
sy := ident;
END; (* IF *)
END; (* keyword / ident *)
ELSE BEGIN sy := errSy; END;
END; (* CASE *)
END; (* NewSy *)
PROCEDURE NewCh;
BEGIN (* NewCh *)
Inc(linePos);
IF (linePos > Length(line)) THEN BEGIN
IF (NOT Eof(inputFile)) THEN BEGIN
ReadLn(inputFile, line);
Inc(lineNr);
linePos := 0;
ch := ' ';
END ELSE BEGIN
ch := EOF_CH;
line := '';
linePos := 0;
Close(inputFile);
END; (* IF *)
END ELSE BEGIN
ch := line[linePos];
END; (* IF *)
END; (* NewCh *)
END. (* MPL *)
|
unit Support;
interface
uses
SysUtils,
Device.SMART.List,
BufferInterpreter;
type
TTotalWriteType =
(WriteNotSupported, WriteSupportedAsCount, WriteSupportedAsValue);
TSupported =
(NotSupported, Supported, CDISupported, CDIInsufficient);
TSupportStatus = record
Supported: TSupported;
FirmwareUpdate: Boolean;
TotalWriteType: TTotalWriteType;
end;
TTotalWriteInCount = record
ValueInCount: UInt64
end;
TTotalWriteInValue = record
TrueHostWriteFalseNANDWrite: Boolean;
ValueInMiB: UInt64;
end;
TTotalWrite = record
case Integer of
0: (InCount: TTotalWriteInCount);
1: (InValue: TTotalWriteInValue);
end;
TReadEraseError = record
TrueReadErrorFalseEraseError: Boolean;
Value: UInt64;
end;
TSMARTAlert = record
ReplacedSector: Boolean;
ReadEraseError: Boolean;
CriticalError: Boolean;
end;
TSMARTInterpreted = record
UsedHour: UInt64;
TotalWrite: TTotalWrite;
ReadEraseError: TReadEraseError;
ReplacedSectors: UInt64;
SMARTAlert: TSMARTAlert;
end;
TNSTSupport = class abstract
private
FIdentify: TIdentifyDeviceResult;
FSMART: TSMARTValueList;
protected
property Identify: TIdentifyDeviceResult read FIdentify;
property SMART: TSMARTValueList read FSMART;
public
constructor Create; overload;
constructor Create(const Identify: TIdentifyDeviceResult;
const SMART: TSMARTValueList); overload;
procedure SetModelAndFirmware(const Identify: TIdentifyDeviceResult;
const SMART: TSMARTValueList);
function GetSupportStatus: TSupportStatus; virtual; abstract;
function GetSMARTInterpreted(SMARTValueList: TSMARTValueList):
TSMARTInterpreted; virtual; abstract;
end;
implementation
{ TNSTSupport }
constructor TNSTSupport.Create(const Identify: TIdentifyDeviceResult;
const SMART: TSMARTValueList);
begin
SetModelAndFirmware(Identify, SMART);
end;
constructor TNSTSupport.Create;
begin
;// Intended to empty because of overloading rule
end;
procedure TNSTSupport.SetModelAndFirmware(const Identify: TIdentifyDeviceResult;
const SMART: TSMARTValueList);
begin
FIdentify := Identify;
FSMART := SMART;
FIdentify.Model := UpperCase(FIdentify.Model);
FIdentify.Firmware := UpperCase(FIdentify.Firmware);
end;
end.
|
unit ULogMsg;
interface
uses
SysUtils, Windows, Forms;
type
TLogMsg = class(TObject)
private
fClearSize: Integer;
fEnableWriteToFile: Boolean;
fLogFileName: string;
fMaxLenWrite: Integer;
fSizeFile: Int64;
function getFileSize(aFileName: string): Int64;
public
constructor Create;
destructor Destroy; override;
procedure write(const aText: string);
//1 Максимальный размер лог файла, после он очищается
property ClearSize: Integer read fClearSize write fClearSize;
property EnableWriteToFile: Boolean read fEnableWriteToFile write
fEnableWriteToFile;
property LogFileName: string read fLogFileName write fLogFileName;
property MaxLenWrite: Integer read fMaxLenWrite write fMaxLenWrite;
end;
procedure error_log(e:Exception;const aClassName:string = '';const aFuncName:string='');overload;
procedure error_log(const aMsg:string ;const aClassName:string = '';const aFuncName:string='');overload;
procedure error_log(const aMsg:string;e:Exception ;const aClassName:string = '';const aFuncName:string='');overload;
procedure error_log(const aMsg:string;const aArgs: array of const;const aClassName:string = '';const aFuncName:string='');overload;
var LogMsg:TLogMsg;
implementation
procedure error_log(const aMsg:string;e:Exception ;const aClassName:string = '';const aFuncName:string='');overload;
var
cClass :string;
cError :string;
cTime :string;
begin
cTime:='['+DateToStr(Now())+' '+TimeToStr(Now())+']';
cClass:='';
if (aClassName<>'') then
cClass:=cClass+aClassName+'.';
if (aFuncName<>'') then
cClass:=cClass+aFuncName;
if (cClass<>'') then cClass:=' {'+cClass+'}';
cError:='';
if (e<>nil) then begin
cError:=' ['+e.ClassName;
if (e.Message<>'') then
cError:=cError+': '+e.Message+' ';
cError:=cError+']';
end;
LogMsg.write(cTime+cClass+cError+' '+aMsg)
end;
procedure error_log(e:Exception;const aClassName:string = '';const aFuncName:string='');
begin
error_log('',e,aClassName,aFuncName);
end;
procedure error_log(const aMsg:string ;const aClassName:string = '';const aFuncName:string='');
begin
error_log(aMsg,nil,aClassName,aFuncName);
end;
procedure error_log(const aMsg:string;const aArgs: array of const;const aClassName:string = '';const aFuncName:string='');overload;
begin
error_log(Format(aMsg,aArgs),aClassName,aFuncName);
end;
{
*********************************** TLogMsg ************************************
}
constructor TLogMsg.Create;
begin
inherited Create;
if(Application<>nil) then begin
fLogFileName:=ExtractFileDir(Application.ExeName)+'/error_log.txt';
end else begin
fLogFileName:='';
end;
fEnableWriteToFile:=false;
fSizeFile:=0;
fClearSize:=1024*1024*10; // 10 mb
fMaxLenWrite:=512*4;
end;
destructor TLogMsg.Destroy;
begin
inherited Destroy;
end;
function TLogMsg.getFileSize(aFileName: string): Int64;
var
cSearchRec: _WIN32_FIND_DATAW;
cFileName: PChar;
hFind: THandle;
begin
result:=0;
try
if FileExists(aFileName) then
begin
cFileName:=PChar(aFileName);
hFind:=Windows.FindFirstFile(cFileName, cSearchRec);
result := cSearchRec.nFileSizeHigh;
result := result shl 32;
result := result + cSearchRec.nFileSizeLow;
Windows.FindClose(hFind);
end;
finally
end;
end;
procedure TLogMsg.write(const aText: string);
var
cStr: string;
hFile: TextFile;
begin
if Length(aText)>MaxLenWrite then
cStr:=copy(aText,1,MaxLenWrite)+'..'
else
cStr:=aText;
Windows.OutputDebugString(PWideChar(cStr));
if (EnableWriteToFile) then begin
try
AssignFile(hFile, LogFileName);
if (not FileExists(fLogFileName)) or (fSizeFile>fClearSize) then
ReWrite(hFile)
else
Append(hFile);
WriteLn(hFile,cStr);
CloseFile(hFile);
fSizeFile:=GetFileSize(LogFileName);
except
on e:Exception do begin
EnableWriteToFile:=false;
end;end;
end;
end;
initialization
LogMsg:=TLogMsg.Create();
finalization
LogMsg.Free();
end.
|
{ *************************************************************************** }
{ }
{ Kylix and Delphi Cross-Platform Visual Component Library }
{ }
{ Copyright (c) 1997, 2001 Borland Software Corporation }
{ }
{ *************************************************************************** }
unit DBLocalS;
{$R-,T-,H+,X+}
interface
{$IFDEF MSWINDOWS}
uses Windows, SysUtils, Variants, Classes, Db, DBCommon, Midas,
SqlTimSt, DBClient, DBLocal, Provider, SqlExpr;
{$ENDIF}
{$IFDEF LINUX}
uses Libc, SysUtils, Variants, Classes, DB, DBCommon, Midas, SqlTimSt,
DBClient, DBLocal, Provider, SqlExpr;
{$ENDIF}
type
{ TSQLClientDataSet }
TSQLClientDataSet = class(TCustomCachedDataSet)
private
FLocalParams: TParams;
FDataSet: TSQLDataSet;
FLocalCommandText: string;
FSQLConnection: TSQLConnection;
{$IFDEF MSWINDOWS}
FCommandType: TSQLCommandType;
FStreamedActive: Boolean;
{$ENDIF}
function GetCommandType: TSQLCommandType;
function GetConnection: TSQLConnection;
function GetConnectionName: string;
function GetMasterFields: string;
function GetObjectView: Boolean;
procedure SetCommandType(const Value: TSQLCommandType);
procedure SetConnection(const Value: TSQLConnection);
procedure SetConnectionName(const Value: string);
procedure SetInternalCommandText(Value: string);
procedure SetLocalParams;
procedure SetMasterFields(const Value: string);
procedure SetObjectView(const Value: Boolean);
{$IFDEF MSWINDOWS}
function GetMasterSource: TDataSource;
procedure SetDataSource(Value: TDataSource);
{$ENDIF}
protected
procedure Loaded; override;
function GetCommandText: string; override;
procedure SetActive(Value: Boolean); override;
procedure SetCommandText(Value: string); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure CloneCursor(Source: TCustomClientDataSet; Reset: Boolean;
KeepSettings: Boolean = False); override;
function GetQuoteChar: string;
published
property CommandText: string read GetCommandText write SetCommandText;
property CommandType: TSQLCommandType read GetCommandType write SetCommandType default ctQuery;
property DBConnection: TSQLConnection read GetConnection write SetConnection;
property ConnectionName: string read GetConnectionName write SetConnectionName;
property MasterFields read GetMasterFields write SetMasterFields;
{$IFDEF MSWINDOWS}
property MasterSource: TDataSource read GetMasterSource write SetDataSource;
{$ENDIF}
property ObjectView read GetObjectView write SetObjectView default False;
end;
implementation
uses MidConst, SqlConst;
const
ProvDataSetName = 'DataSet1';
{ Utility functions }
{ TSQLCDSParams }
type
{ TInternalSQLDataset }
TInternalSQLDataset = class(TSQLDataSet)
private
FKeyFields: string;
protected
function PSGetDefaultOrder: TIndexDef; override;
end;
TSQLCDSParams = class(TParams)
private
FFieldName: TStrings;
protected
procedure ParseSelect(SQL: string);
public
constructor Create(Owner: TPersistent);
Destructor Destroy; override;
end;
constructor TSQLCDSParams.Create(Owner: TPersistent);
begin
inherited;
FFieldName := TStringList.Create;
end;
destructor TSQLCDSParams.Destroy;
begin
FreeAndNil(FFieldName);
inherited;
end;
procedure TSQLCDSParams.ParseSelect(SQL: string);
const
SSelect = 'select';
var
FWhereFound: Boolean;
Start: PChar;
FName, Value: string;
SQLToken, CurSection, LastToken: TSQLToken;
Params: Integer;
begin
if Pos(' ' + SSelect + ' ', LowerCase(string(PChar(SQL)+8))) > 1 then Exit; // can't parse sub queries
Start := PChar(ParseSQL(PChar(SQL), True));
CurSection := stUnknown;
LastToken := stUnknown;
FWhereFound := False;
Params := 0;
repeat
repeat
SQLToken := NextSQLToken(Start, FName, CurSection);
if SQLToken in [stWhere] then
begin
FWhereFound := True;
LastToken := stWhere;
end else if SQLToken in [stTableName] then
begin
{ Check for owner qualified table name }
if Start^ = '.' then
NextSQLToken(Start, FName, CurSection);
end else
if (SQLToken = stValue) and (LastToken = stWhere) then
SQLToken := stFieldName;
if SQLToken in SQLSections then CurSection := SQLToken;
until SQLToken in [stFieldName, stEnd];
if FWhereFound and (SQLToken in [stFieldName]) then
repeat
SQLToken := NextSQLToken(Start, Value, CurSection);
if SQLToken in SQLSections then CurSection := SQLToken;
until SQLToken in [stEnd,stValue,stIsNull,stIsNotNull,stFieldName];
if Value='?' then
begin
FFieldName.Add(FName);
Inc(Params);
end;
until (Params = Count) or (SQLToken in [stEnd]);
end;
{ TInternalSQLDataset }
function TInternalSQLDataset.PSGetDefaultOrder: TIndexDef;
begin
if FKeyFields = '' then
Result := inherited PSGetDefaultOrder
else
begin // detail table default order
Result := TIndexDef.Create(nil);
Result.Options := [ixUnique]; // keyfield is unique
Result.Name := StringReplace(FKeyFields, ';', '_', [rfReplaceAll]);
Result.Fields := FKeyFields;
end;
end;
{ TSQLClientDataSet }
constructor TSQLClientDataSet.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FDataSet := TInternalSQLDataSet.Create(nil);
FDataSet.Name := Self.Name + ProvDataSetName;
Provider.DataSet := FDataSet;
SqlDBType := typeDBX;
FSQLConnection := nil;
FLocalParams := TParams.Create;
end;
destructor TSQLClientDataSet.Destroy;
begin
inherited Destroy;
if Assigned(FDataSet) then
FreeAndNil(FDataSet);
if Assigned(FSQLConnection) then
FreeAndNil(FSQLConnection);
if Assigned(FLocalParams) then
FreeAndNil(FLocalParams);
end;
function TSQLClientDataSet.GetCommandType: TSQLCommandType;
begin
{$IFDEF MSWINDOWS}
Result := FCommandType;
{$ENDIF}
{$IFDEF LINUX}
Result := FDataSet.CommandType;
{$ENDIF}
end;
procedure TSQLClientDataSet.SetCommandType(const Value: TSQLCommandType);
begin
if Value <> CommandType then
begin
{$IFDEF MSWINDOWS}
FCommandType := Value;
{$ENDIF}
{$IFDEF LINUX}
FDataSet.CommandType := Value;
{$ENDIF}
if not (csLoading in ComponentState) then
CommandText := '';
end;
end;
function TSQLClientDataSet.GetCommandText: string;
begin
Result := FLocalCommandText;
end;
procedure TSQLClientDataSet.SetInternalCommandText(Value: string);
var
Q,FCurrentCommand: string;
begin
if Assigned(Provider.DataSet) then
begin
if Assigned(TSQLDataSet(Provider.DataSet).SqlConnection) and (Value <> TSQLDataSet(Provider.DataSet).CommandText) then
begin
if CommandType = ctTable then
begin
Q := TSQLDataSet(Provider.DataSet).GetQuoteChar;
TSQLDataSet(Provider.DataSet).CommandType := ctQuery;
if Pos(Q, Value) = 0 then
FCurrentCommand := 'select * from ' + Q + Value + Q
else
FCurrentCommand := 'select * from ' + Value;
end else
begin
TSQLDataSet(Provider.DataSet).CommandType := TSQLCommandType(CommandType);
FCurrentCommand := Value;
end;
if (FLocalParams.Count > 0) and (Self.MasterFields <> '') then
FCurrentCommand := FCurrentCommand + AddParamSQLForDetail(FLocalParams, '', True);
TSQLDataSet(Provider.DataSet).CommandText := FCurrentCommand;
inherited SetCommandText(TSQLDataSet(Provider.DataSet).CommandText);
end;
end else
DataBaseError(SNoDataProvider);
end;
procedure TSQLClientDataSet.SetCommandText(Value: string);
procedure SetParamsFromSQL(const Value: string);
var
DataSet: TSQLDataSet;
TableName: string;
TempQuery: string;
List: TSQLCDSParams;
I: Integer;
Field: TField;
Q: string;
begin
TableName := GetTableNameFromSQL(Value);
if TableName <> '' then
begin
TempQuery := Value;
List := TSQLCDSParams.Create(Self);
try
List.ParseSelect(TempQuery);
List.AssignValues(Params);
for I := 0 to List.Count - 1 do
List[I].ParamType := ptInput;
DataSet := TSQLDataSet.Create(nil);
try
DataSet.SQLConnection := FDataSet.SQLConnection;
Q := DataSet.GetQuoteChar;
DataSet.CommandText := 'select * from ' + Q + TableName + Q + ' where 0 = 1'; { do not localize }
try
DataSet.Open;
for I := 0 to List.Count - 1 do
begin
if List.FFieldName.Count > I then
begin
try
Field := DataSet.FieldByName(List.FFieldName[I]);
except
Field := nil;
end;
end else
Field := nil;
if Assigned(Field) then
begin
if Field.DataType <> ftString then
List[I].DataType := Field.DataType
else if TStringField(Field).FixedChar then
List[I].DataType := ftFixedChar
else
List[I].DataType := ftString;
end;
end;
except
// ignore cannot open error
end;
finally
DataSet.Free;
end;
finally
if List.Count > 0 then
Params.Assign(List);
List.Free;
end;
end;
end;
begin
if Value <> CommandText then
begin
CheckInactive;
FLocalCommandText := Value;
if not (csLoading in ComponentState) then
begin
TInternalSQLDataSet(FDataSet).FKeyFields := '';
IndexFieldNames := '';
MasterFields := '';
IndexName := '';
IndexDefs.Clear;
Params.Clear;
if (csDesigning in ComponentState) and (Value <> '') and (Assigned(DBConnection)) then
SetParamsFromSQL(Value);
end;
end;
end;
function TSQLClientDataSet.GetConnection: TSQLConnection;
begin
if Assigned(FSQLConnection) then Result := FSQLConnection
else Result := FDataSet.SQLConnection as TSQLConnection;
end;
procedure TSQLClientDataSet.SetConnection(const Value: TSQLConnection);
begin
if FDataSet.SQLConnection <> Value then
begin
CheckInactive;
if Assigned(Value) then
SetConnectionName('');
FDataSet.SQLConnection := Value;
end;
end;
function TSQLClientDataSet.GetConnectionName: string;
begin
if Assigned(FSQLConnection) then
Result := FSQLConnection.ConnectionName
else
Result := '';
end;
procedure TSQLClientDataSet.SetConnectionName(const Value: string);
begin
if Value <> '' then
begin
CheckInactive;
SetConnection(nil);
if Assigned(FSQLConnection) then
begin
FSQLConnection.Close;
if Value = FSQLConnection.ConnectionName then
exit
else
FreeAndNil(FSQLConnection);
end;
FSQLConnection := TSQLConnection.Create(nil);
FSQLConnection.LoadParamsOnConnect := True;
FSQLConnection.ConnectionName := Value;
FDataSet.SQLConnection := FSQLConnection;
end else
begin
if Assigned(FSQLConnection) then
begin
FDataSet.SQLConnection := nil;
FreeAndNil(FSQLConnection);
end;
end;
end;
function TSQLClientDataSet.GetQuoteChar: string;
begin
Result := FDataSet.GetQuoteChar;
end;
function TSQLClientDataSet.GetMasterFields: string;
begin
Result := inherited MasterFields;
end;
procedure TSQLClientDataSet.SetMasterFields(const Value: string);
begin
inherited MasterFields := Value;
if Value <> '' then
IndexFieldNames := Value;
TInternalSQLDataSet(FDataSet).FKeyFields := '';
end;
procedure TSQLClientDataSet.SetLocalParams;
procedure CreateParamsFromMasterFields(Create: Boolean);
var
I: Integer;
List: TStrings;
begin
List := TStringList.Create;
try
if Create then
FLocalParams.Clear;
List.CommaText := StringReplace(MasterFields, ';', ',', [rfReplaceAll]);
TInternalSQLDataSet(FDataSet).FKeyFields := MasterFields;
for I := 0 to List.Count -1 do
begin
if Create then
FLocalParams.CreateParam( ftUnknown, MasterSource.DataSet.FieldByName(List[I]).FieldName,
ptInput);
FLocalParams[I].AssignField(MasterSource.DataSet.FieldByName(List[I]));
end;
finally
List.Free;
end;
end;
begin
if (MasterFields <> '') and Assigned(MasterSource) and Assigned(MasterSource.DataSet) then
begin
CreateParamsFromMasterFields(True);
end;
end;
procedure TSQLClientDataSet.SetActive(Value: Boolean);
procedure CheckMasterSourceActive(const MasterSource: TDataSource);
begin
if Assigned(MasterSource) and Assigned(MasterSource.DataSet) then
if not MasterSource.DataSet.Active then
DatabaseError(SMasterNotOpen);
end;
procedure SetDetailsActive(const Value: Boolean);
var
DetailList: TList;
I: Integer;
begin
DetailList := TList.Create;
try
GetDetailDataSets(DetailList);
for I := 0 to DetailList.Count -1 do
if TDataSet(DetailList[I]) is TSQLClientDataSet then
TSQLClientDataSet(TDataSet(DetailList[I])).Active := Value;
finally
DetailList.Free;
end;
end;
{$IFDEF LINUX}
var
SaveCommandType: TSQLCommandType;
{$ENDIF}
begin
{$IFDEF LINUX}
SaveCommandType := CommandType;
try
{$ENDIF}
if Value then
begin
if csLoading in ComponentState then
begin
{$IFDEF MSWINDOWS}
FStreamedActive := True;
{$ENDIF}
exit;
end;
if MasterFields <> '' then
begin
{$IFDEF LINUX}
if PacketRecords = -1 then PacketRecords := 0;
{$ENDIF}
if not (csLoading in ComponentState) then
CheckMasterSourceActive(MasterSource);
SetLocalParams;
SetInternalCommandText(CommandText);
Params := FLocalParams;
FetchParams;
end else
begin
SetInternalCommandText(FLocalCommandText);
if Params.Count > 0 then
begin
FDataSet.Params := Params;
FetchParams;
end;
end;
end;
if Value and (FDataSet.ObjectView <> ObjectView) then
FDataSet.ObjectView := ObjectView;
inherited SetActive(Value);
SetDetailsActive(Value);
{$IFDEF LINUX}
finally
if FDataSet.CommandType <> SaveCommandType then
FDataSet.CommandType := SaveCommandType;
end;
{$ENDIF}
end;
procedure TSQLClientDataSet.SetObjectView(const Value: Boolean);
begin
inherited ObjectView := Value;
end;
function TSQLClientDataSet.GetObjectView: Boolean;
begin
Result := inherited ObjectView;
end;
{$IFDEF MSWINDOWS}
procedure TSQLClientDataSet.SetDataSource(Value: TDataSource);
begin
inherited MasterSource := Value;
if Assigned(Value) then
begin
if PacketRecords = -1 then PacketRecords := 0;
end else
begin
if PacketRecords = 0 then PacketRecords := -1;
end;
end;
function TSQLClientDataSet.GetMasterSource: TDataSource;
begin
Result := inherited GetDataSource;
end;
{$ENDIF}
procedure TSQLClientDataSet.Loaded;
begin
inherited Loaded;
{$IFDEF MSWINDOWS}
if FStreamedActive then
begin
try
FStreamedActive := False;
SetActive(True);
except
if csDesigning in ComponentState then
InternalHandleException else
raise;
end;
end;
{$ENDIF}
end;
procedure TSQLClientDataSet.CloneCursor(Source: TCustomClientDataSet; Reset: Boolean;
KeepSettings: Boolean = False);
begin
if not (Source is TSQLClientDataSet) then
DatabaseError(SInvalidClone);
Provider.DataSet := TSQLClientDataSet(Source).Provider.DataSet;
DBConnection := TSQLClientDataSet(Source).DBConnection;
FLocalCommandText := TSQLClientDataSet(Source).CommandText;
inherited CloneCursor(Source, Reset, KeepSettings);
end;
end.
|
FUNCTION WaitNAK(timeoutSecs : INTEGER) : ResponseType;
CONST
CTRLC = ^C;
NAK = ^U;
CAN = ^X;
WantCRC = 'C';
VAR
ticks,canCount : INTEGER;
c : CHAR;
BEGIN
ticks := timeoutSecs * 500;
canCount := 0;
c := #$00;
REPEAT
IF KeyPressed THEN BEGIN
Read(Kbd,c);
IF c = CTRLC THEN
WaitNAK := GotABORT
ELSE
c := #$00;
END ELSE IF ModemInReady THEN BEGIN
Read(Aux,c);
CASE c OF
WantCRC: WaitNAK := GotWantCRC;
NAK: WaitNAK := GotNAK;
CAN:
BEGIN
canCount := Succ(canCount);
IF canCount >= 2 THEN
WaitNAK := GotCAN
ELSE
c := #$00;
END;
ELSE
c := #$00;
END;
END;
IF c <> #$00 THEN BEGIN
Delay(2);
ticks := Pred(ticks);
END;
UNTIL (ticks = 0) OR (c <> #$00);
IF ticks = 0 THEN
WaitNAK := GotTIMEOUT;
END;
|
(*
* This code was generated by the TaskGen tool from file
* "CommonOptionsTask.xml"
* Version: 16.0.0.0
* Runtime Version: v2.0.50727
* Changes to this file may cause incorrect behavior and will be
* overwritten when the code is regenerated.
*)
unit CommonOptionStrs;
interface
const
sTaskName = 'commonoptions';
// PathsAndDefines
sDefines = 'Defines';
sIncludePath = 'IncludePath';
sFinalOutputDir = 'FinalOutputDir';
sIntermediateOutputDir = 'IntermediateOutputDir';
// MiscInternalOptions
sShowGeneralMessages = 'ShowGeneralMessages';
// CommonPackageOpts
sPackageImports = 'PackageImports';
sAllPackageLibs = 'AllPackageLibs';
sPackageLibs = 'PackageLibs';
sDesignOnlyPackage = 'DesignOnlyPackage';
sRuntimeOnlyPackage = 'RuntimeOnlyPackage';
// DelphiInternalOptions
sGenPackage = 'GenPackage';
sGenDll = 'GenDll';
sUsePackages = 'UsePackages';
sHasTypeLib = 'HasTypeLib';
sAutoGenImportAssembly = 'AutoGenImportAssembly';
sAutoRegisterTLB = 'AutoRegisterTLB';
sImageDebugInfo = 'ImageDebugInfo';
sDebugSourcePath = 'DebugSourcePath';
// OutputFilenameModifiers
sOutputExt = 'OutputExt';
sOutputName = 'OutputName';
sDllPrefixDefined = 'DllPrefixDefined';
sDllPrefix = 'DllPrefix';
sDllVersion = 'DllVersion';
sDllSuffix = 'DllSuffix';
// C++InternalOptions
sMultithreaded = 'Multithreaded';
sDynamicRTL = 'DynamicRTL';
sUsingDelphiRTL = 'UsingDelphiRTL';
sLinkCodeGuard = 'LinkCodeGuard';
sRunBCCOutOfProcess = 'RunBCCOutOfProcess';
// WindowsVersionInformation
sVerInfo_IncludeVerInfo = 'VerInfo_IncludeVerInfo';
sVerInfo_MajorVer = 'VerInfo_MajorVer';
sVerInfo_MinorVer = 'VerInfo_MinorVer';
sVerInfo_Release = 'VerInfo_Release';
sVerInfo_Build = 'VerInfo_Build';
sVerInfo_Debug = 'VerInfo_Debug';
sVerInfo_PreRelease = 'VerInfo_PreRelease';
sVerInfo_Special = 'VerInfo_Special';
sVerInfo_Private = 'VerInfo_Private';
sVerInfo_DLL = 'VerInfo_DLL';
sVerInfo_Locale = 'VerInfo_Locale';
sVerInfo_CodePage = 'VerInfo_CodePage';
sVerInfo_CompanyName = 'VerInfo_CompanyName';
sVerInfo_FileDescription = 'VerInfo_FileDescription';
sVerInfo_FileVersion = 'VerInfo_FileVersion';
sVerInfo_InternalName = 'VerInfo_InternalName';
sVerInfo_LegalCopyright = 'VerInfo_LegalCopyright';
sVerInfo_LegalTrademarks = 'VerInfo_LegalTrademarks';
sVerInfo_OriginalFilename = 'VerInfo_OriginalFilename';
sVerInfo_ProductName = 'VerInfo_ProductName';
sVerInfo_ProductVersion = 'VerInfo_ProductVersion';
sVerInfo_Comments = 'VerInfo_Comments';
sVerInfo_Keys = 'VerInfo_Keys';
sVerInfo_AutoGenVersion = 'VerInfo_AutoGenVersion';
sIcon_MainIcon = 'Icon_MainIcon';
sManifest_File = 'Manifest_File';
sVCL_Custom_Styles = 'VCL_Custom_Styles';
// DebuggerProjectOptions
sDebugger_RunParams = 'Debugger_RunParams';
sDebugger_RemoteRunParams = 'Debugger_RemoteRunParams';
sDebugger_HostApplication = 'Debugger_HostApplication';
sDebugger_RemotePath = 'Debugger_RemotePath';
sDebugger_RemoteHost = 'Debugger_RemoteHost';
sDebugger_EnvVars = 'Debugger_EnvVars';
sDebugger_SymTabs = 'Debugger_SymTabs';
sDebugger_Launcher = 'Debugger_Launcher';
sDebugger_RemoteLauncher = 'Debugger_RemoteLauncher';
sDebugger_IncludeSystemVars = 'Debugger_IncludeSystemVars';
sDebugger_UseLauncher = 'Debugger_UseLauncher';
sDebugger_UseRemoteLauncher = 'Debugger_UseRemoteLauncher';
sDebugger_CWD = 'Debugger_CWD';
sDebugger_RemoteCWD = 'Debugger_RemoteCWD';
sDebugger_RemoteDebug = 'Debugger_RemoteDebug';
sDebugger_DebugSourcePath = 'Debugger_DebugSourcePath';
sDebugger_LoadAllSymbols = 'Debugger_LoadAllSymbols';
sDebugger_LoadUnspecifiedSymbols = 'Debugger_LoadUnspecifiedSymbols';
sDebugger_SymbolSourcePath = 'Debugger_SymbolSourcePath';
// BuildEvents
sPreBuildEvent = 'PreBuildEvent';
sPreBuildEventCancelOnError = 'PreBuildEventCancelOnError';
sPreLinkEvent = 'PreLinkEvent';
sPreLinkEventCancelOnError = 'PreLinkEventCancelOnError';
sPostBuildEvent = 'PostBuildEvent';
sPostBuildEventExecuteWhen = 'PostBuildEventExecuteWhen';
sPostBuildEventExecuteWhen_Always = 'Always';
sPostBuildEventExecuteWhen_TargetOutOfDate = 'TargetOutOfDate';
sPostBuildEventCancelOnError = 'PostBuildEventCancelOnError';
implementation
end.
|
unit AviWriter_2;
/////////////////////////////////////////////////////////////////////////////
// //
// AviWriter -- a component to create rudimentary AVI files //
// by Elliott Shevin, with large pieces of code //
// stolen from Anders Melander //
// version 1.0. Please send comments, suggestions, and advice //
// to shevine@aol.com. //
// //
// Extended to AviWriter_2 by Renate Schaaf //
// renates@xmission.com //
// http://www.xydot.com/delphi/ //
/////////////////////////////////////////////////////////////////////////////
// //
// AviWriter will build an AVI file containing one stream of any //
// number of TBitmaps, plus a single WAV file. //
// //
// Properties: //
// Bitmaps : A TList of pointers to TBitmap objects which become //
// frames of the AVI video stream. The component //
// allocates and frees the TList, but the caller //
// is responsible for managing the TBitmaps themselves. //
// Manipulate the list as you would any other TList. //
// At least one bitmap is required. //
// Height, Width: //
// The dimensions of the AVI video, in pixels. //
// FrameTime: //
// The duration of each video frame, in milliseconds. //
// Stretch: If TRUE, each TBitmap on the Bitmaps list is //
// stretches to the dimensions specified in Height //
// and Width. If FALSE, each TBitmap is copied from //
// its upper left corner without stretching. //
// FileName: The name of the AVI file to be written. //
// WAVFileName: //
// The name of a WAV file which will become the audio //
// stream for the AVI. Optional. //
// //
// Method: //
// Write: Creates the AVI file named by FileName. //
/////////////////////////////////////////////////////////////////////////////
// Wish List: //
// I'd like to be able to enhance this component in two ways, but //
// don't know how. Please send ideas to shevine@aol.com. //
// 1. So far, it's necessary to transform the video stream into //
// and AVI file on disk. I'd prefer to do this in memory. //
// 2. MIDI files for audio. //
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// Modifications by Renate Schaaf (renates@xmission.com): //
// //
// 1. Support for pixel-formats other than pf8bit //
// (in the routines I added, the AddVideo and Write routines //
// are unchanged)
// 2. Support for adding bitmaps on the fly //
// (the bitmap list is OK for small avis, but not for "movies") // //
// 3. Avi-Compression support, optionally with On-the-fly compression, //
// which avoids the writing of a temporary uncompressed file. // //
// 4. Support for progress feedback //
// 5. Got the on-the-fly bitmap adding to work in my threads by //
// avoiding the use of InternalGet... functions. It uses a //
// TDIBSection and GetObject instead in AddFrame. //
// 6. More than one wave file can be written to Audiostream, //
// and start times can be specified in ms-delays //
// //
// Methods added: //
// Compressionlist //
// (Utility to get a list of supported codecs //
// The first 4 characters in each item are the FourCC-code. //
// Pass a list which has ancestor type TStrings, and //
// which has been created. TCombobox.Items is a good one.) //
// SetCompression //
// (Set FourCC-code for compression) //
// SetCompressionQuality //
// (Set a value between 0 and 10 000 for the quality of the //
// compression. How it interpretes it, is up to the Codec :( //
// InitVideo //
// (call before adding any bitmaps) //
// AddFrame //
// (add a bitmap as the next (key-)frame) //
// AddStillImage //
// (add a bitmap which is to be shown unchanged for //
// more than the frame time. Helps to keep an uncompressed //
// file smaller and saves a bit of time.) //
// AddWaveFile //
// (add wavefile(s) to be included as audiostream. Specify a delay //
// in ms for when the file should start playing. All wave files //
// must have the same format. The format is determined by the //
// first file. If a subsequent file does not match, is is being //
// skipped. //
// Exception: if OnTheFlyCompression is false, only one wave file //
// can be added.) //
// FinalizeVideo //
// (no more bitmaps to add) //
// WriteAvi //
// (combine the video and audiostream to the final .avi. //
// if OnTheFlyCompression is false, but compression is requested, //
// then the videostream is compressed here. Otherwise just the //
// audiostream is added.) //
// Events added: //
// OnProgress //
// (Sends the current framecount for your update procedure. //
// Set Abort to true, if the user or you requests termination.) //
// Properties added: //
// Pixelformat (needs to be global for the whole movie) //
// OnTheFlyCompression (if true (default), frames are compressed //
// as they come in. Careful, some codecs, like MS-RLE //
// do not support it. Most of mine do, though.) //
// Aborted //
// (read whether the user or you or me killed the writing. //
// The user's input can be fetched in OnProgress.) //
// Fields added/changed: //
// Several private fields/methods //
// TempfileName (made public, the default temp-folder //
// would not have enough disk-space on my system) //
// Types added/changed: //
// axed TPixelFormat //
// (the original overwrites the same type in graphics.pas, //
// as a result MyBitmap.pixelformat:=pf24bit would not compile, //
// but I wonder whether it hadn't been there for a reason... ) //
// TFourCC //
// (string[4] for FourCC-codes of compression codecs) //
// TProgressEvent //
//Constants changed: //
// Typecast of AVIERR_*** as HResult to avoid compiler //
// warnings. //
// //
// //
/////////////////////////////////////////////////////////////////////////////
// Procedures/Types/Constants to convert part of MS VCM (MSVFW32.DLL). //
///////////////////////////////////////////////////////////////////////////// //
// Source: //
// VFW.pas available from delphi-jedi.org. //
// by Ronald Dittrich, Ivo Steinmann, Peter Haas //
// //
/////////////////////////////////////////////////////////////////////////////
// //
// //
// ***********No guaranties, warranty, liability :)**** //
// //
// //
// Thanks: To all cited authors! I would not have dared to get into this //
// stuff without this component plus the API-headers //
// being available. //
// //
// //
// Comments: //
// The component now seems to work in my threads. Thread safety //
// turned out not to have anything to do with it being a class //
// or a component, but everything with protecting the incoming bitmaps //
// via locking/unlocking the canvas. Another important step seemed to //
// be to avoid using the routine InternalGetDIB. It kept failing for //
// me on larger frame sizes, as soon as another one of my threads //
// started. Don't know why, but maybe //
// Graphics.pas didn't like it with its shared handles. //
// //
////////////////////////////////////////////////////////////////////////////
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs,
StdCtrls,
{$IFDEF VER90}
ole2;
{$ELSE}
ActiveX;
{$ENDIF}
////////////////////////////////////////////////////////////////////////////////
// //
// Video for Windows //
// //
////////////////////////////////////////////////////////////////////////////////
// //
// Adapted from Thomas Schimming's VFW.PAS //
// (c) 1996 Thomas Schimming, schimmin@iee1.et.tu-dresden.de //
// (c) 1998,99 Anders Melander //
// //
////////////////////////////////////////////////////////////////////////////////
// //
// Ripped all COM/ActiveX stuff and added some AVI stream functions. //
// //
////////////////////////////////////////////////////////////////////////////////
type
LONG = Longint;
PAVIStream = Pointer;
PAVIFile = Pointer;
TAVIStreamList = array[0..0] of PAVIStream;
PAVIStreamList = ^TAVIStreamList;
PAVIStreamInfo = ^TAviStreamInfo;
TAviStreamInfo = packed record
fccType: DWord;
fccHandler: DWord;
dwFlags: DWord; // Contains AVITF_* flags
dwCaps: DWord;
wPriority: Word;
wLanguage: Word;
dwScale: DWord;
dwRate: DWord; // dwRate / dwScale == samples/second
dwStart: DWord;
dwLength: DWord; // In units above...
dwInitialFrames: DWord;
dwSuggestedBufferSize: DWord;
dwQuality: DWord;
dwSampleSize: DWord;
rcFrame: TRect;
dwEditCount: DWord;
dwFormatChangeCount: DWord;
szName: array[0..63] of WideChar;
end;
PAVICompressOptions = ^TAVICompressOptions;
TAVICompressOptions = packed record
fccType: DWord; // stream type, for consistency
fccHandler: DWord; // compressor
dwKeyFrameEvery: DWord; // keyframe rate
dwQuality: DWord; // compress quality 0-10,000
dwBytesPerSecond: DWord; // bytes per second
dwFlags: DWord; // flags... see below
lpFormat: Pointer; // save format
cbFormat: DWord;
lpParms: Pointer; // compressor options
cbParms: DWord;
dwInterleaveEvery: DWord; // for non-video streams only
end;
APAVISTREAM = array[0..1] of PAVIStream;
APAVICompressOptions = array[0..1] of PAVICompressOptions;
TAVISaveCallback = function(i: integer): LONG; pascal;
procedure AVIFileInit; stdcall;
procedure AVIFileExit; stdcall;
function AVIFileOpen(var ppfile: PAVIFile; szFile: PChar; uMode: UINT; lpHandler: Pointer): HRESULT; stdcall;
function AVIFileCreateStream(pfile: PAVIFile; var ppavi: PAVIStream; var psi: TAviStreamInfo): HRESULT; stdcall;
function AVIStreamSetFormat(pavi: PAVIStream; lPos: LONG; lpFormat: Pointer; cbFormat: LONG): HRESULT; stdcall;
function AVIStreamReadFormat(pavi: PAVIStream; lPos: LONG; lpFormat: Pointer; var cbFormat: LONG): HRESULT; stdcall;
function AVIStreamWrite(pavi: PAVIStream; lStart, lSamples: LONG; lpBuffer: Pointer; cbBuffer: LONG; dwFlags: DWord; var plSampWritten: LONG; var plBytesWritten: LONG): HRESULT; stdcall;
function AVIStreamRelease(pavi: PAVIStream): ULONG; stdcall;
function AVIFileRelease(pfile: PAVIFile): ULONG; stdcall;
function AVIFileGetStream(pfile: PAVIFile; var ppavi: PAVIStream; fccType: DWord; LParam: LONG): HRESULT; stdcall;
function CreateEditableStream(var ppsEditable: PAVIStream; psSource: PAVIStream): HRESULT; stdcall;
function AVISaveV(szFile: PChar; pclsidHandler: PCLSID; lpfnCallback: TAVISaveCallback;
nStreams: integer; pavi: APAVISTREAM; lpOptions: APAVICompressOptions): HRESULT; stdcall;
function AVIMakeCompressedStream(
var ppsCompressed: PAVIStream;
ppsSource: PAVIStream;
lpOptions: PAVICompressOptions;
pclsidHandler: PCLSID
): HRESULT; stdcall;
function AVIStreamInfo(pavi: PAVIStream; var psi: TAviStreamInfo; lSize: LONG): HRESULT; stdcall;
function AVIStreamRead(
pavi: PAVIStream;
lStart: LONG;
lSamples: LONG;
lpBuffer: Pointer;
cbBuffer: LONG;
plBytes: PInteger;
plSamples: PInteger
): HRESULT; stdcall;
function AVIStreamStart(pavi: PAVIStream): LONG; stdcall;
function AVIStreamLength(pavi: PAVIStream): LONG; stdcall;
function EditStreamCopy(pavi: PAVIStream; var plStart, plLength: LONG; var ppResult: PAVIStream): HRESULT; stdcall;
function EditStreamPaste(pavi: PAVIStream; var plPos, plLength: LONG; pstream: PAVIStream; lStart, lEnd: LONG): HRESULT; stdcall;
function EditStreamSetInfo(pavi: PAVIStream; lpInfo: PAVIStreamInfo; cbInfo: LONG): HRESULT; stdcall;
type TFourCC = string[4];
type
TProgressEvent = procedure(Sender: TObject; FrameCount: integer; var abort: boolean) of object;
TBadBitmapEvent = procedure(Sender: TObject; bmp: TBitmap; InfoHeaderSize, BitsSize: integer) of object;
type
TAviWriter_2 = class(TComponent)
private
pfile: PAVIFile;
fHeight: integer;
fWidth: integer;
fStretch: boolean;
fFrameTime: integer;
fFilename: string;
fWavFileName: string;
VideoStream: PAVIStream;
AudioStream: PAVIStream;
fPstream, fCompStream: PAVIStream;
fStreamInfo: TAviStreamInfo;
fFrameCount: integer;
fFourCC: TFourCC;
fPixelFormat: TPixelFormat;
//fInHeader: TBitmapInfoHeader;
fPInInfo: PBitmapInfo;
fInInfoSize: integer;
AviCompressoptions: TAVICompressOptions;
fAbort: boolean;
fCompressionQuality: integer;
fInitialized, fFinalized: boolean;
fWaveFileList: TStringList;
fCompOnFly: boolean;
fOnProgress: TProgressEvent;
fOnBadBitmap: TBadBitmapEvent;
procedure AddVideo;
procedure AddAudio;
procedure InternalGetDIBSizes(Bitmap: HBITMAP; var InfoHeaderSize: integer;
var ImageSize: Longint; PixelFormat: TPixelFormat);
function InternalGetDIB(Bitmap: HBITMAP; Palette: Hpalette;
var BitmapInfo; var Bits; PixelFormat: TPixelFormat): boolean;
procedure InitializeBitmapInfoHeader(Bitmap: HBITMAP; var Info: TBitmapInfoHeader;
PixelFormat: TPixelFormat);
procedure SetWavFileName(value: string);
function AviSaveCallback(i: integer): LONG; pascal;
procedure SetPixelFormat(const value: TPixelFormat);
procedure InitStreamFormat(const bm: TBitmap);
procedure AddAudioMod;
procedure InternalAddFrame(const Bitmap: TBitmap; Key: boolean);
{ Private declarations }
protected
{ Protected declarations }
public
Bitmaps: TList;
TempFileName: string;
SilenceName: string;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Write;
procedure InitVideo;
procedure AddFrame(const ABmp: TBitmap);
procedure AddStillImage(const ABmp: TBitmap; Showtime: integer);
//showtime is in ms
procedure FinalizeVideo;
procedure WriteAvi;
procedure Compressorlist(const List: TStrings);
procedure SetCompression(FourCC: TFourCC);
procedure SetCompressionQuality(q: integer);
procedure ShowCompressorDialog(ADialogParent: TWinControl);
procedure AddWaveFile(const filename: string; Delay: integer);
//properties:
property Aborted: boolean read fAbort;
property OnTheFlyCompression: boolean read fCompOnFly write fCompOnFly;
property OnBadBitmap: TBadBitmapEvent read fOnBadBitmap write fOnBadBitmap;
published
property Height: integer read fHeight write fHeight;
property Width: integer read fWidth write fWidth;
property FrameTime: integer read fFrameTime write fFrameTime;
property Stretch: boolean read fStretch write fStretch;
property PixelFormat: TPixelFormat read fPixelFormat write SetPixelFormat;
property filename: string read fFilename write fFilename;
property WavFileName: string read fWavFileName write SetWavFileName;
property OnProgress: TProgressEvent read fOnProgress write fOnProgress;
end;
procedure Register;
implementation
uses MMsystem, Silence;
procedure Register;
begin
RegisterComponents('Custom', [TAviWriter_2]);
end;
type
PICINFO = ^TICINFO;
TICINFO = packed record
dwSize: DWord; // sizeof(ICINFO)
fccType: DWord; // compressor type 'vidc' 'audc'
fccHandler: DWord; // compressor sub-type 'rle ' 'jpeg' 'pcm '
dwFlags: DWord; // flags LOWORD is type specific
dwVersion: DWord; // version of the driver
dwVersionICM: DWord; // version of the ICM used
//
// under Win32, the driver always returns UNICODE strings.
//
szName: array[0..15] of WChar; // short name
szDescription: array[0..127] of WChar; // DWORD name
szDriver: array[0..127] of WChar; // driver that contains compressor
end;
const
AVICOMPRESSF_INTERLEAVE = $00000001; // interleave
AVICOMPRESSF_DATARATE = $00000002; // use a data rate
AVICOMPRESSF_KEYFRAMES = $00000004; // use keyframes
AVICOMPRESSF_VALID = $00000008; // has valid data?
//Typecast as HResult to eliminate compiler warnings
//about violating subrange bounds
AVIERR_OK = 0;
AVIERR_UNSUPPORTED = HRESULT($80044065); // MAKE_AVIERR(101)
AVIERR_BADFORMAT = HRESULT($80044066); // MAKE_AVIERR(102)
AVIERR_MEMORY = HRESULT($80044067); // MAKE_AVIERR(103)
AVIERR_INTERNAL = HRESULT($80044068); // MAKE_AVIERR(104)
AVIERR_BADFLAGS = HRESULT($80044069); // MAKE_AVIERR(105)
AVIERR_BADPARAM = HRESULT($8004406A); // MAKE_AVIERR(106)
AVIERR_BADSIZE = HRESULT($8004406B); // MAKE_AVIERR(107)
AVIERR_BADHANDLE = HRESULT($8004406C); // MAKE_AVIERR(108)
AVIERR_FILEREAD = HRESULT($8004406D); // MAKE_AVIERR(109)
AVIERR_FILEWRITE = HRESULT($8004406E); // MAKE_AVIERR(110)
AVIERR_FILEOPEN = HRESULT($8004406F); // MAKE_AVIERR(111)
AVIERR_COMPRESSOR = HRESULT($80044070); // MAKE_AVIERR(112)
AVIERR_NOCOMPRESSOR = HRESULT($80044071); // MAKE_AVIERR(113)
AVIERR_READONLY = HRESULT($80044072); // MAKE_AVIERR(114)
AVIERR_NODATA = HRESULT($80044073); // MAKE_AVIERR(115)
AVIERR_BUFFERTOOSMALL = HRESULT($80044074); // MAKE_AVIERR(116)
AVIERR_CANTCOMPRESS = HRESULT($80044075); // MAKE_AVIERR(117)
AVIERR_USERABORT = HRESULT($800440C6); // MAKE_AVIERR(198)
AVIERR_ERROR = HRESULT($800440C7); // MAKE_AVIERR(199)
streamtypeVIDEO = $73646976; // mmioFOURCC('v', 'i', 'd', 's')
streamtypeAUDIO = $73647561; // mmioFOURCC('a', 'u', 'd', 's')
AVIIF_KEYFRAME = $00000010;
ICTYPE_VIDEO = $63646976; {vidc}
ICMODE_COMPRESS = 1;
ICMODE_QUERY = 4;
ICM_USER = (DRV_USER + $0000);
ICM_RESERVED_LOW = (DRV_USER + $1000);
ICM_RESERVED_HIGH = (DRV_USER + $2000);
ICM_RESERVED = ICM_RESERVED_LOW;
ICM_COMPRESS_QUERY = (ICM_USER + 6); // query support for compress
ICM_CONFIGURE = (ICM_RESERVED + 10); // show the configure dialog
ICMF_CONFIGURE_QUERY = $00000001;
procedure AVIFileInit; stdcall; external 'avifil32.dll' Name 'AVIFileInit';
procedure AVIFileExit; stdcall; external 'avifil32.dll' Name 'AVIFileExit';
function AVIFileOpen; external 'avifil32.dll' Name 'AVIFileOpenA';
function AVIFileCreateStream; external 'avifil32.dll' Name 'AVIFileCreateStreamA';
function AVIStreamSetFormat; external 'avifil32.dll' Name 'AVIStreamSetFormat';
function AVIStreamReadFormat; external 'avifil32.dll' Name 'AVIStreamReadFormat';
function AVIStreamWrite; external 'avifil32.dll' Name 'AVIStreamWrite';
function AVIStreamRelease; external 'avifil32.dll' Name 'AVIStreamRelease';
function AVIFileRelease; external 'avifil32.dll' Name 'AVIFileRelease';
function AVIFileGetStream; external 'avifil32.dll' Name 'AVIFileGetStream';
function CreateEditableStream; external 'avifil32.dll' Name 'CreateEditableStream';
function AVISaveV; external 'avifil32.dll' Name 'AVISaveV';
function AVIMakeCompressedStream; external 'avifil32.dll' Name 'AVIMakeCompressedStream';
function AVIStreamInfo(pavi: PAVIStream; var psi: TAviStreamInfo; lSize: LONG): HRESULT; stdcall; external 'avifil32.dll' Name 'AVIStreamInfoA';
function AVIStreamRead(
pavi: PAVIStream;
lStart: LONG;
lSamples: LONG;
lpBuffer: Pointer;
cbBuffer: LONG;
plBytes: PInteger;
plSamples: PInteger
): HRESULT; stdcall; external 'avifil32.dll';
function AVIStreamStart(pavi: PAVIStream): LONG; stdcall; external 'avifil32.dll';
function AVIStreamLength(pavi: PAVIStream): LONG; stdcall; external 'avifil32.dll';
function EditStreamCopy(pavi: PAVIStream; var plStart, plLength: LONG; var ppResult: PAVIStream): HRESULT; stdcall; external 'avifil32.dll';
function EditStreamPaste(pavi: PAVIStream; var plPos, plLength: LONG; pstream: PAVIStream; lStart, lEnd: LONG): HRESULT; stdcall; external 'avifil32.dll';
function EditStreamSetInfo(pavi: PAVIStream; lpInfo: PAVIStreamInfo; cbInfo: LONG): HRESULT; stdcall; external 'avifil32.dll' Name 'EditStreamSetInfoA';
function ICInfo(fccType, fccHandler: DWord; lpicinfo: PICINFO): BOOL; stdcall; external 'MSVFW32.DLL';
function ICOpen(fccType, fccHandler: DWord; wMode: UINT): THandle; stdcall; external 'MSVFW32.DLL';
function ICSendMessage(hic: THandle; Msg: UINT; dw1, dw2: DWord): DWord; stdcall; external 'MSVFW32.DLL';
function ICCompressQuery(hic: THandle; lpbiInput, lpbiOutput: PBitmapInfoHeader): DWord;
begin
Result := ICSendMessage(hic, ICM_COMPRESS_QUERY, DWord(lpbiInput), DWord(lpbiOutput));
end;
function ICGetInfo(hic: THandle; PICINFO: PICINFO; cb: DWord): DWord; stdcall; external 'MSVFW32.DLL';
function ICClose(hic: THandle): DWord; stdcall; external 'MSVFW32.DLL';
function ICLocate(fccType, fccHandler: DWord; lpbiIn, lpbiOut: PBitmapInfoHeader; wFlags: Word): THandle; stdcall; external 'MSVFW32.DLL';
function ICQueryConfigure(hic: THandle): BOOL;
begin
Result := ICSendMessage(hic, ICM_CONFIGURE, DWord(-1), ICMF_CONFIGURE_QUERY) = 0;
end;
function ICConfigure(hic: THandle; HWND: HWND): DWord;
begin
Result := ICSendMessage(hic, ICM_CONFIGURE, HWND, 0);
end;
{TAVIWriter_2}
constructor TAviWriter_2.Create(AOwner: TComponent);
var
TempDir: string;
l: integer;
begin
inherited Create(AOwner);
fHeight := screen.Height div 10;
fWidth := screen.Width div 10;
fFrameTime := 1000;
fStretch := true;
fFilename := '';
Bitmaps := TList.Create;
AVIFileInit;
fFourCC := '';
fPixelFormat := pf24bit;
fAbort := false;
fCompressionQuality := 5000;
fCompOnFly := true;
fWaveFileList := TStringList.Create;
SetLength(TempDir, MAX_PATH + 1);
l := GetTempPath(MAX_PATH, PChar(TempDir));
SetLength(TempDir, l);
if copy(TempDir, Length(TempDir), 1) <> '\'
then TempDir := TempDir + '\';
TempFileName := TempDir + '~AWTemp.avi';
end;
destructor TAviWriter_2.Destroy;
var refcount: integer;
begin
Bitmaps.Free;
fWaveFileList.Free;
if fPInInfo <> nil then
FreeMem(fPInInfo);
//any junk from a previous bomb?
if Assigned(pfile) then
try
repeat
refcount := AVIFileRelease(pfile);
until refcount <= 0;
except
pfile := nil;
end;
if Assigned(fCompStream) then
AVIStreamRelease(fCompStream);
if Assigned(fPstream) then
AVIStreamRelease(fPstream);
if Assigned(VideoStream) then
AVIStreamRelease(VideoStream);
if Assigned(AudioStream) then
AVIStreamRelease(AudioStream);
if FileExists(TempFileName) then
Deletefile(TempFileName);
AVIFileExit;
inherited;
end;
procedure TAviWriter_2.Write;
var
ExtBitmap: TBitmap;
nStreams: integer;
i: integer;
Streams: APAVISTREAM;
CompOptions: APAVICompressOptions;
AVIERR: HRESULT;
refcount: integer;
begin
AudioStream := nil;
VideoStream := nil;
// If no bitmaps are on the list, raise an error.
if Bitmaps.Count < 1 then
raise Exception.Create('No bitmaps on the Bitmaps list');
// If anything on the Bitmaps TList is not a bitmap, raise
// an error.
for i := 0 to Bitmaps.Count - 1 do begin
ExtBitmap := Bitmaps[i];
if not (ExtBitmap is TBitmap)
then raise Exception.Create('Bitmaps[' + IntToStr(i)
+ '] is not a TBitmap');
end;
try
AddVideo;
if WavFileName <> ''
then AddAudio;
// Create the output file.
if WavFileName <> ''
then nStreams := 2
else nStreams := 1;
Streams[0] := VideoStream;
Streams[1] := AudioStream;
CompOptions[0] := nil;
CompOptions[1] := nil;
AVIERR := AVISaveV(PChar(filename), nil, nil, nStreams, Streams, CompOptions);
if AVIERR <> AVIERR_OK then
raise Exception.Create('Unable to write output file');
finally
if Assigned(VideoStream)
then AVIStreamRelease(VideoStream);
if Assigned(AudioStream)
then AVIStreamRelease(AudioStream);
try
repeat
refcount := AVIFileRelease(pfile);
until refcount <= 0;
except
end;
pfile := nil;
VideoStream := nil;
AudioStream := nil;
Deletefile(TempFileName);
end;
end;
procedure TAviWriter_2.AddVideo;
var
pstream: PAVIStream;
StreamInfo: TAviStreamInfo;
BitmapInfo: PBitmapInfoHeader;
BitmapInfoSize: integer;
BitmapSize: Longint;
BitmapBits: Pointer;
Bitmap: TBitmap;
ExtBitmap: TBitmap;
Samples_Written: LONG;
Bytes_Written: LONG;
AVIERR: integer;
i: integer;
begin
// Open AVI file for write
if (AVIFileOpen(pfile, PChar(TempFileName),
OF_WRITE or OF_CREATE or OF_SHARE_EXCLUSIVE, nil)
<> AVIERR_OK)
then
raise Exception.Create('Failed to create AVI video work file');
// Allocate the bitmap to which the bitmaps on the Bitmaps Tlist
// will be copied.
Bitmap := TBitmap.Create;
Bitmap.Height := Self.Height;
Bitmap.Width := Self.Width;
// Write the stream header.
try
FillChar(StreamInfo, SizeOf(StreamInfo), 0);
// Set frame rate and scale
StreamInfo.dwRate := 1000;
StreamInfo.dwScale := fFrameTime;
StreamInfo.fccType := streamtypeVIDEO;
StreamInfo.fccHandler := 0;
StreamInfo.dwFlags := 0;
StreamInfo.dwSuggestedBufferSize := 0;
StreamInfo.rcFrame.Right := Self.Width;
StreamInfo.rcFrame.Bottom := Self.Height;
// Open AVI data stream
if (AVIFileCreateStream(pfile, pstream, StreamInfo) <> AVIERR_OK) then
raise Exception.Create('Failed to create AVI video stream');
try
// Write the bitmaps to the stream.
for i := 0 to Bitmaps.Count - 1 do begin
BitmapInfo := nil;
BitmapBits := nil;
try
// Copy the bitmap from the list to the AVI bitmap,
// stretching if desired. If the caller elects not to
// stretch, use the first pixel in the bitmap as a
// background color in case either the height or
// width of the source is smaller than the output.
// If Draw fails, do a StretchDraw.
ExtBitmap := Bitmaps[i];
if fStretch
then Bitmap.Canvas.stretchdraw
(Rect(0, 0, Self.Width, Self.Height), ExtBitmap)
else try
with Bitmap.Canvas do begin
Brush.Color := ExtBitmap.Canvas.Pixels[0, 0];
Brush.Style := bsSolid;
FillRect(Rect(0, 0, Bitmap.Width, Bitmap.Height));
draw(0, 0, ExtBitmap);
end;
except
Bitmap.Canvas.stretchdraw
(Rect(0, 0, Self.Width, Self.Height), ExtBitmap);
end;
// Determine size of DIB
InternalGetDIBSizes(Bitmap.Handle, BitmapInfoSize, BitmapSize, pf8bit);
if (BitmapInfoSize = 0) then
raise Exception.Create('Failed to retrieve bitmap info');
// Get DIB header and pixel buffers
GetMem(BitmapInfo, BitmapInfoSize);
GetMem(BitmapBits, BitmapSize);
InternalGetDIB
(Bitmap.Handle, 0, BitmapInfo^, BitmapBits^, pf8bit);
// On the first time through, set the stream format.
if i = 0 then
if (AVIStreamSetFormat(pstream, 0, BitmapInfo, BitmapInfoSize) <> AVIERR_OK) then
raise Exception.Create('Failed to set AVI stream format');
// Write frame to the video stream
AVIERR :=
AVIStreamWrite(pstream, i, 1, BitmapBits, BitmapSize, AVIIF_KEYFRAME,
Samples_Written, Bytes_Written);
if AVIERR <> AVIERR_OK then
raise Exception.Create
('Failed to add frame to AVI.')
finally
if (BitmapInfo <> nil) then
FreeMem(BitmapInfo);
if (BitmapBits <> nil) then
FreeMem(BitmapBits);
end;
end;
// Create the editable VideoStream from pStream.
if CreateEditableStream(VideoStream, pstream) <> AVIERR_OK then
raise Exception.Create
('Could not create Video Stream');
finally
AVIStreamRelease(pstream);
end;
finally
Bitmap.Free;
end;
end;
procedure TAviWriter_2.AddAudio;
var
InputFile: PAVIFile;
hr: HRESULT;
InputStream: PAVIStream;
begin
// Open the audio file.
try
hr := AVIFileOpen(InputFile, PChar(WavFileName), OF_READ, nil);
if hr <> 0 then
fWavFileName := '';
case hr of
0: ;
AVIERR_BADFORMAT: raise Exception.Create('The file could not be read, indicating a corrupt file or an unrecognized format.');
AVIERR_MEMORY: raise Exception.Create('The file could not be opened because of insufficient memory.');
AVIERR_FILEREAD: raise Exception.Create('A disk error occurred while reading the audio file.');
AVIERR_FILEOPEN: raise Exception.Create('A disk error occurred while opening the audio file.');
REGDB_E_CLASSNOTREG: raise Exception.Create('According to the registry, the type of audio file specified in AVIFileOpen does not have a handler to process it.');
else raise Exception.Create('Unknown error opening audio file');
end;
// Open the audio stream.
if (AVIFileGetStream(InputFile, InputStream, streamtypeAUDIO, 0) <> AVIERR_OK) then
raise Exception.Create('Unable to get audio stream');
try
// Create AudioStream as a copy of InputStream
if (CreateEditableStream(AudioStream, InputStream) <> AVIERR_OK) then
raise Exception.Create('Failed to create editable AVI audio stream');
finally
AVIStreamRelease(InputStream);
end;
finally
AVIFileRelease(InputFile);
end;
end;
function SortCompare(AList: TStringList; Index1, Index2: integer): integer;
begin
if integer(AList.Objects[Index1]) < integer(AList.Objects[Index2]) then
Result := -1 else
if integer(AList.Objects[Index1]) > integer(AList.Objects[Index2]) then
Result := 1 else
Result := 0;
end;
function IsCompatible(si1, si2: TAviStreamInfo): boolean;
//checks compatibility of 2 audiostreams
begin
Result := false;
if si1.fccType <> si2.fccType then exit;
if si1.dwScale <> si2.dwScale then exit;
if si1.dwRate <> si2.dwRate then exit;
if si1.dwSampleSize <> si2.dwSampleSize then exit;
Result := true;
end;
function IsCompatibleWavefmt(w1, w2: TWaveFormatEx): boolean;
begin
Result := (w1.nChannels = w2.nChannels) and (w1.wBitsPerSample = w2.wBitsPerSample);
end;
procedure TAviWriter_2.AddAudioMod;
var
InputFile: PAVIFile;
InputStream, AudStream: PAVIStream;
hr: HRESULT;
OldInfo, AudStreamInfo: TAviStreamInfo;
fsize, fNewSize: integer;
pformat: Pointer;
i, j, il, jp, jmin, ss: integer;
SampleSize: integer;
pSample: Pointer;
SamplesWritten, BytesWritten: integer;
SamplesSoFar, l: Cardinal;
Start, NextStart: Cardinal;
SampPerSec: double;
pSilence, pModSilence: PByteArray;
Wavefmt, NewWavefmt: TWaveFormatEx;
begin
if fWaveFileList.Count = 0 then
if fWavFileName <> '' then
AddWaveFile(fWavFileName, 0);
if fWaveFileList.Count = 0 then
exit;
fWaveFileList.CustomSort(SortCompare);
//sort by delay
AudStream := nil;
InputFile := nil;
InputStream := nil;
try
SamplesSoFar := 0;
for i := 0 to fWaveFileList.Count - 1 do
begin
if InputStream <> nil then AVIStreamRelease(InputStream);
if InputFile <> nil then AVIFileRelease(InputFile);
InputFile := nil;
InputStream := nil;
hr := AVIFileOpen(InputFile, PChar(fWaveFileList.Strings[i]), OF_READ, nil);
Assert(hr = 0, 'FileOpen failed. Err: $' + IntToHex(hr, 8));
// Open the audio stream.
hr := AVIFileGetStream(InputFile, InputStream, streamtypeAUDIO, 0);
Assert(hr = 0, 'GetStream failed. Err: $' + IntToHex(hr, 8));
hr := AVIStreamInfo(InputStream, OldInfo, SizeOf(OldInfo));
Assert(hr = 0, 'StreamInfo failed. Err: $' + IntToHex(hr, 8));
if i > 0 then
if not IsCompatible(OldInfo, AudStreamInfo) then
Continue; //no sense in writing combined stream wouldn't play. try next one.
hr := AVIStreamReadFormat(InputStream, 0, nil, fsize);
Assert(hr = 0, 'ReadFormat failed. Err: $' + IntToHex(hr, 8));
GetMem(pformat, fsize);
try
hr := AVIStreamReadFormat(InputStream, 0, pformat, fsize);
Assert(hr = 0, 'ReadFormat failed. Err: $' + IntToHex(hr, 8));
NewWavefmt := TWaveFormatEx(pformat^);
finally
FreeMem(pformat);
end;
if i > 0 then
if (not IsCompatibleWavefmt(Wavefmt, NewWavefmt)) then
Continue; //incompatible files, skip
with OldInfo do
SampPerSec := dwRate / dwScale;
Start := trunc(1 / 1000 * SampPerSec * integer(fWaveFileList.Objects[i]));
if i = 0 then
begin
AudStreamInfo := OldInfo;
//AudStreamInfo.dwInitialFrames := round(0.75 * 1000 / fFrameTime); //not sure about that one.
AudStreamInfo.dwLength := 0;
AudStreamInfo.dwStart := 0;//FirstStart;
//the rest should be OK from copying from first stream.
//create the audiostream
hr := AVIFileCreateStream(pfile, AudStream, AudStreamInfo);
Assert(hr = 0, 'CreateStream failed. Err: $' + IntToHex(hr, 8));
//write format to first sample
hr := AVIStreamReadFormat(InputStream, 0, nil, fsize);
Assert(hr = 0, 'ReadFormat failed. Err: $' + IntToHex(hr, 8));
GetMem(pformat, fsize);
try
hr := AVIStreamReadFormat(InputStream, 0, pformat, fsize);
Assert(hr = 0, 'ReadFormat failed. Err: $' + IntToHex(hr, 8));
hr := AVIStreamSetFormat(AudStream, 0, pformat, fsize);
Assert(hr = 0, 'SetFormat failed. Err: $' + IntToHex(hr, 8));
Wavefmt := TWaveFormatEx(pformat^);
finally
FreeMem(pformat);
end;
end;
if Start > SamplesSoFar then
//if i > 0 then
begin //pad with "silent" samples
jmin := SamplesSoFar;
pSilence := GetSilence(AudStreamInfo, Wavefmt, fsize);
if pSilence <> nil then
begin
if fsize < integer(AudStreamInfo.dwSampleSize) then
fNewSize := AudStreamInfo.dwSampleSize
else
fNewSize := fsize;
GetMem(pModSilence, fNewSize);
try
ss := fNewSize div fsize;
//write pSilence into pModSilence (fNewsize div fSize) times
for j := 0 to ss - 1 do
for jp := 0 to fsize - 1 do
pModSilence^[ss * j + jp] := pSilence^[jp];
j := jmin;
il := fNewSize div integer(AudStreamInfo.dwSampleSize);
while j + il < integer(Start) do
//dunno, the avistream things take integers,
//the format has cardinals. That means,
//it won't work anyway above the integer range.
//So I can typecast these guys anywhich way I like.
begin
jp := j;
hr := AVIStreamWrite(AudStream, jp, il, pModSilence, fNewSize, 0, SamplesWritten, BytesWritten);
Assert(hr = 0, 'StreamWrite failed. Err: $' + IntToHex(hr, 8));
j := jp + il;
inc(SamplesSoFar, il);
end;
il := Start - Cardinal(j);
if il > 0 then
begin
jp := j;
hr := AVIStreamWrite(AudStream, jp, il, pModSilence, fNewSize, 0, SamplesWritten, BytesWritten);
Assert(hr = 0, 'StreamWrite failed. Err: $' + IntToHex(hr, 8));
inc(SamplesSoFar, il);
end;
finally
FreeMem(pModSilence);
end;
end;
end;
l := AVIStreamLength(InputStream);
if i < fWaveFileList.Count - 1 then
begin
NextStart := trunc(1 / 1000 * SampPerSec * integer(fWaveFileList.Objects[i + 1]));
if NextStart < Start + l then
l := NextStart - Start; //shorten audio length
end;
//write next audiofile into audstream.
//if the silence didn't work, it goes at the end of
//the previous file.
SampleSize := l * AudStreamInfo.dwSampleSize;
GetMem(pSample, SampleSize);
try
hr := AVIStreamRead(InputStream, OldInfo.dwStart, l, pSample, SampleSize, nil, nil);
Assert(hr = 0, 'StreamRead failed. Err: $' + IntToHex(hr, 8));
hr := AVIStreamWrite(AudStream, SamplesSoFar, l, pSample, SampleSize, 0, SamplesWritten, BytesWritten);
Assert(hr = 0, 'StreamWrite failed. Err: $' + IntToHex(hr, 8));
inc(SamplesSoFar, l);
finally
FreeMem(pSample);
end;
end; //for i looping through the wavefilelist
finally
if InputStream <> nil then
AVIStreamRelease(InputStream);
if InputFile <> nil then
AVIFileRelease(InputFile);
if AudStream <> nil then
AVIStreamRelease(AudStream);
end;
end;
// --------------
// InternalGetDIB
// --------------
// Converts a bitmap to a DIB of a specified PixelFormat.
//
// Parameters:
// Bitmap The handle of the source bitmap.
// Pal The handle of the source palette.
// BitmapInfo The buffer that will receive the DIB's TBitmapInfo structure.
// A buffer of sufficient size must have been allocated prior to
// calling this function.
// Bits The buffer that will receive the DIB's pixel data.
// A buffer of sufficient size must have been allocated prior to
// calling this function.
// PixelFormat The pixel format of the destination DIB.
//
// Returns:
// True on success, False on failure.
//
// Note: The InternalGetDIBSizes function can be used to calculate the
// necessary sizes of the BitmapInfo and Bits buffers.
//
function TAviWriter_2.InternalGetDIB(Bitmap: HBITMAP; Palette: Hpalette;
var BitmapInfo; var Bits; PixelFormat: TPixelFormat): boolean;
// From graphics.pas, "optimized" for our use
var
OldPal: Hpalette;
DC: HDC;
begin
InitializeBitmapInfoHeader(Bitmap, TBitmapInfoHeader(BitmapInfo), PixelFormat);
OldPal := 0;
DC := CreateCompatibleDC(0);
try
if (Palette <> 0) then
begin
OldPal := SelectPalette(DC, Palette, false);
realizepalette(DC);
end;
GDIFlush;
Result := (GetDIBits(DC, Bitmap, 0, abs(TBitmapInfoHeader(BitmapInfo).biHeight),
@Bits, TBitmapInfo(BitmapInfo), DIB_RGB_COLORS) <> 0);
finally
if (OldPal <> 0) then
SelectPalette(DC, OldPal, false);
DeleteDC(DC);
end;
end;
// -------------------
// InternalGetDIBSizes
// -------------------
// Calculates the buffer sizes nescessary for convertion of a bitmap to a DIB
// of a specified PixelFormat.
// See the GetDIBSizes API function for more info.
//
// Parameters:
// Bitmap The handle of the source bitmap.
// InfoHeaderSize
// The returned size of a buffer that will receive the DIB's
// TBitmapInfo structure.
// ImageSize The returned size of a buffer that will receive the DIB's
// pixel data.
// PixelFormat The pixel format of the destination DIB.
//
procedure TAviWriter_2.InternalGetDIBSizes(Bitmap: HBITMAP; var InfoHeaderSize: integer;
var ImageSize: Longint; PixelFormat: TPixelFormat);
// From graphics.pas, "optimized" for our use
var
Info: TBitmapInfoHeader;
begin
InitializeBitmapInfoHeader(Bitmap, Info, PixelFormat);
// Check for palette device format
if (Info.biBitCount > 8) then
begin
// Header but no palette
InfoHeaderSize := SizeOf(TBitmapInfoHeader);
if ((Info.biCompression and BI_BITFIELDS) <> 0) then
inc(InfoHeaderSize, 12);
end else
// Header and palette
InfoHeaderSize := SizeOf(TBitmapInfoHeader) + SizeOf(TRGBQuad) * (1 shl Info.biBitCount);
ImageSize := Info.biSizeImage;
end;
// --------------------------
// InitializeBitmapInfoHeader
// --------------------------
// Fills a TBitmapInfoHeader with the values of a bitmap when converted to a
// DIB of a specified PixelFormat.
//
// Parameters:
// Bitmap The handle of the source bitmap.
// Info The TBitmapInfoHeader buffer that will receive the values.
// PixelFormat The pixel format of the destination DIB.
//
{$IFDEF BAD_STACK_ALIGNMENT}
// Disable optimization to circumvent optimizer bug...
{$IFOPT O+}
{$DEFINE O_PLUS}
{$O-}
{$ENDIF}
{$ENDIF}
procedure TAviWriter_2.InitializeBitmapInfoHeader(Bitmap: HBITMAP; var Info: TBitmapInfoHeader;
PixelFormat: TPixelFormat);
// From graphics.pas, "optimized" for our use
var
DIB: TDIBSection;
Bytes: integer;
function AlignBit(Bits, BitsPerPixel, Alignment: Cardinal): Cardinal;
begin
Dec(Alignment);
Result := ((Bits * BitsPerPixel) + Alignment) and not Alignment;
Result := Result shr 3;
end;
begin
DIB.dsbmih.biSize := 0;
Bytes := GetObject(Bitmap, SizeOf(DIB), @DIB);
if (Bytes = 0) then
raise Exception.Create('Invalid bitmap');
// Error(sInvalidBitmap);
if (Bytes >= (SizeOf(DIB.dsBm) + SizeOf(DIB.dsbmih))) and
(DIB.dsbmih.biSize >= SizeOf(DIB.dsbmih)) then
Info := DIB.dsbmih
else
begin
FillChar(Info, SizeOf(Info), 0);
with Info, DIB.dsBm do
begin
biSize := SizeOf(Info);
biWidth := bmWidth;
biHeight := bmHeight;
end;
end;
case PixelFormat of
pf1Bit: Info.biBitCount := 1;
pf4Bit: Info.biBitCount := 4;
pf8bit: Info.biBitCount := 8;
pf24bit: Info.biBitCount := 24;
else
// Error(sInvalidPixelFormat);
raise Exception.Create('Invalid pixel foramt');
// Info.biBitCount := DIB.dsbm.bmBitsPixel * DIB.dsbm.bmPlanes;
end;
Info.biPlanes := 1;
Info.biCompression := BI_RGB; // Always return data in RGB format
Info.biSizeImage := AlignBit(Info.biWidth, Info.biBitCount, 32) * Cardinal(abs(Info.biHeight));
end;
{$IFDEF O_PLUS}
{$O+}
{$UNDEF O_PLUS}
{$ENDIF}
procedure TAviWriter_2.SetWavFileName(value: string);
begin
if LowerCase(fWavFileName) <> LowerCase(value)
then if value <> ''
then if LowerCase(ExtractFileExt(value)) <> '.wav'
then raise Exception.Create('WavFileName must name a file '
+ 'with the .wav extension')
else fWavFileName := value
else fWavFileName := value;
end;
procedure TAviWriter_2.InternalAddFrame(const Bitmap: TBitmap; Key: boolean);
var
Samples_Written: LONG;
Bytes_Written: LONG;
AVIERR: integer;
DIB: TDIBSection;
DIBErr: integer;
flag: DWord;
begin
// On the first time through, set the stream format.
// A bit roundabout so the colors can be retrieved
// in case of pixelformats <=pf8bit, but I'd rather
// be safe.
if fFrameCount = 0 then
begin
InitStreamFormat(Bitmap);
end;
FillChar(DIB, SizeOf(DIB), 0);
DIBErr := GetObject(Bitmap.Handle, SizeOf(DIB), @DIB);
if DIBErr = 0 then
begin
//fire event for troubleshooting
if Assigned(fOnBadBitmap) then
fOnBadBitmap(Self, Bitmap, SizeOf(DIB.dsbmih), DIB.dsbmih.biSizeImage);
raise Exception.Create('Failed to retrieve bitmap header and pixels. Err: ' + IntToStr(GetLastError));
end;
// Write frame to the video stream
if Key then
flag := AVIIF_KEYFRAME
else
flag := 0;
try
AVIERR :=
AVIStreamWrite(fCompStream, fFrameCount, 1, DIB.dsBm.bmBits, DIB.dsbmih.biSizeImage, flag,
Samples_Written, Bytes_Written);
except
AVIERR := AVIERR_ERROR; //for the DivX unhandled floating point..
end;
if AVIERR <> AVIERR_OK then
raise Exception.Create('Failed to add Frame. Err: ' + IntToHex(AVIERR, 8));
inc(fFrameCount);
if Assigned(fOnProgress) then
if (fFrameCount mod 20 = 0) then
fOnProgress(Self, fFrameCount, fAbort);
end;
procedure TAviWriter_2.FinalizeVideo;
begin
fInitialized := false;
fFinalized := true;
//Doesn't do much anymore...
end;
procedure TAviWriter_2.InitVideo;
var S, Workfile: string;
AVIERR: HRESULT;
begin
VideoStream := nil;
fCompStream := nil;
fPstream := nil;
AudioStream := nil;
fAbort := false;
pfile := nil;
if fPixelFormat = pfDevice then
begin
fAbort := true;
raise Exception.Create('For adding frames on the fly the pixelformat must be <> pfDevice');
exit;
end;
if fCompOnFly then
Workfile := fFilename
else
Workfile := TempFileName;
if FileExists(Workfile) then
if not Deletefile(Workfile) then
raise Exception.Create('Could not delete ' + Workfile + ' file might be in use. Try to close the folder if it''s open in Explorer');
//need to start with new files,
//otherwise the compression doesn't
//work, and the files just get larger and larger
// Open AVI file for write
AVIERR := AVIFileOpen(pfile, PChar(Workfile),
OF_WRITE or OF_CREATE, nil);
//Shareexclusive causes nothing but trouble on an exception
if AVIERR <> AVIERR_OK
then
raise Exception.Create('Failed to create AVI video file. Err: $' + IntToHex(AVIERR, 8));
// Write the stream header.
FillChar(fStreamInfo, SizeOf(fStreamInfo), 0);
// Set frame rate and scale
fStreamInfo.dwRate := 1000;
fStreamInfo.dwScale := fFrameTime;
fStreamInfo.fccType := streamtypeVIDEO;
S := fFourCC;
if S = '' then
fStreamInfo.fccHandler := 0
else
fStreamInfo.fccHandler := mmioStringToFOURCC(PChar(S), 0);
fStreamInfo.dwQuality := fCompressionQuality;
fStreamInfo.dwFlags := 0;
fStreamInfo.dwSuggestedBufferSize := 0;
fStreamInfo.rcFrame.Right := Self.Width;
fStreamInfo.rcFrame.Bottom := Self.Height;
// Open AVI data stream
if (AVIFileCreateStream(pfile, fPstream, fStreamInfo) <> AVIERR_OK) then
raise Exception.Create('Failed to create AVI video stream');
//the initialization of the compressed stream needs to
//be deferred until the first frame comes in.
fFrameCount := 0;
fInitialized := true;
end;
function TAviWriter_2.AviSaveCallback(i: integer): LONG; pascal;
begin
if Assigned(fOnProgress) then fOnProgress(Self, trunc(1 / 100 * fFrameCount * i), fAbort);
if fAbort then
Result := AVIERR_USERABORT
else
Result := AVIERR_OK;
end;
procedure TAviWriter_2.WriteAvi;
type
TCallbackThunk = packed record
POPEDX: byte;
MOVEAX: byte;
SelfPtr: Pointer;
PUSHEAX: byte;
PUSHEDX: byte;
JMP: byte;
JmpOffset: integer;
end;
var
Callback: TCallbackThunk;
nStreams: integer;
Streams: APAVISTREAM;
CompOptions: APAVICompressOptions;
AVIERR: HRESULT;
refcount: integer;
begin
if fAbort or (not fFinalized) then
begin
if fPstream <> nil then
AVIStreamRelease(fPstream);
if fCompStream <> nil then
AVIStreamRelease(fCompStream);
fCompStream := nil;
fPstream := nil;
fWaveFileList.Clear;
try
repeat
refcount := AVIFileRelease(pfile);
until refcount <= 0;
pfile := nil;
except
pfile := nil;
end;
if not fFinalized then
raise Exception.Create('Video must be finalized');
exit;
end;
try
if not fCompOnFly then
if fWavFileName = '' then
if fWaveFileList.Count > 0 then
fWavFileName := fWaveFileList.Strings[0];
if fCompOnFly then
AddAudioMod
else
if WavFileName <> '' then
AddAudio;
if not fCompOnFly then
begin
if FileExists(filename) then
if not Deletefile(filename) then
raise Exception.Create('File ' + ExtractFileName(filename) + ' could not be deleted. It could be in use by another application.');
if WavFileName <> ''
then nStreams := 2
else nStreams := 1;
Streams[0] := fCompStream;
Streams[1] := AudioStream;
if fFourCC = '' then
CompOptions[0] := nil
else
CompOptions[0] := @AviCompressoptions;
CompOptions[1] := nil;
//trick a method into a callback.
//from SysUtils.TLanguages.Create
Callback.POPEDX := $5A;
Callback.MOVEAX := $B8;
Callback.SelfPtr := Self;
Callback.PUSHEAX := $50;
Callback.PUSHEDX := $52;
Callback.JMP := $E9;
Callback.JmpOffset := integer(@TAviWriter_2.AviSaveCallback) - integer(@Callback.JMP) - 5;
AVIERR := AVISaveV(PChar(filename), nil, TAVISaveCallback(@Callback), nStreams, Streams, CompOptions);
if AVIERR <> AVIERR_OK then
if not fAbort then
raise Exception.Create('Unable to write output file. Error ' + IntToHex(AVIERR, 8));
end;
finally
if fCompStream <> nil then
AVIStreamRelease(fCompStream);
if fPstream <> nil then
AVIStreamRelease(fPstream);
if AudioStream <> nil then
AVIStreamRelease(AudioStream);
AudioStream := nil;
fCompStream := nil;
fPstream := nil;
fWaveFileList.Clear;
if FileExists(TempFileName) then
Deletefile(TempFileName);
try
repeat
refcount := AVIFileRelease(pfile);
until refcount <= 0;
pfile := nil;
except
pfile := nil;
end;
fFinalized := false;
end;
end;
const
BitCounts: array[pf1Bit..pf32Bit] of byte = (1, 4, 8, 16, 16, 24, 32);
function FourCCToString(f: DWord): TFourCC;
var
S, s1: string;
b: byte;
c: Char;
begin
SetLength(Result, 4);
S := IntToHex(f, 8);
s1 := '$' + copy(S, 7, 2);
b := StrToInt(s1);
c := chr(b);
Result[1] := c;
Result[2] := chr(StrToInt('$' + copy(S, 5, 2)));
Result[3] := chr(StrToInt('$' + copy(S, 3, 2)));
Result[4] := chr(StrToInt('$' + copy(S, 1, 2)));
//strings are easier than math :)
end;
procedure TAviWriter_2.Compressorlist(const List: TStrings);
var
ii: TICINFO;
i: DWord;
ic: THandle;
BitmapInfoHeader: TBitmapInfoHeader;
Name: WideString;
j: integer;
begin
List.Clear;
List.add('No Compression');
FillChar(BitmapInfoHeader, SizeOf(BitmapInfoHeader), 0);
with BitmapInfoHeader do
begin
biSize := SizeOf(BitmapInfoHeader);
biWidth := fWidth;
biHeight := fHeight;
biPlanes := 1;
biCompression := BI_RGB;
biBitCount := BitCounts[fPixelFormat];
end;
ii.dwSize := SizeOf(ii);
for i := 0 to 200 do //what's a safe number to get all?
begin
if ICInfo(ICTYPE_VIDEO, i, @ii) then
begin
ic := ICOpen(ICTYPE_VIDEO, ii.fccHandler, ICMODE_QUERY);
try
if ic <> 0 then
begin
if ICCompressQuery(ic, @BitmapInfoHeader, nil) = 0 then
begin
ICGetInfo(ic, @ii, SizeOf(ii));
//can the following be done any simpler?
Name := '';
for j := 0 to 15 do
Name := Name + ii.szName[j];
List.add(FourCCToString(ii.fccHandler) + ' ' + string(Name));
end;
end;
finally
ICClose(ic);
end;
end;
end;
end;
procedure TAviWriter_2.SetCompression(FourCC: TFourCC);
var S: string;
ic: THandle;
BitmapInfoHeader: TBitmapInfoHeader;
begin
fFourCC := '';
if FourCC = '' then
exit;
FillChar(BitmapInfoHeader, SizeOf(BitmapInfoHeader), 0);
with BitmapInfoHeader do
begin
biSize := SizeOf(BitmapInfoHeader);
biWidth := fWidth;
biHeight := fHeight;
biPlanes := 1;
biCompression := BI_RGB;
biBitCount := BitCounts[fPixelFormat];
end;
S := FourCC;
ic := ICLocate(ICTYPE_VIDEO, mmioStringToFOURCC(PChar(S), 0), @BitmapInfoHeader, nil,
ICMODE_COMPRESS);
if ic <> 0 then
begin
fFourCC := FourCC;
ICClose(ic);
end
else
raise Exception.Create('No compressor for ' + FourCC + ' available');
end;
procedure TAviWriter_2.AddStillImage(const ABmp: TBitmap; Showtime: integer);
var i: integer;
Samples_Written: LONG;
Bytes_Written: LONG;
AVIERR: HRESULT;
Bitmap: TBitmap;
r1, r2: TRect;
begin
if fAbort then
exit;
if not fInitialized then
raise Exception.Create('Video must be initialized.');
if (fFourCC = '') or (not fCompOnFly) then
begin
AddFrame(ABmp);
for i := 1 to (Showtime div FrameTime) do
//might be a tad longer than showtime
begin
// Write empty frame to the video stream
AVIERR :=
AVIStreamWrite(fCompStream, fFrameCount, 1, nil, 0, 0,
Samples_Written, Bytes_Written);
if AVIERR <> AVIERR_OK then
raise Exception.Create
('Failed to add frame to AVI. Err='
+ IntToHex(AVIERR, 8));
inc(fFrameCount);
if (fFrameCount mod 10 = 0) then
if Assigned(fOnProgress) then
fOnProgress(Self, fFrameCount, fAbort);
end;
end
else
begin
Bitmap := TBitmap.Create;
try
Bitmap.PixelFormat := fPixelFormat;
//need to force the same for all
Bitmap.Width := Self.Width;
Bitmap.Height := Self.Height;
Bitmap.Canvas.Lock;
try
ABmp.Canvas.Lock;
try
if fStretch
then Bitmap.Canvas.stretchdraw
(Rect(0, 0, Self.Width, Self.Height), ABmp)
else
//center image on black background
with Bitmap.Canvas do begin
Brush.Color := clBlack;
Brush.Style := bsSolid;
FillRect(ClipRect);
r1 := Rect(0, 0, ABmp.Width, ABmp.Height);
r2 := r1;
OffsetRect(r2, (Width - ABmp.Width) div 2, (Height - ABmp.Height) div 2);
CopyRect(r2, ABmp.Canvas, r1);
end;
finally
ABmp.Canvas.Unlock;
end;
finally
Bitmap.Canvas.Unlock;
end;
for i := 0 to (Showtime div FrameTime) do
InternalAddFrame(Bitmap, true);
finally
Bitmap.Free;
end;
end;
end;
procedure TAviWriter_2.SetCompressionQuality(q: integer);
begin
fCompressionQuality := q;
end;
procedure TAviWriter_2.ShowCompressorDialog(ADialogParent: TWinControl);
var ic: THandle;
S: string;
begin
if fFourCC = '' then
exit;
S := fFourCC;
ic := ICOpen(ICTYPE_VIDEO, mmioStringToFOURCC(PChar(S), 0), ICMODE_QUERY);
try
if ic <> 0 then
begin
if ICQueryConfigure(ic) then
ICConfigure(ic, ADialogParent.Handle);
end;
finally
ICClose(ic);
end;
end;
procedure TAviWriter_2.SetPixelFormat(const value: TPixelFormat);
begin
if not (value in [pf1Bit, pf4Bit, pf8bit, pf24bit, pf32Bit]) then
raise Exception.Create('Pixelformat not supported');
fPixelFormat := value;
end;
procedure TAviWriter_2.InitStreamFormat(const bm: TBitmap);
var DIB: TDIBSection;
Bits: Pointer;
DIBErr: integer;
S: string;
begin
FillChar(DIB, SizeOf(DIB), 0);
DIBErr := GetObject(bm.Handle, SizeOf(DIB), @DIB);
if DIBErr = 0 then
begin
//fire event for troubleshooting
if Assigned(fOnBadBitmap) then
fOnBadBitmap(Self, bm, SizeOf(DIB.dsbmih), DIB.dsbmih.biSizeImage);
raise Exception.Create('Failed to retrieve bitmap header and pixels. Err: ' + IntToStr(GetLastError));
end;
if fPInInfo <> nil then
FreeMem(fPInInfo);
fPInInfo := nil;
fInInfoSize := SizeOf(TBitmapInfoHeader);
if DIB.dsbmih.biBitCount <= 8 then
fInInfoSize := fInInfoSize + SizeOf(TRGBQuad) * (1 shl DIB.dsbmih.biBitCount);
GetMem(fPInInfo, fInInfoSize);
GetMem(Bits, DIB.dsbmih.biSizeImage);
try
if not GetDIB(bm.Handle, 0, fPInInfo^, Bits^)
then raise Exception.Create('Failed to retrieve bitmap info');
finally
FreeMem(Bits);
//fPInInfo^ needs to stay around
end;
FillChar(AviCompressoptions, SizeOf(AviCompressoptions), 0);
if fFourCC <> '' then
begin
with AviCompressoptions do
begin
fccType := streamtypeVIDEO;
S := fFourCC;
fccHandler := mmioStringToFOURCC(PChar(S), 0);
dwKeyFrameEvery := round(1000 / fFrameTime);
dwQuality := fCompressionQuality;
dwFlags := AVICOMPRESSF_KEYFRAMES or AVICOMPRESSF_VALID;
lpFormat := fPInInfo;
cbFormat := fInInfoSize;
end;
if fCompOnFly then
begin
if AVIMakeCompressedStream(fCompStream, fPstream, @AviCompressoptions, nil) <> AVIERR_OK then
raise Exception.Create('Failed to create compressed stream');
end
else
begin
fCompStream := fPstream;
fPstream := nil;
end;
end
else
begin
fCompStream := fPstream;
fPstream := nil;
end;
if (AVIStreamSetFormat(fCompStream, 0, fPInInfo, fInInfoSize) <> AVIERR_OK) then
raise Exception.Create('Failed to set AVI stream format');
end;
procedure TAviWriter_2.AddWaveFile(const filename: string; Delay: integer);
begin
if LowerCase(ExtractFileExt(filename)) <> '.wav'
then raise Exception.Create('WavFileName must name a file '
+ 'with the .wav extension')
else
fWaveFileList.AddObject(filename, TObject(Delay))
end;
procedure TAviWriter_2.AddFrame(const ABmp: TBitmap);
var Bitmap: TBitmap;
r1, r2: TRect;
begin
if fAbort then
exit;
if not fInitialized then
raise Exception.Create('Video must be initialized.');
Bitmap := TBitmap.Create;
try
Bitmap.PixelFormat := fPixelFormat;
//need to force the same for all
Bitmap.Width := Self.Width;
Bitmap.Height := Self.Height;
Bitmap.Canvas.Lock;
try
ABmp.Canvas.Lock;
try
if fStretch
then Bitmap.Canvas.stretchdraw
(Rect(0, 0, Self.Width, Self.Height), ABmp)
else
//center image on black background
with Bitmap.Canvas do begin
Brush.Color := clBlack;
Brush.Style := bsSolid;
FillRect(ClipRect);
r1 := Rect(0, 0, ABmp.Width, ABmp.Height);
r2 := r1;
OffsetRect(r2, (Width - ABmp.Width) div 2, (Height - ABmp.Height) div 2);
CopyRect(r2, ABmp.Canvas, r1);
end;
finally
ABmp.Canvas.Unlock;
end;
finally
Bitmap.Canvas.Unlock;
end;
InternalAddFrame(Bitmap, true);
finally
Bitmap.Free;
end;
end;
end.
|
unit NtUtils.ErrorMsg;
interface
uses
Ntapi.ntdef;
// Converts common error codes to strings, for example:
// 1314 => "ERROR_PRIVILEGE_NOT_HELD"
// $C00000BB => "STATUS_NOT_SUPPORTED"
// Returns empty string if the name is not found.
function NtxpWin32ErrorToString(Code: Cardinal): String;
function NtxpStatusToString(Status: NTSTATUS): String;
// The same as above, but on unknown errors returns their decimal/hexadecimal
// representations.
function NtxWin32ErrorToString(Code: Cardinal): String;
function NtxStatusToString(Status: NTSTATUS): String;
// Converts common error codes to their short descriptions, for example:
// 1314 => "Privilege not held"
// $C00000BB => "Not supported"
// Returns empty string if the name is not found.
function NtxWin32ErrorDescription(Code: Cardinal): String;
function NtxStatusDescription(Status: NTSTATUS): String;
// Retrieves a full description of a native error.
function NtxFormatErrorMessage(Status: NTSTATUS): String;
implementation
uses
Ntapi.ntldr, Winapi.WinBase, System.SysUtils, DelphiUtils.Strings,
Ntapi.ntstatus;
{$R 'NtUtils.ErrorMsg.res' 'NtUtils.ErrorMsg.rc'}
const
{
The resource file contains the names of some common Win32 Errors and
NTSTATUS values. To fit into the format of the .rc file each category
(i.e. Win32, NT Success, NT Information, NT Warning, and NT Error) was
shifted, so it starts from the values listed above. Each group of values
can contain the maximum count of RC_STATUS_EACH_MAX - 1 items to make sure
they don't overlap.
}
RC_STATUS_SIFT_WIN32 = $8000;
RC_STATUS_SIFT_NT_SUCCESS = $9000; // Success severity
RC_STATUS_SIFT_NT_INFO = $A000; // Informational severity
RC_STATUS_SIFT_NT_WARNING = $B000; // Warning severity
RC_STATUS_SIFT_NT_ERROR = $C000; // Error severity
RC_STATUS_SIFT_NT_FACILITIES = $D000; // Error severity with non-zero facility
RC_STATUS_EACH_MAX = $1000;
RC_FACILITY_SHIFT_RPC_RUNTIME = $0; // FACILITY_RPC_RUNTIME
RC_FACILITY_SHIFT_RPC_STUBS = $100; // FACILITY_RPC_STUBS
RC_FACILITY_SHIFT_TRANSACTION = $200; // FACILITY_TRANSACTION
RC_FACILITY_EACH_MAX = $100;
function NtxpWin32ErrorToString(Code: Cardinal): String;
var
Buf: PWideChar;
begin
// Make sure the error is within the range
if Code >= RC_STATUS_EACH_MAX then
Exit('');
// Shift it to obtain the resource index
Code := Code or RC_STATUS_SIFT_WIN32;
// Extract the string representation
SetString(Result, Buf, LoadStringW(HInstance, Code, Buf));
end;
function NtxpStatusToString(Status: NTSTATUS): String;
var
ResIndex: Cardinal;
Buf: PWideChar;
begin
Result := '';
// Clear bits that indicate severity and facility
ResIndex := Status and $3000FFFF;
if NT_FACILITY(Status) = FACILITY_NONE then
begin
// Make sure the substatus is within the range
if ResIndex >= RC_STATUS_EACH_MAX then
Exit;
// Shift it to obtain a resource index
case NT_SEVERITY(Status) of
SEVERITY_SUCCESS: ResIndex := ResIndex or RC_STATUS_SIFT_NT_SUCCESS;
SEVERITY_INFORMATIONAL: ResIndex := ResIndex or RC_STATUS_SIFT_NT_INFO;
SEVERITY_WARNING: ResIndex := ResIndex or RC_STATUS_SIFT_NT_WARNING;
SEVERITY_ERROR: ResIndex := ResIndex or RC_STATUS_SIFT_NT_ERROR;
end;
end
else if NT_SEVERITY(Status) = SEVERITY_ERROR then
begin
// Make sure the substatus is within the range
if ResIndex >= RC_FACILITY_EACH_MAX then
Exit;
// Shift resource index to facilities section
ResIndex := ResIndex or RC_STATUS_SIFT_NT_FACILITIES;
// Shift resource index to each facility
case NT_FACILITY(Status) of
FACILITY_RPC_RUNTIME:
ResIndex := ResIndex or RC_FACILITY_SHIFT_RPC_RUNTIME;
FACILITY_RPC_STUBS:
ResIndex := ResIndex or RC_FACILITY_SHIFT_RPC_STUBS;
FACILITY_TRANSACTION:
ResIndex := ResIndex or RC_FACILITY_SHIFT_TRANSACTION;
else
Exit;
end;
end
else
Exit;
// Extract the string representation
SetString(Result, Buf, LoadStringW(HInstance, ResIndex, Buf));
end;
function NtxWin32ErrorToString(Code: Cardinal): String;
begin
Result := NtxpWin32ErrorToString(Code);
if Result = '' then
Result := IntToStr(Code);
end;
function NtxStatusToString(Status: NTSTATUS): String;
begin
// Check if it's a fake status based on a Win32 error.
// In this case use "ERROR_SOMETHING_WENT_WRONG" messages.
if NT_NTWIN32(Status) then
Result := NtxpWin32ErrorToString(WIN32_FROM_NTSTATUS(Status))
else
Result := NtxpStatusToString(Status);
if Result = '' then
Result := IntToHexEx(Status, 8);
end;
function NtxWin32ErrorDescription(Code: Cardinal): String;
begin
// We query the code name which looks like "ERROR_SOMETHING_WENT_WRONG"
// and prettify it so it appears like "Something went wrong"
Result := NtxpWin32ErrorToString(Code);
if Result = '' then
Exit;
Result := PrettifySnakeCase(Result, 'ERROR_');
end;
function NtxStatusDescription(Status: NTSTATUS): String;
begin
if NT_NTWIN32(Status) then
begin
// This status was converted from a Win32 error.
Result := NtxWin32ErrorDescription(WIN32_FROM_NTSTATUS(Status));
end
else
begin
// We query the status name which looks like "STATUS_SOMETHING_WENT_WRONG"
// and prettify it so it appears like "Something went wrong"
Result := NtxpStatusToString(Status);
if Result = '' then
Exit;
Result := PrettifySnakeCase(Result, 'STATUS_');
end;
end;
function NtxFormatErrorMessage(Status: NTSTATUS): String;
var
StartFrom: Integer;
begin
if NT_NTWIN32(Status) then
begin
// This status was converted from a Win32 errors.
Result := SysErrorMessage(WIN32_FROM_NTSTATUS(Status));
end
else
begin
// Get error message from ntdll
Result := SysErrorMessage(Status, hNtdll);
// Fix those messages which are formatted like:
// {Asdf}
// Asdf asdf asdf...
if (Length(Result) > 0) and (Result[Low(Result)] = '{') then
begin
StartFrom := Pos('}'#$D#$A, Result);
if StartFrom >= Low(Result) then
Delete(Result, Low(Result), StartFrom + 2);
end;
end;
if Result = '' then
Result := '<No description available>';
end;
end.
|
unit FC.StockData.Export.CSVExporter.Dialog;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufmDialogOKCancel_B, ActnList, StdCtrls, ExtendControls, ExtCtrls,
StockChart.Definitions,FC.Definitions, StockChart.Obj, ComCtrls;
type
TfmExportDialog = class(TfmDialogOkCancel_B)
Label1: TLabel;
cbDateFormat: TExtendComboBox;
Label2: TLabel;
cbSeparator: TExtendComboBox;
Label3: TLabel;
mmPreview: TMemo;
pbProgress: TProgressBar;
Label4: TLabel;
cbTimeFormat: TExtendComboBox;
Bevel1: TBevel;
ckExportFrom: TExtendCheckBox;
dtDateFrom: TExtendDateTimePicker;
dtTimeFrom: TExtendDateTimePicker;
dtTimeTo: TExtendDateTimePicker;
dtDateTo: TExtendDateTimePicker;
ckExportTo: TExtendCheckBox;
procedure acOKUpdate(Sender: TObject);
procedure OnSettingsChange(Sender: TObject);
procedure acOKExecute(Sender: TObject);
private
FDS: IStockDataSource;
FStream: TStream;
FLocked: boolean;
procedure ExportInternal(aStream: TStream; aCount: integer);
public
constructor Create(AOwner: TComponent); override;
class procedure Run(const aDS: IStockDataSource; aStream: TStream);
end;
implementation
uses Math,
SystemService,
FC.Factory,
FC.DataUtils;
{$R *.dfm}
const
DateFormat1 = 'YYYY.MM.DD';
DateFormat2 = 'DD.MM.YYYY';
DateFormat3 = 'DD.MM.YY';
DateFormat4 = 'YYYYMMDD';
TimeFormat1 = 'HH:MM';
TimeFormat2 = 'HH:MM:SS';
TimeFormat3 = 'HHMM';
TimeFormat4 = 'HHMMSS';
{ TfmExportDialog }
procedure TfmExportDialog.OnSettingsChange(Sender: TObject);
var
aStream: TMemoryStream;
begin
if FLocked then
exit;
aStream:=TStringStream.Create('');
try
ExportInternal(aStream,min(10,FDS.RecordCount));
mmPreview.Text:=PAnsiChar(aStream.Memory);
finally
aStream.Free;
end;
end;
procedure TfmExportDialog.acOKUpdate(Sender: TObject);
begin
inherited;
dtDateFrom.Enabled:=ckExportFrom.Checked;
dtTimeFrom.Enabled:=ckExportFrom.Checked;
dtDateTo.Enabled:=ckExportTo.Checked;
dtTimeTo.Enabled:=ckExportTo.Checked;
end;
constructor TfmExportDialog.Create(AOwner: TComponent);
begin
inherited;
FLocked:=true;
cbDateFormat.Clear;
cbDateFormat.Items.Add(DateFormat1);
cbDateFormat.Items.Add(DateFormat2);
cbDateFormat.Items.Add(DateFormat3);
cbDateFormat.Items.Add(DateFormat4);
cbDateFormat.ItemIndex:=0;
cbTimeFormat.Clear;
cbTimeFormat.Items.Add(TimeFormat1);
cbTimeFormat.Items.Add(TimeFormat2);
cbTimeFormat.Items.Add(TimeFormat3);
cbTimeFormat.Items.Add(TimeFormat4);
cbTimeFormat.ItemIndex:=0;
dtTimeTo.DateTime:=Trunc(Now);
dtTimeFrom.DateTime:=Trunc(Now);
cbSeparator.Clear;
cbSeparator.Items.Add(',');
cbSeparator.Items.Add(';');
cbSeparator.Items.Add('tab');
cbSeparator.ItemIndex:=0;
FLocked:=false;
end;
procedure TfmExportDialog.acOKExecute(Sender: TObject);
begin
inherited;
ModalResult:=mrNone;
pbProgress.Position:=0;
if FDS.RecordCount>100 then
pbProgress.Visible:=true;
try
ExportInternal(FStream,FDS.RecordCount);
finally
pbProgress.Visible:=false;
end;
ModalResult:=mrOk;
end;
procedure TfmExportDialog.ExportInternal(aStream: TStream; aCount: integer);
var
i: integer;
s: AnsiString;
FormatMath: TFormatSettings;
aPercent: integer;
aDateFormat: string;
aTimeFormat: string;
aSeparator: string;
aFrom,aTo: TDateTime;
b : boolean;
begin
GetLocaleFormatSettings(GetThreadLocale,FormatMath);
FormatMath.DecimalSeparator:='.';
TWaitCursor.SetUntilIdle;
aPercent:=0;
aDateFormat:=AnsiLowerCase(cbDateFormat.Text);
aTimeFormat:=StringReplace(AnsiLowerCase(cbTimeFormat.Text),'mm','nn',[]);
aSeparator:=cbSeparator.Text;
if AnsiSameText(aSeparator,'tab') then
aSeparator:=#9;
aFrom:=-1;
aTo:=-1;
if ckExportFrom.Checked then
aFrom:=Trunc(dtDateFrom.DateTime)+Frac(dtTimeFrom.DateTime);
if ckExportTo.Checked then
aTo:=Trunc(dtDateTo.DateTime)+Frac(dtTimeTo.DateTime);
for i := 0 to aCount- 1 do
begin
b:=true;
if aFrom>=0 then
if FDS.GetDataDateTime(i)<aFrom then
b:=false;
if aTo>=0 then
if FDS.GetDataDateTime(i)>aTo then
begin
pbProgress.Position:=pbProgress.Max;
break;
end;
if b then
begin
s:= FormatDateTime(aDateFormat,FDS.GetDataDateTime(i))+aSeparator+
FormatDateTime(aTimeFormat,FDS.GetDataDateTime(i))+aSeparator+
PriceToStr(FDS, FDS.GetDataOpen(i))+aSeparator+
PriceToStr(FDS,FDS.GetDataHigh(i))+aSeparator+
PriceToStr(FDS,FDS.GetDataLow(i))+aSeparator+
PriceToStr(FDS,FDS.GetDataClose(i))+aSeparator+
IntToStr(FDS.GetDataVolume(i))+#13#10;
aStream.Write(PAnsiChar(s)^,Length(s));
end;
if (aCount>100) and (Round(i/aCount*100)<>aPercent) then
begin
aPercent:=Round(i/FDS.RecordCount*100);
pbProgress.Position:=aPercent;
self.Repaint;
end;
end;
end;
class procedure TfmExportDialog.Run(const aDS: IStockDataSource; aStream: TStream);
begin
with TfmExportDialog.Create(nil) do
try
FDS:=aDS;
FStream:=aStream;
OnSettingsChange(nil);
ShowModal;
finally
Free;
end;
end;
end.
|
PROGRAM Test;
TYPE ListNodePtr = ^ListNode;
ListNode = RECORD
val: integer;
next: ListNodePtr;
END;
List = ListNodePtr;
PROCEDURE DeleteAt(var l: List; at: integer);
var curr, toDel: ListNodePtr;
count: integer;
BEGIN (* DeleteAt *)
count := 1;
curr := l;
if curr <> NIL then begin
while (curr^.next <> NIL) AND (count < at -1) do begin
curr := curr^.next;
count := count + 1;
end;
if(count <> at-1) then begin
toDel := curr^.next;
if (curr^.next^.next <> NIL) then
curr^.next := curr^.next^.next
else
curr^.next := NIL;
Dispose(toDel);
end;
end;
END; (* DeleteAt *)
PROCEDURE Prepand(var l: List; n: ListNodePtr);
BEGIN (* Prepand *)
n^.next := l;
l := n;
END; (* Prepand *)
FUNCTION NewNode(val: integer): ListNodePtr;
var node: ListNodePtr;
BEGIN (* NewNode *)
New(node);
node^.val := val;
node^.next := NIL;
NewNode := node;
END; (* NewNode *)
PROCEDURE WriteList(l: List);
BEGIN (* WriteList *)
while l <> nil do begin
Write(' -> ');
Write(l^.val);
l := l^.next;
end;
WriteLn(' -| ');
END; (* WriteList *)
var l: List;
BEGIN
l := NIL;
Prepand(l, NewNode(7));
Prepand(l, NewNode(6));
Prepand(l, NewNode(5));
Prepand(l, NewNode(4));
Prepand(l, NewNode(3));
Prepand(l, NewNode(2));
Prepand(l, NewNode(1));
WriteList(l);
DeleteAt(l, 5);
DeleteAt(l, 1);
DeleteAt(l, 6);
//DeleteAt(l, 9);
WriteList(l);
END. |
{******************************************}
{ TeeChart. Mini-Charts Example }
{ Copyright (c) 1995-2001 by David Berneda }
{ All Rights Reserved }
{******************************************}
unit umain;
interface
{ This project show some very small mini-charts and some animation }
{ That mini-charts could be useful as small data-monitors in your forms,
or reports }
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, Chart, Series, ExtCtrls, Teengine, TeeProcs;
type
TMiniForm = class(TForm)
LineSeries1: TLineSeries;
Panel1: TPanel;
Panel2: TPanel;
Chart1: TChart;
Chart2: TChart;
Chart3: TChart;
Chart4: TChart;
PieSeries1: TPieSeries;
AreaSeries1: TAreaSeries;
LineSeries2: TLineSeries;
BarSeries1: TBarSeries;
LineSeries3: TLineSeries;
Timer1: TTimer;
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure LineSeries2AfterDrawValues(Sender: TObject);
procedure LineSeries3AfterDrawValues(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
PosChart1,PosChart4:Longint; { used to draw vertical lines over charts }
end;
implementation
{$R *.dfm}
Const NumPoints=30;
procedure TMiniForm.FormCreate(Sender: TObject);
begin
PosChart1:=-1; { starting position of vertical divider }
PosChart4:=NumPoints div 2;
{ Generate some random points ... }
LineSeries1.FillSampleValues(NumPoints);
PieSeries1.FillSampleValues(8);
AreaSeries1.FillSampleValues(NumPoints);
LineSeries2.FillSampleValues(NumPoints);
BarSeries1.FillSampleValues(6);
LineSeries3.FillSampleValues(NumPoints);
end;
procedure TMiniForm.FormResize(Sender: TObject);
begin
{ Equally resize the panels to center charts }
Chart2.Height:=ClientHeight div 2;
Chart3.Height:=ClientHeight div 2;
Panel1.Width:=ClientWidth div 2;
end;
procedure TMiniForm.Timer1Timer(Sender: TObject);
{ This procedure changes the Series values every second }
Procedure RefreshMonitorChart(Chart:TChart; Var PosChart:Longint);
var t:Longint;
LastValueWas:Double;
Begin
Inc(PosChart);
if PosChart >= NumPoints then PosChart:=0;
for t:=0 to Chart.SeriesCount-1 do
Begin
if PosChart=0 then
Begin
With Chart do { reset scales at the end of monitoring. }
Begin
LeftAxis.Automatic:=True;
LeftAxis.SetMinMax(MinYValue(LeftAxis),MaxYValue(LeftAxis));
end;
LastValueWas:=Chart.Series[t].YValues.Last;
end
else LastValueWas:=Chart.Series[t].YValue[PosChart-1];
{ change the value for a new random one }
Chart.Series[t].YValue[PosChart]:= LastValueWas+Random(ChartSamplesMax)-
(ChartSamplesMax div 2);
end;
end;
var tmpPos:Longint;
begin
RefreshMonitorChart(Chart1,PosChart1); { refresh chart1 }
RefreshMonitorChart(Chart4,PosChart4); { refresh chart4 }
With PieSeries1 do RotationAngle:=(RotationAngle+1) mod 359; { rotate pie }
{ change Bar Series values }
With BarSeries1 do
Begin
tmpPos:=Random(Count);
YValue[tmpPos]:=YValue[tmpPos]*(80.0+Random(40))/100.0;
end;
end;
procedure TMiniForm.LineSeries2AfterDrawValues(Sender: TObject);
begin
{ this event draws the red divider in Chart1 }
if PosChart1>=0 then
With Chart1,Canvas do
Begin
Pen.Color:=clRed;
DoVertLine( Series[0].CalcXPos(PosChart1), { x }
ChartRect.Top+1, { initial Y }
ChartRect.Bottom-1 { ending Y }
);
end;
end;
procedure TMiniForm.LineSeries3AfterDrawValues(Sender: TObject);
begin
{ this event draws the blue divider in Chart4 }
if PosChart4>=0 then
With Chart4,Canvas do
Begin
Pen.Color:=clBlue;
DoVertLine( Series[0].CalcXPos(PosChart4), { x }
ChartRect.Top+1, { initial Y }
ChartRect.Bottom-1 { ending Y }
);
end;
end;
end.
|
unit uPlDirectSoundPluginInterface;
interface
uses
Windows, MMSystem, DirectSound;
const
Class_PlDirectSoundPlugin: TGUID = '{2DCAC7E0-BA75-49A7-986D-B0957A50F7D7}';
type
HIMAGE = Integer;
HEFFECT = Integer;
IPlDirectSoundPluginInterface = interface(IInterface)
['{5EE2A534-7412-4CEB-ABB1-6C41B13F203E}']
function DSEffect_Load(PWaveFormat: PWaveFormatEX; PData: Pointer; DataSize: Integer): HEFFECT;
function DSEffect_GetStatus(AEffect: HEFFECT; var PdwStatus: Cardinal): HRESULT;
function DSEffect_StartPlay(AEffect: HEFFECT; PlayLooping: Boolean): HRESULT;
function DSEffect_StopPlay(AEffect: HEFFECT): HRESULT;
function DSEffect_StartCapture: HEFFECT;
function DSEffect_StopCapture(AEffect: HEFFECT): HRESULT;
function DSEffect_GetSize(AEffect: HEFFECT; pdwAudioBytes: PDWORD): HRESULT;
function DSEffect_GetFormat(AEffect: HEFFECT; pWaveFormat: PWaveFormatEx): HRESULT;
function DSEffect_Lock(AEffect: HEFFECT; dwOffset, dwBytes: DWORD; ppvAudioPtr1: PPointer;
pdwAudioBytes1: PDWORD; ppvAudioPtr2: PPointer; pdwAudioBytes2: PDWORD; dwFlags: DWORD): HResult;
function DSEffect_Unlock(AEffect: HEFFECT; pvAudioPtr1: Pointer; dwAudioBytes1: DWORD;
pvAudioPtr2: Pointer; dwAudioBytes2: DWORD): HResult;
function DSEffect_Duplicate(AEffect: HEFFECT): HEFFECT;
procedure DSEffect_Free(AEffect: HEFFECT);
procedure DSSetWindowHandle(Win: HWND);
function DSPluginInitialize: HRESULT;
end;
implementation
end.
|
namespace RemObjects.Elements.System;
interface
type
ValueType = public abstract class
end;
&Enum = public abstract class
end;
Void = public record
public
method ToString: String; override; empty; // not callable
method GetHashCode: Integer; override; empty; // not callable
end;
Boolean = public record
public
method ToString: String; override;
method GetHashCode: Integer; override;
method &Equals(obj: Object): Boolean; override;
end;
Char = public record
public
method ToString: String; override;
method GetHashCode: Integer; override;
method &Equals(obj: Object): Boolean; override;
class method IsWhiteSpace(aChar: Char): Boolean;
end;
AnsiChar = public record
public
method ToString: String; override;
method GetHashCode: Integer; override;
method &Equals(obj: Object): Boolean; override;
end;
Debug = public static class
public
[Conditional('DEBUG')]
class method Assert(aFail: Boolean; aMessage: String; aFile: String := currentFilename(); aLine: Integer := currentLineNumber());
begin
if aFail then
raise new AssertionException('Assertion failed: '+aMessage+' at '+aFile+'('+aLine+')');
end;
class method Throw(s: string);
begin
raise new Exception(s);
end;
end;
implementation
method Boolean.ToString: String;
begin
exit if self then 'True' else 'False';
end;
method Boolean.GetHashCode: Integer;
begin
exit if self then 1 else 0;
end;
method Boolean.&Equals(obj: Object): Boolean;
begin
if Assigned(obj) and (obj is Boolean) then
exit self = Boolean(obj)
else
exit False;
end;
method Char.ToString: String;
begin
exit string(self);
end;
method Char.GetHashCode: Integer;
begin
exit Integer(self);
end;
method Char.&Equals(obj: Object): Boolean;
begin
if Assigned(obj) and (obj is Char) then
exit self = Char(obj)
else
exit False;
end;
class method Char.IsWhiteSpace(aChar: Char): Boolean;
begin
// from https://msdn.microsoft.com/en-us/library/system.char.iswhitespace%28v=vs.110%29.aspx
exit Word(aChar) in
($0020, $1680, $2000, $2001, $2002, $2003, $2004, $2005, $2006, $2007, $2008, $2009, $200A, $202F, $205F, $3000, //space separators
$2028, //Line Separator
$2029, //Paragraph Separator
$0009, $000A, $000B, $000C, $000D,$0085,$00A0 // other special symbols
);
end;
method AnsiChar.ToString: String;
begin
exit string(char(self));
end;
method AnsiChar.GetHashCode: Integer;
begin
exit Integer(self);
end;
method AnsiChar.&Equals(obj: Object): Boolean;
begin
if Assigned(obj) and (obj is AnsiChar) then
exit self = AnsiChar(obj)
else
exit False;
end;
end. |
{ Copyright (C) 1998-2018, written by Shkolnik Mike, Scalabium Software
E-Mail: mshkolnik@scalabium.com
mshkolnik@yahoo.com
WEB: http://www.scalabium.com
Эта компонента - это аналог TLabel, но с возможностью
привязать к нему картинку и при наведении курсора на
Label или Image будет производиться их подсветка.
}
unit SMHLLbl;
interface
{$I SMVersion.inc}
uses
Windows, Messages, Classes, Graphics, Controls;
type
TState = (stEnter, stLeave);
TSMAlignment = (taLeftJustify, taRightJustify);
TTextLayout = (tlTop, tlCenter, tlBottom);
{$IFDEF SM_ADD_ComponentPlatformsAttribute}
[ComponentPlatformsAttribute(pidWin32 or pidWin64)]
{$ENDIF}
THighLightLabel = class(TGraphicControl)
private
{ Private declarations }
FState: TState;
FPicActive: TPicture;
FPicPassive: TPicture;
FFontActive: TFont;
FFontPassive: TFont;
FFocusControl: TWinControl;
FAlignment: TSMAlignment;
FAutoSize: Boolean;
FLayout: TTextLayout;
FWordWrap: Boolean;
FShowAccelChar: Boolean;
procedure AdjustBounds;
procedure DoDrawText(var ARect: TRect; Flags: Word);
function GetTransparent: Boolean;
procedure SetAlignment(Value: TSMAlignment);
procedure SetFocusControl(Value: TWinControl);
procedure SetShowAccelChar(Value: Boolean);
procedure SetTransparent(Value: Boolean);
procedure SetLayout(Value: TTextLayout);
procedure SetWordWrap(Value: Boolean);
procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED;
procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED;
procedure CMDialogChar(var Message: TCMDialogChar); message CM_DIALOGCHAR;
procedure SetPictureActive(Value: TPicture);
procedure SetPicturePassive(Value: TPicture);
procedure SetFontActive(Value: TFont);
procedure SetFontPassive(Value: TFont);
procedure SetState(Value: TState);
protected
{ Protected declarations }
function GetLabelText: string; virtual;
procedure Loaded; override;
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
procedure Paint; override;
procedure SetHLAutoSize(Value: Boolean); virtual;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure CMMouseEnter(var Msg: TMessage); message CM_MOUSEENTER;
procedure CMMouseLeave(var Msg: TMessage); message CM_MOUSELEAVE;
property Canvas;
property State: TState read FState write SetState;
published
{ Published declarations }
property FontActive: TFont read FFontActive write SetFontActive;
property FontPassive: TFont read FFontPassive write SetFontPassive;
property PicActive: TPicture read FPicActive write SetPictureActive;
property PicPassive: TPicture read FPicPassive write SetPicturePassive;
property Alignment: TSMAlignment read FAlignment write SetAlignment default taLeftJustify;
property AutoSize: Boolean read FAutoSize write SetHLAutoSize default True;
property FocusControl: TWinControl read FFocusControl write SetFocusControl;
property ShowAccelChar: Boolean read FShowAccelChar write SetShowAccelChar default True;
property Transparent: Boolean read GetTransparent write SetTransparent default False;
property Layout: TTextLayout read FLayout write SetLayout default tlTop;
property WordWrap: Boolean read FWordWrap write SetWordWrap default False;
property Align;
property Caption;
property Color;
property DragCursor;
property DragMode;
property Enabled;
property ParentColor;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property Visible;
property OnClick;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnStartDrag;
end;
procedure Register;
implementation
{$R *.RES}
uses SysUtils;
procedure Register;
begin
RegisterComponents('SMComponents', [THighLightLabel]);
end;
{ THighLightLabel }
constructor THighLightLabel.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ControlStyle := ControlStyle + [csOpaque, csReplicatable];
Width := 65;
Height := 17;
FAutoSize := True;
FShowAccelChar := True;
FFontActive := TFont.Create;
FFontActive.Assign(Font);
FFontPassive := TFont.Create;
FFontPassive.Assign(Font);
FPicActive := TPicture.Create;
FPicActive.Bitmap.TransparentColor := clSilver;
FPicActive.Bitmap.Transparent := True;
FPicActive.Bitmap.Handle := LoadBitmap(hInstance, 'PICENTER');
FPicPassive := TPicture.Create;
FPicPassive.Bitmap.TransparentColor := clSilver;
FPicPassive.Bitmap.Transparent := True;
FPicPassive.Bitmap.Handle := LoadBitmap(hInstance, 'PICLEAVE');
FState := stLeave;
end;
destructor THighLightLabel.Destroy;
begin
FFontActive.Free;
FFontPassive.Free;
FPicActive.Free;
FPicPassive.Free;
inherited Destroy;
end;
function THighLightLabel.GetLabelText: string;
begin
Result := Caption;
end;
procedure THighLightLabel.DoDrawText(var ARect: TRect; Flags: Word);
var
Text: string;
BRect: TRect;
intLeft, intHeight: Integer;
FPicture: TPicture;
begin
if FState = stEnter then
begin
FPicture := FPicActive;
Canvas.Font := FFontActive;
end
else
begin
FPicture := FPicPassive;
Canvas.Font := FFontPassive;
end;
Text := GetLabelText;
if (Flags and DT_CALCRECT <> 0) and ((Text = '') or FShowAccelChar and
(Text[1] = '&') and (Text[2] = #0)) then Text := Text + ' ';
if not FShowAccelChar then Flags := Flags or DT_NOPREFIX;
if not Enabled then
begin
OffsetRect(ARect, 1, 1);
Canvas.Font.Color := clBtnHighlight;
DrawText(Canvas.Handle, PChar(Text), Length(Text), ARect, Flags);
OffsetRect(ARect, -1, -1);
Canvas.Font.Color := clBtnShadow;
DrawText(Canvas.Handle, PChar(Text), Length(Text), ARect, Flags);
end
else
begin
intLeft := 0;
intHeight := 0;
case FAlignment of
taLeftJustify: begin
intLeft := 0;
ARect.Left := ARect.Left + FPicture.Width + 5;
intHeight := DrawText(Canvas.Handle, PChar(Text), Length(Text), ARect, Flags);
ARect.Left := ARect.Left - FPicture.Width;
end;
taRightJustify: begin
intLeft := Width - FPicture.Width;
ARect.Right := ARect.Right - FPicture.Width - 5;
intHeight := DrawText(Canvas.Handle, PChar(Text), Length(Text), ARect, Flags);
ARect.Right := ARect.Right + FPicture.Width;
end;
end;
if Flags and DT_CALCRECT = 0 then
begin
BRect := Bounds(intLeft, ARect.Top + (intHeight - FPicture.Height) div 2, FPicture.Width, FPicture.Height);
Canvas.StretchDraw(BRect, FPicture.Graphic);
end;
end;
end;
procedure THighLightLabel.Paint;
const
Alignments: array[TSMAlignment] of Word = (DT_LEFT, DT_RIGHT);
WordWraps: array[Boolean] of Word = (0, DT_WORDBREAK);
var
Rect, CalcRect: TRect;
DrawStyle: Integer;
begin
with Canvas do
begin
if not Transparent then
begin
Brush.Color := Self.Color;
Brush.Style := bsSolid;
FillRect(ClientRect);
end;
Brush.Style := bsClear;
Rect := ClientRect;
DrawStyle := DT_EXPANDTABS or WordWraps[FWordWrap] or Alignments[FAlignment];
{ Calculate vertical layout }
if FLayout <> tlTop then
begin
CalcRect := Rect;
DoDrawText(CalcRect, DrawStyle or DT_CALCRECT);
if FLayout = tlBottom then
OffsetRect(Rect, 0, Height - CalcRect.Bottom)
else
OffsetRect(Rect, 0, (Height - CalcRect.Bottom) div 2);
end;
DoDrawText(Rect, DrawStyle);
end;
end;
procedure THighLightLabel.Loaded;
begin
inherited Loaded;
AdjustBounds;
end;
procedure THighLightLabel.AdjustBounds;
const
WordWraps: array[Boolean] of Word = (0, DT_WORDBREAK);
var
DC: HDC;
X: Integer;
Rect: TRect;
begin
if not (csReading in ComponentState) and FAutoSize then
begin
Rect := ClientRect;
DC := GetDC(0);
Canvas.Handle := DC;
DoDrawText(Rect, (DT_EXPANDTABS or DT_CALCRECT) or WordWraps[FWordWrap]);
Canvas.Handle := 0;
ReleaseDC(0, DC);
X := Left;
if FAlignment = taRightJustify then
Inc(X, Width - Rect.Right);
SetBounds(X, Top, Rect.Right, Rect.Bottom);
end;
end;
procedure THighLightLabel.SetAlignment(Value: TSMAlignment);
begin
if FAlignment <> Value then
begin
FAlignment := Value;
Invalidate;
end;
end;
procedure THighLightLabel.SetHLAutoSize(Value: Boolean);
begin
if FAutoSize <> Value then
begin
FAutoSize := Value;
AdjustBounds;
end;
end;
function THighLightLabel.GetTransparent: Boolean;
begin
Result := not (csOpaque in ControlStyle);
end;
procedure THighLightLabel.SetFocusControl(Value: TWinControl);
begin
FFocusControl := Value;
if Value <> nil then Value.FreeNotification(Self);
end;
procedure THighLightLabel.SetShowAccelChar(Value: Boolean);
begin
if FShowAccelChar <> Value then
begin
FShowAccelChar := Value;
Invalidate;
end;
end;
procedure THighLightLabel.SetTransparent(Value: Boolean);
begin
if Transparent <> Value then
begin
if Value then
ControlStyle := ControlStyle - [csOpaque]
else
ControlStyle := ControlStyle + [csOpaque];
Invalidate;
end;
end;
procedure THighLightLabel.SetLayout(Value: TTextLayout);
begin
if FLayout <> Value then
begin
FLayout := Value;
Invalidate;
end;
end;
procedure THighLightLabel.SetWordWrap(Value: Boolean);
begin
if FWordWrap <> Value then
begin
FWordWrap := Value;
AdjustBounds;
Invalidate;
end;
end;
procedure THighLightLabel.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation = opRemove) and (AComponent = FFocusControl) then
FFocusControl := nil;
end;
procedure THighLightLabel.CMTextChanged(var Message: TMessage);
begin
Invalidate;
AdjustBounds;
end;
procedure THighLightLabel.CMFontChanged(var Message: TMessage);
begin
inherited;
AdjustBounds;
end;
function IsAccel(VK: Word; const Str: string): Boolean;
var
P: Integer;
begin
P := Pos('&', Str);
Result := (P <> 0) and (P < Length(Str)) and
(AnsiCompareText(Str[P + 1], Char(VK)) = 0);
end;
procedure THighLightLabel.CMDialogChar(var Message: TCMDialogChar);
begin
if (FFocusControl <> nil) and Enabled and ShowAccelChar and
IsAccel(Message.CharCode, Caption) then
with FFocusControl do
if CanFocus then
begin
SetFocus;
Message.Result := 1;
end;
end;
procedure THighLightLabel.SetFontActive(Value: TFont);
begin
if FFontActive <> nil then
begin
FFontActive.Assign(Value);
Invalidate;
end;
end;
procedure THighLightLabel.SetFontPassive(Value: TFont);
begin
if FFontPassive <> nil then
begin
FFontPassive.Assign(Value);
Invalidate;
end;
end;
procedure THighLightLabel.SetPictureActive(Value: TPicture);
begin
FPicActive.Assign(FPicActive.Graphic);
if Assigned(FPicActive.Graphic) then
FPicActive.Graphic.Transparent := True;
end;
procedure THighLightLabel.SetPicturePassive(Value: TPicture);
begin
FPicPassive.Assign(Value);
if Assigned(FPicPassive.Graphic) then
FPicPassive.Graphic.Transparent := True;
end;
procedure THighLightLabel.SetState(Value: TState);
begin
if (FState <> Value) then
begin
FState := Value;
Invalidate;
end;
end;
procedure THighLightLabel.CMMouseEnter(var Msg: TMessage);
begin
//Change color when mouse is over label
if (FState = stLeave) then
State := stEnter;
end;
procedure THighLightLabel.CMMouseLeave(var Msg: TMessage);
begin
//Change color when mouse leaves label
if (FState = stEnter) then
State := stLeave;
end;
end.
|
unit clientfr;
{
This is the client portion of a MIDAS demo. Make sure that you compile and
run the server project before trying to run this probject.
This project demonstrates dynamically passing SQL to the server using the
Provider.DataRequest event.
}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
DB, DBClient, ExtCtrls, Grids, DBGrids, StdCtrls, MConnect, Variants;
type
TForm1 = class(TForm)
SQL: TMemo;
Label1: TLabel;
DatabaseName: TComboBox;
RunButton: TButton;
DataSource1: TDataSource;
DBGrid1: TDBGrid;
Bevel1: TBevel;
RemoteServer: TDCOMConnection;
ClientData: TClientDataSet;
procedure DatabaseNameClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure RunButtonClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
var
I: Integer;
DBNames: OleVariant;
begin
{ Connect to the server and get a list of available database names }
RemoteServer.Connected := True;
DBNames := RemoteServer.AppServer.GetDatabaseNames;
if VarIsArray(DBNames) then
for I := 0 to VarArrayHighBound(DBNames, 1) do
DatabaseName.Items.Add(DBNames[I]);
DatabaseNameClick(Self);
end;
procedure TForm1.RunButtonClick(Sender: TObject);
begin
{ Send the query string to the server and try to open the client dataset }
ClientData.Close;
ClientData.CommandText := SQL.Lines.Text;
ClientData.Open;
end;
procedure TForm1.DatabaseNameClick(Sender: TObject);
var
Password: string;
begin
{ Change the database name on the server }
if DatabaseName.Text <> '' then
begin
ClientData.Close;
try
RemoteServer.AppServer.SetDatabaseName(DatabaseName.Text, '');
except
{ This is a crude mechanism for getting the password on SQL Databases }
on E: Exception do
if E.Message = 'Password Required' then
begin
if InputQuery(E.Message, 'Enter password', Password) then
RemoteServer.AppServer.SetDatabaseName(DatabaseName.Text, Password);
end else
raise;
end;
end;
end;
end.
|
unit Params_int64;
interface
implementation
var G: int64;
procedure P(i: int64);
begin
G := i;
end;
procedure Test;
begin
p(64);
end;
initialization
Test();
finalization
Assert(G = 64);
end. |
program CreationLectureEcrireFichier;
uses crt;
procedure CreerFichier(var f:Textfile); // la procedure servira a creer le fichier en supposant qu'il n'existe pas encore
begin
Assign(f,'TestFichier.txt'); // va indiquer que f correspond au fichier TestFichier, dans la destination en question (ici dans le meme fichier que le programme)
rewrite(f); // permet de creer le fichier si il n'existe pas encore, et si il existe, efface son contenu
writeln(f,'Bonjour'); // va mettre le texte bonjour dans le fichier
close(f); // ferme le fichier
end;
procedure LectureFichier(var f:Textfile; choix:char; s:string); // va permettre a l'utilisateur de lire le fichier
begin
writeln('Appuyez sur O pour lire le fichier pour voir ce qu il y a ecrit dedans.');
choix:=ReadKey; // va lire la touche entree par l'utilisateur au lieu de passer par un readln
if(upCase(choix)='O') then
begin
Reset(f); // Va ouvrir le fichier uniquement en lecture, et donc non modifiable
while not Eof(f) do // tant qu'il n'est a la fin du fichier
begin
readln(f,s); // va mettre les donnes du fichier dans la variable s
writeln(s); // va afficher la variable s
end;
close(f); //ferme le fichier
end
else
begin
writeln('La lecture du fichier a ete refusee par l''utilisateur');
end;
end;
procedure EcrireFin(var f:TextFile; s:string);
begin
Append(f); // permet d'ouvrir le fichier pour le modifier, se met directement a la fin
writeln('Vous pouvez ajouter quelque chose a la fin du fichier, que voulez vous mettre ?');
readln(s);
writeln(f,s);
close(f);
end;
var
f:Textfile; // pour dire que f correspond a un fichier
choix:char;
s:string;
begin
clrscr;
CreerFichier(f);
LectureFichier(f,choix,s);
EcrireFin(f,s);
LectureFichier(f,choix,s);
readln;
END. |
unit ANU_INTF;
(*************************************************************************
DESCRIPTION : Interface unit for ANU_DLL
REQUIREMENTS : D2-D7/D9-D10/D12, FPC
EXTERNAL DATA : ---
MEMORY USAGE : ---
DISPLAY MODE : ---
Version Date Author Modification
------- -------- ------- ------------------------------------------
0.10 08.08.08 W.Ehrhardt Initial version
0.11 16.08.08 we Removed ANU_Reset
0.12 13.07.09 we ANU_DLL_Version returns PAnsiChar, external 'ANU_DLL.DLL'
0.13 01.08.10 we Longint ILen in ANU_xxx_En/Decrypt, ANU_OMAC_UpdateXL removed
0.14 02.08.10 we ANU_CTR_Seek, ANU_CTR_Seek64 via anu_seek.inc
**************************************************************************)
(*-------------------------------------------------------------------------
(C) Copyright 2008-2010 Wolfgang Ehrhardt
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.
----------------------------------------------------------------------------*)
{$i STD.INC}
interface
const
ANU_Err_Invalid_Key_Size = -1; {Key size in bits not 128, 192, or 256}
ANU_Err_Invalid_Mode = -2; {Encr/Decr with Init for Decr/Encr}
ANU_Err_Invalid_Length = -3; {No full block for cipher stealing}
ANU_Err_Data_After_Short_Block = -4; {Short block must be last}
ANU_Err_MultipleIncProcs = -5; {More than one IncProc Setting}
ANU_Err_NIL_Pointer = -6; {nil pointer to block with nonzero length}
ANU_Err_EAX_Inv_Text_Length = -7; {More than 64K text length in EAX all-in-one for 16 Bit}
ANU_Err_EAX_Inv_TAG_Length = -8; {EAX all-in-one tag length not 0..16}
ANU_Err_EAX_Verify_Tag = -9; {EAX all-in-one tag does not compare}
ANU_Err_CTR_SeekOffset = -15; {Negative offset in ANU_CTR_Seek}
ANU_Err_Invalid_16Bit_Length = -20; {Pointer + Offset > $FFFF for 16 bit code}
type
TANURndKey = packed array[0..18,0..3] of longint; {Round key schedule}
TANUBlock = packed array[0..15] of byte; {128 bit block}
PANUBlock = ^TANUBlock;
type
TANUIncProc = procedure(var CTR: TANUBlock); {user supplied IncCTR proc}
{$ifdef USEDLL} stdcall; {$endif}
type
TANUContext = packed record
IV : TANUBlock; {IV or CTR }
buf : TANUBlock; {Work buffer }
bLen : word; {Bytes used in buf }
Rounds : word; {Number of rounds }
KeyBits : word; {Number of bits in key }
Decrypt : byte; {<>0 if decrypting key }
Flag : byte; {Bit 1: Short block }
IncProc : TANUIncProc; {Increment proc CTR-Mode}
RK : TANURndKey; {Encr/Decr round keys }
end;
type
TANU_EAXContext = packed record
HdrOMAC : TANUContext; {Hdr OMAC1 context}
MsgOMAC : TANUContext; {Msg OMAC1 context}
ctr_ctx : TANUContext; {Msg ANUCTR context}
NonceTag: TANUBlock; {nonce tag }
tagsize : word; {tag size (unused) }
flags : word; {ctx flags (unused)}
end;
const
ANUBLKSIZE = sizeof(TANUBlock); {Anubis block size in bytes}
function ANU_DLL_Version: PAnsiChar;
stdcall; external 'ANU_DLL.DLL' name 'ANU_DLL_Version';
{-Return DLL version as PAnsiChar}
function ANU_Init2(const Key; KeyBits: word; var ctx: TANUContext; decr: byte): integer;
stdcall; external 'ANU_DLL.DLL' name 'ANU_Init2';
{-Anubis context/round key initialization, Inverse key if decr<>0}
function ANU_Init_Encr(const Key; KeyBits: word; var ctx: TANUContext): integer;
stdcall; external 'ANU_DLL.DLL' name 'ANU_Init_Encr';
{-Anubis key expansion, error if invalid key size}
function ANU_Init_Decr(const Key; KeyBits: word; var ctx: TANUContext): integer;
stdcall; external 'ANU_DLL.DLL' name 'ANU_Init_Decr';
{-Anubis key expansion, InvMixColumn(Key) for Decypt, error if invalid key size}
procedure ANU_Encrypt(var ctx: TANUContext; const BI: TANUBlock; var BO: TANUBlock);
stdcall; external 'ANU_DLL.DLL' name 'ANU_Encrypt';
{-encrypt one block, not checked: key must be encryption key}
procedure ANU_Decrypt(var ctx: TANUContext; const BI: TANUBlock; var BO: TANUBlock);
stdcall; external 'ANU_DLL.DLL' name 'ANU_Decrypt';
{-decrypt one block (in ECB mode)}
procedure ANU_XorBlock(const B1, B2: TANUBlock; var B3: TANUBlock);
{-xor two blocks, result in third}
stdcall; external 'ANU_DLL.DLL' name 'ANU_XorBlock';
procedure ANU_SetFastInit(value: boolean);
stdcall; external 'ANU_DLL.DLL' name 'ANU_SetFastInit';
{-set FastInit variable}
function ANU_GetFastInit: boolean;
stdcall; external 'ANU_DLL.DLL' name 'ANU_GetFastInit';
{-Returns FastInit variable}
function ANU_ECB_Init_Encr(const Key; KeyBits: word; var ctx: TANUContext): integer;
stdcall; external 'ANU_DLL.DLL' name 'ANU_ECB_Init_Encr';
{-Anubis key expansion, error if invalid key size, encrypt IV}
function ANU_ECB_Init_Decr(const Key; KeyBits: word; var ctx: TANUContext): integer;
stdcall; external 'ANU_DLL.DLL' name 'ANU_ECB_Init_Decr';
{-Anubis key expansion, error if invalid key size, encrypt IV}
function ANU_ECB_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TANUContext): integer;
stdcall; external 'ANU_DLL.DLL' name 'ANU_ECB_Encrypt';
{-Encrypt ILen bytes from ptp^ to ctp^ in ECB mode}
function ANU_ECB_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TANUContext): integer;
stdcall; external 'ANU_DLL.DLL' name 'ANU_ECB_Decrypt';
{-Decrypt ILen bytes from ctp^ to ptp^ in ECB mode}
function ANU_CBC_Init_Encr(const Key; KeyBits: word; const IV: TANUBlock; var ctx: TANUContext): integer;
stdcall; external 'ANU_DLL.DLL' name 'ANU_CBC_Init_Encr';
{-Anubis key expansion, error if invalid key size, encrypt IV}
function ANU_CBC_Init_Decr(const Key; KeyBits: word; const IV: TANUBlock; var ctx: TANUContext): integer;
stdcall; external 'ANU_DLL.DLL' name 'ANU_CBC_Init_Decr';
{-Anubis key expansion, error if invalid key size, encrypt IV}
function ANU_CBC_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TANUContext): integer;
stdcall; external 'ANU_DLL.DLL' name 'ANU_CBC_Encrypt';
{-Encrypt ILen bytes from ptp^ to ctp^ in CBC mode}
function ANU_CBC_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TANUContext): integer;
stdcall; external 'ANU_DLL.DLL' name 'ANU_CBC_Decrypt';
{-Decrypt ILen bytes from ctp^ to ptp^ in CBC mode}
function ANU_CFB_Init(const Key; KeyBits: word; const IV: TANUBlock; var ctx: TANUContext): integer;
stdcall; external 'ANU_DLL.DLL' name 'ANU_CFB_Init';
{-Anubis key expansion, error if invalid key size, encrypt IV}
function ANU_CFB_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TANUContext): integer;
stdcall; external 'ANU_DLL.DLL' name 'ANU_CFB_Encrypt';
{-Encrypt ILen bytes from ptp^ to ctp^ in CFB128 mode}
function ANU_CFB_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TANUContext): integer;
stdcall; external 'ANU_DLL.DLL' name 'ANU_CFB_Decrypt';
{-Decrypt ILen bytes from ctp^ to ptp^ in CFB128 mode}
function ANU_OFB_Init(const Key; KeyBits: word; const IV: TANUBlock; var ctx: TANUContext): integer;
stdcall; external 'ANU_DLL.DLL' name 'ANU_OFB_Init';
{-Anubis key expansion, error if invalid key size, encrypt IV}
function ANU_OFB_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TANUContext): integer;
stdcall; external 'ANU_DLL.DLL' name 'ANU_OFB_Encrypt';
{-Encrypt ILen bytes from ptp^ to ctp^ in OFB mode}
function ANU_OFB_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TANUContext): integer;
stdcall; external 'ANU_DLL.DLL' name 'ANU_OFB_Decrypt';
{-Decrypt ILen bytes from ctp^ to ptp^ in OFB mode}
function ANU_CTR_Init(const Key; KeyBits: word; const CTR: TANUBlock; var ctx: TANUContext): integer;
stdcall; external 'ANU_DLL.DLL' name 'ANU_CTR_Init';
{-Anubis key expansion, error if inv. key size, encrypt CTR}
function ANU_CTR_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TANUContext): integer;
stdcall; external 'ANU_DLL.DLL' name 'ANU_CTR_Encrypt';
{-Encrypt ILen bytes from ptp^ to ctp^ in CTR mode}
function ANU_CTR_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TANUContext): integer;
stdcall; external 'ANU_DLL.DLL' name 'ANU_CTR_Decrypt';
{-Decrypt ILen bytes from ctp^ to ptp^ in CTR mode}
function ANU_CTR_Seek(const iCTR: TANUBlock; SOL, SOH: longint; var ctx: TANUContext): integer;
{-Setup ctx for random access crypto stream starting at 64 bit offset SOH*2^32+SOL,}
{ SOH >= 0. iCTR is the initial CTR for offset 0, i.e. the same as in ANU_CTR_Init.}
{$ifdef HAS_INT64}
function ANU_CTR_Seek64(const iCTR: TANUBlock; SO: int64; var ctx: TANUContext): integer;
{-Setup ctx for random access crypto stream starting at 64 bit offset SO >= 0;}
{ iCTR is the initial CTR value for offset 0, i.e. the same as in ANU_CTR_Init.}
{$endif}
function ANU_SetIncProc(IncP: TANUIncProc; var ctx: TANUContext): integer;
stdcall; external 'ANU_DLL.DLL' name 'ANU_SetIncProc';
{-Set user supplied IncCTR proc}
procedure ANU_IncMSBFull(var CTR: TANUBlock);
stdcall; external 'ANU_DLL.DLL' name 'ANU_IncMSBFull';
{-Increment CTR[15]..CTR[0]}
procedure ANU_IncLSBFull(var CTR: TANUBlock);
stdcall; external 'ANU_DLL.DLL' name 'ANU_IncLSBFull';
{-Increment CTR[0]..CTR[15]}
procedure ANU_IncMSBPart(var CTR: TANUBlock);
stdcall; external 'ANU_DLL.DLL' name 'ANU_IncMSBPart';
{-Increment CTR[15]..CTR[8]}
procedure ANU_IncLSBPart(var CTR: TANUBlock);
stdcall; external 'ANU_DLL.DLL' name 'ANU_IncLSBPart';
{-Increment CTR[0]..CTR[7]}
function ANU_OMAC_Init(const Key; KeyBits: word; var ctx: TANUContext): integer;
stdcall; external 'ANU_DLL.DLL' name 'ANU_OMAC_Init';
{-OMAC init: Anubis key expansion, error if inv. key size}
function ANU_OMAC_Update(data: pointer; ILen: longint; var ctx: TANUContext): integer;
stdcall; external 'ANU_DLL.DLL' name 'ANU_OMAC_Update';
{-OMAC data input, may be called more than once}
procedure ANU_OMAC_Final(var tag: TANUBlock; var ctx: TANUContext);
stdcall; external 'ANU_DLL.DLL' name 'ANU_OMAC_Final';
{-end data input, calculate OMAC=OMAC1 tag}
procedure ANU_OMAC1_Final(var tag: TANUBlock; var ctx: TANUContext);
stdcall; external 'ANU_DLL.DLL' name 'ANU_OMAC1_Final';
{-end data input, calculate OMAC1 tag}
procedure ANU_OMAC2_Final(var tag: TANUBlock; var ctx: TANUContext);
stdcall; external 'ANU_DLL.DLL' name 'ANU_OMAC2_Final';
{-end data input, calculate OMAC2 tag}
procedure ANU_OMACx_Final(OMAC2: boolean; var tag: TANUBlock; var ctx: TANUContext);
stdcall; external 'ANU_DLL.DLL' name 'ANU_OMACx_Final';
{-end data input, calculate OMAC tag}
function ANU_EAX_Init(const Key; KBits: word; const nonce; nLen: word; var ctx: TANU_EAXContext): integer;
stdcall; external 'ANU_DLL.DLL' name 'ANU_EAX_Init';
{-Init hdr and msg OMACs, setp ANUCTR with nonce tag}
function ANU_EAX_Provide_Header(Hdr: pointer; hLen: word; var ctx: TANU_EAXContext): integer;
stdcall; external 'ANU_DLL.DLL' name 'ANU_EAX_Provide_Header';
{-Supply a message header. The header "grows" with each call}
function ANU_EAX_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TANU_EAXContext): integer;
stdcall; external 'ANU_DLL.DLL' name 'ANU_EAX_Encrypt';
{-Encrypt ILen bytes from ptp^ to ctp^ in CTR mode, update OMACs}
function ANU_EAX_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TANU_EAXContext): integer;
stdcall; external 'ANU_DLL.DLL' name 'ANU_EAX_Decrypt';
{-Encrypt ILen bytes from ptp^ to ctp^ in CTR mode, update OMACs}
procedure ANU_EAX_Final(var tag: TANUBlock; var ctx: TANU_EAXContext);
stdcall; external 'ANU_DLL.DLL' name 'ANU_EAX_Final';
{-Compute EAX tag from context}
function ANU_EAX_Enc_Auth(var tag: TANUBlock; {Tag record}
const Key; KBits: word; {key and bitlength of key}
const nonce; nLen: word; {nonce: address / length}
Hdr: pointer; hLen: word; {header: address / length}
ptp: pointer; pLen: longint; {plaintext: address / length}
ctp: pointer {ciphertext: address}
): integer;
stdcall; external 'ANU_DLL.DLL' name 'ANU_EAX_Enc_Auth';
{-All-in-one call to encrypt/authenticate}
function ANU_EAX_Dec_Veri( ptag: pointer; tLen : word; {Tag: address / length (0..16)}
const Key; KBits: word; {key and bitlength of key}
const nonce; nLen : word; {nonce: address / length}
Hdr: pointer; hLen: word; {header: address / length}
ctp: pointer; cLen: longint; {ciphertext: address / length}
ptp: pointer {plaintext: address}
): integer;
stdcall; external 'ANU_DLL.DLL' name 'ANU_EAX_Dec_Veri';
{-All-in-one call to decrypt/verify. Decryption is done only if ptag^ is verified}
implementation
{$i anu_seek.inc}
end.
|
unit Spring.Persistence.Adapters.IBX.Test;
interface
uses
IBX.IBDatabase,
Spring.Persistence.Core.ConnectionFactory,
Spring.Persistence.Core.Interfaces,
Spring.Persistence.Core.Session,
Spring.Persistence.Adapters.IBX,
Spring.Collections,
Spring.Persistence.SQL.Params,
Spring.Persistence.Criteria.Interfaces,
Spring.Persistence.Criteria.Restrictions,
DUnitX.TestFramework,
Base.Test,
ORM.Model.EMPLOYEE,
ORM.Model.COUNTRY,
ORM.Model.SALARY_HISTORY;
{$M+}
type
[TestFixture]
TTestIBXAdapter = class(TTestBaseORM)
public
[Test]
procedure Test_ExecuteScalar();
[Test]
procedure Test_ExecuteScalar_TwoTimes();
[Test]
procedure Test_ExecuteScalar_WithParams();
[Test]
[TestCase('TestFindOne1', '72,Claudia,Sutherland')]
[TestCase('TestFindOne2', '141,Pierre,Osborne')]
procedure Test_FindOne_TEmployee(AId: Integer; const AFName, ALName: string);
[Test]
procedure Test_FindAll_TEmployee();
[Test]
procedure Test_Execute_TCountry();
[Test]
procedure Test_InsertsUpdatesAndDeletes_TEmployee();
[Test]
procedure Test_CriteriaAPI_LooksLikeLinq_TEmployee();
[Test]
procedure Test_FindOne_TCountry();
[Test]
procedure Test_FindOne_TSalaryHistory();
[Test]
procedure Test_FindOne_TEmployee_TSalaryHistory();
[Test]
procedure Test_FindOne_TSalaryHistoryFull();
end;
{$M-}
implementation
uses
System.SysUtils;
procedure TTestIBXAdapter.Test_ExecuteScalar;
var
Actual: Integer;
begin
Actual := Session.ExecuteScalar<Integer>('SELECT COUNT(*) FROM CUSTOMER', []);
Assert.AreEqual(15, Actual);
end;
procedure TTestIBXAdapter.Test_ExecuteScalar_TwoTimes;
var
Actual: Integer;
begin
Actual := Session.ExecuteScalar<Integer>('SELECT COUNT(*) FROM CUSTOMER', []);
Assert.AreEqual(15, Actual);
Actual := Session.ExecuteScalar<Integer>('SELECT COUNT(*) FROM COUNTRY', []);
Assert.AreEqual(14, Actual);
end;
procedure TTestIBXAdapter.Test_ExecuteScalar_WithParams;
var
ActualStr: string;
ActualInt: Integer;
begin
ActualStr := Session.ExecuteScalar<string>('SELECT CONTACT_FIRST FROM CUSTOMER WHERE CUST_NO = :0;', [1010]);
Assert.AreEqual('Miwako', ActualStr);
ActualInt := Session.ExecuteScalar<Integer>('SELECT COUNT(*) FROM CUSTOMER WHERE CUST_NO = :0;', [1012]);
Assert.AreEqual(1, ActualInt);
ActualInt := Session.ExecuteScalar<Integer>('SELECT COUNT(*) FROM COUNTRY WHERE COUNTRY LIKE :0;', ['Switzerland']);
Assert.AreEqual(1, ActualInt);
end;
procedure TTestIBXAdapter.Test_FindOne_TEmployee(AId: Integer; const AFName, ALName: string);
var
Actual: TEmployee;
begin
Actual := Session.FindOne<TEmployee>(AId);
try
Assert.IsNotNull(Actual);
Assert.AreEqual(AID, Actual.Id);
Assert.AreEqual(AFName, Actual.Firstname);
Assert.AreEqual(ALName, Actual.Lastname);
finally
FreeAndNil(Actual);
end;
end;
procedure TTestIBXAdapter.Test_FindAll_TEmployee;
var
Actual: IList<TEmployee>;
begin
Actual := Session.FindAll<TEmployee>;
Assert.AreEqual(42, Actual.Count);
Assert.AreEqual(2, Actual[0].Id);
Assert.AreEqual('Robert', Actual[0].Firstname);
Assert.AreEqual('Nelson', Actual[0].Lastname);
Assert.AreEqual('600', Actual[0].DepartmentId);
Assert.AreEqual(4, Actual[1].Id);
Assert.AreEqual('Bruce', Actual[1].Firstname);
Assert.AreEqual('Young', Actual[1].Lastname);
Assert.AreEqual('621', Actual[1].DepartmentId);
end;
procedure TTestIBXAdapter.Test_Execute_TCountry;
const
InsertMcd = 'INSERT INTO COUNTRY (COUNTRY, CURRENCY) VALUES (''EURO'', ''EUR'');';
var
Actual: NativeUInt;
begin
Actual := Session.Execute(InsertMcd, []);
Assert.AreEqual(1, Actual);
Actual := Session.ExecuteScalar<Integer>('SELECT COUNT(*) FROM COUNTRY', []);
Assert.AreEqual(15, Actual);
end;
procedure TTestIBXAdapter.Test_InsertsUpdatesAndDeletes_TEmployee;
var
Actual: TEmployee;
begin
Connection.AddExecutionListener(
procedure(const command: string; const params: IEnumerable<TDBParam>)
begin
Assert.AreNotEqual('', command);
end);
Actual := TEmployee.Create;
try
Actual.Firstname := 'Nathan';
Actual.Lastname := 'Thurnreiter';
Actual.PhoneExt := '221';
Actual.HireDate := Now();
Actual.DepartmentId := '622';
Actual.JobCode := 'Eng';
Actual.JobGrande := 5;
Actual.JobCountry := 'USA';
Actual.Salary := 32000;
// most of the time you should use save, which will automatically insert or update your PODO based on it's state...
Session.Save(Actual);
// explicitly inserts customer into the database...
// don't call again, after save...
// Session.Insert(Actual);
Actual.JobCode := 'CEO';
// explicitly updates customer's name in the database...
Session.Update(Actual);
// deletes customer from the database...
Session.Delete(Actual);
finally
FreeAndNil(Actual);
end;
Actual := Session.FindOne<TEmployee>(146);
Assert.IsNull(Actual);
end;
procedure TTestIBXAdapter.Test_CriteriaAPI_LooksLikeLinq_TEmployee;
var
Actual: IList<TEmployee>;
Linq: ICriteria<TEmployee>;
begin
Linq := Session.CreateCriteria<TEmployee>;
Actual := Linq.Add(
Restrictions.Eq('JOB_CODE', 'Eng')
).ToList;
Assert.AreEqual(15, Actual.Count);
end;
procedure TTestIBXAdapter.Test_FindOne_TCountry;
var
Actual: TCountry;
begin
// Actual := Session.SingleOrDefault<TArbeit>('SELECT * FROM ARBEIT WHERE ARB_FNR=:0', [365]);
Actual := Session.FindOne<TCountry>('Switzerland');
try
Assert.IsNotNull(Actual);
Assert.AreEqual('Switzerland', Actual.Country);
Assert.AreEqual('SFranc', Actual.Currency);
finally
Actual.Free;
end;
end;
procedure TTestIBXAdapter.Test_FindOne_TSalaryHistory;
var
Actual: TSalaryHistory;
begin
Actual := Session.FindOne<TSalaryHistory>(105);
try
Assert.IsNotNull(Actual);
Assert.AreEqual(105, Actual.Id);
Assert.AreEqual(220000, Actual.OldSalary, 1);
Assert.AreEqual(-3.25, Actual.PercentChange, 1);
Assert.AreEqual(212850, Actual.NewSalary, 1);
finally
Actual.Free;
end;
end;
procedure TTestIBXAdapter.Test_FindOne_TEmployee_TSalaryHistory;
var
Actual: TEmployee;
begin
Actual := Session.FindOne<TEmployee>(105);
try
Assert.IsNotNull(Actual);
Assert.AreEqual(105, Actual.Id);
Assert.AreEqual('Oliver H.', Actual.Firstname);
Assert.AreEqual('Bender', Actual.Lastname);
Assert.AreEqual(1, Actual.SalaryHistory.Count);
Assert.AreEqual(220000, Actual.SalaryHistory[0].OldSalary, 1);
finally
Actual.Free;
end;
end;
procedure TTestIBXAdapter.Test_FindOne_TSalaryHistoryFull;
var
Actual: TSalaryHistory;
begin
Actual := Session.FindOne<TSalaryHistory>(121);
try
Assert.IsNotNull(Actual);
Assert.AreEqual(121, Actual.ID);
Assert.AreEqual('20.12.1993', DateToStr(Actual.ChangeDate));
Assert.AreEqual('elaine', Actual.UpdaterId);
Assert.AreEqual(90000000, Actual.OldSalary, 1);
Assert.AreEqual(10, Actual.PercentChange, 1);
Assert.AreEqual(99000000, Actual.NewSalary, 1);
finally
Actual.Free;
end;
end;
initialization
TDUnitX.RegisterTestFixture(TTestIBXAdapter);
end.
|
unit OpenCncDialog;
interface
uses
SysUtils, Classes, Dialogs;
type
TOpenCncDialog = class(TOpenDialog)
private
FPicturePanel: TPanel;
FPictureLabel: TLabel;
FPreviewButton: TSpeedButton;
FPaintPanel: TPanel;
FImageCtrl: TImage;
FSavedFilename: string;
function IsFilterStored: Boolean;
procedure PreviewKeyPress(Sender: TObject; var Key: Char);
protected
procedure PreviewClick(Sender: TObject); virtual;
procedure DoClose; override;
procedure DoSelectionChange; override;
procedure DoShow; override;
property ImageCtrl: TImage read FImageCtrl;
property PictureLabel: TLabel read FPictureLabel;
published
property Filter stored IsFilterStored;
public
constructor Create(AOwner: TComponent); override;
function Execute: Boolean; override;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Cnc', [TOpenCncDialog]);
end;
end.
|
// **************************************************************************************************
// CPUID for Delphi.
// Unit CPUID
// https://github.com/MahdiSafsafi/delphi-detours-library
// 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 CPUID.pas.
//
// The Initial Developer of the Original Code is Mahdi Safsafi [SMP3].
// Portions created by Mahdi Safsafi . are Copyright (C) 2013-2017 Mahdi Safsafi .
// All Rights Reserved.
//
// **************************************************************************************************
unit CPUID;
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF FPC}
interface
{$I Defs.inc}
uses SysUtils;
type
{ Do not change registers order ! }
TCPUIDStruct = packed record
rEAX: UInt32; { EAX Register }
rEBX: UInt32; { EBX Register }
rEDX: UInt32; { EDX Register }
rECX: UInt32; { ECX Register }
end;
PCPUIDStruct = ^TCPUIDStruct;
procedure CallCPUID(const ID: NativeUInt; var CPUIDStruct: TCPUIDStruct);
function IsCPUIDSupported: Boolean;
type
TCPUVendor = (vUnknown, vIntel, vAMD, vNextGen);
TCPUEncoding = set of (REX, VEX, EVEX);
TCPUInstructions = set of (iMultiNop);
var
CPUVendor: TCPUVendor;
CPUEncoding: TCPUEncoding;
CPUInsts: TCPUInstructions;
implementation
var
CPUIDSupported: Boolean = False;
function ___IsCPUIDSupported: Boolean;
asm
{$IFDEF CPUX86}
PUSH ECX
PUSHFD
POP EAX { EAX = EFLAGS }
MOV ECX, EAX { Save the original EFLAGS value . }
{
CPUID is supported only if we can modify
bit 21 of EFLAGS register !
}
XOR EAX, $200000
PUSH EAX
POPFD { Set the new EFLAGS value }
PUSHFD
POP EAX { Read EFLAGS }
{
Check if the 21 bit was modified !
If so ==> Return True .
else ==> Return False.
}
XOR EAX, ECX
SHR EAX, 21
AND EAX, 1
PUSH ECX
POPFD { Restore original EFLAGS value . }
POP ECX
{$ELSE !CPUX86}
PUSH RCX
MOV RCX,RCX
PUSHFQ
POP RAX
MOV RCX, RAX
XOR RAX, $200000
PUSH RAX
POPFQ
PUSHFQ
POP RAX
XOR RAX, RCX
SHR RAX, 21
AND RAX, 1
PUSH RCX
POPFQ
POP RCX
{$ENDIF CPUX86}
end;
procedure ___CallCPUID(const ID: NativeInt; var CPUIDStruct);
asm
{
ALL REGISTERS (rDX,rCX,rBX) MUST BE SAVED BEFORE
EXECUTING CPUID INSTRUCTION !
}
{$IFDEF CPUX86}
PUSH EDI
PUSH ECX
PUSH EBX
MOV EDI,EDX
CPUID
{$IFNDEF FPC}
MOV EDI.TCPUIDStruct.rEAX,EAX
MOV EDI.TCPUIDStruct.rEBX,EBX
MOV EDI.TCPUIDStruct.rECX,ECX
MOV EDI.TCPUIDStruct.rEDX,EDX
{$ELSE FPC}
MOV [EDI].TCPUIDStruct.rEAX,EAX
MOV [EDI].TCPUIDStruct.rEBX,EBX
MOV [EDI].TCPUIDStruct.rECX,ECX
MOV [EDI].TCPUIDStruct.rEDX,EDX
{$ENDIF !FPC}
POP EBX
POP ECX
POP EDI
{$ELSE !CPUX86}
PUSH R9
PUSH RBX
PUSH RDX
MOV RAX,RCX
MOV R9,RDX
CPUID
MOV [R9].TCPUIDStruct.rEAX,EAX
MOV [R9].TCPUIDStruct.rEBX,EBX
MOV [R9].TCPUIDStruct.rECX,ECX
MOV [R9].TCPUIDStruct.rEDX,EDX
POP RDX
POP RBX
POP R9
{$ENDIF CPUX86}
end;
function ___IsAVXSupported: Boolean;
asm
{
Checking for AVX support requires 3 steps:
1) Detect CPUID.1:ECX.OSXSAVE[bit 27] = 1
=> XGETBV enabled for application use
2) Detect CPUID.1:ECX.AVX[bit 28] = 1
=> AVX instructions supported.
3) Issue XGETBV and verify that XCR0[2:1] = ‘11b’
=> XMM state and YMM state are enabled by OS.
}
{ Steps : 1 and 2 }
{$IFDEF CPUX64}
MOV RAX, 1
PUSH RCX
PUSH RBX
PUSH RDX
{$ELSE !CPUX64}
MOV EAX, 1
PUSH ECX
PUSH EBX
PUSH EDX
{$ENDIF CPUX64}
CPUID
AND ECX, $018000000
CMP ECX, $018000000
JNE @@NOT_SUPPORTED
XOR ECX,ECX
{
Delphi does not support XGETBV !
=> We need to use the XGETBV opcodes !
}
DB $0F DB $01 DB $D0 // XGETBV
{ Step :3 }
AND EAX, $06
CMP EAX, $06
JNE @@NOT_SUPPORTED
MOV EAX, 1
JMP @@END
@@NOT_SUPPORTED:
XOR EAX,EAX
@@END:
{$IFDEF CPUX64}
POP RDX
POP RBX
POP RCX
{$ELSE !CPUX64}
POP EDX
POP EBX
POP ECX
{$ENDIF CPUX64}
end;
procedure CallCPUID(const ID: NativeUInt; var CPUIDStruct: TCPUIDStruct);
begin
FillChar(CPUIDStruct, SizeOf(TCPUIDStruct), #0);
if not CPUIDSupported then
raise Exception.Create('CPUID instruction not supported.')
else
___CallCPUID(ID, CPUIDStruct);
end;
function IsCPUIDSupported: Boolean;
begin
Result := CPUIDSupported;
end;
type
TVendorName = array [0 .. 12] of AnsiChar;
function GetVendorName: TVendorName;
var
Info: PCPUIDStruct;
P: PByte;
begin
Result := '';
if not IsCPUIDSupported then
Exit;
Info := GetMemory(SizeOf(TCPUIDStruct));
CallCPUID(0, Info^);
P := PByte(Info) + 4; // Skip EAX !
Move(P^, PByte(@Result[0])^, 12);
FreeMemory(Info);
end;
procedure __Init__;
var
vn: TVendorName;
Info: TCPUIDStruct;
r: UInt32;
begin
CPUVendor := vUnknown;
{$IFDEF CPUX64}
CPUEncoding := [REX];
{$ELSE !CPUX64}
CPUEncoding := [];
{$ENDIF CPUX64}
CPUInsts := [];
if IsCPUIDSupported then
begin
vn := GetVendorName();
if vn = 'GenuineIntel' then
CPUVendor := vIntel
else if vn = 'AuthenticAMD' then
CPUVendor := vAMD
else if vn = 'NexGenDriven' then
CPUVendor := vNextGen;
CallCPUID(1, Info);
r := Info.rEAX and $F00;
case r of
$F00, $600: Include(CPUInsts, iMultiNop);
end;
if ___IsAVXSupported then
Include(CPUEncoding, VEX);
end;
end;
initialization
CPUIDSupported := ___IsCPUIDSupported;
__Init__;
end.
|
{*******************************************************}
{ }
{ Delphi REST Client Framework }
{ }
{ Copyright(c) 2013-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
/// <summary>
/// Declares various common types and constants that are used throughout the REST library.
/// </summary>
unit REST.Types;
interface
uses
System.Classes,
System.SysUtils,
System.Math;
type
TMethod = Procedure of Object;
TMethod<T> = Procedure(Arg1: T) of Object;
/// <summary>
/// A TCompletionHandler is an anonymous method, that gets called after a asynchronous operation successfully
/// completes.
/// </summary>
TCompletionHandler = TProc;
TCompletionHandlerWithError = TProc<TObject>;
TRESTObjectOwnership = (ooCopy, ooREST, ooApp);
/// <summary>
/// Flags that control the utilization of request-parameters
/// </summary>
TRESTRequestParameterOption = (
/// <summary>
/// Indicates that the value of this parameter should be used as-is
/// and not encoded by the component
/// </summary>
poDoNotEncode,
/// <summary>
/// A transient parameter is typically created and managed by
/// attached components (like an authenticator) at runtime
/// </summary>
poTransient,
/// <summary>
/// Indicates that a parameter was created by the component
/// while parsing the base-url or resource
/// </summary>
poAutoCreated,
/// <summary>
/// Indicates that the ';' separated list of values of this parameter
/// should be expanded into name=val1&...&name=valN
/// </summary>
poFlatArray,
/// <summary>
/// Indicates that the ';' separated list of values of this parameter
/// should be expanded into name[]=val1&...&name[]=valN
/// </summary>
poPHPArray,
/// <summary>
/// Indicates that the ';' separated list of values of this parameter
/// should be expanded into name=val1,...,valN
/// </summary>
poListArray
);
TRESTRequestParameterOptions = set of TRESTRequestParameterOption;
/// <summary>
/// Types of parameters that can be added to requests
/// </summary>
TRESTRequestParameterKind = (
/// <summary>
/// Parameter is put into a cookie
/// </summary>
pkCOOKIE,
/// <summary>
/// Parameter will sent as URL parameter (for GET requests) or as body
/// parameter (for POST/PUT requests)
/// </summary>
pkGETorPOST,
/// <summary>
/// <para>
/// Parameter will used as value for a URL segment. A URL segment can be
/// defined in a request's resource path: customer/{ID}
/// </para>
/// <para>
/// If a URL Segment parameter with a name of "ID", then its value will be
/// replaced for {ID} in the example above
/// </para>
/// </summary>
pkURLSEGMENT,
/// <summary>
/// Parameter will be put in the request's HTTP header
/// </summary>
pkHTTPHEADER,
/// <summary>
/// The parameter's value will be used as request body. If more than one
/// RequestBody parameter exists, the request will use a multi-part body.
/// </summary>
pkREQUESTBODY,
/// <summary>
/// The parameter's value will be used to attach file content to the request.
/// If this parameter exists, the request will use a multi-part body.
/// </summary>
pkFILE,
/// <summary>
/// Parameter will be explicitly sent as URL parameter (for all requests) in
/// contrast to pkGETorPOST, when parameter location depends on request type.
/// </summary>
pkQUERY
);
var
DefaultRESTRequestParameterKind: TRESTRequestParameterKind = TRESTRequestParameterKind.pkGETorPOST;
function RESTRequestParameterKindToString(const AKind: TRESTRequestParameterKind): string;
function RESTRequestParameterKindFromString(const AKindString: string): TRESTRequestParameterKind;
type
/// <summary>
/// Content
/// </summary>
TRESTContentType = (ctNone, ctAPPLICATION_ATOM_XML, ctAPPLICATION_ECMASCRIPT, ctAPPLICATION_EDI_X12,
ctAPPLICATION_EDIFACT, ctAPPLICATION_JSON, ctAPPLICATION_JAVASCRIPT, ctAPPLICATION_OCTET_STREAM, ctAPPLICATION_OGG,
ctAPPLICATION_PDF, ctAPPLICATION_POSTSCRIPT, ctAPPLICATION_RDF_XML, ctAPPLICATION_RSS_XML, ctAPPLICATION_SOAP_XML,
ctAPPLICATION_FONT_WOFF, ctAPPLICATION_XHTML_XML, ctAPPLICATION_XML, ctAPPLICATION_XML_DTD, ctAPPLICATION_XOP_XML,
ctAPPLICATION_ZIP, ctAPPLICATION_GZIP, ctTEXT_CMD, ctTEXT_CSS, ctTEXT_CSV, ctTEXT_HTML, ctTEXT_JAVASCRIPT,
ctTEXT_PLAIN, ctTEXT_VCARD, ctTEXT_XML, ctAUDIO_BASIC, ctAUDIO_L24, ctAUDIO_MP4, ctAUDIO_MPEG, ctAUDIO_OGG,
ctAUDIO_VORBIS, ctAUDIO_VND_RN_REALAUDIO, ctAUDIO_VND_WAVE, ctAUDIO_WEBM, ctIMAGE_GIF, ctIMAGE_JPEG, ctIMAGE_PJPEG,
ctIMAGE_PNG, ctIMAGE_SVG_XML, ctIMAGE_TIFF, ctMESSAGE_HTTP, ctMESSAGE_IMDN_XML, ctMESSAGE_PARTIAL, ctMESSAGE_RFC822,
ctMODEL_EXAMPLE, ctMODEL_IGES, ctMODEL_MESH, ctMODEL_VRML, ctMODEL_X3D_BINARY, ctMODEL_X3D_VRML, ctMODEL_X3D_XML,
ctMULTIPART_MIXED, ctMULTIPART_ALTERNATIVE, ctMULTIPART_RELATED, ctMULTIPART_FORM_DATA, ctMULTIPART_SIGNED,
ctMULTIPART_ENCRYPTED, ctVIDEO_MPEG, ctVIDEO_MP4, ctVIDEO_OGG, ctVIDEO_QUICKTIME, ctVIDEO_WEBM, ctVIDEO_X_MATROSKA,
ctVIDEO_X_MS_WMV, ctVIDEO_X_FLV, ctAPPLICATION_VND_OASIS_OPENDOCUMENT_TEXT,
ctAPPLICATION_VND_OASIS_OPENDOCUMENT_SPREADSHEET, ctAPPLICATION_VND_OASIS_OPENDOCUMENT_PRESENTATION,
ctAPPLICATION_VND_OASIS_OPENDOCUMENT_GRAPHICS, ctAPPLICATION_VND_MS_EXCEL,
ctAPPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_SPREADSHEETML_SHEET, ctAPPLICATION_VND_MS_POWERPOINT,
ctAPPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_PRESENTATIONML_PRESENTATION,
ctAPPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT, ctAPPLICATION_VND_MOZILLA_XUL_XML,
ctAPPLICATION_VND_GOOGLE_EARTH_KML_XML, ctAPPLICATION_VND_GOOGLE_EARTH_KMZ, ctAPPLICATION_VND_DART,
ctAPPLICATION_VND_ANDROID_PACKAGE_ARCHIVE, ctAPPLICATION_X_DEB, ctAPPLICATION_X_DVI, ctAPPLICATION_X_FONT_TTF,
ctAPPLICATION_X_JAVASCRIPT, ctAPPLICATION_X_LATEX, ctAPPLICATION_X_MPEGURL, ctAPPLICATION_X_RAR_COMPRESSED,
ctAPPLICATION_X_SHOCKWAVE_FLASH, ctAPPLICATION_X_STUFFIT, ctAPPLICATION_X_TAR, ctAPPLICATION_X_WWW_FORM_URLENCODED,
ctAPPLICATION_X_XPINSTALL, ctAUDIO_X_AAC, ctAUDIO_X_CAF, ctIMAGE_X_XCF, ctTEXT_X_GWT_RPC, ctTEXT_X_JQUERY_TMPL,
ctTEXT_X_MARKDOWN, ctAPPLICATION_X_PKCS12, ctAPPLICATION_X_PKCS7_CERTIFICATES, ctAPPLICATION_X_PKCS7_CERTREQRESP,
ctAPPLICATION_X_PKCS7_MIME, ctAPPLICATION_X_PKCS7_SIGNATURE, ctAPPLICATION_VND_EMBARCADERO_FIREDAC_JSON);
var
DefaultRESTContentType: TRESTContentType = TRESTContentType.ctNone;
const
/// <summary>
/// HTTP Content-Type (or MIME Types as per RFC 2046) header definitions.
/// </summary>
/// <remarks>
/// <para>
/// See: http://tools.ietf.org/html/rfc2046
/// </para>
/// <para>
/// Values collected from https://en.wikipedia.org/wiki/MIME_type
/// </para>
/// </remarks>
CONTENTTYPE_NONE = ''; // do not localize
// Type Application
CONTENTTYPE_APPLICATION_ATOM_XML = 'application/atom+xml'; // do not localize
CONTENTTYPE_APPLICATION_ECMASCRIPT = 'application/ecmascript'; // do not localize
CONTENTTYPE_APPLICATION_EDI_X12 = 'application/EDI-X12'; // do not localize
CONTENTTYPE_APPLICATION_EDIFACT = 'application/EDIFACT'; // do not localize
CONTENTTYPE_APPLICATION_JSON = 'application/json'; // do not localize
CONTENTTYPE_APPLICATION_JAVASCRIPT = 'application/javascript'; // do not localize
CONTENTTYPE_APPLICATION_OCTET_STREAM = 'application/octet-stream'; // do not localize
CONTENTTYPE_APPLICATION_OGG = 'application/ogg'; // do not localize
CONTENTTYPE_APPLICATION_PDF = 'application/pdf'; // do not localize
CONTENTTYPE_APPLICATION_POSTSCRIPT = 'application/postscript'; // do not localize
CONTENTTYPE_APPLICATION_RDF_XML = 'application/rdf+xml'; // do not localize
CONTENTTYPE_APPLICATION_RSS_XML = 'application/rss+xml'; // do not localize
CONTENTTYPE_APPLICATION_SOAP_XML = 'application/soap+xml'; // do not localize
CONTENTTYPE_APPLICATION_FONT_WOFF = 'application/font-woff'; // do not localize
CONTENTTYPE_APPLICATION_XHTML_XML = 'application/xhtml+xml'; // do not localize
CONTENTTYPE_APPLICATION_XML = 'application/xml'; // do not localize
CONTENTTYPE_APPLICATION_XML_DTD = 'application/xml-dtd'; // do not localize
CONTENTTYPE_APPLICATION_XOP_XML = 'application/xop+xml'; // do not localize
CONTENTTYPE_APPLICATION_ZIP = 'application/zip'; // do not localize
CONTENTTYPE_APPLICATION_GZIP = 'application/gzip'; // do not localize
// Type Text
CONTENTTYPE_TEXT_CMD = 'text/cmd'; // do not localize
CONTENTTYPE_TEXT_CSS = 'text/css'; // do not localize
CONTENTTYPE_TEXT_CSV = 'text/csv'; // do not localize
CONTENTTYPE_TEXT_HTML = 'text/html'; // do not localize
CONTENTTYPE_TEXT_JAVASCRIPT = 'text/javascript'; // do not localize
CONTENTTYPE_TEXT_PLAIN = 'text/plain'; // do not localize
CONTENTTYPE_TEXT_VCARD = 'text/vcard'; // do not localize
CONTENTTYPE_TEXT_XML = 'text/xml'; // do not localize
// Type Audio
CONTENTTYPE_AUDIO_BASIC = 'audio/basic'; // do not localize
CONTENTTYPE_AUDIO_L24 = 'audio/L24'; // do not localize
CONTENTTYPE_AUDIO_MP4 = 'audio/mp4'; // do not localize
CONTENTTYPE_AUDIO_MPEG = 'audio/mpeg'; // do not localize
CONTENTTYPE_AUDIO_OGG = 'audio/ogg'; // do not localize
CONTENTTYPE_AUDIO_VORBIS = 'audio/vorbis'; // do not localize
CONTENTTYPE_AUDIO_VND_RN_REALAUDIO = 'audio/vnd.rn-realaudio'; // do not localize
CONTENTTYPE_AUDIO_VND_WAVE = 'audio/vnd.wave'; // do not localize
CONTENTTYPE_AUDIO_WEBM = 'audio/webm'; // do not localize
// Type Image
CONTENTTYPE_IMAGE_GIF = 'image/gif'; // do not localize
CONTENTTYPE_IMAGE_JPEG = 'image/jpeg'; // do not localize
CONTENTTYPE_IMAGE_PJPEG = 'image/pjpeg'; // do not localize
CONTENTTYPE_IMAGE_PNG = 'image/png'; // do not localize
CONTENTTYPE_IMAGE_SVG_XML = 'image/svg+xml'; // do not localize
CONTENTTYPE_IMAGE_TIFF = 'image/tiff'; // do not localize
// Type Message
CONTENTTYPE_MESSAGE_HTTP = 'message/http'; // do not localize
CONTENTTYPE_MESSAGE_IMDN_XML = 'message/imdn+xml'; // do not localize
CONTENTTYPE_MESSAGE_PARTIAL = 'message/partial'; // do not localize
CONTENTTYPE_MESSAGE_RFC822 = 'message/rfc822'; // do not localize
// Type Model (3D Models)
CONTENTTYPE_MODEL_EXAMPLE = 'model/example'; // do not localize
CONTENTTYPE_MODEL_IGES = 'model/iges'; // do not localize
CONTENTTYPE_MODEL_MESH = 'model/mesh'; // do not localize
CONTENTTYPE_MODEL_VRML = 'model/vrml'; // do not localize
CONTENTTYPE_MODEL_X3D_BINARY = 'model/x3d+binary'; // do not localize
CONTENTTYPE_MODEL_X3D_VRML = 'model/x3d+vrml'; // do not localize
CONTENTTYPE_MODEL_X3D_XML = 'model/x3d+xml'; // do not localize
// Type Multipart
CONTENTTYPE_MULTIPART_MIXED = 'multipart/mixed'; // do not localize
CONTENTTYPE_MULTIPART_ALTERNATIVE = 'multipart/alternative'; // do not localize
CONTENTTYPE_MULTIPART_RELATED = 'multipart/related'; // do not localize
CONTENTTYPE_MULTIPART_FORM_DATA = 'multipart/form-data'; // do not localize
CONTENTTYPE_MULTIPART_SIGNED = 'multipart/signed'; // do not localize
CONTENTTYPE_MULTIPART_ENCRYPTED = 'multipart/encrypted'; // do not localize
// Type Video
CONTENTTYPE_VIDEO_MPEG = 'video/mpeg'; // do not localize
CONTENTTYPE_VIDEO_MP4 = 'video/mp4'; // do not localize
CONTENTTYPE_VIDEO_OGG = 'video/ogg'; // do not localize
CONTENTTYPE_VIDEO_QUICKTIME = 'video/quicktime'; // do not localize
CONTENTTYPE_VIDEO_WEBM = 'video/webm'; // do not localize
CONTENTTYPE_VIDEO_X_MATROSKA = 'video/x-matroska'; // do not localize
CONTENTTYPE_VIDEO_X_MS_WMV = 'video/x-ms-wmv'; // do not localize
CONTENTTYPE_VIDEO_X_FLV = 'video/x-flv'; // do not localize
// Type Application - Vendor Specific
CONTENTTYPE_APPLICATION_VND_OASIS_OPENDOCUMENT_TEXT = 'application/vnd.oasis.opendocument.text'; // do not localize
CONTENTTYPE_APPLICATION_VND_OASIS_OPENDOCUMENT_SPREADSHEET = 'application/vnd.oasis.opendocument.spreadsheet';
// do not localize
CONTENTTYPE_APPLICATION_VND_OASIS_OPENDOCUMENT_PRESENTATION = 'application/vnd.oasis.opendocument.presentation';
// do not localize
CONTENTTYPE_APPLICATION_VND_OASIS_OPENDOCUMENT_GRAPHICS = 'application/vnd.oasis.opendocument.graphics';
// do not localize
CONTENTTYPE_APPLICATION_VND_MS_EXCEL = 'application/vnd.ms-excel'; // do not localize
CONTENTTYPE_APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_SPREADSHEETML_SHEET =
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; // do not localize
CONTENTTYPE_APPLICATION_VND_MS_POWERPOINT = 'application/vnd.ms-powerpoint'; // do not localize
CONTENTTYPE_APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_PRESENTATIONML_PRESENTATION =
'application/vnd.openxmlformats-officedocument.presentationml.presentation'; // do not localize
CONTENTTYPE_APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT =
'application/vnd.openxmlformats-officedocument.wordprocessingml.document'; // do not localize
CONTENTTYPE_APPLICATION_VND_MOZILLA_XUL_XML = 'application/vnd.mozilla.xul+xml'; // do not localize
CONTENTTYPE_APPLICATION_VND_GOOGLE_EARTH_KML_XML = 'application/vnd.google-earth.kml+xml'; // do not localize
CONTENTTYPE_APPLICATION_VND_GOOGLE_EARTH_KMZ = 'application/vnd.google-earth.kmz'; // do not localize
CONTENTTYPE_APPLICATION_VND_DART = 'application/vnd.dart'; // do not localize
CONTENTTYPE_APPLICATION_VND_ANDROID_PACKAGE_ARCHIVE = 'application/vnd.android.package-archive'; // do not localize
// Type X (RFC 6648)
CONTENTTYPE_APPLICATION_X_DEB = 'application/x-deb'; // do not localize
CONTENTTYPE_APPLICATION_X_DVI = 'application/x-dvi'; // do not localize
CONTENTTYPE_APPLICATION_X_FONT_TTF = 'application/x-font-ttf'; // do not localize
CONTENTTYPE_APPLICATION_X_JAVASCRIPT = 'application/x-javascript'; // do not localize
CONTENTTYPE_APPLICATION_X_LATEX = 'application/x-latex'; // do not localize
CONTENTTYPE_APPLICATION_X_MPEGURL = 'application/x-mpegURL'; // do not localize
CONTENTTYPE_APPLICATION_X_RAR_COMPRESSED = 'application/x-rar-compressed'; // do not localize
CONTENTTYPE_APPLICATION_X_SHOCKWAVE_FLASH = 'application/x-shockwave-flash'; // do not localize
CONTENTTYPE_APPLICATION_X_STUFFIT = 'application/x-stuffit'; // do not localize
CONTENTTYPE_APPLICATION_X_TAR = 'application/x-tar'; // do not localize
CONTENTTYPE_APPLICATION_X_WWW_FORM_URLENCODED = 'application/x-www-form-urlencoded'; // do not localize
CONTENTTYPE_APPLICATION_X_XPINSTALL = 'application/x-xpinstall'; // do not localize
CONTENTTYPE_AUDIO_X_AAC = 'audio/x-aac'; // do not localize
CONTENTTYPE_AUDIO_X_CAF = 'audio/x-caf'; // do not localize
CONTENTTYPE_IMAGE_X_XCF = 'image/x-xcf'; // do not localize
CONTENTTYPE_TEXT_X_GWT_RPC = 'text/x-gwt-rpc'; // do not localize
CONTENTTYPE_TEXT_X_JQUERY_TMPL = 'text/x-jquery-tmpl'; // do not localize
CONTENTTYPE_TEXT_X_MARKDOWN = 'text/x-markdown'; // do not localize
// Type PKCS (Cryptography)
CONTENTTYPE_APPLICATION_X_PKCS12 = 'application/x-pkcs12'; // do not localize
CONTENTTYPE_APPLICATION_X_PKCS7_CERTIFICATES = 'application/x-pkcs7-certificates'; // do not localize
CONTENTTYPE_APPLICATION_X_PKCS7_CERTREQRESP = 'application/x-pkcs7-certreqresp'; // do not localize
CONTENTTYPE_APPLICATION_X_PKCS7_MIME = 'application/x-pkcs7-mime'; // do not localize
CONTENTTYPE_APPLICATION_X_PKCS7_SIGNATURE = 'application/x-pkcs7-signature'; // do not localize
// Type Application - Embarcadero Specific
CONTENTTYPE_APPLICATION_VND_EMBARCADERO_FIREDAC_JSON = 'application/vnd.embarcadero.firedac+json'; // do not localize
function ContentTypeToString(AContentType: TRESTContentType): string;
function ContentTypeFromString(const AContentType: string): TRESTContentType;
function IsTextualContentType(AContentType: TRESTContentType) : boolean; overload;
function IsTextualContentType(const AContentType: string) : boolean; overload;
type
/// <summary>
/// Structure that holds performance related information that is gathered while executing a request.<br />All
/// values are in milliseconds.
/// </summary>
TExecutionPerformance = record
FStartTime: Cardinal;
procedure Start;
procedure Clear;
procedure PreProcessingDone;
procedure ExecutionDone;
procedure PostProcessingDone;
public
/// <summary>
/// Time from starting the execution until the request is handed over to the the actual http client and sent to
/// the server. This includes time which is needed to prepare parameter, encode a body and other things.
/// </summary>
PreProcessingTime: integer;
/// <summary>
/// The time that the request took to be sent to the server and until the response has been received. This does
/// <i>not</i> include any JSON parsing etc.
/// </summary>
ExecutionTime: integer;
/// <summary>
/// The time from when the server response has been received until all post processing (including JSON parsing).
/// Events, observer notification or completion handlers are <i>not</i> taken into account here.
/// </summary>
PostProcessingTime: integer;
/// <summary>
/// The total execution time, which is the sum of PreProcessingTime, ExecutionTime and PostProcessingTime
/// </summary>
function TotalExecutionTime: integer;
end;
/// <summary>
/// Designates standard HTTP/REST Methods. All methods may affect single or
/// multiple objects/entities.
/// </summary>
/// <remarks>
/// See http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
/// </remarks>
TRESTRequestMethod = (
/// <summary>
/// Sends a NEW object/entity to the server.
/// </summary>
rmPOST,
/// <summary>
/// Updates an already existing object/entity on the server. PUT may also
/// allow for sending a new entity (depends on the actual server/API
/// implementation).
/// </summary>
rmPUT,
/// <summary>
/// Retrieves an object/entity from the server.
/// </summary>
rmGET,
/// <summary>
/// Deletes an object/entity from the server.
/// </summary>
rmDELETE,
/// <summary>
/// Patches an object/entity on the server, by only updating the pairs that are sent within that PATCH body.
/// </summary>
rmPATCH
);
/// <summary>
/// Exceptions coming from the REST Library have this common ancestor
/// </summary>
ERESTException = class(Exception)
end;
ERequestError = class(ERESTException)
private
FResponseContent: string;
FStatusCode: Integer;
FStatusText: string;
public
constructor Create(AStatusCode: Integer; const AStatusText: string; const AResponseContent: string); reintroduce;
property ResponseContent: string read FResponseContent write FResponseContent;
property StatusCode: Integer read FStatusCode write FStatusCode;
property StatusText: string read FStatusText write FStatusText;
end;
var
DefaultRESTRequestMethod: TRESTRequestMethod = TRESTRequestMethod.rmGET;
function RESTRequestMethodToString(const AMethod: TRESTRequestMethod): string;
implementation
uses REST.Consts;
function IsTextualContentType(const AContentType: string) : boolean;
begin
result:= IsTextualContentType( ContentTypeFromString(AContentType) );
end;
function IsTextualContentType(AContentType: TRESTContentType) : boolean;
begin
if (AContentType IN [
ctTEXT_CMD, ctTEXT_CSS, ctTEXT_CSV, ctTEXT_HTML, ctTEXT_JAVASCRIPT,
ctTEXT_PLAIN, ctTEXT_XML,
ctAPPLICATION_ATOM_XML, ctAPPLICATION_JSON, ctAPPLICATION_JAVASCRIPT,
ctAPPLICATION_RDF_XML, ctAPPLICATION_RSS_XML, ctAPPLICATION_SOAP_XML,
ctAPPLICATION_XHTML_XML, ctAPPLICATION_XML, ctAPPLICATION_XML_DTD
]) then
result:= TRUE
else
result:= FALSE;
end;
function RESTRequestParameterKindToString(const AKind: TRESTRequestParameterKind): string;
begin
case AKind of
TRESTRequestParameterKind.pkCOOKIE:
result := 'COOKIE';
TRESTRequestParameterKind.pkGETorPOST:
result := 'GET/POST';
TRESTRequestParameterKind.pkURLSEGMENT:
result := 'URL-SEGMENT';
TRESTRequestParameterKind.pkHTTPHEADER:
result := 'HEADER';
TRESTRequestParameterKind.pkREQUESTBODY:
result := 'BODY';
TRESTRequestParameterKind.pkFILE:
result := 'FILE';
TRESTRequestParameterKind.pkQUERY:
result := 'QUERY';
else
result := Format('RESTRequestParameterKindToString - unknown Kind: %d', [integer(AKind)]);
end;
end;
function RESTRequestParameterKindFromString(const AKindString: string): TRESTRequestParameterKind;
var
LKind: TRESTRequestParameterKind;
begin
result := DefaultRESTRequestParameterKind;
for LKind in [low(TRESTRequestParameterKind) .. high(TRESTRequestParameterKind)] do
if (SameText(AKindString, RESTRequestParameterKindToString(LKind))) then
begin
result := LKind;
BREAK;
end;
end;
function RESTRequestMethodToString(const AMethod: TRESTRequestMethod): string;
begin
case AMethod of
TRESTRequestMethod.rmPOST:
result := 'POST';
TRESTRequestMethod.rmPUT:
result := 'PUT';
TRESTRequestMethod.rmGET:
result := 'GET';
TRESTRequestMethod.rmDELETE:
result := 'DELETE';
TRESTRequestMethod.rmPATCH:
result := 'PATCH'
else
result := Format('RESTRequestMethod2String - unknown Method: %d', [integer(AMethod)]);
end;
end;
function ContentTypeFromString(const AContentType: string): TRESTContentType;
var
LContentType: string;
begin
LContentType := AContentType.ToLower.Trim;
if LContentType = CONTENTTYPE_APPLICATION_ATOM_XML then
result := ctAPPLICATION_ATOM_XML
else if LContentType = CONTENTTYPE_APPLICATION_ECMASCRIPT then
result := ctAPPLICATION_ECMASCRIPT
else if LContentType = CONTENTTYPE_APPLICATION_EDI_X12 then
result := ctAPPLICATION_EDI_X12
else if LContentType = CONTENTTYPE_APPLICATION_EDIFACT then
result := ctAPPLICATION_EDIFACT
else if LContentType = CONTENTTYPE_APPLICATION_JSON then
result := ctAPPLICATION_JSON
else if LContentType = CONTENTTYPE_APPLICATION_JAVASCRIPT then
result := ctAPPLICATION_JAVASCRIPT
else if LContentType = CONTENTTYPE_APPLICATION_OCTET_STREAM then
result := ctAPPLICATION_OCTET_STREAM
else if LContentType = CONTENTTYPE_APPLICATION_OGG then
result := ctAPPLICATION_OGG
else if LContentType = CONTENTTYPE_APPLICATION_PDF then
result := ctAPPLICATION_PDF
else if LContentType = CONTENTTYPE_APPLICATION_POSTSCRIPT then
result := ctAPPLICATION_POSTSCRIPT
else if LContentType = CONTENTTYPE_APPLICATION_RDF_XML then
result := ctAPPLICATION_RDF_XML
else if LContentType = CONTENTTYPE_APPLICATION_RSS_XML then
result := ctAPPLICATION_RSS_XML
else if LContentType = CONTENTTYPE_APPLICATION_SOAP_XML then
result := ctAPPLICATION_SOAP_XML
else if LContentType = CONTENTTYPE_APPLICATION_FONT_WOFF then
result := ctAPPLICATION_FONT_WOFF
else if LContentType = CONTENTTYPE_APPLICATION_XHTML_XML then
result := ctAPPLICATION_XHTML_XML
else if LContentType = CONTENTTYPE_APPLICATION_XML then
result := ctAPPLICATION_XML
else if LContentType = CONTENTTYPE_APPLICATION_XML_DTD then
result := ctAPPLICATION_XML_DTD
else if LContentType = CONTENTTYPE_APPLICATION_XOP_XML then
result := ctAPPLICATION_XOP_XML
else if LContentType = CONTENTTYPE_APPLICATION_ZIP then
result := ctAPPLICATION_ZIP
else if LContentType = CONTENTTYPE_APPLICATION_GZIP then
result := ctAPPLICATION_GZIP
else if LContentType = CONTENTTYPE_TEXT_CMD then
result := ctTEXT_CMD
else if LContentType = CONTENTTYPE_TEXT_CSS then
result := ctTEXT_CSS
else if LContentType = CONTENTTYPE_TEXT_CSV then
result := ctTEXT_CSV
else if LContentType = CONTENTTYPE_TEXT_HTML then
result := ctTEXT_HTML
else if LContentType = CONTENTTYPE_TEXT_JAVASCRIPT then
result := ctTEXT_JAVASCRIPT
else if LContentType = CONTENTTYPE_TEXT_PLAIN then
result := ctTEXT_PLAIN
else if LContentType = CONTENTTYPE_TEXT_VCARD then
result := ctTEXT_VCARD
else if LContentType = CONTENTTYPE_TEXT_XML then
result := ctTEXT_XML
else if LContentType = CONTENTTYPE_AUDIO_BASIC then
result := ctAUDIO_BASIC
else if LContentType = CONTENTTYPE_AUDIO_L24 then
result := ctAUDIO_L24
else if LContentType = CONTENTTYPE_AUDIO_MP4 then
result := ctAUDIO_MP4
else if LContentType = CONTENTTYPE_AUDIO_MPEG then
result := ctAUDIO_MPEG
else if LContentType = CONTENTTYPE_AUDIO_OGG then
result := ctAUDIO_OGG
else if LContentType = CONTENTTYPE_AUDIO_VORBIS then
result := ctAUDIO_VORBIS
else if LContentType = CONTENTTYPE_AUDIO_VND_RN_REALAUDIO then
result := ctAUDIO_VND_RN_REALAUDIO
else if LContentType = CONTENTTYPE_AUDIO_VND_WAVE then
result := ctAUDIO_VND_WAVE
else if LContentType = CONTENTTYPE_AUDIO_WEBM then
result := ctAUDIO_WEBM
else if LContentType = CONTENTTYPE_IMAGE_GIF then
result := ctIMAGE_GIF
else if LContentType = CONTENTTYPE_IMAGE_JPEG then
result := ctIMAGE_JPEG
else if LContentType = CONTENTTYPE_IMAGE_PJPEG then
result := ctIMAGE_PJPEG
else if LContentType = CONTENTTYPE_IMAGE_PNG then
result := ctIMAGE_PNG
else if LContentType = CONTENTTYPE_IMAGE_SVG_XML then
result := ctIMAGE_SVG_XML
else if LContentType = CONTENTTYPE_IMAGE_TIFF then
result := ctIMAGE_TIFF
else if LContentType = CONTENTTYPE_MESSAGE_HTTP then
result := ctMESSAGE_HTTP
else if LContentType = CONTENTTYPE_MESSAGE_IMDN_XML then
result := ctMESSAGE_IMDN_XML
else if LContentType = CONTENTTYPE_MESSAGE_PARTIAL then
result := ctMESSAGE_PARTIAL
else if LContentType = CONTENTTYPE_MESSAGE_RFC822 then
result := ctMESSAGE_RFC822
else if LContentType = CONTENTTYPE_MODEL_EXAMPLE then
result := ctMODEL_EXAMPLE
else if LContentType = CONTENTTYPE_MODEL_IGES then
result := ctMODEL_IGES
else if LContentType = CONTENTTYPE_MODEL_MESH then
result := ctMODEL_MESH
else if LContentType = CONTENTTYPE_MODEL_VRML then
result := ctMODEL_VRML
else if LContentType = CONTENTTYPE_MODEL_X3D_BINARY then
result := ctMODEL_X3D_BINARY
else if LContentType = CONTENTTYPE_MODEL_X3D_VRML then
result := ctMODEL_X3D_VRML
else if LContentType = CONTENTTYPE_MODEL_X3D_XML then
result := ctMODEL_X3D_XML
else if LContentType = CONTENTTYPE_MULTIPART_MIXED then
result := ctMULTIPART_MIXED
else if LContentType = CONTENTTYPE_MULTIPART_ALTERNATIVE then
result := ctMULTIPART_ALTERNATIVE
else if LContentType = CONTENTTYPE_MULTIPART_RELATED then
result := ctMULTIPART_RELATED
else if LContentType = CONTENTTYPE_MULTIPART_FORM_DATA then
result := ctMULTIPART_FORM_DATA
else if LContentType = CONTENTTYPE_MULTIPART_SIGNED then
result := ctMULTIPART_SIGNED
else if LContentType = CONTENTTYPE_MULTIPART_ENCRYPTED then
result := ctMULTIPART_ENCRYPTED
else if LContentType = CONTENTTYPE_VIDEO_MPEG then
result := ctVIDEO_MPEG
else if LContentType = CONTENTTYPE_VIDEO_MP4 then
result := ctVIDEO_MP4
else if LContentType = CONTENTTYPE_VIDEO_OGG then
result := ctVIDEO_OGG
else if LContentType = CONTENTTYPE_VIDEO_QUICKTIME then
result := ctVIDEO_QUICKTIME
else if LContentType = CONTENTTYPE_VIDEO_WEBM then
result := ctVIDEO_WEBM
else if LContentType = CONTENTTYPE_VIDEO_X_MATROSKA then
result := ctVIDEO_X_MATROSKA
else if LContentType = CONTENTTYPE_VIDEO_X_MS_WMV then
result := ctVIDEO_X_MS_WMV
else if LContentType = CONTENTTYPE_VIDEO_X_FLV then
result := ctVIDEO_X_FLV
else if LContentType = CONTENTTYPE_APPLICATION_VND_OASIS_OPENDOCUMENT_TEXT then
result := ctAPPLICATION_VND_OASIS_OPENDOCUMENT_TEXT
else if LContentType = CONTENTTYPE_APPLICATION_VND_OASIS_OPENDOCUMENT_SPREADSHEET then
result := ctAPPLICATION_VND_OASIS_OPENDOCUMENT_SPREADSHEET
else if LContentType = CONTENTTYPE_APPLICATION_VND_OASIS_OPENDOCUMENT_PRESENTATION then
result := ctAPPLICATION_VND_OASIS_OPENDOCUMENT_PRESENTATION
else if LContentType = CONTENTTYPE_APPLICATION_VND_OASIS_OPENDOCUMENT_GRAPHICS then
result := ctAPPLICATION_VND_OASIS_OPENDOCUMENT_GRAPHICS
else if LContentType = CONTENTTYPE_APPLICATION_VND_MS_EXCEL then
result := ctAPPLICATION_VND_MS_EXCEL
else if LContentType = CONTENTTYPE_APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_SPREADSHEETML_SHEET then
result := ctAPPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_SPREADSHEETML_SHEET
else if LContentType = CONTENTTYPE_APPLICATION_VND_MS_POWERPOINT then
result := ctAPPLICATION_VND_MS_POWERPOINT
else if LContentType = CONTENTTYPE_APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_PRESENTATIONML_PRESENTATION then
result := ctAPPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_PRESENTATIONML_PRESENTATION
else if LContentType = CONTENTTYPE_APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT then
result := ctAPPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT
else if LContentType = CONTENTTYPE_APPLICATION_VND_MOZILLA_XUL_XML then
result := ctAPPLICATION_VND_MOZILLA_XUL_XML
else if LContentType = CONTENTTYPE_APPLICATION_VND_GOOGLE_EARTH_KML_XML then
result := ctAPPLICATION_VND_GOOGLE_EARTH_KML_XML
else if LContentType = CONTENTTYPE_APPLICATION_VND_GOOGLE_EARTH_KMZ then
result := ctAPPLICATION_VND_GOOGLE_EARTH_KMZ
else if LContentType = CONTENTTYPE_APPLICATION_VND_DART then
result := ctAPPLICATION_VND_DART
else if LContentType = CONTENTTYPE_APPLICATION_VND_ANDROID_PACKAGE_ARCHIVE then
result := ctAPPLICATION_VND_ANDROID_PACKAGE_ARCHIVE
else if LContentType = CONTENTTYPE_APPLICATION_X_DEB then
result := ctAPPLICATION_X_DEB
else if LContentType = CONTENTTYPE_APPLICATION_X_DVI then
result := ctAPPLICATION_X_DVI
else if LContentType = CONTENTTYPE_APPLICATION_X_FONT_TTF then
result := ctAPPLICATION_X_FONT_TTF
else if LContentType = CONTENTTYPE_APPLICATION_X_JAVASCRIPT then
result := ctAPPLICATION_X_JAVASCRIPT
else if LContentType = CONTENTTYPE_APPLICATION_X_LATEX then
result := ctAPPLICATION_X_LATEX
else if LContentType = CONTENTTYPE_APPLICATION_X_MPEGURL then
result := ctAPPLICATION_X_MPEGURL
else if LContentType = CONTENTTYPE_APPLICATION_X_RAR_COMPRESSED then
result := ctAPPLICATION_X_RAR_COMPRESSED
else if LContentType = CONTENTTYPE_APPLICATION_X_SHOCKWAVE_FLASH then
result := ctAPPLICATION_X_SHOCKWAVE_FLASH
else if LContentType = CONTENTTYPE_APPLICATION_X_STUFFIT then
result := ctAPPLICATION_X_STUFFIT
else if LContentType = CONTENTTYPE_APPLICATION_X_TAR then
result := ctAPPLICATION_X_TAR
else if LContentType = CONTENTTYPE_APPLICATION_X_WWW_FORM_URLENCODED then
result := ctAPPLICATION_X_WWW_FORM_URLENCODED
else if LContentType = CONTENTTYPE_APPLICATION_X_XPINSTALL then
result := ctAPPLICATION_X_XPINSTALL
else if LContentType = CONTENTTYPE_AUDIO_X_AAC then
result := ctAUDIO_X_AAC
else if LContentType = CONTENTTYPE_AUDIO_X_CAF then
result := ctAUDIO_X_CAF
else if LContentType = CONTENTTYPE_IMAGE_X_XCF then
result := ctIMAGE_X_XCF
else if LContentType = CONTENTTYPE_TEXT_X_GWT_RPC then
result := ctTEXT_X_GWT_RPC
else if LContentType = CONTENTTYPE_TEXT_X_JQUERY_TMPL then
result := ctTEXT_X_JQUERY_TMPL
else if LContentType = CONTENTTYPE_TEXT_X_MARKDOWN then
result := ctTEXT_X_MARKDOWN
else if LContentType = CONTENTTYPE_APPLICATION_X_PKCS12 then
result := ctAPPLICATION_X_PKCS12
else if LContentType = CONTENTTYPE_APPLICATION_X_PKCS7_CERTIFICATES then
result := ctAPPLICATION_X_PKCS7_CERTIFICATES
else if LContentType = CONTENTTYPE_APPLICATION_X_PKCS7_CERTREQRESP then
result := ctAPPLICATION_X_PKCS7_CERTREQRESP
else if LContentType = CONTENTTYPE_APPLICATION_X_PKCS7_MIME then
result := ctAPPLICATION_X_PKCS7_MIME
else if LContentType = CONTENTTYPE_APPLICATION_X_PKCS7_SIGNATURE then
result := ctAPPLICATION_X_PKCS7_SIGNATURE
else if LContentType = CONTENTTYPE_APPLICATION_VND_EMBARCADERO_FIREDAC_JSON then
result := ctAPPLICATION_VND_EMBARCADERO_FIREDAC_JSON
else
raise Exception.CreateFmt(sUnknownContentType, [LContentType]);
end;
function ContentTypeToString(AContentType: TRESTContentType): string;
begin
case AContentType of
ctAPPLICATION_ATOM_XML:
result := CONTENTTYPE_APPLICATION_ATOM_XML;
ctAPPLICATION_ECMASCRIPT:
result := CONTENTTYPE_APPLICATION_ECMASCRIPT;
ctAPPLICATION_EDI_X12:
result := CONTENTTYPE_APPLICATION_EDI_X12;
ctAPPLICATION_EDIFACT:
result := CONTENTTYPE_APPLICATION_EDIFACT;
ctAPPLICATION_JSON:
result := CONTENTTYPE_APPLICATION_JSON;
ctAPPLICATION_JAVASCRIPT:
result := CONTENTTYPE_APPLICATION_JAVASCRIPT;
ctAPPLICATION_OCTET_STREAM:
result := CONTENTTYPE_APPLICATION_OCTET_STREAM;
ctAPPLICATION_OGG:
result := CONTENTTYPE_APPLICATION_OGG;
ctAPPLICATION_PDF:
result := CONTENTTYPE_APPLICATION_PDF;
ctAPPLICATION_POSTSCRIPT:
result := CONTENTTYPE_APPLICATION_POSTSCRIPT;
ctAPPLICATION_RDF_XML:
result := CONTENTTYPE_APPLICATION_RDF_XML;
ctAPPLICATION_RSS_XML:
result := CONTENTTYPE_APPLICATION_RSS_XML;
ctAPPLICATION_SOAP_XML:
result := CONTENTTYPE_APPLICATION_SOAP_XML;
ctAPPLICATION_FONT_WOFF:
result := CONTENTTYPE_APPLICATION_FONT_WOFF;
ctAPPLICATION_XHTML_XML:
result := CONTENTTYPE_APPLICATION_XHTML_XML;
ctAPPLICATION_XML:
result := CONTENTTYPE_APPLICATION_XML;
ctAPPLICATION_XML_DTD:
result := CONTENTTYPE_APPLICATION_XML_DTD;
ctAPPLICATION_XOP_XML:
result := CONTENTTYPE_APPLICATION_XOP_XML;
ctAPPLICATION_ZIP:
result := CONTENTTYPE_APPLICATION_ZIP;
ctAPPLICATION_GZIP:
result := CONTENTTYPE_APPLICATION_GZIP;
ctTEXT_CMD:
result := CONTENTTYPE_TEXT_CMD;
ctTEXT_CSS:
result := CONTENTTYPE_TEXT_CSS;
ctTEXT_CSV:
result := CONTENTTYPE_TEXT_CSV;
ctTEXT_HTML:
result := CONTENTTYPE_TEXT_HTML;
ctTEXT_JAVASCRIPT:
result := CONTENTTYPE_TEXT_JAVASCRIPT;
ctTEXT_PLAIN:
result := CONTENTTYPE_TEXT_PLAIN;
ctTEXT_VCARD:
result := CONTENTTYPE_TEXT_VCARD;
ctTEXT_XML:
result := CONTENTTYPE_TEXT_XML;
ctAUDIO_BASIC:
result := CONTENTTYPE_AUDIO_BASIC;
ctAUDIO_L24:
result := CONTENTTYPE_AUDIO_L24;
ctAUDIO_MP4:
result := CONTENTTYPE_AUDIO_MP4;
ctAUDIO_MPEG:
result := CONTENTTYPE_AUDIO_MPEG;
ctAUDIO_OGG:
result := CONTENTTYPE_AUDIO_OGG;
ctAUDIO_VORBIS:
result := CONTENTTYPE_AUDIO_VORBIS;
ctAUDIO_VND_RN_REALAUDIO:
result := CONTENTTYPE_AUDIO_VND_RN_REALAUDIO;
ctAUDIO_VND_WAVE:
result := CONTENTTYPE_AUDIO_VND_WAVE;
ctAUDIO_WEBM:
result := CONTENTTYPE_AUDIO_WEBM;
ctIMAGE_GIF:
result := CONTENTTYPE_IMAGE_GIF;
ctIMAGE_JPEG:
result := CONTENTTYPE_IMAGE_JPEG;
ctIMAGE_PJPEG:
result := CONTENTTYPE_IMAGE_PJPEG;
ctIMAGE_PNG:
result := CONTENTTYPE_IMAGE_PNG;
ctIMAGE_SVG_XML:
result := CONTENTTYPE_IMAGE_SVG_XML;
ctIMAGE_TIFF:
result := CONTENTTYPE_IMAGE_TIFF;
ctMESSAGE_HTTP:
result := CONTENTTYPE_MESSAGE_HTTP;
ctMESSAGE_IMDN_XML:
result := CONTENTTYPE_MESSAGE_IMDN_XML;
ctMESSAGE_PARTIAL:
result := CONTENTTYPE_MESSAGE_PARTIAL;
ctMESSAGE_RFC822:
result := CONTENTTYPE_MESSAGE_RFC822;
ctMODEL_EXAMPLE:
result := CONTENTTYPE_MODEL_EXAMPLE;
ctMODEL_IGES:
result := CONTENTTYPE_MODEL_IGES;
ctMODEL_MESH:
result := CONTENTTYPE_MODEL_MESH;
ctMODEL_VRML:
result := CONTENTTYPE_MODEL_VRML;
ctMODEL_X3D_BINARY:
result := CONTENTTYPE_MODEL_X3D_BINARY;
ctMODEL_X3D_VRML:
result := CONTENTTYPE_MODEL_X3D_VRML;
ctMODEL_X3D_XML:
result := CONTENTTYPE_MODEL_X3D_XML;
ctMULTIPART_MIXED:
result := CONTENTTYPE_MULTIPART_MIXED;
ctMULTIPART_ALTERNATIVE:
result := CONTENTTYPE_MULTIPART_ALTERNATIVE;
ctMULTIPART_RELATED:
result := CONTENTTYPE_MULTIPART_RELATED;
ctMULTIPART_FORM_DATA:
result := CONTENTTYPE_MULTIPART_FORM_DATA;
ctMULTIPART_SIGNED:
result := CONTENTTYPE_MULTIPART_SIGNED;
ctMULTIPART_ENCRYPTED:
result := CONTENTTYPE_MULTIPART_ENCRYPTED;
ctVIDEO_MPEG:
result := CONTENTTYPE_VIDEO_MPEG;
ctVIDEO_MP4:
result := CONTENTTYPE_VIDEO_MP4;
ctVIDEO_OGG:
result := CONTENTTYPE_VIDEO_OGG;
ctVIDEO_QUICKTIME:
result := CONTENTTYPE_VIDEO_QUICKTIME;
ctVIDEO_WEBM:
result := CONTENTTYPE_VIDEO_WEBM;
ctVIDEO_X_MATROSKA:
result := CONTENTTYPE_VIDEO_X_MATROSKA;
ctVIDEO_X_MS_WMV:
result := CONTENTTYPE_VIDEO_X_MS_WMV;
ctVIDEO_X_FLV:
result := CONTENTTYPE_VIDEO_X_FLV;
ctAPPLICATION_VND_OASIS_OPENDOCUMENT_TEXT:
result := CONTENTTYPE_APPLICATION_VND_OASIS_OPENDOCUMENT_TEXT;
ctAPPLICATION_VND_OASIS_OPENDOCUMENT_SPREADSHEET:
result := CONTENTTYPE_APPLICATION_VND_OASIS_OPENDOCUMENT_SPREADSHEET;
ctAPPLICATION_VND_OASIS_OPENDOCUMENT_PRESENTATION:
result := CONTENTTYPE_APPLICATION_VND_OASIS_OPENDOCUMENT_PRESENTATION;
ctAPPLICATION_VND_OASIS_OPENDOCUMENT_GRAPHICS:
result := CONTENTTYPE_APPLICATION_VND_OASIS_OPENDOCUMENT_GRAPHICS;
ctAPPLICATION_VND_MS_EXCEL:
result := CONTENTTYPE_APPLICATION_VND_MS_EXCEL;
ctAPPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_SPREADSHEETML_SHEET:
result := CONTENTTYPE_APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_SPREADSHEETML_SHEET;
ctAPPLICATION_VND_MS_POWERPOINT:
result := CONTENTTYPE_APPLICATION_VND_MS_POWERPOINT;
ctAPPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_PRESENTATIONML_PRESENTATION:
result := CONTENTTYPE_APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_PRESENTATIONML_PRESENTATION;
ctAPPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT:
result := CONTENTTYPE_APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT;
ctAPPLICATION_VND_MOZILLA_XUL_XML:
result := CONTENTTYPE_APPLICATION_VND_MOZILLA_XUL_XML;
ctAPPLICATION_VND_GOOGLE_EARTH_KML_XML:
result := CONTENTTYPE_APPLICATION_VND_GOOGLE_EARTH_KML_XML;
ctAPPLICATION_VND_GOOGLE_EARTH_KMZ:
result := CONTENTTYPE_APPLICATION_VND_GOOGLE_EARTH_KMZ;
ctAPPLICATION_VND_DART:
result := CONTENTTYPE_APPLICATION_VND_DART;
ctAPPLICATION_VND_ANDROID_PACKAGE_ARCHIVE:
result := CONTENTTYPE_APPLICATION_VND_ANDROID_PACKAGE_ARCHIVE;
ctAPPLICATION_X_DEB:
result := CONTENTTYPE_APPLICATION_X_DEB;
ctAPPLICATION_X_DVI:
result := CONTENTTYPE_APPLICATION_X_DVI;
ctAPPLICATION_X_FONT_TTF:
result := CONTENTTYPE_APPLICATION_X_FONT_TTF;
ctAPPLICATION_X_JAVASCRIPT:
result := CONTENTTYPE_APPLICATION_X_JAVASCRIPT;
ctAPPLICATION_X_LATEX:
result := CONTENTTYPE_APPLICATION_X_LATEX;
ctAPPLICATION_X_MPEGURL:
result := CONTENTTYPE_APPLICATION_X_MPEGURL;
ctAPPLICATION_X_RAR_COMPRESSED:
result := CONTENTTYPE_APPLICATION_X_RAR_COMPRESSED;
ctAPPLICATION_X_SHOCKWAVE_FLASH:
result := CONTENTTYPE_APPLICATION_X_SHOCKWAVE_FLASH;
ctAPPLICATION_X_STUFFIT:
result := CONTENTTYPE_APPLICATION_X_STUFFIT;
ctAPPLICATION_X_TAR:
result := CONTENTTYPE_APPLICATION_X_TAR;
ctAPPLICATION_X_WWW_FORM_URLENCODED:
result := CONTENTTYPE_APPLICATION_X_WWW_FORM_URLENCODED;
ctAPPLICATION_X_XPINSTALL:
result := CONTENTTYPE_APPLICATION_X_XPINSTALL;
ctAUDIO_X_AAC:
result := CONTENTTYPE_AUDIO_X_AAC;
ctAUDIO_X_CAF:
result := CONTENTTYPE_AUDIO_X_CAF;
ctIMAGE_X_XCF:
result := CONTENTTYPE_IMAGE_X_XCF;
ctTEXT_X_GWT_RPC:
result := CONTENTTYPE_TEXT_X_GWT_RPC;
ctTEXT_X_JQUERY_TMPL:
result := CONTENTTYPE_TEXT_X_JQUERY_TMPL;
ctTEXT_X_MARKDOWN:
result := CONTENTTYPE_TEXT_X_MARKDOWN;
ctAPPLICATION_X_PKCS12:
result := CONTENTTYPE_APPLICATION_X_PKCS12;
ctAPPLICATION_X_PKCS7_CERTIFICATES:
result := CONTENTTYPE_APPLICATION_X_PKCS7_CERTIFICATES;
ctAPPLICATION_X_PKCS7_CERTREQRESP:
result := CONTENTTYPE_APPLICATION_X_PKCS7_CERTREQRESP;
ctAPPLICATION_X_PKCS7_MIME:
result := CONTENTTYPE_APPLICATION_X_PKCS7_MIME;
ctAPPLICATION_X_PKCS7_SIGNATURE:
result := CONTENTTYPE_APPLICATION_X_PKCS7_SIGNATURE;
ctAPPLICATION_VND_EMBARCADERO_FIREDAC_JSON:
result := CONTENTTYPE_APPLICATION_VND_EMBARCADERO_FIREDAC_JSON;
end;
end;
{ TExecutionPerformance }
procedure TExecutionPerformance.Clear;
begin
PreProcessingTime := -1;
ExecutionTime := -1;
PostProcessingTime := -1;
end;
procedure TExecutionPerformance.ExecutionDone;
begin
// if Post or Pre are never set, they are at -1
ExecutionTime := TThread.GetTickCount - FStartTime - Cardinal(max(PreProcessingTime, 0));
// Cardinal typecast to avoid compiler warnings
end;
procedure TExecutionPerformance.PostProcessingDone;
begin
PostProcessingTime := TThread.GetTickCount - FStartTime - Cardinal(max(ExecutionTime, 0)) -
Cardinal(max(PreProcessingTime, 0)); // Cardinal typecast to avoid compiler warnings
end;
procedure TExecutionPerformance.PreProcessingDone;
begin
PreProcessingTime := TThread.GetTickCount - FStartTime;
end;
procedure TExecutionPerformance.Start;
begin
Clear;
FStartTime := TThread.GetTickCount;
end;
function TExecutionPerformance.TotalExecutionTime: integer;
begin
result := max(PreProcessingTime, 0) + max(ExecutionTime, 0) + max(PostProcessingTime, 0);
end;
{ ERequestError }
constructor ERequestError.Create(AStatusCode: Integer; const
AStatusText: string; const AResponseContent: string);
begin
if AResponseContent <> '' then
inherited Create(AResponseContent)
else
inherited Create(AStatusText);
FResponseContent := AResponseContent;
FStatusCode := AStatusCode;
FStatusText := AStatusText;
end;
end.
|
// Warning: Best read if using a monospaced/fixed-width font and tab width of 4.
program xor_;
(** -------------------------------------------------------------------------------------
This program performs XOR operation on input data from standard input and
sends to standard output.
License:
The MIT License (MIT)
Copyright (c) 2020 Renan Souza da Motta <renansouzadamotta@yahoo.com>
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------------- **)
uses
SysUtils;
const
stdin = 0;
stdout = 1;
stderr = 2;
var
fd0 : file of byte;
buf0 : ^byte;
count_read : sizeint;
count_read2: sizeint;
secret_key : ^byte;
key_len : sizeuint;
key_pos : sizeuint;
lp0 : sizeuint;
var
exe_name: string;
procedure show_help();
begin
WriteLn({$I %LOCAL_DATE%});
WriteLn('xor is a program to perform XOR operation on files.');
WriteLn();
WriteLn('Usage:');
WriteLn('To XOR a file:');
WriteLn(#09,'head -c <length> /dev/urandom | ',exe_name,' /path/to/file.data');
WriteLn();
WriteLn('Note:');
WriteLn(#09,'Key file must be of same length as input data.');
halt(0);
end;
begin
exe_name := ExtractFileName(ParamStr(0));
count_read := 0;
if (ParamCount <> 1) or not (FileExists(ParamStr(1))) then show_help();
// read key data from file
Assign(fd0, ParamStr(1));
Reset(fd0);
secret_key := GetMem(1024*1024);
buf0 := GetMem(1024*1024);
BlockRead(fd0, secret_key^, 1024*1024, count_read);
key_len := count_read;
key_pos := 0;
repeat
count_read2 := FileRead(stdin, buf0^, 1024*1024);
if count_read2 = 0 then break;
for lp0 := 0 to count_read2-1 do
begin
buf0[lp0] := buf0[lp0] xor secret_key[key_pos];
inc(key_pos);
if key_pos = key_len then
begin
BlockRead(fd0, secret_key^, 1024*1024, count_read);
key_len := count_read;
key_pos := 0;
end;
end;
FileWrite(stdout, buf0^, count_read2);
until 0<>0;
FreeMem(buf0);
FreeMem(secret_key);
end.
|
unit EventDispatcher;
interface
uses
System.Classes, System.SysUtils, Data.db;
(*
Note:
HINS OFF in order for hiding
H2269 Overriding virtual method XX has lower visibility (strict protected) than base class YY (public)
*)
type
{$HINTS OFF}
TEventDispatcher<T> = class abstract(TComponent)
strict protected
FClosure: TProc<T>;
constructor Create(aOwner: TComponent); override;
procedure Notify(Sender: T);
end;
{$HINTS ON}
TNotifyEventDispatcher = class sealed(TEventDispatcher<TObject>)
public
class function Construct(Owner: TComponent; Closure: TProc<TObject>): TNotifyEvent; overload;
function Attach(Closure: TProc<TObject>): TNotifyEvent;
end;
TDataSetNotifyEventDispatcher = class sealed(TEventDispatcher<TDataSet>)
public
class function Construct(Owner: TComponent; Closure: TProc<TDataSet>): TDataSetNotifyEvent; overload;
function Attach(Closure: TProc<TDataSet>): TDataSetNotifyEvent;
end;
implementation
class function TNotifyEventDispatcher.Construct(Owner: TComponent; Closure: TProc<TObject>): TNotifyEvent;
begin
Result := TNotifyEventDispatcher.Create(Owner).Attach(Closure)
end;
function TNotifyEventDispatcher.Attach(Closure: TProc<TObject>): TNotifyEvent;
begin
FClosure := Closure;
Result := Notify;
end;
{ TDataSetNotifyEventDispatcher }
function TDataSetNotifyEventDispatcher.Attach(Closure: TProc<TDataSet>): TDataSetNotifyEvent;
begin
FClosure := Closure;
Result := Notify;
end;
class function TDataSetNotifyEventDispatcher.Construct(Owner: TComponent; Closure: TProc<TDataSet>): TDataSetNotifyEvent;
begin
Result := TDataSetNotifyEventDispatcher.Create(Owner).Attach(Closure);
end;
{ TEventDispatcher }
constructor TEventDispatcher<T>.Create(aOwner: TComponent);
begin
inherited;
end;
procedure TEventDispatcher<T>.Notify(Sender: T);
begin
if Assigned(FClosure) then
FClosure(Sender)
end;
end.
|
{
Copyright (C) 2012 Matthias Bolte <matthias@tinkerforge.com>
Redistribution and use in source and binary forms of this file,
with or without modification, are permitted. See the Creative
Commons Zero (CC0 1.0) License for more details.
}
unit BlockingQueue;
{$ifdef FPC}{$mode OBJFPC}{$H+}{$endif}
{$ifndef FPC}
{$ifdef CONDITIONALEXPRESSIONS}
{$if CompilerVersion >= 20.0}
{$define USE_GENERICS}
{$ifend}
{$endif}
{$endif}
interface
uses
{$ifdef USE_GENERICS}
Generics.Collections,
{$else}
Contnrs,
{$endif}
SyncObjs, LEConverter, TimedSemaphore;
type
TBlockingQueue = class
private
mutex: TCriticalSection;
semaphore: TTimedSemaphore;
{$ifdef USE_GENERICS}
kinds: TQueue<PByte>;
items: TQueue<PByteArray>;
{$else}
kinds: TQueue;
items: TQueue;
{$endif}
public
constructor Create;
destructor Destroy; override;
procedure Enqueue(const kind: byte; const item: TByteArray);
function Dequeue(out kind: byte; out item: TByteArray; const timeout: longint): boolean;
end;
implementation
constructor TBlockingQueue.Create;
begin
inherited;
mutex := TCriticalSection.Create;
semaphore := TTimedSemaphore.Create;
{$ifdef USE_GENERICS}
kinds := TQueue<PByte>.Create;
items := TQueue<PByteArray>.Create;
{$else}
kinds := TQueue.Create;
items := TQueue.Create;
{$endif}
end;
destructor TBlockingQueue.Destroy;
var pkind: PByte; pitem: PByteArray;
begin
mutex.Acquire;
try
while (kinds.Count > 0) do begin
{$ifdef USE_GENERICS}
pkind := kinds.Dequeue;
{$else}
pkind := kinds.Pop;
{$endif}
Dispose(pkind);
end;
while (items.Count > 0) do begin
{$ifdef USE_GENERICS}
pitem := items.Dequeue;
{$else}
pitem := items.Pop;
{$endif}
Dispose(pitem);
end;
finally
mutex.Release;
end;
mutex.Destroy;
semaphore.Destroy;
kinds.Destroy;
items.Destroy;
inherited Destroy;
end;
procedure TBlockingQueue.Enqueue(const kind: byte; const item: TByteArray);
var pkind: PByte; pitem: PByteArray;
begin
mutex.Acquire;
try
New(pkind);
pkind^ := kind;
{$ifdef USE_GENERICS}
kinds.Enqueue(pkind);
{$else}
kinds.Push(pkind);
{$endif}
New(pitem);
pitem^ := item;
{$ifdef USE_GENERICS}
items.Enqueue(pitem);
{$else}
items.Push(pitem);
{$endif}
semaphore.Release;
finally
mutex.Release;
end;
end;
function TBlockingQueue.Dequeue(out kind: byte; out item: TByteArray; const timeout: longint): boolean;
var pkind: PByte; pitem: PByteArray;
begin
result := false;
if (semaphore.Acquire(timeout)) then begin
mutex.Acquire;
try
{$ifdef USE_GENERICS}
pkind := kinds.Dequeue;
{$else}
pkind := kinds.Pop;
{$endif}
kind := pkind^;
Dispose(pkind);
{$ifdef USE_GENERICS}
pitem := items.Dequeue;
{$else}
pitem := items.Pop;
{$endif}
item := pitem^;
Dispose(pitem);
result := true;
finally
mutex.Release;
end;
end;
end;
end.
|
{
Maze scaling form of the Lazarus Mazes program
Copyright (C) 2012 G.A. Nijland (eny @ lazarus forum http://www.lazarus.freepascal.org/)
This source is free software; you can redistribute it and/or modify it under the terms of the GNU General Public
License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later
version.
This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
details.
A copy of the GNU General Public License is available on the World Wide Web at
<http://www.gnu.org/copyleft/gpl.html>. You can also obtain it by writing to the Free Software Foundation, Inc., 59
Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
unit ufrmScaling;
{$mode objfpc}{$H+}
interface
uses
LazesGlobals,
Windows,
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ComCtrls, StdCtrls;
type
{ TfrmScaling }
TfrmScaling = class(TForm)
cbLocked: TCheckBox;
cbLockedDrawing: TCheckBox;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
tbHeightDrawing: TTrackBar;
tbWidth: TTrackBar;
tbHeight: TTrackBar;
tbWidthDrawing: TTrackBar;
procedure cbLockedChange(Sender: TObject);
procedure cbLockedDrawingChange(Sender: TObject);
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure tbHeightChange(Sender: TObject);
procedure tbHeightDrawingChange(Sender: TObject);
procedure tbWidthChange(Sender: TObject);
procedure tbWidthDrawingChange(Sender: TObject);
private
{ private declarations }
MazeMetrics: TMazeUpdateInfo;
procedure CheckLock(pCB: TCheckBox; pMaster, pSlave: TTrackBar);
procedure UpdateMaze;
public
{ public declarations }
end;
var
frmScaling: TfrmScaling;
implementation
{$R *.lfm}
{ TfrmScaling }
procedure TfrmScaling.FormCreate(Sender: TObject);
begin
// Get some global settings
tbWidth.Min := C_MIN_MAZE_SIZE;
tbWidth.Max := C_MAX_MAZE_SIZE;
tbHeight.Min := C_MIN_MAZE_SIZE;
tbHeight.Max := C_MAX_MAZE_SIZE;
// Because of an omission on the OI the checkbox font
// needs to be set separately
cbLocked.Font.Style := [];
cbLocked.Font.Color := Label1.Font.Color;
cbLockedDrawing.Font.Style := [];
cbLockedDrawing.Font.Color := Label1.Font.Color;
end;
procedure TfrmScaling.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin
CloseAction := caHide;
end;
procedure TfrmScaling.CheckLock(pCB: TCheckBox; pMaster, pSlave: TTrackBar);
begin
if pCB.Checked then
if pMaster.Position <> pSlave.Position then
pSlave.Position := pMaster.Position;
UpdateMaze;
end;
procedure TfrmScaling.UpdateMaze;
begin
with MazeMetrics do
begin
MazeWidth := tbWidth.Position;
MazeHeight := tbHeight.Position;
DrawWidth := tbWidthDrawing.Position;
DrawHeight := tbHeightDrawing.Position;
end;
SendMessage(Application.MainFormHandle, C_MAZE_UPDATE_MESSAGE, LongInt(@MazeMetrics), 0);
end;
procedure TfrmScaling.cbLockedChange(Sender: TObject);
begin
CheckLock(cbLocked, tbWidth, tbHeight);
end;
procedure TfrmScaling.cbLockedDrawingChange(Sender: TObject);
begin
CheckLock(cbLockedDrawing, tbWidthDrawing, tbHeightDrawing)
end;
procedure TfrmScaling.tbHeightChange(Sender: TObject);
begin
CheckLock(cbLocked, tbHeight, tbWidth)
end;
procedure TfrmScaling.tbHeightDrawingChange(Sender: TObject);
begin
CheckLock(cbLockedDrawing, tbHeightDrawing, tbWidthDrawing)
end;
procedure TfrmScaling.tbWidthChange(Sender: TObject);
begin
CheckLock(cbLocked, tbWidth, tbHeight)
end;
procedure TfrmScaling.tbWidthDrawingChange(Sender: TObject);
begin
CheckLock(cbLockedDrawing, tbWidthDrawing, tbHeightDrawing)
end;
end.
|
program Automated_graphing_of_functions_and_solving_equations;
uses crt, graphABC;
var
X, Y: integer;
a, b, c, k, x1, x2, D, Root, Value: real;
Equation: char;
function Finding_the_root_of_a_linear_equation(k, b, Value: real): real;
begin
Finding_the_root_of_a_linear_equation := (Value - b) / k
end;
function Inverse_Proportionality_Root(k, Value: real): real;
begin
Inverse_Proportionality_Root := k / Value;
end;
procedure The_solution_of_the_quadratic_equation(a, b, c: real; var D, x1, x2: real);
begin
D := sqr(b) - 4 * a * c;
x1 := (-b + sqrt(D)) / 2 * a;
x2 := (-b - sqrt(D)) / 2 * a;
if D > 0 then
writeln('Дискриминант = ', D, ', больше 0 => уравнение имеет 2 корня. Первый: ', x1, ' Второй: ', x2);
if D = 0 then
writeln('Дискриминант равен 0 => уравнение имеет один корень: ', x1);
if D < 0 then
writeln('Дискриминант = ', D, ', меньше 0 => уравнение не имеет корней.');
end;
procedure Graphics_window_features(Key: integer);
begin
case Key of
VK_E: graphABC.Window.Close;
VK_H:
begin
Openwrite('C:\PABCWork.NET\Compilation Output Files\Help.txt');
end;
VK_L:
begin
k := random(13);
b := random(13);
graphABC.Draw(x -> (k * X) + 15 * b, -390, 390, -390, 390, -390, 391, 389, -390)
end;
VK_Q:
begin
a := random(13);
b := random(13);
c := random(26);
graphABC.Draw(x -> (a * sqr(x) + b * x) / 15 + c * 15, -390, 390, -390, 390, -390, 391, 389, -390);
end;
VK_I:
begin
k := random(26);
graphABC.Draw(x -> (k / x) * 210, -390, 390, -390, 390, -390, 391, 389, -390);
end;
VK_C: graphABC.Draw(x -> sqr(x) * x / 210, -390, 390, -390, 390, -390, 391, 389, -390);
VK_M: graphABC.Draw(x -> abs(x), -390, 390, -390, 390, -390, 391, 389, -390)
end;
end;
begin
//Подготовка окон:
graphABC.InitWindow(750, 10, 840, 820, clWhite);
graphABC.SetWindowCaption('Постройка графика:');
graphABC.SetWindowIsFixedSize(true);
graphABC.SetPenColor(clDimGray);
graphABC.SetFontSize(7);
for X := -25 to 25 do
begin
Line(410 - 15 * X, 20, 410 - 15 * X, 799);
if X > 0 then begin
graphABC.DrawTextCentered(400 - 15 * X, 5, 417 - 15 * X, 20, -X);
graphABC.DrawTextCentered(400 - 15 * X, 801, 417 - 15 * X, 815, -X);
end;
if X = 0 then begin
graphABC.SetFontSize(9); graphABC.SetFontColor(clRed);
graphABC.TextOut(407, 1, '0'); graphABC.TextOut(407, 805, '0');
graphABC.SetFontColor(clBlack); graphABC.SetFontSize(7);
end;
if X < 0 then begin
graphABC.DrawTextCentered(403 - 15 * X, 5, 417 - 15 * X, 20, -X);
graphABC.DrawTextCentered(403 - 15 * X, 801, 417 - 15 * X, 815, -X);
end;
end;
for Y := -25 to 25 do
begin
Line(20, 410 - 15 * Y, 799, 410 - 15 * Y);
if Y > 0 then begin
graphABC.DrawTextCentered(1, 402 - 15 * Y, 20, 419 - 15 * Y, Y);
graphABC.DrawTextCentered(800, 401 - 15 * Y, 820, 418 - 15 * Y, Y);
end;
if Y = 0 then begin
graphABC.SetFontSize(9); graphABC.SetFontColor(clRed);
graphABC.TextOut(7, 403, '0'); graphABC.TextOut(807, 403, '0');
graphABC.SetFontColor(clBlack); graphABC.SetFontSize(7);
end;
if Y < 0 then begin
graphABC.DrawTextCentered(1, 401 - 15 * Y, 20, 418 - 15 * Y, Y);
graphABC.DrawTextCentered(800, 401 - 15 * Y, 820, 418 - 15 * Y, Y);
end;
end;
graphABC.SetPenColor(clBlack);graphABC.SetPenWidth(3);
Line(410, 15, 410, 805); Line(15, 410, 805, 410);
graphABC.DrawRectangle(20, 20, 800, 800);
graphABC.SetCoordinateOrigin(410, 410);graphABC.GraphABCCoordinate.Create.SetMathematic;
graphABC.SetPenColor(clRandom);graphABC.SetPenWidth(3);
graphABC.SetBrushStyle(bsClear);
graphABC.OnKeyDown:=Graphics_window_features;
graphABC.SetConsoleIO;
crt.SetWindowCaption('Решение уравнения:');
crt.SetWindowSize(60, 60);
//Основная программа:
crt.TextColor(2);
writeln(' ');
writeln('Привет! В этом окне ты передаешь нужные данные программе.');
writeln('Не бойся. Если ты запутался или чего-то не понимаешь,перейдя в графическое окно, нажми латинскую H для вызова справки, может быть там есть ответ.');
writeln('Для выхода перейди в графическое окно и нажми два раза латинскую E.');
writeln(' ');
crt.TextColor(15);
Writeln(' > Сколько уравнений решим и графиков мы построим?');
loop ReadInteger do
begin
crt.TextColor(15);
writeln(' > Выбери тип нужного уравнения - нажми на клавишу порядкого номера уравнения.');
writeln(' 1. Линейное. Общий вид функции: y=k*x+b');
writeln(' 2. Квадратное. Общий вид функции: y=x^2+b*x+c');
writeln(' 3. Обратнопропорциональное. Общий вид функции: y=k/x');
writeln(' 4. Куб числа. y=x^3');
writeln(' 5. Корень из числа. y= " квадратный корень из: " x');
writeln(' 6. Модуль числа. y=|x|');
writeln(' ');
Equation := crt.ReadKey;
if Equation = ('1') then begin
crt.TextColor(9);
write('Через');
crt.TextColor(13);
write(' Enter ');
crt.TextColor(9);
write('введите сначала коэффициент');
crt.TextColor(11);
writeln(' k:');
readln(k);
crt.TextColor(9);
write('Затем коэффициент');
crt.TextColor(11);
writeln(' b:');
readln(b);
crt.TextColor(9);
writeln('И чему равно уравнение:');
crt.TextColor(11);
readln(Value);
crt.TextColor(9);
writeln(' ');
writeln('Уравнение имеет вид: ', k, '*x+', b, '= Y(=', Value, ')');
writeln(' ');
write('Согласно формуле " (Y-b)/k) ", корень уравнения равен: ');
crt.TextColor(11);
Root := Finding_the_root_of_a_linear_equation(k, b, Value);
writeln(Root);
writeln(' ');
graphABC.Draw(x -> (k * X) + 15 * b, -390, 390, -390, 390, -390, 391, 389, -390);
crt.TextColor(10);
write('Линейная функция. Графиком является прямая,');
if b = 0 then
write('проходящая через начало координат.');
writeln(' ');
if k > 0 then
writeln('Функция возрастает от: ', Finding_the_root_of_a_linear_equation(k, b, -26), ' до: ', Finding_the_root_of_a_linear_equation(k, b, 26) );
writeln('Функция равна нулю при:', Finding_the_root_of_a_linear_equation(k, b, 0));
if k < 0 then
writeln('Функция убывает от: ', Finding_the_root_of_a_linear_equation(k, b, -26), ' до: ', Finding_the_root_of_a_linear_equation(k, b, 26));
writeln('Функция > 0 при x от: ', Finding_the_root_of_a_linear_equation(k, b, 0), ' до: ', Finding_the_root_of_a_linear_equation(k, b, 26));
writeln('Функция < 0 при x от: ', Finding_the_root_of_a_linear_equation(k, b, -26), ' до: ', Finding_the_root_of_a_linear_equation(k, b, 0));
end;
if Equation = ('2') then begin
crt.TextColor(9);
write('Через');
crt.TextColor(13);
write(' Enter ');
crt.TextColor(9);
write('введите сначала коэффициент');
crt.TextColor(11);
writeln(' a:');
readln(a);
crt.TextColor(9);
write('Затем коэффициент');
crt.TextColor(11);
writeln(' b:');
readln(b);
crt.TextColor(9);
writeln('И, наконец, коэффициент c:');
crt.TextColor(11);
readln(c);
crt.TextColor(9);
writeln(' ');
writeln('Уравнение имеет вид: ', a, '*x^2+', b, '*x+', c, ' =0');
writeln(' ');
The_solution_of_the_quadratic_equation(a, b, c, D, x1, x2);
writeln(' ');
graphABC.Draw(x -> (a * sqr(x) + 15*b * x) / 15 + c * 15, -390, 390, -390, 390, -390, 391, 389, -390);
crt.TextColor(10);
writeln('Квадратичная функция. Графиком является парабола.');
if a > 0 then
writeln('Ветви параболы идут вверх, так как коэффициент a = ', a, ' > 0');
if a < 0 then
writeln('Ветви параболы идут вниз, так как коэффициент a = ', a, ' < 0');
writeln(' ');
if D > 0 then begin
writeln('Нули функции: ', x1, ' и ', x2);
if a > 0 then begin
writeln('Функция > 0 при x от -бесконечности до:', x2, ' и от:', x1, ' до +бесконечности');
writeln('Функция меньше нуля при x от: ', x2, ' до: ', x1);
end;
if a < 0 then begin
writeln('Функция < 0 при x от -бесконечности до:', x2, ' и от:', x1, ' до +бесконечности');
writeln('Функция больше нуля при x от: ', x2, ' до: ', x1);
end;
end;
if D = 0 then begin
writeln('Функция равна нулю при x:', x1);
if a > 0 then
writeln('Функция положительна от - бесконечности до: ', x1,' и от этой точки до +бесконечности.' );
if a < 0 then
writeln('Функция отрицательна от - бесконечности до: ', x1,' и от этой точки до +бесконечности.' );
end;
if D < 0 then begin
writeln('Нет нулей функции.');
if a > 0 then
writeln('Функция положительна от - бесконечности до +бесконечности.' );
if a < 0 then
writeln('Функция отрицательна от - бесконечности до +бесконечности.' );
end;
end;
{Доработать!}
if Equation = ('3') then begin
crt.TextColor(9);
write('Введите коэффициент');
crt.TextColor(11);
writeln(' k ');
crt.TextColor(9);
write('и нажмите - ');
crt.TextColor(13);
writeln(' Enter.');
crt.TextColor(11);
readln(k);
crt.TextColor(9);
writeln('Чему равно уравнение:');
crt.TextColor(11);
readln(Value);
crt.TextColor(9);
writeln(' ');
Root := Inverse_Proportionality_Root(k, Value);
writeln('Уравнение имеет вид: ', k, ' / x');
writeln('Согласно формуле: k/y корень:', Root);
writeln(' ');
graphABC.Draw(x -> (k / x) * 210, -390, 390, -390, 390, -390, 391, 389, -390);
crt.TextColor(10);
writeln('У этой функции нет нулей.');
writeln('Функция положительна от ~0 до +бесконечности.');
writeln('Функция отрицательна от -бесконечности до ~0.');
writeln('Убывающая функция.');
end;
if Equation = ('4') then begin
crt.TextColor(9);
writeln('У этой функции нет коэффициентов.');
crt.TextColor(10);
writeln(' ');
graphABC.Draw(x -> sqr(x) * x / 210, -390, 390, -390, 390, -390, 391, 389, -390);
writeln('Функция равна нули толко если аргумент равен 0.');
writeln('Функция положительна от 0 до +бесконечности.');
writeln('Функция отрицательна от -бесконечности до 0.');
writeln('Возрастающая функция.');
end;
{!}
if Equation = ('5') then begin
crt.TextColor(9);
writeln('У этой функции нет коэффициентов.');
crt.TextColor(10);
writeln(' ');
graphABC.Draw(x -> sqrt(x) / 15, -390, 390, -390, 390, -390, 391, 389, -390);
writeln('Функция равна нули толко если аргумент равен 0.');
writeln('Функция положительна от 0 до +бесконечности.');
writeln('Функция отрицательна от -бесконечности до 0.');
writeln('Возрастающая функция.');
end;
if Equation = ('6') then begin
crt.TextColor(9);
writeln('У этой функции нет коэффициентов.');
crt.TextColor(10);
writeln(' ');
graphABC.Draw(x -> abs(x), -390, 390, -390, 390, -390, 391, 389, -390);
writeln('Функция равна нули толко если аргумент равен 0.');
writeln('Функция положительна от -бесконечности до +бесконечности.');
writeln('Функция убывает и от -бесконечности до 0.');
writeln('Функция возрастает от 0 до +бесконечности');
end;
end;
end. |
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{ Copyright and license exceptions noted in source }
{ }
{*******************************************************}
unit Posix.Termios;
{$WEAKPACKAGEUNIT}
interface
uses Posix.Base;
{$IFDEF MACOS}
{$I osx/TermiosTypes.inc}
{$ENDIF MACOS}
{$IFDEF LINUX}
{$I linux/TermiosTypes.inc}
{$ENDIF LINUX}
{$I TermiosAPI.inc}
{ Compare a character C to a value VAL from the `c_cc' array in a
`struct termios'. If VAL is _POSIX_VDISABLE, no character can match it. }
function CCEQ(val, c: cc_t): Boolean;
{$EXTERNALSYM CCEQ}
implementation
{$HPPEMIT '#include <termios.h>' }
// Macros from termios.h
function CCEQ(val, c: cc_t): Boolean;
begin
Result := (c = val) and (val <> _POSIX_VDISABLE);
end;
end.
|
//
// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
{$POINTERMATH ON}
unit RN_InputGeom;
interface
uses Math, SysUtils, RN_Helper, RN_ChunkyTriMesh, RN_MeshLoaderObj, RN_Recast, RN_DebugDraw;
const MAX_CONVEXVOL_PTS = 12;
type
TConvexVolume = record
verts: array [0..MAX_CONVEXVOL_PTS*3-1] of Single;
hmin, hmax: Single;
nverts: Integer;
area: Integer;
end;
PConvexVolume = ^TConvexVolume;
const MAX_VOLUMES = 256;
type
TIGConvexVolumeArray = array [0..MAX_VOLUMES-1] of TConvexVolume;
TInputGeom = class
private
m_chunkyMesh: TrcChunkyTriMesh;
m_mesh: TrcMeshLoaderObj;
m_meshBMin, m_meshBMax: array [0..2] of Single;
/// @name Off-Mesh connections.
///@{
const MAX_OFFMESH_CONNECTIONS = 256;
var
m_offMeshConVerts: array [0..MAX_OFFMESH_CONNECTIONS*3*2-1] of Single;
m_offMeshConRads: array [0..MAX_OFFMESH_CONNECTIONS-1] of Single;
m_offMeshConDirs: array [0..MAX_OFFMESH_CONNECTIONS-1] of Byte;
m_offMeshConAreas: array [0..MAX_OFFMESH_CONNECTIONS-1] of Byte;
m_offMeshConFlags: array [0..MAX_OFFMESH_CONNECTIONS-1] of Word;
m_offMeshConId: array [0..MAX_OFFMESH_CONNECTIONS-1] of Cardinal;
m_offMeshConCount: Integer;
///@}
/// @name Convex Volumes.
///@{
var
m_volumes: TIGConvexVolumeArray;
m_volumeCount: Integer;
///@}
public
destructor Destroy; override;
function loadMesh(ctx: TrcContext; const filepath: string): Boolean;
function load(ctx: TrcContext; const filepath: string): Boolean;
function save(const filepath: string): Boolean;
/// Method to return static mesh data.
property getMesh: TrcMeshLoaderObj read m_mesh;
function getMeshBoundsMin: PSingle;
function getMeshBoundsMax: PSingle;
property getChunkyMesh: TrcChunkyTriMesh read m_chunkyMesh;
function raycastMesh(src, dst: PSingle; tmin: PSingle): Boolean;
/// @name Off-Mesh connections.
///@{
property getOffMeshConnectionCount: Integer read m_offMeshConCount;
function getOffMeshConnectionVerts: PSingle;
function getOffMeshConnectionRads: PSingle;
function getOffMeshConnectionDirs: PByte;
function getOffMeshConnectionAreas: PByte;
function getOffMeshConnectionFlags: PWord;
function getOffMeshConnectionId: PCardinal;
procedure addOffMeshConnection(const spos, epos: PSingle; const rad: Single;
bidir, area: Byte; flags: Word);
procedure deleteOffMeshConnection(i: Integer);
procedure drawOffMeshConnections(dd: TduDebugDraw; hilight: Boolean = false);
///@}
/// @name Box Volumes.
///@{
property getConvexVolumeCount: Integer read m_volumeCount;
property getConvexVolumes: TIGConvexVolumeArray read m_volumes;
procedure addConvexVolume(const verts: PSingle; const nverts: Integer;
const minh, maxh: Single; area: Byte);
procedure deleteConvexVolume(i: Integer);
procedure drawConvexVolumes(dd: TduDebugDraw; hilight: Boolean = false);
///@}
end;
implementation
uses RN_RecastHelper;
function intersectSegmentTriangle(sp, sq, a, b, c: PSingle; t: PSingle): Boolean;
var v,w,d: Single; ab,ac,qp,ap,norm,e: array [0..2] of Single;
begin
rcVsub(@ab[0], b, a);
rcVsub(@ac[0], c, a);
rcVsub(@qp[0], sp, sq);
// Compute triangle normal. Can be precalculated or cached if
// intersecting multiple segments against the same triangle
rcVcross(@norm[0], @ab[0], @ac[0]);
// Compute denominator d. If d <= 0, segment is parallel to or points
// away from triangle, so exit early
d := rcVdot(@qp[0], @norm[0]);
if (d <= 0.0) then Exit(false);
// Compute intersection t value of pq with plane of triangle. A ray
// intersects iff 0 <= t. Segment intersects iff 0 <= t <= 1. Delay
// dividing by d until intersection has been found to pierce triangle
rcVsub(@ap[0], sp, a);
t^ := rcVdot(@ap[0], @norm[0]);
if (t^ < 0.0) then Exit(false);
if (t^ > d) then Exit(false); // For segment; exclude this code line for a ray test
// Compute barycentric coordinate components and test if within bounds
rcVcross(@e[0], @qp[0], @ap[0]);
v := rcVdot(@ac[0], @e[0]);
if (v < 0.0) or (v > d) then Exit(false);
w := -rcVdot(@ab[0], @e[0]);
if (w < 0.0) or (v + w > d) then Exit(false);
// Segment/ray intersects triangle. Perform delayed division
t^ := t^/d;
Result := True;
end;
{static char* parseRow(char* buf, char* bufEnd, char* row, int len)
begin
bool start := true;
bool done := false;
int n := 0;
while (not done and (buf < bufEnd) do
begin
char c := *buf;
buf++;
// multirow
switch (c)
begin
case '\n':
if (start) break;
done := true;
break;
case '\r':
break;
case '\t':
case ' ':
if (start) break;
default:
start := false;
row[n++] := c;
if (n >= len-1)
done := true;
break;
end;
end;
row[n] := '\0';
return buf;
end;}
destructor TInputGeom.Destroy;
begin
FreeAndNil(m_mesh);
inherited;
end;
function TInputGeom.getMeshBoundsMax: PSingle;
begin
Result := @m_meshBMax[0];
end;
function TInputGeom.getMeshBoundsMin: PSingle;
begin
Result := @m_meshBMin[0];
end;
function TInputGeom.getOffMeshConnectionAreas: PByte;
begin
Result := @m_offMeshConAreas[0];
end;
function TInputGeom.getOffMeshConnectionDirs: PByte;
begin
Result := @m_offMeshConDirs[0];
end;
function TInputGeom.getOffMeshConnectionFlags: PWord;
begin
Result := @m_offMeshConFlags[0];
end;
function TInputGeom.getOffMeshConnectionId: PCardinal;
begin
Result := @m_offMeshConId[0];
end;
function TInputGeom.getOffMeshConnectionRads: PSingle;
begin
Result := @m_offMeshConRads[0];
end;
function TInputGeom.getOffMeshConnectionVerts: PSingle;
begin
Result := @m_offMeshConVerts[0];
end;
function TInputGeom.loadMesh(ctx: TrcContext; const filepath: string): Boolean;
begin
if (m_mesh <> nil) then
begin
m_mesh.Free;
m_mesh := nil;
end;
m_offMeshConCount := 0;
m_volumeCount := 0;
m_mesh := TrcMeshLoaderObj.Create;
if (not m_mesh.load(filepath)) then
begin
ctx.log(RC_LOG_ERROR, Format('buildTiledNavigation: Could not load ''%s''', [filepath]));
Exit(false);
end;
rcCalcBounds(m_mesh.getVerts, m_mesh.getVertCount, @m_meshBMin[0], @m_meshBMax[0]);
if (not rcCreateChunkyTriMesh(m_mesh.getVerts, m_mesh.getTris, m_mesh.getTriCount, 256, @m_chunkyMesh)) then
begin
ctx.log(RC_LOG_ERROR, 'buildTiledNavigation: Failed to build chunky mesh.');
Exit(false);
end;
Result := true;
end;
function TInputGeom.load(ctx: TrcContext; const filepath: string): Boolean;
begin
{ char* buf := 0;
FILE* fp := fopen(filePath, 'rb');
if (!fp)
return false;
fseek(fp, 0, SEEK_END);
int bufSize := ftell(fp);
fseek(fp, 0, SEEK_SET);
buf := new char[bufSize];
if (!buf)
begin
fclose(fp);
return false;
end;
size_t readLen := fread(buf, bufSize, 1, fp);
fclose(fp);
if (readLen != 1)
begin
return false;
end;
m_offMeshConCount := 0;
m_volumeCount := 0;
m_mesh.Free;
m_mesh := nil;
char* src := buf;
char* srcEnd := buf + bufSize;
char row[512];
while (src < srcEnd)
begin
// Parse one row
row[0] := '\0';
src := parseRow(src, srcEnd, row, sizeof(row)/sizeof(char));
if (row[0] == 'f')
begin
// File name.
const char* name := row+1;
// Skip white spaces
while (*name && isspace(*name))
name++;
if (*name)
begin
if (!loadMesh(ctx, name))
begin
delete [] buf;
return false;
end;
end;
end;
else if (row[0] == 'c')
begin
// Off-mesh connection
if (m_offMeshConCount < MAX_OFFMESH_CONNECTIONS)
begin
float* v := &m_offMeshConVerts[m_offMeshConCount*3*2];
int bidir, area := 0, flags := 0;
float rad;
sscanf(row+1, '%f %f %f %f %f %f %f %d %d %d',
&v[0], &v[1], &v[2], &v[3], &v[4], &v[5], &rad, &bidir, &area, &flags);
m_offMeshConRads[m_offMeshConCount] := rad;
m_offMeshConDirs[m_offMeshConCount] := (unsigned char)bidir;
m_offMeshConAreas[m_offMeshConCount] := (unsigned char)area;
m_offMeshConFlags[m_offMeshConCount] := (unsigned short)flags;
m_offMeshConCount++;
end;
end;
else if (row[0] == 'v')
begin
// Convex volumes
if (m_volumeCount < MAX_VOLUMES)
begin
ConvexVolume* vol := &m_volumes[m_volumeCount++];
sscanf(row+1, '%d %d %f %f', &vol.nverts, &vol.area, &vol.hmin, &vol.hmax);
for (int i := 0; i < vol.nverts; ++i)
begin
row[0] := '\0';
src := parseRow(src, srcEnd, row, sizeof(row)/sizeof(char));
sscanf(row, '%f %f %f', &vol.verts[i*3+0], &vol.verts[i*3+1], &vol.verts[i*3+2]);
end;
end;
end;
end;
delete [] buf;
}
Result := true;
end;
function TInputGeom.save(const filepath: string): Boolean;
begin
if (m_mesh = nil) then Exit(false);
{ FILE* fp := fopen(filepath, 'w');
if (!fp) return false;
// Store mesh filename.
fprintf(fp, 'f %s\n', m_mesh.getFileName());
// Store off-mesh links.
for (int i := 0; i < m_offMeshConCount; ++i)
begin
const float* v := &m_offMeshConVerts[i*3*2];
const float rad := m_offMeshConRads[i];
const int bidir := m_offMeshConDirs[i];
const int area := m_offMeshConAreas[i];
const int flags := m_offMeshConFlags[i];
fprintf(fp, 'c %f %f %f %f %f %f %f %d %d %d\n',
v[0], v[1], v[2], v[3], v[4], v[5], rad, bidir, area, flags);
end;
// Convex volumes
for (int i := 0; i < m_volumeCount; ++i)
begin
ConvexVolume* vol := &m_volumes[i];
fprintf(fp, 'v %d %d %f %f\n', vol.nverts, vol.area, vol.hmin, vol.hmax);
for (int j := 0; j < vol.nverts; ++j)
fprintf(fp, '%f %f %f\n', vol.verts[j*3+0], vol.verts[j*3+1], vol.verts[j*3+2]);
end;
fclose(fp);
}
Result := true;
end;
function isectSegAABB(const sp, sq, amin, amax: PSingle;
tmin, tmax: PSingle): Boolean;
const EPS = 0.000001;
var d: array [0..2] of Single; i: Integer; ood,t1,t2,tmp: Single;
begin
d[0] := sq[0] - sp[0];
d[1] := sq[1] - sp[1];
d[2] := sq[2] - sp[2];
tmin^ := 0.0;
tmax^ := 1.0;
for i := 0 to 2 do
begin
if (Abs(d[i]) < EPS) then
begin
if (sp[i] < amin[i]) or (sp[i] > amax[i]) then
Exit(false);
end
else
begin
ood := 1.0 / d[i];
t1 := (amin[i] - sp[i]) * ood;
t2 := (amax[i] - sp[i]) * ood;
if (t1 > t2) then begin tmp := t1; t1 := t2; t2 := tmp; end;
if (t1 > tmin^) then tmin^ := t1;
if (t2 < tmax^) then tmax^ := t2;
if (tmin^ > tmax^) then Exit(false);
end;
end;
Result := true;
end;
function TInputGeom.raycastMesh(src, dst: PSingle; tmin: PSingle): Boolean;
var dir: array [0..2] of Single; p,q: array [0..1] of Single; btmin,btmax,t: Single; hit: Boolean; ncid: Integer; verts: PSingle;
cid: array [0..511] of Integer; tris: PInteger; i,j,ntris: Integer; node: PrcChunkyTriMeshNode;
begin
rcVsub(@dir[0], dst, src);
// Prune hit ray.
if (not isectSegAABB(src, dst, @m_meshBMin[0], @m_meshBMax[0], @btmin, @btmax)) then Exit(false);
p[0] := src[0] + (dst[0]-src[0])*btmin;
p[1] := src[2] + (dst[2]-src[2])*btmin;
q[0] := src[0] + (dst[0]-src[0])*btmax;
q[1] := src[2] + (dst[2]-src[2])*btmax;
ncid := rcGetChunksOverlappingSegment(@m_chunkyMesh, @p[0], @q[0], @cid[0], 512);
if (ncid = 0) then
Exit(false);
tmin^ := 1.0;
hit := false;
verts := m_mesh.getVerts;
for i := 0 to ncid - 1 do
begin
node := @m_chunkyMesh.nodes[cid[i]];
tris := @m_chunkyMesh.tris[node.i*3];
ntris := node.n;
for j := 0 to ntris - 1 do
begin
t := 1;
if (intersectSegmentTriangle(src, dst,
@verts[tris[j*3]*3],
@verts[tris[j*3+1]*3],
@verts[tris[j*3+2]*3], @t)) then
begin
if (t < tmin^) then
tmin^ := t;
hit := true;
end;
end;
end;
Result := hit;
end;
procedure TInputGeom.addOffMeshConnection(const spos, epos: PSingle; const rad: Single;
bidir, area: Byte; flags: Word);
var v: PSingle;
begin
if (m_offMeshConCount >= MAX_OFFMESH_CONNECTIONS) then Exit;
v := @m_offMeshConVerts[m_offMeshConCount*3*2];
m_offMeshConRads[m_offMeshConCount] := rad;
m_offMeshConDirs[m_offMeshConCount] := bidir;
m_offMeshConAreas[m_offMeshConCount] := area;
m_offMeshConFlags[m_offMeshConCount] := flags;
m_offMeshConId[m_offMeshConCount] := 1000 + m_offMeshConCount;
rcVcopy(PSingle(v[0]), spos);
rcVcopy(PSingle(v[3]), epos);
Inc(m_offMeshConCount);
end;
procedure TInputGeom.deleteOffMeshConnection(i: Integer);
var src,dst: PSingle;
begin
Dec(m_offMeshConCount);
src := @m_offMeshConVerts[m_offMeshConCount*3*2];
dst := @m_offMeshConVerts[i*3*2];
rcVcopy(PSingle(dst[0]), PSingle(src[0]));
rcVcopy(PSingle(dst[3]), PSingle(src[3]));
m_offMeshConRads[i] := m_offMeshConRads[m_offMeshConCount];
m_offMeshConDirs[i] := m_offMeshConDirs[m_offMeshConCount];
m_offMeshConAreas[i] := m_offMeshConAreas[m_offMeshConCount];
m_offMeshConFlags[i] := m_offMeshConFlags[m_offMeshConCount];
end;
procedure TInputGeom.drawOffMeshConnections(dd: TduDebugDraw; hilight: Boolean = false);
var conColor,baseColor: Cardinal; i: Integer; v: PSingle;
begin
conColor := duRGBA(192,0,128,192);
baseColor := duRGBA(0,0,0,64);
dd.depthMask(false);
dd.&begin(DU_DRAW_LINES, 2.0);
for i := 0 to m_offMeshConCount - 1 do
begin
v := @m_offMeshConVerts[i*3*2];
dd.vertex(v[0],v[1],v[2], baseColor);
dd.vertex(v[0],v[1]+0.2,v[2], baseColor);
dd.vertex(v[3],v[4],v[5], baseColor);
dd.vertex(v[3],v[4]+0.2,v[5], baseColor);
duAppendCircle(dd, v[0],v[1]+0.1,v[2], m_offMeshConRads[i], baseColor);
duAppendCircle(dd, v[3],v[4]+0.1,v[5], m_offMeshConRads[i], baseColor);
if (hilight) then
begin
duAppendArc(dd, v[0],v[1],v[2], v[3],v[4],v[5], 0.25,
Byte(m_offMeshConDirs[i] and 1) * 0.6, 0.6, conColor);
end;
end;
dd.&end();
dd.depthMask(true);
end;
procedure TInputGeom.addConvexVolume(const verts: PSingle; const nverts: Integer;
const minh, maxh: Single; area: Byte);
var vol: PConvexVolume;
begin
if (m_volumeCount >= MAX_VOLUMES) then Exit;
vol := @m_volumes[m_volumeCount];
Inc(m_volumeCount);
Move(verts^, vol.verts[0], sizeof(Single)*3*nverts);
vol.hmin := minh;
vol.hmax := maxh;
vol.nverts := nverts;
vol.area := area;
end;
procedure TInputGeom.deleteConvexVolume(i: Integer);
begin
Dec(m_volumeCount);
m_volumes[i] := m_volumes[m_volumeCount];
end;
procedure TInputGeom.drawConvexVolumes(dd: TduDebugDraw; hilight: Boolean = false);
var i,k,j: Integer; vol: PConvexVolume; col: Cardinal; va,vb: PSingle;
begin
dd.depthMask(false);
dd.&begin(DU_DRAW_TRIS);
for i := 0 to m_volumeCount - 1 do
begin
vol := @m_volumes[i];
col := duIntToCol(vol.area, 32);
j := 0;
k := vol.nverts-1;
while (j < vol.nverts) do
begin
va := @vol.verts[k*3];
vb := @vol.verts[j*3];
dd.vertex(vol.verts[0],vol.hmax,vol.verts[2], col);
dd.vertex(vb[0],vol.hmax,vb[2], col);
dd.vertex(va[0],vol.hmax,va[2], col);
dd.vertex(va[0],vol.hmin,va[2], duDarkenCol(col));
dd.vertex(va[0],vol.hmax,va[2], col);
dd.vertex(vb[0],vol.hmax,vb[2], col);
dd.vertex(va[0],vol.hmin,va[2], duDarkenCol(col));
dd.vertex(vb[0],vol.hmax,vb[2], col);
dd.vertex(vb[0],vol.hmin,vb[2], duDarkenCol(col));
k := j;
Inc(j);
end;
end;
dd.&end();
dd.&begin(DU_DRAW_LINES, 2.0);
for i := 0 to m_volumeCount - 1 do
begin
vol := @m_volumes[i];
col := duIntToCol(vol.area, 220);
j := 0;
k := vol.nverts-1;
while (j < vol.nverts) do
begin
va := @vol.verts[k*3];
vb := @vol.verts[j*3];
dd.vertex(va[0],vol.hmin,va[2], duDarkenCol(col));
dd.vertex(vb[0],vol.hmin,vb[2], duDarkenCol(col));
dd.vertex(va[0],vol.hmax,va[2], col);
dd.vertex(vb[0],vol.hmax,vb[2], col);
dd.vertex(va[0],vol.hmin,va[2], duDarkenCol(col));
dd.vertex(va[0],vol.hmax,va[2], col);
k := j;
Inc(j);
end;
end;
dd.&end();
dd.&begin(DU_DRAW_POINTS, 3.0);
for i := 0 to m_volumeCount - 1 do
begin
vol := @m_volumes[i];
col := duDarkenCol(duIntToCol(vol.area, 255));
for j := 0 to vol.nverts - 1 do
begin
dd.vertex(vol.verts[j*3+0],vol.verts[j*3+1]+0.1,vol.verts[j*3+2], col);
dd.vertex(vol.verts[j*3+0],vol.hmin,vol.verts[j*3+2], col);
dd.vertex(vol.verts[j*3+0],vol.hmax,vol.verts[j*3+2], col);
end;
end;
dd.&end();
dd.depthMask(true);
end;
end.
|
unit LoanClassificationList;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseDocked, Data.DB, RzButton, RzRadChk,
RzDBChk, Vcl.DBCtrls, RzDBCmbo, Vcl.StdCtrls, Vcl.Mask, RzEdit, RzDBEdit,
RzTabs, Vcl.Grids, Vcl.DBGrids, RzDBGrid, RzLabel, Vcl.ExtCtrls, RzPanel, SaveIntf,
RzLstBox, RzChkLst, NewIntf, RzCmboBx, RzGrids, RzBtnEdt, RzRadGrp, RzDBRGrp;
type
TfrmLoanClassificationList = class(TfrmBaseDocked,ISave,INew)
pnlList: TRzPanel;
grList: TRzDBGrid;
edClassName: TRzDBEdit;
edTerm: TRzDBEdit;
edComakersMin: TRzDBEdit;
dbluCompMethod: TRzDBLookupComboBox;
edInterest: TRzDBNumericEdit;
edMaxLoan: TRzDBNumericEdit;
dbluBranch: TRzDBLookupComboBox;
dteFrom: TRzDBDateTimeEdit;
dteUntil: TRzDBDateTimeEdit;
dbluPayFreq: TRzDBLookupComboBox;
pnlDetail: TRzPanel;
pnlAdd: TRzPanel;
sbtnNew: TRzShapeButton;
RzDBEdit2: TRzDBEdit;
Label1: TLabel;
cmbBranch: TRzComboBox;
bteGroup: TRzButtonEdit;
pnlActivate: TRzPanel;
sbtnActivate: TRzShapeButton;
RzPanel3: TRzPanel;
RzShapeButton1: TRzShapeButton;
edComakersMax: TRzDBEdit;
urlClassCharges: TRzURLLabel;
urlAdvancePayment: TRzURLLabel;
rbgDiminishingType: TRzDBRadioGroup;
edMaxAdvancePayment: TRzDBNumericEdit;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
Label9: TLabel;
Label10: TLabel;
Label11: TLabel;
Label12: TLabel;
Label13: TLabel;
Label14: TLabel;
Label15: TLabel;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure urlRefreshListClick(Sender: TObject);
procedure grChargesDblClick(Sender: TObject);
procedure sbtnNewClick(Sender: TObject);
procedure dbluBranchClick(Sender: TObject);
procedure bteGroupButtonClick(Sender: TObject);
procedure grListCellClick(Column: TColumn);
procedure grListKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure FormShow(Sender: TObject);
procedure sbtnActivateClick(Sender: TObject);
procedure dbluCompMethodClick(Sender: TObject);
procedure urlClassChargesClick(Sender: TObject);
procedure urlAdvancePaymentClick(Sender: TObject);
procedure cmbBranchChange(Sender: TObject);
private
{ Private declarations }
procedure ChangeControlState;
function EntryIsValid: boolean;
function ConfirmDate: string;
procedure SetUnboundControls;
public
{ Public declarations }
function Save: boolean;
procedure Cancel;
procedure New;
end;
implementation
{$R *.dfm}
uses
LoansAuxData, FormsUtil, IFinanceDialogs, AuxData, LoanClassChargeDetail, DecisionBox,
LoanType, LoanClassification, Group, GroupUtils, GroupSearch, EntitiesData,
LoanClassChargeList, LoanClassAdvancePayment;
function TfrmLoanClassificationList.Save: boolean;
begin
Result := false;
with grList.DataSource.DataSet do
begin
if EntryIsValid then
begin
if State in [dsInsert,dsEdit] then
begin
Post;
Result := true;
ChangeControlState;
end;
end
end;
end;
function TfrmLoanClassificationList.ConfirmDate;
var
msg: string;
begin
msg := 'Setting the end date will restrict making any changes to this classification. Do you want to proceed?';
if ShowWarningBox(msg) = mrYes then Result := ''
else Result := 'Saving has been cancelled.';
end;
procedure TfrmLoanClassificationList.SetUnboundControls;
begin
if (Assigned(lnc)) and (Assigned(lnc.Group)) then
bteGroup.Text := lnc.Group.GroupName;
end;
procedure TfrmLoanClassificationList.sbtnActivateClick(Sender: TObject);
begin
inherited;
if not lnc.IsActive then ShowErrorBox('Loan class is already active.');
end;
procedure TfrmLoanClassificationList.sbtnNewClick(Sender: TObject);
begin
New;
end;
procedure TfrmLoanClassificationList.New;
begin
grList.DataSource.DataSet.Append;
ChangeControlState;
bteGroup.Clear;
// focus the first control
grList.DataSource.DataSet.FieldByName('loc_code').AsString := cmbBranch.Value;
dbluBranch.SetFocus;
end;
procedure TfrmLoanClassificationList.urlAdvancePaymentClick(Sender: TObject);
begin
with TfrmLoanClassAdvancePaymentDetail.Create(nil) do
begin
ShowModal;
Free;
end;
end;
procedure TfrmLoanClassificationList.urlClassChargesClick(Sender: TObject);
begin
with TfrmLoanClassChargeList.Create(nil) do
begin
ShowModal;
Free;
end;
end;
procedure TfrmLoanClassificationList.urlRefreshListClick(Sender: TObject);
begin
inherited;
with grList.DataSource.DataSet do
begin
Close;
Open;
end
end;
procedure TfrmLoanClassificationList.Cancel;
begin
with grList.DataSource.DataSet do
begin
if State in [dsInsert,dsEdit] then
Cancel;
ChangeControlState;
SetUnboundControls;
end;
end;
procedure TfrmLoanClassificationList.dbluBranchClick(Sender: TObject);
begin
inherited;
// filter groups
with dmAux.dstGroups do
begin
Filter := 'loc_code = ''' + dbluBranch.GetKeyValue + '''';
Filtered := true;
PopulateGroupList(dmAux.dstGroups);
// clear the group field
bteGroup.Clear;
grList.DataSource.DataSet.FieldByName('grp_id').Clear;
end;
end;
procedure TfrmLoanClassificationList.dbluCompMethodClick(Sender: TObject);
var
diminishing: boolean;
begin
inherited;
diminishing := dbluCompMethod.KeyValue = 'D';
if not diminishing then rbgDiminishingType.Value := '0'
else rbgDiminishingType.Value := '1';
rbgDiminishingType.ReadOnly := not diminishing;
end;
function TfrmLoanClassificationList.EntryIsValid: boolean;
var
error: string;
begin
if dbluBranch.Text = '' then error := 'Please select a branch.'
else if Trim(bteGroup.Text) = '' then error := 'Please select a group.'
else if Trim(edClassName.Text) = '' then error := 'Please enter a class name.'
else if edInterest.Text = '' then error := 'Please enter an interest rate.'
else if edTerm.Text = '' then error := 'Please enter the terms of this loan class.'
else if edMaxLoan.Value <= 0 then error := 'Please enter a maximum loan.'
else if dbluCompMethod.Text = '' then error := 'Please select a computation method.'
else if dbluPayFreq.Text = '' then error := 'Please select a payment frequency.'
else if dteFrom.Text = '' then error := 'Please specify a start date.'
// else if edMaxLoan.Value > ltype then
// error := 'Maximum loan exceeds the maximum total amount for the selected group.'
else if dteUntil.Text <> '' then
begin
if dteUntil.Date <= dteFrom.Date then error := 'End date cannot be less than or equal to the start date.'
else error := ConfirmDate;
end;
if error <> '' then ShowErrorBox(error);
Result := error = '';
end;
procedure TfrmLoanClassificationList.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
OpenDropdownDataSources(pnlDetail,false);
OpenGridDataSources(pnlList,false);
dmAux.Free;
dmLoansAux.Free;
inherited;
end;
procedure TfrmLoanClassificationList.FormCreate(Sender: TObject);
begin
inherited;
dmAux := TdmAux.Create(self);
dmLoansAux := TdmLoansAux.Create(self);
OpenDropdownDataSources(pnlDetail);
OpenGridDataSources(pnlList);
PopulateBranchComboBox(cmbBranch);
ChangeControlState;
end;
procedure TfrmLoanClassificationList.FormShow(Sender: TObject);
begin
inherited;
SetUnboundControls;
end;
procedure TfrmLoanClassificationList.grChargesDblClick(Sender: TObject);
begin
with TfrmLoanClassChargeDetail.Create(nil) do
begin
try
ShowModal;
Free;
except
on e: Exception do
ShowMessage(e.Message);
end;
end;
end;
procedure TfrmLoanClassificationList.grListCellClick(Column: TColumn);
begin
inherited;
SetUnboundControls;
end;
procedure TfrmLoanClassificationList.grListKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
inherited;
if Key in [VK_UP, VK_DOWN] then SetUnboundControls;
end;
procedure TfrmLoanClassificationList.bteGroupButtonClick(Sender: TObject);
begin
inherited;
if dbluBranch.Text = '' then
begin
ShowErrorBox('Please select a branch.');
Exit;
end;
dmEntities := TdmEntities.Create(self);
with TfrmGroupSearch.Create(self,dbluBranch.KeyValue) do
begin
try
try
grp := TGroup.Create;
ShowModal;
if ModalResult = mrOK then
begin
with grList.DataSource.DataSet do
begin
if State <> dsInsert then Edit;
FieldByName('grp_id').AsString := grp.GroupId;
bteGroup.Text := grp.GroupName;
end;
end;
except
on e: Exception do
ShowErrorBox(e.Message);
end;
finally
dmEntities.Free;
Free;
end;
end;
end;
procedure TfrmLoanClassificationList.ChangeControlState;
begin
with grList.DataSource.DataSet do
begin
urlClassCharges.Enabled := (State <> dsInsert) and (RecordCount > 0);
urlAdvancePayment.Enabled := (State <> dsInsert) and (RecordCount > 0);
end;
end;
procedure TfrmLoanClassificationList.cmbBranchChange(Sender: TObject);
begin
inherited;
if cmbBranch.ItemIndex > -1 then
grList.DataSource.DataSet.Filter := 'loc_code = ' + QuotedStr(Trim(cmbBranch.Value))
else
grList.DataSource.DataSet.Filter := '';
bteGroup.Clear;
end;
end.
|
{
This file is part of the Free Pascal run time library.
Copyright (c) 2008 Free Pascal development team.
See the file COPYING.FPC, included in this distribution,
for details about the copyright.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
********************************************************************** }
//
// Module Name:
//
// mmreg.h
//
// Abstract:
//
// Multimedia Registration
//
//
// Microsoft Windows Mobile 6.0 for PocketPC SDK.
//
unit mmreg;
interface
uses Windows;
{
Automatically converted by H2Pas 1.0.0 from mmreg.h
The following command line parameters were used:
-d
-w
-D
-l
mmreg.h
}
{ Define the following to skip definitions }
{ }
{ NOMMIDS Multimedia IDs are not defined }
{ NONEWWAVE No new waveform types are defined except WAVEFORMATEX }
{ NONEWRIFF No new RIFF forms are defined }
{ NOJPEGDIB No JPEG DIB definitions }
{ NONEWIC No new Image Compressor types are defined }
{ NOBITMAP No extended bitmap info header definition }
{$PACKRECORDS 1} // {#include "pshpack1.h" /* Assume byte packing throughout */ }
type
FOURCC = DWORD; //* a four character code */
{$IFNDEF NOMMIDS}
// manufacturer IDs
const
MM_MICROSOFT = 1; // Microsoft Corporation
MM_CREATIVE = 2; // Creative Labs, Inc
{ Media Vision, Inc. }
MM_MEDIAVISION = 3;
{ Fujitsu Corp. }
MM_FUJITSU = 4;
{ Artisoft, Inc. }
MM_ARTISOFT = 20;
{ Turtle Beach, Inc. }
MM_TURTLE_BEACH = 21;
{ IBM Corporation }
MM_IBM = 22;
{ Vocaltec LTD. }
MM_VOCALTEC = 23;
{ Roland }
MM_ROLAND = 24;
{ DSP Solutions, Inc. }
MM_DSP_SOLUTIONS = 25;
{ NEC }
MM_NEC = 26;
{ ATI }
MM_ATI = 27;
{ Wang Laboratories, Inc }
MM_WANGLABS = 28;
{ Tandy Corporation }
MM_TANDY = 29;
{ Voyetra }
MM_VOYETRA = 30;
{ Antex Electronics Corporation }
MM_ANTEX = 31;
{ ICL Personal Systems }
MM_ICL_PS = 32;
{ Intel Corporation }
MM_INTEL = 33;
{ Advanced Gravis }
MM_GRAVIS = 34;
{ Video Associates Labs, Inc. }
MM_VAL = 35;
{ InterActive Inc }
MM_INTERACTIVE = 36;
{ Yamaha Corporation of America }
MM_YAMAHA = 37;
{ Everex Systems, Inc }
MM_EVEREX = 38;
{ Echo Speech Corporation }
MM_ECHO = 39;
{ Sierra Semiconductor Corp }
MM_SIERRA = 40;
{ Computer Aided Technologies }
MM_CAT = 41;
{ APPS Software International }
MM_APPS = 42;
{ DSP Group, Inc }
MM_DSP_GROUP = 43;
{ microEngineering Labs }
MM_MELABS = 44;
{ Computer Friends, Inc. }
MM_COMPUTER_FRIENDS = 45;
{ ESS Technology }
MM_ESS = 46;
{ Audio, Inc. }
MM_AUDIOFILE = 47;
{ Motorola, Inc. }
MM_MOTOROLA = 48;
{ Canopus, co., Ltd. }
MM_CANOPUS = 49;
{ Seiko Epson Corporation }
MM_EPSON = 50;
{ Truevision }
MM_TRUEVISION = 51;
{ Aztech Labs, Inc. }
MM_AZTECH = 52;
{ Videologic }
MM_VIDEOLOGIC = 53;
{ SCALACS }
MM_SCALACS = 54;
{ Korg Inc. }
MM_KORG = 55;
{ Audio Processing Technology }
MM_APT = 56;
{ Integrated Circuit Systems, Inc. }
MM_ICS = 57;
{ Iterated Systems, Inc. }
MM_ITERATEDSYS = 58;
{ Metheus }
MM_METHEUS = 59;
{ Logitech, Inc. }
MM_LOGITECH = 60;
{ Winnov, Inc. }
MM_WINNOV = 61;
{ NCR Corporation }
MM_NCR = 62;
{ EXAN }
MM_EXAN = 63;
{ AST Research Inc. }
MM_AST = 64;
{ Willow Pond Corporation }
MM_WILLOWPOND = 65;
{ Sonic Foundry }
MM_SONICFOUNDRY = 66;
{ Vitec Multimedia }
MM_VITEC = 67;
{ MOSCOM Corporation }
MM_MOSCOM = 68;
{ Silicon Soft, Inc. }
MM_SILICONSOFT = 69;
{ Supermac }
MM_SUPERMAC = 73;
{ Audio Processing Technology }
MM_AUDIOPT = 74;
{ Speech Compression }
MM_SPEECHCOMP = 76;
{ Ahead, Inc. }
MM_AHEAD = 77;
{ Dolby Laboratories }
MM_DOLBY = 78;
{ OKI }
MM_OKI = 79;
{ AuraVision Corporation }
MM_AURAVISION = 80;
{ Ing C. Olivetti & C., S.p.A. }
MM_OLIVETTI = 81;
{ I/O Magic Corporation }
MM_IOMAGIC = 82;
{ Matsushita Electric Industrial Co., LTD. }
MM_MATSUSHITA = 83;
{ Control Resources Limited }
MM_CONTROLRES = 84;
{ Xebec Multimedia Solutions Limited }
MM_XEBEC = 85;
{ New Media Corporation }
MM_NEWMEDIA = 86;
{ Natural MicroSystems }
MM_NMS = 87;
{ Lyrrus Inc. }
MM_LYRRUS = 88;
{ Compusic }
MM_COMPUSIC = 89;
{ OPTi Computers Inc. }
MM_OPTI = 90;
{ Adlib Accessories Inc. }
MM_ADLACC = 91;
{ Compaq Computer Corp. }
MM_COMPAQ = 92;
{ Dialogic Corporation }
MM_DIALOGIC = 93;
{ InSoft, Inc. }
MM_INSOFT = 94;
{ M.P. Technologies, Inc. }
MM_MPTUS = 95;
{ Weitek }
MM_WEITEK = 96;
{ Lernout & Hauspie }
MM_LERNOUT_AND_HAUSPIE = 97;
{ Quanta Computer Inc. }
MM_QCIAR = 98;
{ Apple Computer, Inc. }
MM_APPLE = 99;
{ Digital Equipment Corporation }
MM_DIGITAL = 100;
{ Mark of the Unicorn }
MM_MOTU = 101;
{ Workbit Corporation }
MM_WORKBIT = 102;
{ Ositech Communications Inc. }
MM_OSITECH = 103;
{ miro Computer Products AG }
MM_MIRO = 104;
{ Cirrus Logic }
MM_CIRRUSLOGIC = 105;
{ ISOLUTION B.V. }
MM_ISOLUTION = 106;
{ Horizons Technology, Inc }
MM_HORIZONS = 107;
{ Computer Concepts Ltd }
MM_CONCEPTS = 108;
{ Voice Technologies Group, Inc. }
MM_VTG = 109;
{ Radius }
MM_RADIUS = 110;
{ Rockwell International }
MM_ROCKWELL = 111;
{ Co. XYZ for testing }
MM_XYz = 112;
{ Opcode Systems }
MM_OPCODE = 113;
{ Voxware Inc }
MM_VOXWARE = 114;
{ Northern Telecom Limited }
MM_NORTHERN_TELECOM = 115;
{ APICOM }
MM_APICOM = 116;
{ Grande Software }
MM_GRANDE = 117;
{ ADDX }
MM_ADDX = 118;
{ Wildcat Canyon Software }
MM_WILDCAT = 119;
{ Rhetorex Inc }
MM_RHETOREX = 120;
{ Brooktree Corporation }
MM_BROOKTREE = 121;
{ ENSONIQ Corporation }
MM_ENSONIQ = 125;
{ ///FAST Multimedia AG }
MM_FAST = 126;
{ NVidia Corporation }
MM_NVIDIA = 127;
{ OKSORI Co., Ltd. }
MM_OKSORI = 128;
{ DiAcoustics, Inc. }
MM_DIACOUSTICS = 129;
{ Gulbransen, Inc. }
MM_GULBRANSEN = 130;
{ Kay Elemetrics, Inc. }
MM_KAY_ELEMETRICS = 131;
{ Crystal Semiconductor Corporation }
MM_CRYSTAL = 132;
{ Splash Studios }
MM_SPLASH_STUDIOS = 133;
{ Quarterdeck Corporation }
MM_QUARTERDECK = 134;
{ TDK Corporation }
MM_TDK = 135;
{ Digital Audio Labs, Inc. }
MM_DIGITAL_AUDIO_LABS = 136;
{ Seer Systems, Inc. }
MM_SEERSYS = 137;
{ PictureTel Corporation }
MM_PICTURETEL = 138;
{ AT&T Microelectronics }
MM_ATT_MICROELECTRONICS = 139;
{ Osprey Technologies, Inc. }
MM_OSPREY = 140;
{ Mediatrix Peripherals }
MM_MEDIATRIX = 141;
{ SounDesignS M.C.S. Ltd. }
MM_SOUNDESIGNS = 142;
{ A.L. Digital Ltd. }
MM_ALDIGITAL = 143;
{ Spectrum Signal Processing, Inc. }
MM_SPECTRUM_SIGNAL_PROCESSING = 144;
{ Electronic Courseware Systems, Inc. }
MM_ECS = 145;
{ AMD }
MM_AMD = 146;
{ Core Dynamics }
MM_COREDYNAMICS = 147;
{ CANAM Computers }
MM_CANAM = 148;
{ Softsound, Ltd. }
MM_SOFTSOUND = 149;
{ Norris Communications, Inc. }
MM_NORRIS = 150;
{ Danka Data Devices }
MM_DDD = 151;
{ EuPhonics }
MM_EUPHONICS = 152;
{ Precept Software, Inc. }
MM_PRECEPT = 153;
{ Crystal Net Corporation }
MM_CRYSTAL_NET = 154;
{ Chromatic Research, Inc }
MM_CHROMATIC = 155;
{ Voice Information Systems, Inc }
MM_VOICEINFO = 156;
{ Vienna Systems }
MM_VIENNASYS = 157;
{ Connectix Corporation }
MM_CONNECTIX = 158;
{ Gadget Labs LLC }
MM_GADGETLABS = 159;
{ Frontier Design Group LLC }
MM_FRONTIER = 160;
{ Viona Development GmbH }
MM_VIONA = 161;
{ Casio Computer Co., LTD }
MM_CASIO = 162;
{ Diamond Multimedia }
MM_DIAMONDMM = 163;
{ S3 }
MM_S3 = 164;
{ Fraunhofer }
MM_FRAUNHOFER_IIS = 172;
{ MM_MICROSOFT product IDs }
{$IFNDEF MM_MIDI_MAPPER}
const
MM_MIDI_MAPPER = 1; // Midi Mapper
{ Wave Mapper }
MM_WAVE_MAPPER = 2;
{ Sound Blaster MIDI output port }
MM_SNDBLST_MIDIOUT = 3;
{ Sound Blaster MIDI input port }
MM_SNDBLST_MIDIIN = 4;
{ Sound Blaster internal synth }
MM_SNDBLST_SYNTH = 5;
{ Sound Blaster waveform output }
MM_SNDBLST_WAVEOUT = 6;
{ Sound Blaster waveform input }
MM_SNDBLST_WAVEIN = 7;
{ Ad Lib Compatible synth }
MM_ADLIB = 9;
{ MPU 401 compatible MIDI output port }
MM_MPU401_MIDIOUT = 10;
{ MPU 401 compatible MIDI input port }
MM_MPU401_MIDIIN = 11;
{ Joystick adapter }
MM_PC_JOYSTICK = 12;
{$ENDIF MM_MIDI_MAPPER}
const
MM_PCSPEAKER_WAVEOUT = 13; { PC speaker waveform output }
{ MS Audio Board waveform input }
MM_MSFT_WSS_WAVEIN = 14;
{ MS Audio Board waveform output }
MM_MSFT_WSS_WAVEOUT = 15;
{ MS Audio Board Stereo FM synth }
MM_MSFT_WSS_FMSYNTH_STEREO = 16;
{ MS Audio Board Mixer Driver }
MM_MSFT_WSS_MIXER = 17;
{ MS OEM Audio Board waveform input }
MM_MSFT_WSS_OEM_WAVEIN = 18;
{ MS OEM Audio Board waveform output }
MM_MSFT_WSS_OEM_WAVEOUT = 19;
{ MS OEM Audio Board Stereo FM Synth }
MM_MSFT_WSS_OEM_FMSYNTH_STEREO = 20;
{ MS Audio Board Aux. Port }
MM_MSFT_WSS_AUX = 21;
{ MS OEM Audio Aux Port }
MM_MSFT_WSS_OEM_AUX = 22;
{ MS Vanilla driver waveform input }
MM_MSFT_GENERIC_WAVEIN = 23;
{ MS Vanilla driver wavefrom output }
MM_MSFT_GENERIC_WAVEOUT = 24;
{ MS Vanilla driver MIDI in }
MM_MSFT_GENERIC_MIDIIN = 25;
{ MS Vanilla driver MIDI external out }
MM_MSFT_GENERIC_MIDIOUT = 26;
{ MS Vanilla driver MIDI synthesizer }
MM_MSFT_GENERIC_MIDISYNTH = 27;
{ MS Vanilla driver aux (line in) }
MM_MSFT_GENERIC_AUX_LINE = 28;
{ MS Vanilla driver aux (mic) }
MM_MSFT_GENERIC_AUX_MIC = 29;
{ MS Vanilla driver aux (CD) }
MM_MSFT_GENERIC_AUX_CD = 30;
{ MS OEM Audio Board Mixer Driver }
MM_MSFT_WSS_OEM_MIXER = 31;
{ MS Audio Compression Manager }
MM_MSFT_MSACM = 32;
{ MS ADPCM Codec }
MM_MSFT_ACM_MSADPCM = 33;
{ IMA ADPCM Codec }
MM_MSFT_ACM_IMAADPCM = 34;
{ MS Filter }
MM_MSFT_ACM_MSFILTER = 35;
{ GSM 610 codec }
MM_MSFT_ACM_GSM610 = 36;
{ G.711 codec }
MM_MSFT_ACM_G711 = 37;
{ PCM converter }
MM_MSFT_ACM_PCM = 38;
{ Microsoft Windows Sound System drivers }
{ Sound Blaster 16 waveform input }
MM_WSS_SB16_WAVEIN = 39;
{ Sound Blaster 16 waveform output }
MM_WSS_SB16_WAVEOUT = 40;
{ Sound Blaster 16 midi-in }
MM_WSS_SB16_MIDIIN = 41;
{ Sound Blaster 16 midi out }
MM_WSS_SB16_MIDIOUT = 42;
{ Sound Blaster 16 FM Synthesis }
MM_WSS_SB16_SYNTH = 43;
{ Sound Blaster 16 aux (line in) }
MM_WSS_SB16_AUX_LINE = 44;
{ Sound Blaster 16 aux (CD) }
MM_WSS_SB16_AUX_CD = 45;
{ Sound Blaster 16 mixer device }
MM_WSS_SB16_MIXER = 46;
{ Sound Blaster Pro waveform input }
MM_WSS_SBPRO_WAVEIN = 47;
{ Sound Blaster Pro waveform output }
MM_WSS_SBPRO_WAVEOUT = 48;
{ Sound Blaster Pro midi in }
MM_WSS_SBPRO_MIDIIN = 49;
{ Sound Blaster Pro midi out }
MM_WSS_SBPRO_MIDIOUT = 50;
{ Sound Blaster Pro FM synthesis }
MM_WSS_SBPRO_SYNTH = 51;
{ Sound Blaster Pro aux (line in ) }
MM_WSS_SBPRO_AUX_LINE = 52;
{ Sound Blaster Pro aux (CD) }
MM_WSS_SBPRO_AUX_CD = 53;
{ Sound Blaster Pro mixer }
MM_WSS_SBPRO_MIXER = 54;
{ WSS NT wave in }
MM_MSFT_WSS_NT_WAVEIN = 55;
{ WSS NT wave out }
MM_MSFT_WSS_NT_WAVEOUT = 56;
{ WSS NT FM synth }
MM_MSFT_WSS_NT_FMSYNTH_STEREO = 57;
{ WSS NT mixer }
MM_MSFT_WSS_NT_MIXER = 58;
{ WSS NT aux }
MM_MSFT_WSS_NT_AUX = 59;
{ Sound Blaster 16 waveform input }
MM_MSFT_SB16_WAVEIN = 60;
{ Sound Blaster 16 waveform output }
MM_MSFT_SB16_WAVEOUT = 61;
{ Sound Blaster 16 midi-in }
MM_MSFT_SB16_MIDIIN = 62;
{ Sound Blaster 16 midi out }
MM_MSFT_SB16_MIDIOUT = 63;
{ Sound Blaster 16 FM Synthesis }
MM_MSFT_SB16_SYNTH = 64;
{ Sound Blaster 16 aux (line in) }
MM_MSFT_SB16_AUX_LINE = 65;
{ Sound Blaster 16 aux (CD) }
MM_MSFT_SB16_AUX_CD = 66;
{ Sound Blaster 16 mixer device }
MM_MSFT_SB16_MIXER = 67;
{ Sound Blaster Pro waveform input }
MM_MSFT_SBPRO_WAVEIN = 68;
{ Sound Blaster Pro waveform output }
MM_MSFT_SBPRO_WAVEOUT = 69;
{ Sound Blaster Pro midi in }
MM_MSFT_SBPRO_MIDIIN = 70;
{ Sound Blaster Pro midi out }
MM_MSFT_SBPRO_MIDIOUT = 71;
{ Sound Blaster Pro FM synthesis }
MM_MSFT_SBPRO_SYNTH = 72;
{ Sound Blaster Pro aux (line in ) }
MM_MSFT_SBPRO_AUX_LINE = 73;
{ Sound Blaster Pro aux (CD) }
MM_MSFT_SBPRO_AUX_CD = 74;
{ Sound Blaster Pro mixer }
MM_MSFT_SBPRO_MIXER = 75;
{ Yamaha OPL2/OPL3 compatible FM synthesis }
MM_MSFT_MSOPL_SYNTH = 76;
{ Voice Modem Serial Line Wave Input }
MM_MSFT_VMDMS_LINE_WAVEIN = 80;
{ Voice Modem Serial Line Wave Output }
MM_MSFT_VMDMS_LINE_WAVEOUT = 81;
{ Voice Modem Serial Handset Wave Input }
MM_MSFT_VMDMS_HANDSET_WAVEIN = 82;
{ Voice Modem Serial Handset Wave Output }
MM_MSFT_VMDMS_HANDSET_WAVEOUT = 83;
{ Voice Modem Wrapper Line Wave Input }
MM_MSFT_VMDMW_LINE_WAVEIN = 84;
{ Voice Modem Wrapper Line Wave Output }
MM_MSFT_VMDMW_LINE_WAVEOUT = 85;
{ Voice Modem Wrapper Handset Wave Input }
MM_MSFT_VMDMW_HANDSET_WAVEIN = 86;
{ Voice Modem Wrapper Handset Wave Output }
MM_MSFT_VMDMW_HANDSET_WAVEOUT = 87;
{ Voice Modem Wrapper Mixer }
MM_MSFT_VMDMW_MIXER = 88;
{ Voice Modem Game Compatible Wave Device }
MM_MSFT_VMDM_GAME_WAVEOUT = 89;
{ Voice Modem Game Compatible Wave Device }
MM_MSFT_VMDM_GAME_WAVEIN = 90;
{ }
MM_MSFT_ACM_MSNAUDIO = 91;
{ }
MM_MSFT_ACM_MSG723 = 92;
{ Generic id for WDM Audio drivers }
MM_MSFT_WDMAUDIO_WAVEOUT = 100;
{ Generic id for WDM Audio drivers }
MM_MSFT_WDMAUDIO_WAVEIN = 101;
{ Generic id for WDM Audio drivers }
MM_MSFT_WDMAUDIO_MIDIOUT = 102;
{ Generic id for WDM Audio drivers }
MM_MSFT_WDMAUDIO_MIDIIN = 103;
{ Generic id for WDM Audio drivers }
MM_MSFT_WDMAUDIO_MIXER = 104;
{ MM_CREATIVE product IDs }
MM_CREATIVE_SB15_WAVEIN = 1; { SB (r) 1.5 waveform input }
MM_CREATIVE_SB20_WAVEIN = 2;
MM_CREATIVE_SBPRO_WAVEIN = 3;
MM_CREATIVE_SBP16_WAVEIN = 4;
MM_CREATIVE_PHNBLST_WAVEIN = 5;
MM_CREATIVE_SB15_WAVEOUT = 101;
MM_CREATIVE_SB20_WAVEOUT = 102;
MM_CREATIVE_SBPRO_WAVEOUT = 103;
MM_CREATIVE_SBP16_WAVEOUT = 104;
MM_CREATIVE_PHNBLST_WAVEOUT = 105;
{ SB (r) }
MM_CREATIVE_MIDIOUT = 201;
{ SB (r) }
MM_CREATIVE_MIDIIN = 202;
{ SB (r) }
MM_CREATIVE_FMSYNTH_MONO = 301;
{ SB Pro (r) stereo synthesizer }
MM_CREATIVE_FMSYNTH_STEREO = 302;
MM_CREATIVE_MIDI_AWE32 = 303;
{ SB Pro (r) aux (CD) }
MM_CREATIVE_AUX_CD = 401;
{ SB Pro (r) aux (Line in ) }
MM_CREATIVE_AUX_LINE = 402;
{ SB Pro (r) aux (mic) }
MM_CREATIVE_AUX_MIC = 403;
MM_CREATIVE_AUX_MASTER = 404;
MM_CREATIVE_AUX_PCSPK = 405;
MM_CREATIVE_AUX_WAVE = 406;
MM_CREATIVE_AUX_MIDI = 407;
MM_CREATIVE_SBPRO_MIXER = 408;
MM_CREATIVE_SB16_MIXER = 409;
{ MM_MEDIAVISION product IDs }
{ Pro Audio Spectrum }
MM_MEDIAVISION_PROAUDIO = $10;
MM_PROAUD_MIDIOUT = MM_MEDIAVISION_PROAUDIO+1;
MM_PROAUD_MIDIIN = MM_MEDIAVISION_PROAUDIO+2;
MM_PROAUD_SYNTH = MM_MEDIAVISION_PROAUDIO+3;
MM_PROAUD_WAVEOUT = MM_MEDIAVISION_PROAUDIO+4;
MM_PROAUD_WAVEIN = MM_MEDIAVISION_PROAUDIO+5;
MM_PROAUD_MIXER = MM_MEDIAVISION_PROAUDIO+6;
MM_PROAUD_AUX = MM_MEDIAVISION_PROAUDIO+7;
{ Thunder Board }
MM_MEDIAVISION_THUNDER = $20;
MM_THUNDER_SYNTH = MM_MEDIAVISION_THUNDER+3;
MM_THUNDER_WAVEOUT = MM_MEDIAVISION_THUNDER+4;
MM_THUNDER_WAVEIN = MM_MEDIAVISION_THUNDER+5;
MM_THUNDER_AUX = MM_MEDIAVISION_THUNDER+7;
{ Audio Port }
MM_MEDIAVISION_TPORT = $40;
MM_TPORT_WAVEOUT = MM_MEDIAVISION_TPORT+1;
MM_TPORT_WAVEIN = MM_MEDIAVISION_TPORT+2;
MM_TPORT_SYNTH = MM_MEDIAVISION_TPORT+3;
{ Pro Audio Spectrum Plus }
MM_MEDIAVISION_PROAUDIO_PLUS = $50;
MM_PROAUD_PLUS_MIDIOUT = MM_MEDIAVISION_PROAUDIO_PLUS+1;
MM_PROAUD_PLUS_MIDIIN = MM_MEDIAVISION_PROAUDIO_PLUS+2;
MM_PROAUD_PLUS_SYNTH = MM_MEDIAVISION_PROAUDIO_PLUS+3;
MM_PROAUD_PLUS_WAVEOUT = MM_MEDIAVISION_PROAUDIO_PLUS+4;
MM_PROAUD_PLUS_WAVEIN = MM_MEDIAVISION_PROAUDIO_PLUS+5;
MM_PROAUD_PLUS_MIXER = MM_MEDIAVISION_PROAUDIO_PLUS+6;
MM_PROAUD_PLUS_AUX = MM_MEDIAVISION_PROAUDIO_PLUS+7;
{ Pro Audio Spectrum 16 }
MM_MEDIAVISION_PROAUDIO_16 = $60;
MM_PROAUD_16_MIDIOUT = MM_MEDIAVISION_PROAUDIO_16+1;
MM_PROAUD_16_MIDIIN = MM_MEDIAVISION_PROAUDIO_16+2;
MM_PROAUD_16_SYNTH = MM_MEDIAVISION_PROAUDIO_16+3;
MM_PROAUD_16_WAVEOUT = MM_MEDIAVISION_PROAUDIO_16+4;
MM_PROAUD_16_WAVEIN = MM_MEDIAVISION_PROAUDIO_16+5;
MM_PROAUD_16_MIXER = MM_MEDIAVISION_PROAUDIO_16+6;
MM_PROAUD_16_AUX = MM_MEDIAVISION_PROAUDIO_16+7;
{ Pro Audio Studio 16 }
MM_MEDIAVISION_PROSTUDIO_16 = $60;
MM_STUDIO_16_MIDIOUT = MM_MEDIAVISION_PROSTUDIO_16+1;
MM_STUDIO_16_MIDIIN = MM_MEDIAVISION_PROSTUDIO_16+2;
MM_STUDIO_16_SYNTH = MM_MEDIAVISION_PROSTUDIO_16+3;
MM_STUDIO_16_WAVEOUT = MM_MEDIAVISION_PROSTUDIO_16+4;
MM_STUDIO_16_WAVEIN = MM_MEDIAVISION_PROSTUDIO_16+5;
MM_STUDIO_16_MIXER = MM_MEDIAVISION_PROSTUDIO_16+6;
MM_STUDIO_16_AUX = MM_MEDIAVISION_PROSTUDIO_16+7;
{ CDPC }
MM_MEDIAVISION_CDPC = $70;
MM_CDPC_MIDIOUT = MM_MEDIAVISION_CDPC+1;
MM_CDPC_MIDIIN = MM_MEDIAVISION_CDPC+2;
MM_CDPC_SYNTH = MM_MEDIAVISION_CDPC+3;
MM_CDPC_WAVEOUT = MM_MEDIAVISION_CDPC+4;
MM_CDPC_WAVEIN = MM_MEDIAVISION_CDPC+5;
MM_CDPC_MIXER = MM_MEDIAVISION_CDPC+6;
MM_CDPC_AUX = MM_MEDIAVISION_CDPC+7;
{ Opus MV 1208 Chipsent }
MM_MEDIAVISION_OPUS1208 = $80;
MM_OPUS401_MIDIOUT = MM_MEDIAVISION_OPUS1208+1;
MM_OPUS401_MIDIIN = MM_MEDIAVISION_OPUS1208+2;
MM_OPUS1208_SYNTH = MM_MEDIAVISION_OPUS1208+3;
MM_OPUS1208_WAVEOUT = MM_MEDIAVISION_OPUS1208+4;
MM_OPUS1208_WAVEIN = MM_MEDIAVISION_OPUS1208+5;
MM_OPUS1208_MIXER = MM_MEDIAVISION_OPUS1208+6;
MM_OPUS1208_AUX = MM_MEDIAVISION_OPUS1208+7;
{ Opus MV 1216 chipset }
MM_MEDIAVISION_OPUS1216 = $90;
MM_OPUS1216_MIDIOUT = MM_MEDIAVISION_OPUS1216+1;
MM_OPUS1216_MIDIIN = MM_MEDIAVISION_OPUS1216+2;
MM_OPUS1216_SYNTH = MM_MEDIAVISION_OPUS1216+3;
MM_OPUS1216_WAVEOUT = MM_MEDIAVISION_OPUS1216+4;
MM_OPUS1216_WAVEIN = MM_MEDIAVISION_OPUS1216+5;
MM_OPUS1216_MIXER = MM_MEDIAVISION_OPUS1216+6;
MM_OPUS1216_AUX = MM_MEDIAVISION_OPUS1216+7;
{ MM_ARTISOFT product IDs }
{ Artisoft sounding Board waveform input }
MM_ARTISOFT_SBWAVEIN = 1;
{ Artisoft sounding Board waveform output }
MM_ARTISOFT_SBWAVEOUT = 2;
{ MM_IBM product IDs }
{ IBM M-Motion Auxiliary Device }
MM_MMOTION_WAVEAUX = 1;
{ IBM M-Motion Waveform output }
MM_MMOTION_WAVEOUT = 2;
{ IBM M-Motion Waveform Input }
MM_MMOTION_WAVEIN = 3;
{ IBM waveform input }
MM_IBM_PCMCIA_WAVEIN = 11;
{ IBM Waveform output }
MM_IBM_PCMCIA_WAVEOUT = 12;
{ IBM Midi Synthesis }
MM_IBM_PCMCIA_SYNTH = 13;
{ IBM external MIDI in }
MM_IBM_PCMCIA_MIDIIN = 14;
{ IBM external MIDI out }
MM_IBM_PCMCIA_MIDIOUT = 15;
{ IBM auxiliary control }
MM_IBM_PCMCIA_AUX = 16;
MM_IBM_THINKPAD200 = 17;
MM_IBM_MWAVE_WAVEIN = 18;
MM_IBM_MWAVE_WAVEOUT = 19;
MM_IBM_MWAVE_MIXER = 20;
MM_IBM_MWAVE_MIDIIN = 21;
MM_IBM_MWAVE_MIDIOUT = 22;
MM_IBM_MWAVE_AUX = 23;
MM_IBM_WC_MIDIOUT = 30;
MM_IBM_WC_WAVEOUT = 31;
MM_IBM_WC_MIXEROUT = 33;
{ MM_VOCALTEC product IDs }
MM_VOCALTEC_WAVEOUT = 1;
MM_VOCALTEC_WAVEIN = 2;
{ MM_ROLAND product IDs }
{ MM_ROLAND_RAP10 }
MM_ROLAND_RAP10_MIDIOUT = 10;
{ MM_ROLAND_RAP10 }
MM_ROLAND_RAP10_MIDIIN = 11;
{ MM_ROLAND_RAP10 }
MM_ROLAND_RAP10_SYNTH = 12;
{ MM_ROLAND_RAP10 }
MM_ROLAND_RAP10_WAVEOUT = 13;
{ MM_ROLAND_RAP10 }
MM_ROLAND_RAP10_WAVEIN = 14;
MM_ROLAND_MPU401_MIDIOUT = 15;
MM_ROLAND_MPU401_MIDIIN = 16;
MM_ROLAND_SMPU_MIDIOUTA = 17;
MM_ROLAND_SMPU_MIDIOUTB = 18;
MM_ROLAND_SMPU_MIDIINA = 19;
MM_ROLAND_SMPU_MIDIINB = 20;
MM_ROLAND_SC7_MIDIOUT = 21;
MM_ROLAND_SC7_MIDIIN = 22;
MM_ROLAND_SERIAL_MIDIOUT = 23;
MM_ROLAND_SERIAL_MIDIIN = 24;
MM_ROLAND_SCP_MIDIOUT = 38;
MM_ROLAND_SCP_MIDIIN = 39;
MM_ROLAND_SCP_WAVEOUT = 40;
MM_ROLAND_SCP_WAVEIN = 41;
MM_ROLAND_SCP_MIXER = 42;
MM_ROLAND_SCP_AUX = 48;
{ MM_DSP_SOLUTIONS product IDs }
MM_DSP_SOLUTIONS_WAVEOUT = 1;
MM_DSP_SOLUTIONS_WAVEIN = 2;
MM_DSP_SOLUTIONS_SYNTH = 3;
MM_DSP_SOLUTIONS_AUX = 4;
{ MM_WANGLABS product IDs }
{ Input audio wave on CPU board models: Exec 4010, 4030, 3450; PC 251/25c, pc 461/25s , pc 461/33c }
MM_WANGLABS_WAVEIN1 = 1;
MM_WANGLABS_WAVEOUT1 = 2;
{ MM_TANDY product IDs }
MM_TANDY_VISWAVEIN = 1;
MM_TANDY_VISWAVEOUT = 2;
MM_TANDY_VISBIOSSYNTH = 3;
MM_TANDY_SENS_MMAWAVEIN = 4;
MM_TANDY_SENS_MMAWAVEOUT = 5;
MM_TANDY_SENS_MMAMIDIIN = 6;
MM_TANDY_SENS_MMAMIDIOUT = 7;
MM_TANDY_SENS_VISWAVEOUT = 8;
MM_TANDY_PSSJWAVEIN = 9;
MM_TANDY_PSSJWAVEOUT = 10;
{ product IDs }
{ HID2 WaveAudio Driver }
MM_INTELOPD_WAVEIN = 1;
{ HID2 }
MM_INTELOPD_WAVEOUT = 101;
{ HID2 for mixing }
MM_INTELOPD_AUX = 401;
MM_INTEL_NSPMODEMLINE = 501;
{ MM_INTERACTIVE product IDs }
MM_INTERACTIVE_WAVEIN = $45;
MM_INTERACTIVE_WAVEOUT = $45;
{ MM_YAMAHA product IDs }
MM_YAMAHA_GSS_SYNTH = $01;
MM_YAMAHA_GSS_WAVEOUT = $02;
MM_YAMAHA_GSS_WAVEIN = $03;
MM_YAMAHA_GSS_MIDIOUT = $04;
MM_YAMAHA_GSS_MIDIIN = $05;
MM_YAMAHA_GSS_AUX = $06;
MM_YAMAHA_SERIAL_MIDIOUT = $07;
MM_YAMAHA_SERIAL_MIDIIN = $08;
MM_YAMAHA_OPL3SA_WAVEOUT = $10;
MM_YAMAHA_OPL3SA_WAVEIN = $11;
MM_YAMAHA_OPL3SA_FMSYNTH = $12;
MM_YAMAHA_OPL3SA_YSYNTH = $13;
MM_YAMAHA_OPL3SA_MIDIOUT = $14;
MM_YAMAHA_OPL3SA_MIDIIN = $15;
MM_YAMAHA_OPL3SA_MIXER = $17;
MM_YAMAHA_OPL3SA_JOYSTICK = $18;
{ MM_EVEREX product IDs }
MM_EVEREX_CARRIER = $01;
{ MM_ECHO product IDs }
MM_ECHO_SYNTH = $01;
MM_ECHO_WAVEOUT = $02;
MM_ECHO_WAVEIN = $03;
MM_ECHO_MIDIOUT = $04;
MM_ECHO_MIDIIN = $05;
MM_ECHO_AUX = $06;
{ MM_SIERRA product IDs }
MM_SIERRA_ARIA_MIDIOUT = $14;
MM_SIERRA_ARIA_MIDIIN = $15;
MM_SIERRA_ARIA_SYNTH = $16;
MM_SIERRA_ARIA_WAVEOUT = $17;
MM_SIERRA_ARIA_WAVEIN = $18;
MM_SIERRA_ARIA_AUX = $19;
MM_SIERRA_ARIA_AUX2 = $20;
MM_SIERRA_QUARTET_WAVEIN = $50;
MM_SIERRA_QUARTET_WAVEOUT = $51;
MM_SIERRA_QUARTET_MIDIIN = $52;
MM_SIERRA_QUARTET_MIDIOUT = $53;
MM_SIERRA_QUARTET_SYNTH = $54;
MM_SIERRA_QUARTET_AUX_CD = $55;
MM_SIERRA_QUARTET_AUX_LINE = $56;
MM_SIERRA_QUARTET_AUX_MODEM = $57;
MM_SIERRA_QUARTET_MIXER = $58;
{ MM_CAT product IDs }
MM_CAT_WAVEOUT = 1;
{ MM_DSP_GROUP product IDs }
MM_DSP_GROUP_TRUESPEECH = $01;
{ MM_MELABS product IDs }
MM_MELABS_MIDI2GO = $01;
{ MM_ESS product IDs }
MM_ESS_AMWAVEOUT = $01;
MM_ESS_AMWAVEIN = $02;
MM_ESS_AMAUX = $03;
MM_ESS_AMSYNTH = $04;
MM_ESS_AMMIDIOUT = $05;
MM_ESS_AMMIDIIN = $06;
MM_ESS_MIXER = $07;
MM_ESS_AUX_CD = $08;
MM_ESS_MPU401_MIDIOUT = $09;
MM_ESS_MPU401_MIDIIN = $0A;
MM_ESS_ES488_WAVEOUT = $10;
MM_ESS_ES488_WAVEIN = $11;
MM_ESS_ES488_MIXER = $12;
MM_ESS_ES688_WAVEOUT = $13;
MM_ESS_ES688_WAVEIN = $14;
MM_ESS_ES688_MIXER = $15;
MM_ESS_ES1488_WAVEOUT = $16;
MM_ESS_ES1488_WAVEIN = $17;
MM_ESS_ES1488_MIXER = $18;
MM_ESS_ES1688_WAVEOUT = $19;
MM_ESS_ES1688_WAVEIN = $1A;
MM_ESS_ES1688_MIXER = $1B;
MM_ESS_ES1788_WAVEOUT = $1C;
MM_ESS_ES1788_WAVEIN = $1D;
MM_ESS_ES1788_MIXER = $1E;
MM_ESS_ES1888_WAVEOUT = $1F;
MM_ESS_ES1888_WAVEIN = $20;
MM_ESS_ES1888_MIXER = $21;
MM_ESS_ES1868_WAVEOUT = $22;
MM_ESS_ES1868_WAVEIN = $23;
MM_ESS_ES1868_MIXER = $24;
MM_ESS_ES1878_WAVEOUT = $25;
MM_ESS_ES1878_WAVEIN = $26;
MM_ESS_ES1878_MIXER = $27;
{ product IDs }
MM_EPS_FMSND = 1;
{ MM_TRUEVISION product IDs }
MM_TRUEVISION_WAVEIN1 = 1;
MM_TRUEVISION_WAVEOUT1 = 2;
{ MM_AZTECH product IDs }
MM_AZTECH_MIDIOUT = 3;
MM_AZTECH_MIDIIN = 4;
MM_AZTECH_WAVEIN = 17;
MM_AZTECH_WAVEOUT = 18;
MM_AZTECH_FMSYNTH = 20;
MM_AZTECH_MIXER = 21;
MM_AZTECH_PRO16_WAVEIN = 33;
MM_AZTECH_PRO16_WAVEOUT = 34;
MM_AZTECH_PRO16_FMSYNTH = 38;
MM_AZTECH_DSP16_WAVEIN = 65;
MM_AZTECH_DSP16_WAVEOUT = 66;
MM_AZTECH_DSP16_FMSYNTH = 68;
MM_AZTECH_DSP16_WAVESYNTH = 70;
MM_AZTECH_NOVA16_WAVEIN = 71;
MM_AZTECH_NOVA16_WAVEOUT = 72;
MM_AZTECH_NOVA16_MIXER = 73;
MM_AZTECH_WASH16_WAVEIN = 74;
MM_AZTECH_WASH16_WAVEOUT = 75;
MM_AZTECH_WASH16_MIXER = 76;
MM_AZTECH_AUX_CD = 401;
MM_AZTECH_AUX_LINE = 402;
MM_AZTECH_AUX_MIC = 403;
MM_AZTECH_AUX = 404;
{ MM_VIDEOLOGIC product IDs }
MM_VIDEOLOGIC_MSWAVEIN = 1;
MM_VIDEOLOGIC_MSWAVEOUT = 2;
{ MM_KORG product IDs }
MM_KORG_PCIF_MIDIOUT = 1;
MM_KORG_PCIF_MIDIIN = 2;
{ MM_APT product IDs }
MM_APT_ACE100CD = 1;
{ MM_ICS product IDs }
{ MS WSS compatible card and driver }
MM_ICS_WAVEDECK_WAVEOUT = 1;
MM_ICS_WAVEDECK_WAVEIN = 2;
MM_ICS_WAVEDECK_MIXER = 3;
MM_ICS_WAVEDECK_AUX = 4;
MM_ICS_WAVEDECK_SYNTH = 5;
MM_ICS_WAVEDEC_SB_WAVEOUT = 6;
MM_ICS_WAVEDEC_SB_WAVEIN = 7;
MM_ICS_WAVEDEC_SB_FM_MIDIOUT = 8;
MM_ICS_WAVEDEC_SB_MPU401_MIDIOUT = 9;
MM_ICS_WAVEDEC_SB_MPU401_MIDIIN = 10;
MM_ICS_WAVEDEC_SB_MIXER = 11;
MM_ICS_WAVEDEC_SB_AUX = 12;
MM_ICS_2115_LITE_MIDIOUT = 13;
MM_ICS_2120_LITE_MIDIOUT = 14;
{ MM_ITERATEDSYS product IDs }
MM_ITERATEDSYS_FUFCODEC = 1;
{ MM_METHEUS product IDs }
MM_METHEUS_ZIPPER = 1;
{ MM_WINNOV product IDs }
MM_WINNOV_CAVIAR_WAVEIN = 1;
MM_WINNOV_CAVIAR_WAVEOUT = 2;
MM_WINNOV_CAVIAR_VIDC = 3;
{ Fourcc is CHAM }
MM_WINNOV_CAVIAR_CHAMPAGNE = 4;
{ Fourcc is YUV8 }
MM_WINNOV_CAVIAR_YUV8 = 5;
{ MM_NCR product IDs }
MM_NCR_BA_WAVEIN = 1;
MM_NCR_BA_WAVEOUT = 2;
MM_NCR_BA_SYNTH = 3;
MM_NCR_BA_AUX = 4;
MM_NCR_BA_MIXER = 5;
{ MM_VITEC product IDs }
MM_VITEC_VMAKER = 1;
MM_VITEC_VMPRO = 2;
{ MM_MOSCOM product IDs }
{ Four Port Voice Processing / Voice Recognition Board }
MM_MOSCOM_VPC2400_IN = 1;
{ VPC2400 }
MM_MOSCOM_VPC2400_OUT = 2;
{ MM_SILICONSOFT product IDs }
{ Waveform in , high sample rate }
MM_SILICONSOFT_SC1_WAVEIN = 1;
{ Waveform out , high sample rate }
MM_SILICONSOFT_SC1_WAVEOUT = 2;
{ Waveform in 2 channels, high sample rate }
MM_SILICONSOFT_SC2_WAVEIN = 3;
{ Waveform out 2 channels, high sample rate }
MM_SILICONSOFT_SC2_WAVEOUT = 4;
{ Waveform out, self powered, efficient }
MM_SILICONSOFT_SOUNDJR2_WAVEOUT = 5;
{ Waveform in, self powered, efficient }
MM_SILICONSOFT_SOUNDJR2PR_WAVEIN = 6;
{ Waveform out 2 channels, self powered, efficient }
MM_SILICONSOFT_SOUNDJR2PR_WAVEOUT = 7;
{ Waveform in 2 channels, self powered, efficient }
MM_SILICONSOFT_SOUNDJR3_WAVEOUT = 8;
{ MM_OLIVETTI product IDs }
MM_OLIVETTI_WAVEIN = 1;
MM_OLIVETTI_WAVEOUT = 2;
MM_OLIVETTI_MIXER = 3;
MM_OLIVETTI_AUX = 4;
MM_OLIVETTI_MIDIIN = 5;
MM_OLIVETTI_MIDIOUT = 6;
MM_OLIVETTI_SYNTH = 7;
MM_OLIVETTI_JOYSTICK = 8;
MM_OLIVETTI_ACM_GSM = 9;
MM_OLIVETTI_ACM_ADPCM = 10;
MM_OLIVETTI_ACM_CELP = 11;
MM_OLIVETTI_ACM_SBC = 12;
MM_OLIVETTI_ACM_OPR = 13;
{ MM_IOMAGIC product IDs }
{ The I/O Magic Tempo is a PCMCIA Type 2 audio card featuring wave audio
record and playback, FM synthesizer, and MIDI output. The I/O Magic
Tempo WaveOut device supports mono and stereo PCM playback at rates
of 7350, 11025, 22050, and 44100 samples }
MM_IOMAGIC_TEMPO_WAVEOUT = 1;
MM_IOMAGIC_TEMPO_WAVEIN = 2;
MM_IOMAGIC_TEMPO_SYNTH = 3;
MM_IOMAGIC_TEMPO_MIDIOUT = 4;
MM_IOMAGIC_TEMPO_MXDOUT = 5;
MM_IOMAGIC_TEMPO_AUXOUT = 6;
{ MM_MATSUSHITA product IDs }
MM_MATSUSHITA_WAVEIN = 1;
MM_MATSUSHITA_WAVEOUT = 2;
MM_MATSUSHITA_FMSYNTH_STEREO = 3;
MM_MATSUSHITA_MIXER = 4;
MM_MATSUSHITA_AUX = 5;
{ MM_NEWMEDIA product IDs }
{ WSS Compatible sound card. }
MM_NEWMEDIA_WAVJAMMER = 1;
{ MM_LYRRUS product IDs }
{ Bridge is a MIDI driver that allows the the Lyrrus G-VOX hardware to
communicate with Windows base transcription and sequencer applications.
The driver also provides a mechanism for the user to configure the system
to their personal playing style. }
MM_LYRRUS_BRIDGE_GUITAR = 1;
{ MM_OPTI product IDs }
MM_OPTI_M16_FMSYNTH_STEREO = $0001;
MM_OPTI_M16_MIDIIN = $0002;
MM_OPTI_M16_MIDIOUT = $0003;
MM_OPTI_M16_WAVEIN = $0004;
MM_OPTI_M16_WAVEOUT = $0005;
MM_OPTI_M16_MIXER = $0006;
MM_OPTI_M16_AUX = $0007;
MM_OPTI_P16_FMSYNTH_STEREO = $0010;
MM_OPTI_P16_MIDIIN = $0011;
MM_OPTI_P16_MIDIOUT = $0012;
MM_OPTI_P16_WAVEIN = $0013;
MM_OPTI_P16_WAVEOUT = $0014;
MM_OPTI_P16_MIXER = $0015;
MM_OPTI_P16_AUX = $0016;
MM_OPTI_M32_WAVEIN = $0020;
MM_OPTI_M32_WAVEOUT = $0021;
MM_OPTI_M32_MIDIIN = $0022;
MM_OPTI_M32_MIDIOUT = $0023;
MM_OPTI_M32_SYNTH_STEREO = $0024;
MM_OPTI_M32_MIXER = $0025;
MM_OPTI_M32_AUX = $0026;
{ Product IDs for MM_ADDX - ADDX }
{ MM_ADDX_PCTV_DIGITALMIX }
MM_ADDX_PCTV_DIGITALMIX = 1;
{ MM_ADDX_PCTV_WAVEIN }
MM_ADDX_PCTV_WAVEIN = 2;
{ MM_ADDX_PCTV_WAVEOUT }
MM_ADDX_PCTV_WAVEOUT = 3;
{ MM_ADDX_PCTV_MIXER }
MM_ADDX_PCTV_MIXER = 4;
{ MM_ADDX_PCTV_AUX_CD }
MM_ADDX_PCTV_AUX_CD = 5;
{ MM_ADDX_PCTV_AUX_LINE }
MM_ADDX_PCTV_AUX_LINE = 6;
{ Product IDs for MM_AHEAD - Ahead, Inc. }
MM_AHEAD_MULTISOUND = 1;
MM_AHEAD_SOUNDBLASTER = 2;
MM_AHEAD_PROAUDIO = 3;
MM_AHEAD_GENERIC = 4;
{ Product IDs for MM_AMD - AMD }
MM_AMD_INTERWAVE_WAVEIN = 1;
MM_AMD_INTERWAVE_WAVEOUT = 2;
MM_AMD_INTERWAVE_SYNTH = 3;
MM_AMD_INTERWAVE_MIXER1 = 4;
MM_AMD_INTERWAVE_MIXER2 = 5;
MM_AMD_INTERWAVE_JOYSTICK = 6;
MM_AMD_INTERWAVE_EX_CD = 7;
MM_AMD_INTERWAVE_MIDIIN = 8;
MM_AMD_INTERWAVE_MIDIOUT = 9;
MM_AMD_INTERWAVE_AUX1 = 10;
MM_AMD_INTERWAVE_AUX2 = 11;
MM_AMD_INTERWAVE_AUX_MIC = 12;
MM_AMD_INTERWAVE_AUX_CD = 13;
MM_AMD_INTERWAVE_MONO_IN = 14;
MM_AMD_INTERWAVE_MONO_OUT = 15;
MM_AMD_INTERWAVE_EX_TELEPHONY = 16;
MM_AMD_INTERWAVE_WAVEOUT_BASE = 17;
MM_AMD_INTERWAVE_WAVEOUT_TREBLE = 18;
MM_AMD_INTERWAVE_STEREO_ENHANCED = 19;
{ Product IDs for MM_AST - AST Research Inc. }
MM_AST_MODEMWAVE_WAVEIN = 13;
MM_AST_MODEMWAVE_WAVEOUT = 14;
{ Product IDs for MM_BROOKTREE - Brooktree Corporation }
{ Brooktree PCM Wave Audio In }
MM_BTV_WAVEIN = 1;
{ Brooktree PCM Wave Audio Out }
MM_BTV_WAVEOUT = 2;
{ Brooktree MIDI In }
MM_BTV_MIDIIN = 3;
{ Brooktree MIDI out }
MM_BTV_MIDIOUT = 4;
{ Brooktree MIDI FM synth }
MM_BTV_MIDISYNTH = 5;
{ Brooktree Line Input }
MM_BTV_AUX_LINE = 6;
{ Brooktree Microphone Input }
MM_BTV_AUX_MIC = 7;
{ Brooktree CD Input }
MM_BTV_AUX_CD = 8;
{ Brooktree PCM Wave in with subcode information }
MM_BTV_DIGITALIN = 9;
{ Brooktree PCM Wave out with subcode information }
MM_BTV_DIGITALOUT = 10;
{ Brooktree WaveStream }
MM_BTV_MIDIWAVESTREAM = 11;
{ Brooktree WSS Mixer driver }
MM_BTV_MIXER = 12;
{ Product IDs for MM_CANAM - CANAM Computers }
MM_CANAM_CBXWAVEOUT = 1;
MM_CANAM_CBXWAVEIN = 2;
{ Product IDs for MM_CASIO - Casio Computer Co., LTD }
{ wp150 }
MM_CASIO_WP150_MIDIOUT = 1;
MM_CASIO_WP150_MIDIIN = 2;
{ Product IDs for MM_COMPAQ - Compaq Computer Corp. }
MM_COMPAQ_BB_WAVEIN = 1;
MM_COMPAQ_BB_WAVEOUT = 2;
MM_COMPAQ_BB_WAVEAUX = 3;
{ Product IDs for MM_COREDYNAMICS - Core Dynamics }
{ DynaMax Hi-Rez }
MM_COREDYNAMICS_DYNAMIXHR = 1;
{ DynaSonix }
MM_COREDYNAMICS_DYNASONIX_SYNTH = 2;
MM_COREDYNAMICS_DYNASONIX_MIDI_IN = 3;
MM_COREDYNAMICS_DYNASONIX_MIDI_OUT = 4;
MM_COREDYNAMICS_DYNASONIX_WAVE_IN = 5;
MM_COREDYNAMICS_DYNASONIX_WAVE_OUT = 6;
MM_COREDYNAMICS_DYNASONIX_AUDIO_IN = 7;
MM_COREDYNAMICS_DYNASONIX_AUDIO_OUT = 8;
{ DynaGrfx }
MM_COREDYNAMICS_DYNAGRAFX_VGA = 9;
MM_COREDYNAMICS_DYNAGRAFX_WAVE_IN = 10;
MM_COREDYNAMICS_DYNAGRAFX_WAVE_OUT = 11;
{ Product IDs for MM_CRYSTAL - Crystal Semiconductor Corporation }
MM_CRYSTAL_CS4232_WAVEIN = 1;
MM_CRYSTAL_CS4232_WAVEOUT = 2;
MM_CRYSTAL_CS4232_WAVEMIXER = 3;
MM_CRYSTAL_CS4232_WAVEAUX_AUX1 = 4;
MM_CRYSTAL_CS4232_WAVEAUX_AUX2 = 5;
MM_CRYSTAL_CS4232_WAVEAUX_LINE = 6;
MM_CRYSTAL_CS4232_WAVEAUX_MONO = 7;
MM_CRYSTAL_CS4232_WAVEAUX_MASTER = 8;
MM_CRYSTAL_CS4232_MIDIIN = 9;
MM_CRYSTAL_CS4232_MIDIOUT = 10;
MM_CRYSTAL_CS4232_INPUTGAIN_AUX1 = 13;
MM_CRYSTAL_CS4232_INPUTGAIN_LOOP = 14;
{ Product IDs for MM_DDD - Danka Data Devices }
MM_DDD_MIDILINK_MIDIIN = 1;
MM_DDD_MIDILINK_MIDIOUT = 2;
{ Product IDs for MM_DIACOUSTICS - DiAcoustics, Inc. }
{ Drum Action }
MM_DIACOUSTICS_DRUM_ACTION = 1;
{ Product IDs for MM_DIAMONDMM - Diamond Multimedia }
{ Freedom Audio }
MM_DIMD_PLATFORM = 0;
MM_DIMD_DIRSOUND = 1;
MM_DIMD_VIRTMPU = 2;
MM_DIMD_VIRTSB = 3;
MM_DIMD_VIRTJOY = 4;
MM_DIMD_WAVEIN = 5;
MM_DIMD_WAVEOUT = 6;
MM_DIMD_MIDIIN = 7;
MM_DIMD_MIDIOUT = 8;
MM_DIMD_AUX_LINE = 9;
MM_DIMD_MIXER = 10;
{ Product IDs for MM_DIGITAL_AUDIO_LABS - Digital Audio Labs, Inc. }
MM_DIGITAL_AUDIO_LABS_V8 = $10;
MM_DIGITAL_AUDIO_LABS_CPRO = $11;
{ Product IDs for MM_DIGITAL - Digital Equipment Corporation }
{ Digital Audio Video Compression Board }
MM_DIGITAL_AV320_WAVEIN = 1;
{ Digital Audio Video Compression Board }
MM_DIGITAL_AV320_WAVEOUT = 2;
{ Product IDs for MM_ECS - Electronic Courseware Systems, Inc. }
MM_ECS_AADF_MIDI_IN = 10;
MM_ECS_AADF_MIDI_OUT = 11;
MM_ECS_AADF_WAVE2MIDI_IN = 12;
{ Product IDs for MM_ENSONIQ - ENSONIQ Corporation }
{ ENSONIQ Soundscape }
MM_ENSONIQ_SOUNDSCAPE = $10;
MM_SOUNDSCAPE_WAVEOUT = MM_ENSONIQ_SOUNDSCAPE+1;
MM_SOUNDSCAPE_WAVEOUT_AUX = MM_ENSONIQ_SOUNDSCAPE+2;
MM_SOUNDSCAPE_WAVEIN = MM_ENSONIQ_SOUNDSCAPE+3;
MM_SOUNDSCAPE_MIDIOUT = MM_ENSONIQ_SOUNDSCAPE+4;
MM_SOUNDSCAPE_MIDIIN = MM_ENSONIQ_SOUNDSCAPE+5;
MM_SOUNDSCAPE_SYNTH = MM_ENSONIQ_SOUNDSCAPE+6;
MM_SOUNDSCAPE_MIXER = MM_ENSONIQ_SOUNDSCAPE+7;
MM_SOUNDSCAPE_AUX = MM_ENSONIQ_SOUNDSCAPE+8;
{ Product IDs for MM_FRONTIER - Frontier Design Group LLC }
{ WaveCenter }
MM_FRONTIER_WAVECENTER_MIDIIN = 1;
MM_FRONTIER_WAVECENTER_MIDIOUT = 2;
MM_FRONTIER_WAVECENTER_WAVEIN = 3;
MM_FRONTIER_WAVECENTER_WAVEOUT = 4;
{ Product IDs for MM_GADGETLABS - Gadget Labs LLC }
MM_GADGETLABS_WAVE44_WAVEIN = 1;
MM_GADGETLABS_WAVE44_WAVEOUT = 2;
MM_GADGETLABS_WAVE42_WAVEIN = 3;
MM_GADGETLABS_WAVE42_WAVEOUT = 4;
MM_GADGETLABS_WAVE4_MIDIIN = 5;
MM_GADGETLABS_WAVE4_MIDIOUT = 6;
{ Product IDs for MM_KAY_ELEMETRICS - Kay Elemetrics, Inc. }
MM_KAY_ELEMETRICS_CSL = $4300;
MM_KAY_ELEMETRICS_CSL_DAT = $4308;
MM_KAY_ELEMETRICS_CSL_4CHANNEL = $4309;
{ Product IDs for MM_LERNOUT_AND_HAUSPIE - Lernout & Hauspie }
MM_LERNOUT_ANDHAUSPIE_LHCODECACM = 1;
{ Product IDs for MM_MPTUS - M.P. Technologies, Inc. }
{ Sound Pallette }
MM_MPTUS_SPWAVEOUT = 1;
{ Product IDs for MM_MOTU - Mark of the Unicorn }
MM_MOTU_MTP_MIDIOUT_ALL = 100;
MM_MOTU_MTP_MIDIIN_1 = 101;
MM_MOTU_MTP_MIDIOUT_1 = 101;
MM_MOTU_MTP_MIDIIN_2 = 102;
MM_MOTU_MTP_MIDIOUT_2 = 102;
MM_MOTU_MTP_MIDIIN_3 = 103;
MM_MOTU_MTP_MIDIOUT_3 = 103;
MM_MOTU_MTP_MIDIIN_4 = 104;
MM_MOTU_MTP_MIDIOUT_4 = 104;
MM_MOTU_MTP_MIDIIN_5 = 105;
MM_MOTU_MTP_MIDIOUT_5 = 105;
MM_MOTU_MTP_MIDIIN_6 = 106;
MM_MOTU_MTP_MIDIOUT_6 = 106;
MM_MOTU_MTP_MIDIIN_7 = 107;
MM_MOTU_MTP_MIDIOUT_7 = 107;
MM_MOTU_MTP_MIDIIN_8 = 108;
MM_MOTU_MTP_MIDIOUT_8 = 108;
MM_MOTU_MTPII_MIDIOUT_ALL = 200;
MM_MOTU_MTPII_MIDIIN_SYNC = 200;
MM_MOTU_MTPII_MIDIIN_1 = 201;
MM_MOTU_MTPII_MIDIOUT_1 = 201;
MM_MOTU_MTPII_MIDIIN_2 = 202;
MM_MOTU_MTPII_MIDIOUT_2 = 202;
MM_MOTU_MTPII_MIDIIN_3 = 203;
MM_MOTU_MTPII_MIDIOUT_3 = 203;
MM_MOTU_MTPII_MIDIIN_4 = 204;
MM_MOTU_MTPII_MIDIOUT_4 = 204;
MM_MOTU_MTPII_MIDIIN_5 = 205;
MM_MOTU_MTPII_MIDIOUT_5 = 205;
MM_MOTU_MTPII_MIDIIN_6 = 206;
MM_MOTU_MTPII_MIDIOUT_6 = 206;
MM_MOTU_MTPII_MIDIIN_7 = 207;
MM_MOTU_MTPII_MIDIOUT_7 = 207;
MM_MOTU_MTPII_MIDIIN_8 = 208;
MM_MOTU_MTPII_MIDIOUT_8 = 208;
MM_MOTU_MTPII_NET_MIDIIN_1 = 209;
MM_MOTU_MTPII_NET_MIDIOUT_1 = 209;
MM_MOTU_MTPII_NET_MIDIIN_2 = 210;
MM_MOTU_MTPII_NET_MIDIOUT_2 = 210;
MM_MOTU_MTPII_NET_MIDIIN_3 = 211;
MM_MOTU_MTPII_NET_MIDIOUT_3 = 211;
MM_MOTU_MTPII_NET_MIDIIN_4 = 212;
MM_MOTU_MTPII_NET_MIDIOUT_4 = 212;
MM_MOTU_MTPII_NET_MIDIIN_5 = 213;
MM_MOTU_MTPII_NET_MIDIOUT_5 = 213;
MM_MOTU_MTPII_NET_MIDIIN_6 = 214;
MM_MOTU_MTPII_NET_MIDIOUT_6 = 214;
MM_MOTU_MTPII_NET_MIDIIN_7 = 215;
MM_MOTU_MTPII_NET_MIDIOUT_7 = 215;
MM_MOTU_MTPII_NET_MIDIIN_8 = 216;
MM_MOTU_MTPII_NET_MIDIOUT_8 = 216;
MM_MOTU_MXP_MIDIIN_MIDIOUT_ALL = 300;
MM_MOTU_MXP_MIDIIN_SYNC = 300;
MM_MOTU_MXP_MIDIIN_MIDIIN_1 = 301;
MM_MOTU_MXP_MIDIIN_MIDIOUT_1 = 301;
MM_MOTU_MXP_MIDIIN_MIDIIN_2 = 302;
MM_MOTU_MXP_MIDIIN_MIDIOUT_2 = 302;
MM_MOTU_MXP_MIDIIN_MIDIIN_3 = 303;
MM_MOTU_MXP_MIDIIN_MIDIOUT_3 = 303;
MM_MOTU_MXP_MIDIIN_MIDIIN_4 = 304;
MM_MOTU_MXP_MIDIIN_MIDIOUT_4 = 304;
MM_MOTU_MXP_MIDIIN_MIDIIN_5 = 305;
MM_MOTU_MXP_MIDIIN_MIDIOUT_5 = 305;
MM_MOTU_MXP_MIDIIN_MIDIIN_6 = 306;
MM_MOTU_MXP_MIDIIN_MIDIOUT_6 = 306;
MM_MOTU_MXPMPU_MIDIOUT_ALL = 400;
MM_MOTU_MXPMPU_MIDIIN_SYNC = 400;
MM_MOTU_MXPMPU_MIDIIN_1 = 401;
MM_MOTU_MXPMPU_MIDIOUT_1 = 401;
MM_MOTU_MXPMPU_MIDIIN_2 = 402;
MM_MOTU_MXPMPU_MIDIOUT_2 = 402;
MM_MOTU_MXPMPU_MIDIIN_3 = 403;
MM_MOTU_MXPMPU_MIDIOUT_3 = 403;
MM_MOTU_MXPMPU_MIDIIN_4 = 404;
MM_MOTU_MXPMPU_MIDIOUT_4 = 404;
MM_MOTU_MXPMPU_MIDIIN_5 = 405;
MM_MOTU_MXPMPU_MIDIOUT_5 = 405;
MM_MOTU_MXPMPU_MIDIIN_6 = 406;
MM_MOTU_MXPMPU_MIDIOUT_6 = 406;
MM_MOTU_MXN_MIDIOUT_ALL = 500;
MM_MOTU_MXN_MIDIIN_SYNC = 500;
MM_MOTU_MXN_MIDIIN_1 = 501;
MM_MOTU_MXN_MIDIOUT_1 = 501;
MM_MOTU_MXN_MIDIIN_2 = 502;
MM_MOTU_MXN_MIDIOUT_2 = 502;
MM_MOTU_MXN_MIDIIN_3 = 503;
MM_MOTU_MXN_MIDIOUT_3 = 503;
MM_MOTU_MXN_MIDIIN_4 = 504;
MM_MOTU_MXN_MIDIOUT_4 = 504;
MM_MOTU_FLYER_MIDI_IN_SYNC = 600;
MM_MOTU_FLYER_MIDI_IN_A = 601;
MM_MOTU_FLYER_MIDI_OUT_A = 601;
MM_MOTU_FLYER_MIDI_IN_B = 602;
MM_MOTU_FLYER_MIDI_OUT_B = 602;
MM_MOTU_PKX_MIDI_IN_SYNC = 700;
MM_MOTU_PKX_MIDI_IN_A = 701;
MM_MOTU_PKX_MIDI_OUT_A = 701;
MM_MOTU_PKX_MIDI_IN_B = 702;
MM_MOTU_PKX_MIDI_OUT_B = 702;
MM_MOTU_DTX_MIDI_IN_SYNC = 800;
MM_MOTU_DTX_MIDI_IN_A = 801;
MM_MOTU_DTX_MIDI_OUT_A = 801;
MM_MOTU_DTX_MIDI_IN_B = 802;
MM_MOTU_DTX_MIDI_OUT_B = 802;
MM_MOTU_MTPAV_MIDIOUT_ALL = 900;
MM_MOTU_MTPAV_MIDIIN_SYNC = 900;
MM_MOTU_MTPAV_MIDIIN_1 = 901;
MM_MOTU_MTPAV_MIDIOUT_1 = 901;
MM_MOTU_MTPAV_MIDIIN_2 = 902;
MM_MOTU_MTPAV_MIDIOUT_2 = 902;
MM_MOTU_MTPAV_MIDIIN_3 = 903;
MM_MOTU_MTPAV_MIDIOUT_3 = 903;
MM_MOTU_MTPAV_MIDIIN_4 = 904;
MM_MOTU_MTPAV_MIDIOUT_4 = 904;
MM_MOTU_MTPAV_MIDIIN_5 = 905;
MM_MOTU_MTPAV_MIDIOUT_5 = 905;
MM_MOTU_MTPAV_MIDIIN_6 = 906;
MM_MOTU_MTPAV_MIDIOUT_6 = 906;
MM_MOTU_MTPAV_MIDIIN_7 = 907;
MM_MOTU_MTPAV_MIDIOUT_7 = 907;
MM_MOTU_MTPAV_MIDIIN_8 = 908;
MM_MOTU_MTPAV_MIDIOUT_8 = 908;
MM_MOTU_MTPAV_NET_MIDIIN_1 = 909;
MM_MOTU_MTPAV_NET_MIDIOUT_1 = 909;
MM_MOTU_MTPAV_NET_MIDIIN_2 = 910;
MM_MOTU_MTPAV_NET_MIDIOUT_2 = 910;
MM_MOTU_MTPAV_NET_MIDIIN_3 = 911;
MM_MOTU_MTPAV_NET_MIDIOUT_3 = 911;
MM_MOTU_MTPAV_NET_MIDIIN_4 = 912;
MM_MOTU_MTPAV_NET_MIDIOUT_4 = 912;
MM_MOTU_MTPAV_NET_MIDIIN_5 = 913;
MM_MOTU_MTPAV_NET_MIDIOUT_5 = 913;
MM_MOTU_MTPAV_NET_MIDIIN_6 = 914;
MM_MOTU_MTPAV_NET_MIDIOUT_6 = 914;
MM_MOTU_MTPAV_NET_MIDIIN_7 = 915;
MM_MOTU_MTPAV_NET_MIDIOUT_7 = 915;
MM_MOTU_MTPAV_NET_MIDIIN_8 = 916;
MM_MOTU_MTPAV_NET_MIDIOUT_8 = 916;
MM_MOTU_MTPAV_MIDIIN_ADAT = 917;
MM_MOTU_MTPAV_MIDIOUT_ADAT = 917;
{ Product IDs for MM_MIRO - miro Computer Products AG }
{ miroMOVIE pro }
MM_MIRO_MOVIEPRO = 1;
{ miroVIDEO D1 }
MM_MIRO_VIDEOD1 = 2;
{ miroVIDEO DC1 tv }
MM_MIRO_VIDEODC1TV = 3;
{ miroVIDEO 10/20 TD }
MM_MIRO_VIDEOTD = 4;
MM_MIRO_DC30_WAVEOUT = 5;
MM_MIRO_DC30_WAVEIN = 6;
MM_MIRO_DC30_MIX = 7;
{ Product IDs for MM_NEC - NEC }
MM_NEC_73_86_SYNTH = 5;
MM_NEC_73_86_WAVEOUT = 6;
MM_NEC_73_86_WAVEIN = 7;
MM_NEC_26_SYNTH = 9;
MM_NEC_MPU401_MIDIOUT = 10;
MM_NEC_MPU401_MIDIIN = 11;
MM_NEC_JOYSTICK = 12;
{ Product IDs for MM_NORRIS - Norris Communications, Inc. }
MM_NORRIS_VOICELINK = 1;
{ Product IDs for MM_NORTHERN_TELECOM - Northern Telecom Limited }
{ MPX Audio Card Wave Input Device }
MM_NORTEL_MPXAC_WAVEIN = 1;
{ MPX Audio Card Wave Output Device }
MM_NORTEL_MPXAC_WAVEOUT = 2;
{ Product IDs for MM_NVIDIA - NVidia Corporation }
MM_NVIDIA_WAVEOUT = 1;
MM_NVIDIA_WAVEIN = 2;
MM_NVIDIA_MIDIOUT = 3;
MM_NVIDIA_MIDIIN = 4;
MM_NVIDIA_GAMEPORT = 5;
MM_NVIDIA_MIXER = 6;
MM_NVIDIA_AUX = 7;
{ Product IDs for MM_OKSORI - OKSORI Co., Ltd. }
{ Oksori Base }
MM_OKSORI_BASE = 0;
MM_OKSORI_OSR8_WAVEOUT = MM_OKSORI_BASE+1; { Oksori 8bit Wave out }
MM_OKSORI_OSR8_WAVEIN = MM_OKSORI_BASE+2; { Oksori 8bit Wave in }
MM_OKSORI_OSR16_WAVEOUT = MM_OKSORI_BASE+3; { Oksori 16 bit Wave out }
MM_OKSORI_OSR16_WAVEIN = MM_OKSORI_BASE+4; { Oksori 16 bit Wave in }
MM_OKSORI_FM_OPL4 = MM_OKSORI_BASE+5; { Oksori FM Synth Yamaha OPL4 }
MM_OKSORI_MIX_MASTER = MM_OKSORI_BASE+6; { Oksori DSP Mixer - Master Volume }
MM_OKSORI_MIX_WAVE = MM_OKSORI_BASE+7; { Oksori DSP Mixer - Wave Volume }
MM_OKSORI_MIX_FM = MM_OKSORI_BASE+8; { Oksori DSP Mixer - FM Volume }
MM_OKSORI_MIX_LINE = MM_OKSORI_BASE+9; { Oksori DSP Mixer - Line Volume }
MM_OKSORI_MIX_CD = MM_OKSORI_BASE+10; { Oksori DSP Mixer - CD Volume }
MM_OKSORI_MIX_MIC = MM_OKSORI_BASE+11; { Oksori DSP Mixer - MIC Volume }
MM_OKSORI_MIX_ECHO = MM_OKSORI_BASE+12; { Oksori DSP Mixer - Echo Volume }
MM_OKSORI_MIX_AUX1 = MM_OKSORI_BASE+13; { Oksori AD1848 - AUX1 Volume }
MM_OKSORI_MIX_LINE1 = MM_OKSORI_BASE+14; { Oksori AD1848 - LINE1 Volume }
MM_OKSORI_EXT_MIC1 = MM_OKSORI_BASE+15; { Oksori External - One Mic Connect }
MM_OKSORI_EXT_MIC2 = MM_OKSORI_BASE+16; { Oksori External - Two Mic Connect }
MM_OKSORI_MIDIOUT = MM_OKSORI_BASE+17; { Oksori MIDI Out Device }
MM_OKSORI_MIDIIN = MM_OKSORI_BASE+18; { Oksori MIDI In Device }
MM_OKSORI_MPEG_CDVISION = MM_OKSORI_BASE+19; { Oksori CD-Vision MPEG Decoder }
{ Product IDs for MM_OSITECH - Ositech Communications Inc. }
{ Trumpcard }
MM_OSITECH_TRUMPCARD = 1;
{ Product IDs for MM_OSPREY - Osprey Technologies, Inc. }
MM_OSPREY_1000WAVEIN = 1;
MM_OSPREY_1000WAVEOUT = 2;
{ Product IDs for MM_QUARTERDECK - Quarterdeck Corporation }
{ Quarterdeck L&H Codec Wave In }
MM_QUARTERDECK_LHWAVEIN = 0;
{ Quarterdeck L&H Codec Wave Out }
MM_QUARTERDECK_LHWAVEOUT = 1;
{ Product IDs for MM_RHETOREX - Rhetorex Inc }
MM_RHETOREX_WAVEIN = 1;
MM_RHETOREX_WAVEOUT = 2;
{ Product IDs for MM_ROCKWELL - Rockwell International }
MM_VOICEMIXER = 1;
ROCKWELL_WA1_WAVEIN = 100;
ROCKWELL_WA1_WAVEOUT = 101;
ROCKWELL_WA1_SYNTH = 102;
ROCKWELL_WA1_MIXER = 103;
ROCKWELL_WA1_MPU401_IN = 104;
ROCKWELL_WA1_MPU401_OUT = 105;
ROCKWELL_WA2_WAVEIN = 200;
ROCKWELL_WA2_WAVEOUT = 201;
ROCKWELL_WA2_SYNTH = 202;
ROCKWELL_WA2_MIXER = 203;
ROCKWELL_WA2_MPU401_IN = 204;
ROCKWELL_WA2_MPU401_OUT = 205;
{ Product IDs for MM_S3 - S3 }
MM_S3_WAVEOUT = $1;
MM_S3_WAVEIN = $2;
MM_S3_MIDIOUT = $3;
MM_S3_MIDIIN = $4;
MM_S3_FMSYNTH = $5;
MM_S3_MIXER = $6;
MM_S3_AUX = $7;
{ Product IDs for MM_SEERSYS - Seer Systems, Inc. }
MM_SEERSYS_SEERSYNTH = 1;
MM_SEERSYS_SEERWAVE = 2;
MM_SEERSYS_SEERMIX = 3;
{ Product IDs for MM_SOFTSOUND - Softsound, Ltd. }
MM_SOFTSOUND_CODEC = 1;
{ Product IDs for MM_SOUNDESIGNS - SounDesignS M.C.S. Ltd. }
MM_SOUNDESIGNS_WAVEIN = 1;
MM_SOUNDESIGNS_WAVEOUT = 2;
{ Product IDs for MM_SPECTRUM_SIGNAL_PROCESSING - Spectrum Signal Processing, Inc. }
{ Sound Festa Wave In Device }
MM_SSP_SNDFESWAVEIN = 1;
{ Sound Festa Wave Out Device }
MM_SSP_SNDFESWAVEOUT = 2;
{ Sound Festa MIDI In Device }
MM_SSP_SNDFESMIDIIN = 3;
{ Sound Festa MIDI Out Device }
MM_SSP_SNDFESMIDIOUT = 4;
{ Sound Festa MIDI Synth Device }
MM_SSP_SNDFESSYNTH = 5;
{ Sound Festa Mixer Device }
MM_SSP_SNDFESMIX = 6;
{ Sound Festa Auxilliary Device }
MM_SSP_SNDFESAUX = 7;
{ Product IDs for MM_TDK - TDK Corporation }
MM_TDK_MW_MIDI_SYNTH = 1;
MM_TDK_MW_MIDI_IN = 2;
MM_TDK_MW_MIDI_OUT = 3;
MM_TDK_MW_WAVE_IN = 4;
MM_TDK_MW_WAVE_OUT = 5;
MM_TDK_MW_AUX = 6;
MM_TDK_MW_MIXER = 10;
MM_TDK_MW_AUX_MASTER = 100;
MM_TDK_MW_AUX_BASS = 101;
MM_TDK_MW_AUX_TREBLE = 102;
MM_TDK_MW_AUX_MIDI_VOL = 103;
MM_TDK_MW_AUX_WAVE_VOL = 104;
MM_TDK_MW_AUX_WAVE_RVB = 105;
MM_TDK_MW_AUX_WAVE_CHR = 106;
MM_TDK_MW_AUX_VOL = 107;
MM_TDK_MW_AUX_RVB = 108;
MM_TDK_MW_AUX_CHR = 109;
{ Product IDs for MM_TURTLE_BEACH - Turtle Beach, Inc. }
MM_TBS_TROPEZ_WAVEIN = 37;
MM_TBS_TROPEZ_WAVEOUT = 38;
MM_TBS_TROPEZ_AUX1 = 39;
MM_TBS_TROPEZ_AUX2 = 40;
MM_TBS_TROPEZ_LINE = 41;
{ Product IDs for MM_VIENNASYS - Vienna Systems }
MM_VIENNASYS_TSP_WAVE_DRIVER = 1;
{ Product IDs for MM_VIONA - Viona Development GmbH }
{ Q-Motion PCI II/Bravado 2000 }
MM_VIONA_QVINPCI_MIXER = 1;
MM_VIONA_QVINPCI_WAVEIN = 2;
MM_VIONAQVINPCI_WAVEOUT = 3;
{ Buster }
MM_VIONA_BUSTER_MIXER = 4;
{ Cinemaster }
MM_VIONA_CINEMASTER_MIXER = 5;
{ Concerto }
MM_VIONA_CONCERTO_MIXER = 6;
{ Product IDs for MM_WILDCAT - Wildcat Canyon Software }
{ Autoscore }
MM_WILDCAT_AUTOSCOREMIDIIN = 1;
{ Product IDs for MM_WILLOWPOND - Willow Pond Corporation }
MM_WILLOWPOND_FMSYNTH_STEREO = 20;
MM_WILLOWPOND_SNDPORT_WAVEIN = 100;
MM_WILLOWPOND_SNDPORT_WAVEOUT = 101;
MM_WILLOWPOND_SNDPORT_MIXER = 102;
MM_WILLOWPOND_SNDPORT_AUX = 103;
MM_WILLOWPOND_PH_WAVEIN = 104;
MM_WILLOWPOND_PH_WAVEOUT = 105;
MM_WILLOWPOND_PH_MIXER = 106;
MM_WILLOWPOND_PH_AUX = 107;
{ Product IDs for MM_WORKBIT - Workbit Corporation }
{ Harmony Mixer }
MM_WORKBIT_MIXER = 1;
{ Harmony Mixer }
MM_WORKBIT_WAVEOUT = 2;
{ Harmony Mixer }
MM_WORKBIT_WAVEIN = 3;
{ Harmony Mixer }
MM_WORKBIT_MIDIIN = 4;
{ Harmony Mixer }
MM_WORKBIT_MIDIOUT = 5;
{ Harmony Mixer }
MM_WORKBIT_FMSYNTH = 6;
{ Harmony Mixer }
MM_WORKBIT_AUX = 7;
MM_WORKBIT_JOYSTICK = 8;
{ Product IDs for MM_FRAUNHOFER_IIS - Fraunhofer }
MM_FHGIIS_MPEGLAYER3 = 10;
{$ENDIF NOMMIDS}
{*////////////////////////////////////////////////////////////////////////// */
/* INFO LIST CHUNKS (from the Multimedia Programmer's Reference
plus new ones)
*}
const
RIFFINFO_IARL = FOURCC(byte(AnsiChar('I')) or
(byte(AnsiChar('A')) shl 8) or
(byte(AnsiChar('R')) shl 16) or
(byte(AnsiChar('L')) shl 24)
); //*Archival location */
RIFFINFO_IART = FOURCC(byte(AnsiChar('I')) or
(byte(AnsiChar('A')) shl 8) or
(byte(AnsiChar('R')) shl 16) or
(byte(AnsiChar('T')) shl 24)
); //*Artist */
RIFFINFO_ICMS = FOURCC(byte(AnsiChar('I')) or
(byte(AnsiChar('C')) shl 8) or
(byte(AnsiChar('M')) shl 16) or
(byte(AnsiChar('S'))shl 24)
); //*Commissioned */
RIFFINFO_ICMT = FOURCC(byte(AnsiChar('I')) or
(byte(AnsiChar('C')) shl 8) or
(byte(AnsiChar('M')) shl 16) or
(byte(AnsiChar('T')) shl 24)
); //*Comments */
RIFFINFO_ICOP = FOURCC(byte(AnsiChar('I')) or
(byte(AnsiChar('C')) shl 8) or
(byte(AnsiChar('O')) shl 16) or
(byte(AnsiChar('P')) shl 24)
); //*Copyright */
RIFFINFO_ICRD = FOURCC(byte(AnsiChar('I')) or
(byte(AnsiChar('C')) shl 8) or
(byte(AnsiChar('R')) shl 16) or
(byte(AnsiChar('D')) shl 24)
); //*Creation date of subject */
RIFFINFO_ICRP = FOURCC(byte(AnsiChar('I')) or
(byte(AnsiChar('C')) shl 8) or
(byte(AnsiChar('R')) shl 16) or
(byte(AnsiChar('P')) shl 24)
); //*Cropped */
RIFFINFO_IDIM = FOURCC(byte(AnsiChar('I')) or
(byte(AnsiChar('D')) shl 8) or
(byte(AnsiChar('I')) shl 16) or
(byte(AnsiChar('M')) shl 24)
); //*Dimensions */
RIFFINFO_IDPI = FOURCC(byte(AnsiChar('I')) or
(byte(AnsiChar('D')) shl 8) or
(byte(AnsiChar('P')) shl 16) or
(byte(AnsiChar('I')) shl 24)
); //*Dots per inch */
RIFFINFO_IENG = FOURCC(byte(AnsiChar('I')) or
(byte(AnsiChar('E')) shl 8) or
(byte(AnsiChar('N')) shl 16) or
(byte(AnsiChar('G')) shl 24)
); //*Engineer */
RIFFINFO_IGNR = FOURCC(byte(AnsiChar('I')) or
(byte(AnsiChar('G')) shl 8) or
(byte(AnsiChar('N')) shl 16) or
(byte(AnsiChar('R')) shl 24)
); //*Genre */
RIFFINFO_IKEY = FOURCC(byte(AnsiChar('I')) or
(byte(AnsiChar('K')) shl 8) or
(byte(AnsiChar('E')) shl 16) or
(byte(AnsiChar('Y')) shl 24)
); //*Keywords */
RIFFINFO_ILGT = FOURCC(byte(AnsiChar('I')) or
(byte(AnsiChar('L')) shl 8) or
(byte(AnsiChar('G')) shl 16) or
(byte(AnsiChar('T')) shl 24)
); //*Lightness settings */
RIFFINFO_IMED = FOURCC(byte(AnsiChar('I')) or
(byte(AnsiChar('M')) shl 8) or
(byte(AnsiChar('E')) shl 16) or
(byte(AnsiChar('D')) shl 24)
); //*Medium */
RIFFINFO_INAM = FOURCC(byte(AnsiChar('I')) or
(byte(AnsiChar('N')) shl 8) or
(byte(AnsiChar('A')) shl 16) or
(byte(AnsiChar('M')) shl 24)
); //*Name of subject */
RIFFINFO_IPLT = FOURCC(byte(AnsiChar('I')) or
(byte(AnsiChar('P')) shl 8) or
(byte(AnsiChar('L')) shl 16) or
(byte(AnsiChar('T')) shl 24)
); //*Palette Settings. No. of colors requested. */
RIFFINFO_IPRD = FOURCC(byte(AnsiChar('I')) or
(byte(AnsiChar('P')) shl 8) or
(byte(AnsiChar('R')) shl 16) or
(byte(AnsiChar('D')) shl 24)
); //*Product */
RIFFINFO_ISBJ = FOURCC(byte(AnsiChar('I')) or
(byte(AnsiChar('S')) shl 8) or
(byte(AnsiChar('B')) shl 16) or
(byte(AnsiChar('J')) shl 24)
); //*Subject description */
RIFFINFO_ISFT = FOURCC(byte(AnsiChar('I')) or
(byte(AnsiChar('S')) shl 8) or
(byte(AnsiChar('F')) shl 16) or
(byte(AnsiChar('T')) shl 24)
); //*Software. Name of package used to create file. */
RIFFINFO_ISHP = FOURCC(byte(AnsiChar('I')) or
(byte(AnsiChar('S')) shl 8) or
(byte(AnsiChar('H')) shl 16) or
(byte(AnsiChar('P')) shl 24)
); //*Sharpness. */
RIFFINFO_ISRC = FOURCC(byte(AnsiChar('I')) or
(byte(AnsiChar('S')) shl 8) or
(byte(AnsiChar('R')) shl 16) or
(byte(AnsiChar('C')) shl 24)
); //*Source. */
RIFFINFO_ISRF = FOURCC(byte(AnsiChar('I')) or
(byte(AnsiChar('S')) shl 8) or
(byte(AnsiChar('R')) shl 16) or
(byte(AnsiChar('F')) shl 24)
); //*Source Form. ie slide, paper */
RIFFINFO_ITCH = FOURCC(byte(AnsiChar('I')) or
(byte(AnsiChar('T')) shl 8) or
(byte(AnsiChar('C')) shl 16) or
(byte(AnsiChar('H')) shl 24)
); //*Technician who digitized the subject. */
//* New INFO Chunks as of August 30, 1993: */
RIFFINFO_ISMP = FOURCC(byte(AnsiChar('I')) or
(byte(AnsiChar('S')) shl 8) or
(byte(AnsiChar('M')) shl 16) or
(byte(AnsiChar('P')) shl 24)
); //*SMPTE time code */
{* ISMP: SMPTE time code of digitization start point expressed as a NULL terminated
text string "HH:MM:SS:FF". If performing MCI capture in AVICAP, this
chunk will be automatically set based on the MCI start time.
*}
RIFFINFO_IDIT = FOURCC(byte(AnsiChar('I')) or
(byte(AnsiChar('D')) shl 8) or
(byte(AnsiChar('I')) shl 16) or
(byte(AnsiChar('T')) shl 24)
); //*Digitization Time */
{* IDIT: "Digitization Time" Specifies the time and date that the digitization commenced.
The digitization time is contained in an ASCII string which
contains exactly 26 characters and is in the format
"Wed Jan 02 02:03:55 1990\n\0".
The ctime(), asctime(), functions can be used to create strings
in this format. This chunk is automatically added to the capture
file based on the current system time at the moment capture is initiated.
*}
{*Template line for new additions
RIFFINFO_I = FOURCC(byte(AnsiChar('I')) or
(byte(AnsiChar('')) shl 8) or
(byte(AnsiChar('')) shl 16) or
(byte(AnsiChar('')) shl 24)
); // Comment
}
//*/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////*/
{$IFNDEF NONEWWAVE}
{ WAVE form wFormatTag IDs }
const
WAVE_FORMAT_UNKNOWN = $0000;{ Microsoft Corporation }
{ Microsoft Corporation }
WAVE_FORMAT_ADPCM = $0002;
{ Microsoft Corporation }
WAVE_FORMAT_IEEE_FLOAT = $0003;
{ IEEE754: range (+1, -1] }
{ 32-bit/64-bit format as defined by }
{ MSVC++ float/double type }
{ IBM Corporation }
WAVE_FORMAT_IBM_CVSD = $0005;
{ Microsoft Corporation }
WAVE_FORMAT_ALAW = $0006;
{ Microsoft Corporation }
WAVE_FORMAT_MULAW = $0007;
{ Microsoft Corporation }
WAVE_FORMAT_WMAVOICE9 = $000a;
{ OKI }
WAVE_FORMAT_OKI_ADPCM = $0010;
{ Intel Corporation }
WAVE_FORMAT_DVI_ADPCM = $0011;
{ Intel Corporation }
WAVE_FORMAT_IMA_ADPCM = WAVE_FORMAT_DVI_ADPCM;
{ Videologic }
WAVE_FORMAT_MEDIASPACE_ADPCM = $0012;
{ Sierra Semiconductor Corp }
WAVE_FORMAT_SIERRA_ADPCM = $0013;
{ Antex Electronics Corporation }
WAVE_FORMAT_G723_ADPCM = $0014;
{ DSP Solutions, Inc. }
WAVE_FORMAT_DIGISTD = $0015;
{ DSP Solutions, Inc. }
WAVE_FORMAT_DIGIFIX = $0016;
{ Dialogic Corporation }
WAVE_FORMAT_DIALOGIC_OKI_ADPCM = $0017;
{ Media Vision, Inc. }
WAVE_FORMAT_MEDIAVISION_ADPCM = $0018;
{ Yamaha Corporation of America }
WAVE_FORMAT_YAMAHA_ADPCM = $0020;
{ Speech Compression }
WAVE_FORMAT_SONARC = $0021;
{ DSP Group, Inc }
WAVE_FORMAT_DSPGROUP_TRUESPEECH = $0022;
{ Echo Speech Corporation }
WAVE_FORMAT_ECHOSC1 = $0023;
{ }
WAVE_FORMAT_AUDIOFILE_AF36 = $0024;
{ Audio Processing Technology }
WAVE_FORMAT_APTX = $0025;
{ }
WAVE_FORMAT_AUDIOFILE_AF10 = $0026;
{ Dolby Laboratories }
WAVE_FORMAT_DOLBY_AC2 = $0030;
{ Microsoft Corporation }
WAVE_FORMAT_GSM610 = $0031;
{ Microsoft Corporation }
WAVE_FORMAT_MSNAUDIO = $0032;
{ Antex Electronics Corporation }
WAVE_FORMAT_ANTEX_ADPCME = $0033;
{ Control Resources Limited }
WAVE_FORMAT_CONTROL_RES_VQLPC = $0034;
{ DSP Solutions, Inc. }
WAVE_FORMAT_DIGIREAL = $0035;
{ DSP Solutions, Inc. }
WAVE_FORMAT_DIGIADPCM = $0036;
{ Control Resources Limited }
WAVE_FORMAT_CONTROL_RES_CR10 = $0037;
{ Natural MicroSystems }
WAVE_FORMAT_NMS_VBXADPCM = $0038;
{ Crystal Semiconductor IMA ADPCM }
WAVE_FORMAT_CS_IMAADPCM = $0039;
{ Echo Speech Corporation }
WAVE_FORMAT_ECHOSC3 = $003A;
{ Rockwell International }
WAVE_FORMAT_ROCKWELL_ADPCM = $003B;
{ Rockwell International }
WAVE_FORMAT_ROCKWELL_DIGITALK = $003C;
{ Xebec Multimedia Solutions Limited }
WAVE_FORMAT_XEBEC = $003D;
{ Antex Electronics Corporation }
WAVE_FORMAT_G721_ADPCM = $0040;
{ Antex Electronics Corporation }
WAVE_FORMAT_G728_CELP = $0041;
{ Microsoft Corporation }
WAVE_FORMAT_MPEG = $0050;
{ ISO/MPEG Layer3 Format Tag }
WAVE_FORMAT_MPEGLAYER3 = $0055;
{ Cirrus Logic }
WAVE_FORMAT_CIRRUS = $0060;
{ ESS Technology }
WAVE_FORMAT_ESPCM = $0061;
{ Voxware Inc }
WAVE_FORMAT_VOXWARE = $0062;
{ Canopus, co., Ltd. }
WAVEFORMAT_CANOPUS_ATRAC = $0063;
{ APICOM }
WAVE_FORMAT_G726_ADPCM = $0064;
{ APICOM }
WAVE_FORMAT_G722_ADPCM = $0065;
{ Microsoft Corporation }
WAVE_FORMAT_DSAT = $0066;
{ Microsoft Corporation }
WAVE_FORMAT_DSAT_DISPLAY = $0067;
{ Softsound, Ltd. }
WAVE_FORMAT_SOFTSOUND = $0080;
{ Rhetorex Inc }
WAVE_FORMAT_RHETOREX_ADPCM = $0100;
{ Microsoft Corporation }
WAVE_FORMAT_MSAUDIO1 = $0160;
{ Microsoft Corporation }
WAVE_FORMAT_WMAUDIO2 = $0161;
{ Microsoft Corporation }
WAVE_FORMAT_WMAUDIO3 = $0162;
{ Microsoft Corporation }
WAVE_FORMAT_WMAUDIO_LOSSLESS = $0163;
{ Creative Labs, Inc }
WAVE_FORMAT_CREATIVE_ADPCM = $0200;
{ Creative Labs, Inc }
WAVE_FORMAT_CREATIVE_FASTSPEECH8 = $0202;
{ Creative Labs, Inc }
WAVE_FORMAT_CREATIVE_FASTSPEECH10 = $0203;
{ Quarterdeck Corporation }
WAVE_FORMAT_QUARTERDECK = $0220;
{ Fujitsu Corp. }
WAVE_FORMAT_FM_TOWNS_SND = $0300;
{ Brooktree Corporation }
WAVE_FORMAT_BTV_DIGITAL = $0400;
{ Ing C. Olivetti & C., S.p.A. }
WAVE_FORMAT_OLIGSM = $1000;
{ Ing C. Olivetti & C., S.p.A. }
WAVE_FORMAT_OLIADPCM = $1001;
{ Ing C. Olivetti & C., S.p.A. }
WAVE_FORMAT_OLICELP = $1002;
{ Ing C. Olivetti & C., S.p.A. }
WAVE_FORMAT_OLISBC = $1003;
{ Ing C. Olivetti & C., S.p.A. }
WAVE_FORMAT_OLIOPR = $1004;
{ Lernout & Hauspie }
WAVE_FORMAT_LH_CODEC = $1100;
{ Norris Communications, Inc. }
WAVE_FORMAT_NORRIS = $1400;
const
WAVE_FORMAT_EXTENSIBLE = $FFFE; { Microsoft }
{ }
{ the WAVE_FORMAT_DEVELOPMENT format tag can be used during the }
{ development phase of a new wave format. Before shipping, you MUST }
{ acquire an official format tag from Microsoft. }
{ }
const
WAVE_FORMAT_DEVELOPMENT = $FFFF;
{$ENDIF NONEWWAVE}
type
{ general waveform format structure (information common to all formats) }
waveformat_tag = record
wFormatTag:word; { format type }
nChannels:word; { number of channels (i.e. mono, stereo...) }
nSamplesPerSec:DWORD; { sample rate }
nAvgBytesPerSec:DWORD; { for buffer estimation }
nBlockAlign:word; { block size of data }
end;
WAVEFORMAT = waveformat_tag;
PWAVEFORMAT = ^WAVEFORMAT;
NPWAVEFORMAT = ^WAVEFORMAT;
LPWAVEFORMAT = ^WAVEFORMAT;
LPCWAVEFORMAT = ^WAVEFORMAT;
{ flags for wFormatTag field of WAVEFORMAT }
const
WAVE_FORMAT_PCM = 1;
{ specific waveform format structure for PCM data }
type
pcmwaveformat_tag = record
wf:WAVEFORMAT;
wBitsPerSample:word; // corresponds to MCI_WAVE_SET_.... structure
end;
PCMWAVEFORMAT = pcmwaveformat_tag;
PPCMWAVEFORMAT = ^PCMWAVEFORMAT;
NPPCMWAVEFORMAT = ^PCMWAVEFORMAT;
LPPCMWAVEFORMAT = ^PCMWAVEFORMAT;
{ general extended waveform format structure
Use this for all NON PCM formats (information common to all formats)
}
{*
* extended waveform format structure used for all non-PCM formats. this
* structure is common to all non-PCM formats.
*}
type
tWAVEFORMATEX = record
wFormatTag:word; //* format type */
nChannels:word; //* number of channels (i.e. mono, stereo...) */
nSamplesPerSec:DWORD; //* sample rate */
nAvgBytesPerSec:DWORD; //* for buffer estimation */
nBlockAlign:word; //* block size of data */
wBitsPerSample:word; //* Number of bits per sample of mono data */
cbSize:word; //* The count in bytes of the size of
// extra information (after cbSize) */
end;
WAVEFORMATEX = tWAVEFORMATEX;
PWAVEFORMATEX = ^WAVEFORMATEX;
NPWAVEFORMATEX = ^WAVEFORMATEX;
LPWAVEFORMATEX = ^tWAVEFORMATEX;
LPCWAVEFORMATEX = ^WAVEFORMATEX;
type
WAVEFORMATEXTENSIBLE = record
Format:WAVEFORMATEX;
Samples:record
case longint of
0: (wValidBitsPerSample:word);
1: (wSamplesPerBlock:word);
2: (wReserved:word);
end;
dwChannelMask:DWORD;
SubFormat:TGUID;
end;
PWAVEFORMATEXTENSIBLE = ^WAVEFORMATEXTENSIBLE;
{ Extended PCM waveform format structure based on WAVEFORMATEXTENSIBLE. }
{ Use this for multiple channel and hi-resolution PCM data }
type
WAVEFORMATPCMEX = WAVEFORMATEXTENSIBLE; { Format.cbSize = 22 }
PWAVEFORMATPCMEX = ^WAVEFORMATPCMEX;
NPWAVEFORMATPCMEX = ^WAVEFORMATPCMEX;
LPWAVEFORMATPCMEX = ^WAVEFORMATPCMEX;
{ Extended format structure using IEEE Float data and based }
{ on WAVEFORMATEXTENSIBLE. Use this for multiple channel }
{ and hi-resolution PCM data in IEEE floating point format. }
WAVEFORMATIEEEFLOATEX = WAVEFORMATEXTENSIBLE; { Format.cbSize = 22 }
PWAVEFORMATIEEEFLOATEX = ^WAVEFORMATIEEEFLOATEX;
NPWAVEFORMATIEEEFLOATEX = ^WAVEFORMATIEEEFLOATEX;
LPWAVEFORMATIEEEFLOATEX = ^WAVEFORMATIEEEFLOATEX;
{ Speaker Positions for dwChannelMask in WAVEFORMATEXTENSIBLE: }
const
SPEAKER_FRONT_LEFT = $1;
SPEAKER_FRONT_RIGHT = $2;
SPEAKER_FRONT_CENTER = $4;
SPEAKER_LOW_FREQUENCY = $8;
SPEAKER_BACK_LEFT = $10;
SPEAKER_BACK_RIGHT = $20;
SPEAKER_FRONT_LEFT_OF_CENTER = $40;
SPEAKER_FRONT_RIGHT_OF_CENTER = $80;
SPEAKER_BACK_CENTER = $100;
SPEAKER_SIDE_LEFT = $200;
SPEAKER_SIDE_RIGHT = $400;
SPEAKER_TOP_CENTER = $800;
SPEAKER_TOP_FRONT_LEFT = $1000;
SPEAKER_TOP_FRONT_CENTER = $2000;
SPEAKER_TOP_FRONT_RIGHT = $4000;
SPEAKER_TOP_BACK_LEFT = $8000;
SPEAKER_TOP_BACK_CENTER = $10000;
SPEAKER_TOP_BACK_RIGHT = $20000;
{ Bit mask locations reserved for future use }
SPEAKER_RESERVED = $7FFC0000;
{ Used to specify that any possible permutation of speaker configurations }
SPEAKER_ALL = $80000000;
{$IFNDEF NONEWWAVE}
{ Define data for MS ADPCM }
type
adpcmcoef_tag = record
iCoef1:SmallInt;
iCoef2:SmallInt;
end;
ADPCMCOEFSET = adpcmcoef_tag;
PADPCMCOEFSET = ^ADPCMCOEFSET;
NPADPCMCOEFSET = ^ADPCMCOEFSET;
LPADPCMCOEFSET = ^ADPCMCOEFSET;
type
adpcmwaveformat_tag = record
wfx:WAVEFORMATEX;
wSamplesPerBlock:word;
wNumCoef:word;
aCoef:array[0..0] of ADPCMCOEFSET;
end;
ADPCMWAVEFORMAT = adpcmwaveformat_tag;
PADPCMWAVEFORMAT = ^ADPCMWAVEFORMAT;
NPADPCMWAVEFORMAT = ^ADPCMWAVEFORMAT;
LPADPCMWAVEFORMAT = ^ADPCMWAVEFORMAT;
{ Intel's DVI ADPCM structure definitions }
{ }
{ for WAVE_FORMAT_DVI_ADPCM (0x0011) }
type
dvi_adpcmwaveformat_tag = record
wfx:WAVEFORMATEX;
wSamplesPerBlock:word;
end;
DVIADPCMWAVEFORMAT = dvi_adpcmwaveformat_tag;
PDVIADPCMWAVEFORMAT = ^DVIADPCMWAVEFORMAT;
NPDVIADPCMWAVEFORMAT = ^DVIADPCMWAVEFORMAT;
LPDVIADPCMWAVEFORMAT = ^DVIADPCMWAVEFORMAT;
{ }
{ IMA endorsed ADPCM structure definitions--note that this is exactly }
{ the same format as Intel's DVI ADPCM. }
{ }
{ for WAVE_FORMAT_IMA_ADPCM (0x0011) }
{ }
{ }
ima_adpcmwaveformat_tag = record
wfx:WAVEFORMATEX;
wSamplesPerBlock:word;
end;
IMAADPCMWAVEFORMAT = ima_adpcmwaveformat_tag;
PIMAADPCMWAVEFORMAT = ^IMAADPCMWAVEFORMAT;
NPIMAADPCMWAVEFORMAT = ^IMAADPCMWAVEFORMAT;
LPIMAADPCMWAVEFORMAT = ^IMAADPCMWAVEFORMAT;
{
//VideoLogic's Media Space ADPCM Structure definitions
// for WAVE_FORMAT_MEDIASPACE_ADPCM (0x0012)
//
//
}
mediaspace_adpcmwaveformat_tag = record
wfx:WAVEFORMATEX;
wRevision:word;
end;
MEDIASPACEADPCMWAVEFORMAT = mediaspace_adpcmwaveformat_tag;
PMEDIASPACEADPCMWAVEFORMAT = ^MEDIASPACEADPCMWAVEFORMAT;
NPMEDIASPACEADPCMWAVEFORMAT = ^MEDIASPACEADPCMWAVEFORMAT;
LPMEDIASPACEADPCMWAVEFORMAT = ^MEDIASPACEADPCMWAVEFORMAT;
{ Sierra Semiconductor }
{ }
{ for WAVE_FORMAT_SIERRA_ADPCM (0x0013) }
sierra_adpcmwaveformat_tag = record
wfx:WAVEFORMATEX;
wRevision:word;
end;
SIERRAADPCMWAVEFORMAT = sierra_adpcmwaveformat_tag;
PSIERRAADPCMWAVEFORMAT = ^SIERRAADPCMWAVEFORMAT;
NPSIERRAADPCMWAVEFORMAT = ^SIERRAADPCMWAVEFORMAT;
LPSIERRAADPCMWAVEFORMAT = ^SIERRAADPCMWAVEFORMAT;
{ Antex Electronics structure definitions }
{ }
{ for WAVE_FORMAT_G723_ADPCM (0x0014) }
g723_adpcmwaveformat_tag = record
wfx:WAVEFORMATEX;
cbExtraSize:word;
nAuxBlockSize:word;
end;
G723_ADPCMWAVEFORMAT = g723_adpcmwaveformat_tag;
PG723_ADPCMWAVEFORMAT = ^G723_ADPCMWAVEFORMAT;
NPG723_ADPCMWAVEFORMAT = ^G723_ADPCMWAVEFORMAT;
LPG723_ADPCMWAVEFORMAT = ^G723_ADPCMWAVEFORMAT;
{ }
{ DSP Solutions (formerly DIGISPEECH) structure definitions }
{ }
{ for WAVE_FORMAT_DIGISTD (0x0015) }
digistdwaveformat_tag = record
wfx : WAVEFORMATEX;
end;
DIGISTDWAVEFORMAT = digistdwaveformat_tag;
PDIGISTDWAVEFORMAT = ^DIGISTDWAVEFORMAT;
NPDIGISTDWAVEFORMAT = ^DIGISTDWAVEFORMAT;
LPDIGISTDWAVEFORMAT = ^DIGISTDWAVEFORMAT;
{ }
{ DSP Solutions (formerly DIGISPEECH) structure definitions }
{ }
{ for WAVE_FORMAT_DIGIFIX (0x0016) }
{ }
{ }
digifixwaveformat_tag = record
wfx : WAVEFORMATEX;
end;
DIGIFIXWAVEFORMAT = digifixwaveformat_tag;
PDIGIFIXWAVEFORMAT = ^DIGIFIXWAVEFORMAT;
NPDIGIFIXWAVEFORMAT = ^DIGIFIXWAVEFORMAT;
LPDIGIFIXWAVEFORMAT = ^DIGIFIXWAVEFORMAT;
{ }
{ Dialogic Corporation }
{ WAVEFORMAT_DIALOGIC_OKI_ADPCM (0x0017) }
{ }
creative_fastspeechformat_tag = record
ewf:WAVEFORMATEX;
end;
DIALOGICOKIADPCMWAVEFORMAT = creative_fastspeechformat_tag;
PDIALOGICOKIADPCMWAVEFORMAT = ^DIALOGICOKIADPCMWAVEFORMAT;
NPDIALOGICOKIADPCMWAVEFORMAT = ^DIALOGICOKIADPCMWAVEFORMAT;
LPDIALOGICOKIADPCMWAVEFORMAT = ^DIALOGICOKIADPCMWAVEFORMAT;
{ }
{ Yamaha Compression's ADPCM structure definitions }
{ }
{ for WAVE_FORMAT_YAMAHA_ADPCM (0x0020) }
{ }
{ }
yamaha_adpmcwaveformat_tag = record
wfx : WAVEFORMATEX;
end;
YAMAHA_ADPCMWAVEFORMAT = yamaha_adpmcwaveformat_tag;
PYAMAHA_ADPCMWAVEFORMAT = ^YAMAHA_ADPCMWAVEFORMAT;
(* near ignored *)
NPYAMAHA_ADPCMWAVEFORMAT = ^YAMAHA_ADPCMWAVEFORMAT;
(* far ignored *)
LPYAMAHA_ADPCMWAVEFORMAT = ^YAMAHA_ADPCMWAVEFORMAT;
{ }
{ Speech Compression's Sonarc structure definitions }
{ }
{ for WAVE_FORMAT_SONARC (0x0021) }
{ }
{ }
sonarcwaveformat_tag = record
wfx : WAVEFORMATEX;
wCompType : word;
end;
SONARCWAVEFORMAT = sonarcwaveformat_tag;
PSONARCWAVEFORMAT = ^SONARCWAVEFORMAT;
NPSONARCWAVEFORMAT = ^SONARCWAVEFORMAT;
LPSONARCWAVEFORMAT = SONARCWAVEFORMAT;
{ }
{ DSP Groups's TRUESPEECH structure definitions }
{ }
{ for WAVE_FORMAT_DSPGROUP_TRUESPEECH (0x0022) }
{ }
{ }
truespeechwaveformat_tag = record
wfx : WAVEFORMATEX;
wRevision :word;
nSamplesPerBlock:word;
abReserved :array[0..27] of byte;
end;
TRUESPEECHWAVEFORMAT = truespeechwaveformat_tag;
PTRUESPEECHWAVEFORMAT = ^TRUESPEECHWAVEFORMAT;
NPTRUESPEECHWAVEFORMAT = ^TRUESPEECHWAVEFORMAT;
LPTRUESPEECHWAVEFORMAT = ^TRUESPEECHWAVEFORMAT;
{ }
{ Echo Speech Corp structure definitions }
{ }
{ for WAVE_FORMAT_ECHOSC1 (0x0023) }
echosc1waveformat_tag = record
wfx:WAVEFORMATEX;
end;
ECHOSC1WAVEFORMAT = echosc1waveformat_tag;
PECHOSC1WAVEFORMAT = ^ECHOSC1WAVEFORMAT;
NPECHOSC1WAVEFORMAT = ^ECHOSC1WAVEFORMAT;
LPECHOSC1WAVEFORMAT = ^ECHOSC1WAVEFORMAT;
{ }
{ Audiofile Inc.structure definitions }
{ }
{ for WAVE_FORMAT_AUDIOFILE_AF36 (0x0024) }
{ }
{ }
audiofile_af36waveformat_tag = record
wfx : WAVEFORMATEX;
end;
AUDIOFILE_AF36WAVEFORMAT = audiofile_af36waveformat_tag;
PAUDIOFILE_AF36WAVEFORMAT = ^AUDIOFILE_AF36WAVEFORMAT;
NPAUDIOFILE_AF36WAVEFORMAT = ^AUDIOFILE_AF36WAVEFORMAT;
LPAUDIOFILE_AF36WAVEFORMAT = ^AUDIOFILE_AF36WAVEFORMAT;
{ }
{ Audio Processing Technology structure definitions }
{ }
{ for WAVE_FORMAT_APTX (0x0025) }
{ }
{ }
aptxwaveformat_tag = record
wfx : WAVEFORMATEX;
end;
APTXWAVEFORMAT = aptxwaveformat_tag;
PAPTXWAVEFORMAT = ^APTXWAVEFORMAT;
NPAPTXWAVEFORMAT = ^APTXWAVEFORMAT;
LPAPTXWAVEFORMAT = ^APTXWAVEFORMAT;
{ }
{ Audiofile Inc.structure definitions }
{ }
{ for WAVE_FORMAT_AUDIOFILE_AF10 (0x0026) }
{ }
{ }
audiofile_af10waveformat_tag = record
wfx : WAVEFORMATEX;
end;
AUDIOFILE_AF10WAVEFORMAT = audiofile_af10waveformat_tag;
PAUDIOFILE_AF10WAVEFORMAT = ^AUDIOFILE_AF10WAVEFORMAT;
NPAUDIOFILE_AF10WAVEFORMAT = ^AUDIOFILE_AF10WAVEFORMAT;
LPAUDIOFILE_AF10WAVEFORMAT = ^AUDIOFILE_AF10WAVEFORMAT;
{ }
{ Dolby's AC-2 wave format structure definition
WAVE_FORMAT_DOLBY_AC2 (0x0030) }
{ }
dolbyac2waveformat_tag = record
wfx:WAVEFORMATEX;
nAuxBitsCode:word;
end;
DOLBYAC2WAVEFORMAT = dolbyac2waveformat_tag;
{Microsoft's }
{ WAVE_FORMAT_GSM 610 0x0031 }
{ }
gsm610waveformat_tag = record
wfx : WAVEFORMATEX;
wSamplesPerBlock : word;
end;
GSM610WAVEFORMAT = gsm610waveformat_tag;
PGSM610WAVEFORMAT = ^GSM610WAVEFORMAT;
NPGSM610WAVEFORMAT = ^GSM610WAVEFORMAT;
LPGSM610WAVEFORMAT = ^GSM610WAVEFORMAT;
{ }
{ Antex Electronics Corp }
{ }
{ for WAVE_FORMAT_ADPCME (0x0033) }
{ }
{ }
adpcmewaveformat_tag = record
wfx : WAVEFORMATEX;
wSamplesPerBlock:word;
end;
ADPCMEWAVEFORMAT = adpcmewaveformat_tag;
PADPCMEWAVEFORMAT = ^ADPCMEWAVEFORMAT;
NPADPCMEWAVEFORMAT = ^ADPCMEWAVEFORMAT;
LPADPCMEWAVEFORMAT = ^ADPCMEWAVEFORMAT;
{ Control Resources Limited }
{ WAVE_FORMAT_CONTROL_RES_VQLPC 0x0034 }
{ }
contres_vqlpcwaveformat_tag = record
wfx : WAVEFORMATEX;
wSamplesPerBlock :word;
end;
CONTRESVQLPCWAVEFORMAT = contres_vqlpcwaveformat_tag;
PCONTRESVQLPCWAVEFORMAT = ^CONTRESVQLPCWAVEFORMAT;
(* near ignored *)
NPCONTRESVQLPCWAVEFORMAT = ^CONTRESVQLPCWAVEFORMAT;
(* far ignored *)
LPCONTRESVQLPCWAVEFORMAT = ^CONTRESVQLPCWAVEFORMAT;
{ for WAVE_FORMAT_DIGIREAL (0x0035) }
{ }
{ }
digirealwaveformat_tag = record
wfx : WAVEFORMATEX;
wSamplesPerBlock : word;
end;
DIGIREALWAVEFORMAT = digirealwaveformat_tag;
PDIGIREALWAVEFORMAT = ^DIGIREALWAVEFORMAT;
NPDIGIREALWAVEFORMAT = ^DIGIREALWAVEFORMAT;
LPDIGIREALWAVEFORMAT = ^DIGIREALWAVEFORMAT;
{ DSP Solutions }
{ }
{ for WAVE_FORMAT_DIGIADPCM (0x0036) }
digiadpcmmwaveformat_tag = record
wfx : WAVEFORMATEX;
wSamplesPerBlock:word;
end;
DIGIADPCMWAVEFORMAT = digiadpcmmwaveformat_tag;
PDIGIADPCMWAVEFORMAT = ^DIGIADPCMWAVEFORMAT;
(* near ignored *)
NPDIGIADPCMWAVEFORMAT = ^DIGIADPCMWAVEFORMAT;
(* far ignored *)
LPDIGIADPCMWAVEFORMAT = ^DIGIADPCMWAVEFORMAT;
{ Control Resources Limited }
{ WAVE_FORMAT_CONTROL_RES_CR10 0x0037 }
contres_cr10waveformat_tag = record
wfx : WAVEFORMATEX;
wSamplesPerBlock :word;
end;
CONTRESCR10WAVEFORMAT = contres_cr10waveformat_tag;
PCONTRESCR10WAVEFORMAT = ^CONTRESCR10WAVEFORMAT;
NPCONTRESCR10WAVEFORMAT = ^CONTRESCR10WAVEFORMAT;
LPCONTRESCR10WAVEFORMAT = ^CONTRESCR10WAVEFORMAT;
{ }
{ Natural Microsystems }
{ }
{ for WAVE_FORMAT_NMS_VBXADPCM (0x0038) }
nms_vbxadpcmmwaveformat_tag = record
wfx : WAVEFORMATEX;
wSamplesPerBlock :word;
end;
NMS_VBXADPCMWAVEFORMAT = nms_vbxadpcmmwaveformat_tag;
PNMS_VBXADPCMWAVEFORMAT = ^NMS_VBXADPCMWAVEFORMAT;
(* near ignored *)
NPNMS_VBXADPCMWAVEFORMAT = ^NMS_VBXADPCMWAVEFORMAT;
(* far ignored *)
LPNMS_VBXADPCMWAVEFORMAT = ^NMS_VBXADPCMWAVEFORMAT;
{ }
{ Antex Electronics structure definitions }
{ }
{ for WAVE_FORMAT_G721_ADPCM (0x0040) }
{ }
{ }
g721_adpcmwaveformat_tag = record
wfx : WAVEFORMATEX;
nAuxBlockSize :word;
end;
G721_ADPCMWAVEFORMAT = g721_adpcmwaveformat_tag;
PG721_ADPCMWAVEFORMAT = ^G721_ADPCMWAVEFORMAT;
(* near ignored *)
NPG721_ADPCMWAVEFORMAT = ^G721_ADPCMWAVEFORMAT;
(* far ignored *)
LPG721_ADPCMWAVEFORMAT = ^G721_ADPCMWAVEFORMAT;
{ Microsoft MPEG audio WAV definition }
{ }
{ MPEG-1 audio wave format (audio layer only). (0x0050) }
mpeg1waveformat_tag = record
wfx:WAVEFORMATEX;
fwHeadLayer:word;
dwHeadBitrate:DWORD;
fwHeadMode:word;
fwHeadModeExt:word;
wHeadEmphasis:word;
fwHeadFlags:word;
dwPTSLow:DWORD;
dwPTSHigh:DWORD;
end;
MPEG1WAVEFORMAT = mpeg1waveformat_tag;
PMPEG1WAVEFORMAT = ^MPEG1WAVEFORMAT;
NPMPEG1WAVEFORMAT = ^MPEG1WAVEFORMAT;
LPMPEG1WAVEFORMAT = ^MPEG1WAVEFORMAT;
const
ACM_MPEG_LAYER1 = $0001;
ACM_MPEG_LAYER2 = $0002;
ACM_MPEG_LAYER3 = $0004;
ACM_MPEG_STEREO = $0001;
ACM_MPEG_JOINTSTEREO = $0002;
ACM_MPEG_DUALCHANNEL = $0004;
ACM_MPEG_SINGLECHANNEL = $0008;
ACM_MPEG_PRIVATEBIT = $0001;
ACM_MPEG_COPYRIGHT = $0002;
ACM_MPEG_ORIGINALHOME = $0004;
ACM_MPEG_PROTECTIONBIT = $0008;
ACM_MPEG_ID_MPEG1 = $0010;
{ MPEG Layer3 WAVEFORMATEX structure }
{ for WAVE_FORMAT_MPEGLAYER3 (0x0055) }
MPEGLAYER3_WFX_EXTRA_BYTES = 12;
{ WAVE_FORMAT_MPEGLAYER3 format sructure }
type
mpeglayer3waveformat_tag = record
wfx:WAVEFORMATEX;
wID:word;
fdwFlags:DWORD;
nBlockSize:WORD;
nFramesPerBlock:word;
nCodecDelay:word;
end;
MPEGLAYER3WAVEFORMAT = mpeglayer3waveformat_tag;
PMPEGLAYER3WAVEFORMAT = ^MPEGLAYER3WAVEFORMAT;
NPMPEGLAYER3WAVEFORMAT = ^MPEGLAYER3WAVEFORMAT;
LPMPEGLAYER3WAVEFORMAT = ^MPEGLAYER3WAVEFORMAT;
{==========================================================================; }
const
MPEGLAYER3_ID_UNKNOWN = 0;
MPEGLAYER3_ID_MPEG = 1;
MPEGLAYER3_ID_CONSTANTFRAMESIZE = 2;
MPEGLAYER3_FLAG_PADDING_ISO = $00000000;
MPEGLAYER3_FLAG_PADDING_ON = $00000001;
MPEGLAYER3_FLAG_PADDING_OFF = $00000002;
{ Creative's ADPCM structure definitions }
{ }
{ for WAVE_FORMAT_CREATIVE_ADPCM (0x0200) }
type
creative_adpcmwaveformat_tag = record
wfx:WAVEFORMATEX;
wRevision:word;
end;
CREATIVEADPCMWAVEFORMAT = creative_adpcmwaveformat_tag;
PCREATIVEADPCMWAVEFORMAT = ^CREATIVEADPCMWAVEFORMAT;
NPCREATIVEADPCMWAVEFORMAT = ^CREATIVEADPCMWAVEFORMAT;
LPCREATIVEADPCMWAVEFORMAT = ^CREATIVEADPCMWAVEFORMAT;
{ }
{ Creative FASTSPEECH }
{ WAVEFORMAT_CREATIVE_FASTSPEECH8 (0x0202) }
{ }
creative_fastspeech8format_tag = record
wfx : WAVEFORMATEX;
wRevision : word;
end;
CREATIVEFASTSPEECH8WAVEFORMAT = creative_fastspeech8format_tag;
PCREATIVEFASTSPEECH8WAVEFORMAT = ^CREATIVEFASTSPEECH8WAVEFORMAT;
(* near ignored *)
NPCREATIVEFASTSPEECH8WAVEFORMAT = ^CREATIVEFASTSPEECH8WAVEFORMAT;
(* far ignored *)
LPCREATIVEFASTSPEECH8WAVEFORMAT = ^CREATIVEFASTSPEECH8WAVEFORMAT;
{ }
{ Creative FASTSPEECH }
{ WAVEFORMAT_CREATIVE_FASTSPEECH10 (0x0203) }
{ }
creative_fastspeech10format_tag = record
wfx : WAVEFORMATEX;
wRevision : word;
end;
CREATIVEFASTSPEECH10WAVEFORMAT = creative_fastspeech10format_tag;
PCREATIVEFASTSPEECH10WAVEFORMAT = ^CREATIVEFASTSPEECH10WAVEFORMAT;
(* near ignored *)
NPCREATIVEFASTSPEECH10WAVEFORMAT = ^CREATIVEFASTSPEECH10WAVEFORMAT;
(* far ignored *)
LPCREATIVEFASTSPEECH10WAVEFORMAT = ^CREATIVEFASTSPEECH10WAVEFORMAT;
{ }
{ Fujitsu FM Towns 'SND' structure }
{ }
{ for WAVE_FORMAT_FMMTOWNS_SND (0x0300) }
{ }
{ }
fmtowns_snd_waveformat_tag = record
wfx : WAVEFORMATEX;
wRevision : word;
end;
FMTOWNS_SND_WAVEFORMAT = fmtowns_snd_waveformat_tag;
PFMTOWNS_SND_WAVEFORMAT = ^FMTOWNS_SND_WAVEFORMAT;
(* near ignored *)
NPFMTOWNS_SND_WAVEFORMAT = ^FMTOWNS_SND_WAVEFORMAT;
(* far ignored *)
LPFMTOWNS_SND_WAVEFORMAT = ^FMTOWNS_SND_WAVEFORMAT;
{ Olivetti structure }
{ }
{ for WAVE_FORMAT_OLIGSM (0x1000) }
oligsmwaveformat_tag = record
wfx : WAVEFORMATEX;
end;
OLIGSMWAVEFORMAT = oligsmwaveformat_tag;
POLIGSMWAVEFORMAT = ^OLIGSMWAVEFORMAT;
(* near ignored *)
NPOLIGSMWAVEFORMAT = ^OLIGSMWAVEFORMAT;
(* far ignored *)
LPOLIGSMWAVEFORMAT = ^OLIGSMWAVEFORMAT;
{ }
{ Olivetti structure }
{ }
{ for WAVE_FORMAT_OLIADPCM (0x1001) }
{ }
{ }
oliadpcmwaveformat_tag = record
wfx : WAVEFORMATEX;
end;
OLIADPCMWAVEFORMAT = oliadpcmwaveformat_tag;
POLIADPCMWAVEFORMAT = ^OLIADPCMWAVEFORMAT;
(* near ignored *)
NPOLIADPCMWAVEFORMAT = ^OLIADPCMWAVEFORMAT;
(* far ignored *)
LPOLIADPCMWAVEFORMAT = ^OLIADPCMWAVEFORMAT;
{ }
{ Olivetti structure }
{ }
{ for WAVE_FORMAT_OLICELP (0x1002) }
olicelpwaveformat_tag = record
wfx : WAVEFORMATEX;
end;
OLICELPWAVEFORMAT = olicelpwaveformat_tag;
POLICELPWAVEFORMAT = ^OLICELPWAVEFORMAT;
NPOLICELPWAVEFORMAT = ^OLICELPWAVEFORMAT;
LPOLICELPWAVEFORMAT = ^OLICELPWAVEFORMAT;
{ }
{ Olivetti structure }
{ }
{ for WAVE_FORMAT_OLISBC (0x1003) }
{ }
{ }
olisbcwaveformat_tag = record
wfx : WAVEFORMATEX;
end;
OLISBCWAVEFORMAT = olisbcwaveformat_tag;
POLISBCWAVEFORMAT = ^OLISBCWAVEFORMAT;
(* near ignored *)
NPOLISBCWAVEFORMAT = ^OLISBCWAVEFORMAT;
(* far ignored *)
LPOLISBCWAVEFORMAT = ^OLISBCWAVEFORMAT;
{ }
{ Olivetti structure }
{ }
{ for WAVE_FORMAT_OLIOPR (0x1004) }
{ }
{ }
olioprwaveformat_tag = record
wfx : WAVEFORMATEX;
end;
OLIOPRWAVEFORMAT = olioprwaveformat_tag;
POLIOPRWAVEFORMAT = ^OLIOPRWAVEFORMAT;
(* near ignored *)
NPOLIOPRWAVEFORMAT = ^OLIOPRWAVEFORMAT;
(* far ignored *)
LPOLIOPRWAVEFORMAT = ^OLIOPRWAVEFORMAT;
{ }
{ Crystal Semiconductor IMA ADPCM format }
{ }
{ for WAVE_FORMAT_CS_IMAADPCM (0x0039) }
{ }
{ }
csimaadpcmwaveformat_tag = record
wfx : WAVEFORMATEX;
end;
CSIMAADPCMWAVEFORMAT = csimaadpcmwaveformat_tag;
PCSIMAADPCMWAVEFORMAT = ^CSIMAADPCMWAVEFORMAT;
(* near ignored *)
NPCSIMAADPCMWAVEFORMAT = ^CSIMAADPCMWAVEFORMAT;
(* far ignored *)
LPCSIMAADPCMWAVEFORMAT = ^CSIMAADPCMWAVEFORMAT;
{==========================================================================; }
{ }
{ ACM Wave Filters }
{ }
{ }
{==========================================================================; }
const
WAVE_FILTER_UNKNOWN = $0000;
WAVE_FILTER_DEVELOPMENT = $FFFF;
type
wavefilter_tag = record
cbStruct:DWORD; //* Size of the filter in bytes */
dwFilterTag:DWORD; //* filter type */
fdwFilter:DWORD; //* Flags for the filter (Universal Dfns) */
dwReserved:array[0..4] of DWORD; //* Reserved for system use */
end;
WAVEFILTER = wavefilter_tag;
PWAVEFILTER = ^WAVEFILTER;
NPWAVEFILTER = ^WAVEFILTER;
LPWAVEFILTER = ^WAVEFILTER;
const
WAVE_FILTER_VOLUME = $0001;
type
wavefilter_volume_tag = record
wfltr:WAVEFILTER;
dwVolume:DWORD;
end;
VOLUMEWAVEFILTER = wavefilter_volume_tag;
PVOLUMEWAVEFILTER = ^VOLUMEWAVEFILTER;
NPVOLUMEWAVEFILTER = ^VOLUMEWAVEFILTER;
LPVOLUMEWAVEFILTER = ^VOLUMEWAVEFILTER;
const
WAVE_FILTER_ECHO = $0002;
type
wavefilter_echo_tag = record
wfltr:WAVEFILTER;
dwVolume:DWORD;
dwDelay:DWORD;
end;
ECHOWAVEFILTER = wavefilter_echo_tag;
PECHOWAVEFILTER = ^ECHOWAVEFILTER;
NPECHOWAVEFILTER = ^ECHOWAVEFILTER;
LPECHOWAVEFILTER = ^ECHOWAVEFILTER;
//////////////////////////////////////////////////////////////////////////
//
// New RIFF WAVE Chunks
//
const
RIFFWAVE_inst = FOURCC(byte(AnsiChar('i')) or
(byte(AnsiChar('n')) shl 8) or
(byte(AnsiChar('s')) shl 16) or
(byte(AnsiChar('t')) shl 24)
);
type
tag_s_RIFFWAVE_inst = record
bUnshiftedNote:byte;
chFineTune:ShortInt;
chGain:ShortInt;
bLowNote:byte;
bHighNote:byte;
bLowVelocity:byte;
bHighVelocity:byte;
end;
s_RIFFWAVE_inst = tag_s_RIFFWAVE_INST;
{$ENDIF} // NONEWWAVE
//////////////////////////////////////////////////////////////////////////
//
// New RIFF Forms
//
{$IFNDEF NONEWRIFF}
// RIFF AVI
//
// AVI file format is specified in a seperate file (AVIFMT.H),
// which is available in the VfW and Win 32 SDK
//
// RIFF CPPO
const
RIFFCPPO = FOURCC(byte(AnsiChar('C')) or
(byte(AnsiChar('P')) shl 8) or
(byte(AnsiChar('P')) shl 16) or
(byte(AnsiChar('O')) shl 24)
);
RIFFCPPO_objr = FOURCC(byte(AnsiChar('o')) or
(byte(AnsiChar('b')) shl 8) or
(byte(AnsiChar('j')) shl 16) or
(byte(AnsiChar('r')) shl 24)
);
RIFFCPPO_obji = FOURCC(byte(AnsiChar('o')) or
(byte(AnsiChar('b')) shl 8) or
(byte(AnsiChar('j')) shl 16) or
(byte(AnsiChar('i')) shl 24)
);
RIFFCPPO_clsr = FOURCC(byte(AnsiChar('c')) or
(byte(AnsiChar('l')) shl 8) or
(byte(AnsiChar('s')) shl 16) or
(byte(AnsiChar('r')) shl 24)
);
RIFFCPPO_clsi = FOURCC(byte(AnsiChar('c')) or
(byte(AnsiChar('l')) shl 8) or
(byte(AnsiChar('s')) shl 16) or
(byte(AnsiChar('i')) shl 24)
);
RIFFCPPO_mbr = FOURCC(byte(AnsiChar('m')) or
(byte(AnsiChar('b')) shl 8) or
(byte(AnsiChar('r')) shl 16) or
(byte(AnsiChar(' ')) shl 24)
);
RIFFCPPO_char = FOURCC(byte(AnsiChar('c')) or
(byte(AnsiChar('h')) shl 8) or
(byte(AnsiChar('a')) shl 16) or
(byte(AnsiChar('r')) shl 24)
);
RIFFCPPO_byte = FOURCC(byte(AnsiChar('b')) or
(byte(AnsiChar('y')) shl 8) or
(byte(AnsiChar('t')) shl 16) or
(byte(AnsiChar('e')) shl 24)
);
RIFFCPPO_int = FOURCC(byte(AnsiChar('i')) or
(byte(AnsiChar('n')) shl 8) or
(byte(AnsiChar('t')) shl 16) or
(byte(AnsiChar(' ')) shl 24)
);
RIFFCPPO_word = FOURCC(byte(AnsiChar('w')) or
(byte(AnsiChar('o')) shl 8) or
(byte(AnsiChar('r')) shl 16) or
(byte(AnsiChar('d')) shl 24)
);
RIFFCPPO_long = FOURCC(byte(AnsiChar('l')) or
(byte(AnsiChar('o')) shl 8) or
(byte(AnsiChar('n')) shl 16) or
(byte(AnsiChar('g')) shl 24)
);
RIFFCPPO_dwrd = FOURCC(byte(AnsiChar('d')) or
(byte(AnsiChar('w')) shl 8) or
(byte(AnsiChar('r')) shl 16) or
(byte(AnsiChar('d')) shl 24)
);
RIFFCPPO_flt = FOURCC(byte(AnsiChar('f')) or
(byte(AnsiChar('l')) shl 8) or
(byte(AnsiChar('t')) shl 16) or
(byte(AnsiChar(' ')) shl 24)
);
RIFFCPPO_dbl = FOURCC(byte(AnsiChar('d')) or
(byte(AnsiChar('b')) shl 8) or
(byte(AnsiChar('l')) shl 16) or
(byte(AnsiChar(' ')) shl 24)
);
RIFFCPPO_str = FOURCC(byte(AnsiChar('s')) or
(byte(AnsiChar('t')) shl 8) or
(byte(AnsiChar('r')) shl 16) or
(byte(AnsiChar(' ')) shl 24)
);
{$ENDIF} // NONEWRIFF
//////////////////////////////////////////////////////////////////////////
//
// DIB Compression Defines
//
const
BI_BITFIELDS = 3;
const
QUERYDIBSUPPORT = 3073;
QDI_SETDIBITS = $0001;
QDI_GETDIBITS = $0002;
QDI_DIBTOSCREEN = $0004;
QDI_STRETCHDIB = $0008;
{ @CESYSGEN IF GWES_PGDI || GWES_MGBASE }
{$IFNDEF NOBITMAP}
type
tagEXBMINFOHEADER = record
bmi:BITMAPINFOHEADER;
// extended BITMAPINFOHEADER fields
biExtDataOffset:DWORD;
// Other elements will go here
// ...
// Format-specific information
// biExtDataOffset points here
end;
EXBMINFOHEADER = tagEXBMINFOHEADER;
{$ENDIF} // NOBITMAP
{ @CESYSGEN ENDIF }
// New DIB Compression Defines
const
BICOMP_IBMULTIMOTION = FOURCC(byte(AnsiChar('U')) or
(byte(AnsiChar('L')) shl 8) or
(byte(AnsiChar('T')) shl 16) or
(byte(AnsiChar('I')) shl 24)
);
BICOMP_IBMPHOTOMOTION = FOURCC(byte(AnsiChar('P')) or
(byte(AnsiChar('H')) shl 8) or
(byte(AnsiChar('M')) shl 16) or
(byte(AnsiChar('O')) shl 24)
);
BICOMP_CREATIVEYUV = FOURCC(byte(AnsiChar('c')) or
(byte(AnsiChar('y')) shl 8) or
(byte(AnsiChar('u')) shl 16) or
(byte(AnsiChar('v')) shl 24)
);
{$IFNDEF NOJPEGDIB}
// New DIB Compression Defines
const
JPEG_DIB = FOURCC(byte(AnsiChar('J')) or
(byte(AnsiChar('P')) shl 8) or
(byte(AnsiChar('E')) shl 16) or
(byte(AnsiChar('G')) shl 24)
); // Still image JPEG DIB biCompression
MJPG_DIB = FOURCC(byte(AnsiChar('M')) or
(byte(AnsiChar('J')) shl 8) or
(byte(AnsiChar('P')) shl 16) or
(byte(AnsiChar('G')) shl 24)
); // Motion JPEG DIB biCompression
{ JPEGProcess Definitions }
const
JPEG_PROCESS_BASELINE = 0; { Baseline DCT }
{ AVI File format extensions }
AVIIF_CONTROLFRAME = $00000200; { This is a control frame }
{ JIF Marker byte pairs in JPEG Interchange Format sequence }
{ SOF Huff - Baseline DCT }
JIFMK_SOF0 = $FFC0;
{ SOF Huff - Extended sequential DCT }
JIFMK_SOF1 = $FFC1;
{ SOF Huff - Progressive DCT }
JIFMK_SOF2 = $FFC2;
{ SOF Huff - Spatial (sequential) lossless }
JIFMK_SOF3 = $FFC3;
{ SOF Huff - Differential sequential DCT }
JIFMK_SOF5 = $FFC5;
{ SOF Huff - Differential progressive DCT }
JIFMK_SOF6 = $FFC6;
{ SOF Huff - Differential spatial }
JIFMK_SOF7 = $FFC7;
{ SOF Arith - Reserved for JPEG extensions }
JIFMK_JPG = $FFC8;
{ SOF Arith - Extended sequential DCT }
JIFMK_SOF9 = $FFC9;
{ SOF Arith - Progressive DCT }
JIFMK_SOF10 = $FFCA;
{ SOF Arith - Spatial (sequential) lossless }
JIFMK_SOF11 = $FFCB;
{ SOF Arith - Differential sequential DCT }
JIFMK_SOF13 = $FFCD;
{ SOF Arith - Differential progressive DCT }
JIFMK_SOF14 = $FFCE;
{ SOF Arith - Differential spatial }
JIFMK_SOF15 = $FFCF;
{ Define Huffman Table(s) }
JIFMK_DHT = $FFC4;
{ Define Arithmetic coding conditioning(s) }
JIFMK_DAC = $FFCC;
{ Restart with modulo 8 count 0 }
JIFMK_RST0 = $FFD0;
{ Restart with modulo 8 count 1 }
JIFMK_RST1 = $FFD1;
{ Restart with modulo 8 count 2 }
JIFMK_RST2 = $FFD2;
{ Restart with modulo 8 count 3 }
JIFMK_RST3 = $FFD3;
{ Restart with modulo 8 count 4 }
JIFMK_RST4 = $FFD4;
{ Restart with modulo 8 count 5 }
JIFMK_RST5 = $FFD5;
{ Restart with modulo 8 count 6 }
JIFMK_RST6 = $FFD6;
{ Restart with modulo 8 count 7 }
JIFMK_RST7 = $FFD7;
{ Start of Image }
JIFMK_SOI = $FFD8;
{ End of Image }
JIFMK_EOI = $FFD9;
{ Start of Scan }
JIFMK_SOS = $FFDA;
{ Define quantization Table(s) }
JIFMK_DQT = $FFDB;
{ Define Number of Lines }
JIFMK_DNL = $FFDC;
{ Define Restart Interval }
JIFMK_DRI = $FFDD;
{ Define Hierarchical progression }
JIFMK_DHP = $FFDE;
{ Expand Reference Component(s) }
JIFMK_EXP = $FFDF;
{ Application Field 0 }
JIFMK_APP0 = $FFE0;
{ Application Field 1 }
JIFMK_APP1 = $FFE1;
{ Application Field 2 }
JIFMK_APP2 = $FFE2;
{ Application Field 3 }
JIFMK_APP3 = $FFE3;
{ Application Field 4 }
JIFMK_APP4 = $FFE4;
{ Application Field 5 }
JIFMK_APP5 = $FFE5;
{ Application Field 6 }
JIFMK_APP6 = $FFE6;
{ Application Field 7 }
JIFMK_APP7 = $FFE7;
{ Reserved for JPEG extensions }
JIFMK_JPG0 = $FFF0;
{ Reserved for JPEG extensions }
JIFMK_JPG1 = $FFF1;
{ Reserved for JPEG extensions }
JIFMK_JPG2 = $FFF2;
{ Reserved for JPEG extensions }
JIFMK_JPG3 = $FFF3;
{ Reserved for JPEG extensions }
JIFMK_JPG4 = $FFF4;
{ Reserved for JPEG extensions }
JIFMK_JPG5 = $FFF5;
{ Reserved for JPEG extensions }
JIFMK_JPG6 = $FFF6;
{ Reserved for JPEG extensions }
JIFMK_JPG7 = $FFF7;
{ Reserved for JPEG extensions }
JIFMK_JPG8 = $FFF8;
{ Reserved for JPEG extensions }
JIFMK_JPG9 = $FFF9;
{ Reserved for JPEG extensions }
JIFMK_JPG10 = $FFFA;
{ Reserved for JPEG extensions }
JIFMK_JPG11 = $FFFB;
{ Reserved for JPEG extensions }
JIFMK_JPG12 = $FFFC;
{ Reserved for JPEG extensions }
JIFMK_JPG13 = $FFFD;
{ Comment }
JIFMK_COM = $FFFE;
{ for temp private use arith code }
JIFMK_TEM = $FF01;
{ Reserved }
JIFMK_RES = $FF02;
{ Zero stuffed byte - entropy data }
JIFMK_00 = $FF00;
{ Fill byte }
JIFMK_FF = $FFFF;
{ JPEGColorSpaceID Definitions }
{ Y only component of YCbCr }
JPEG_Y = 1;
{ YCbCr as define by CCIR 601 }
JPEG_YCbCr = 2;
{ 3 component RGB }
JPEG_RGB = 3;
{ Structure definitions }
{ compression-specific fields }
{ these fields are defined for 'JPEG' and 'MJPG' }
{ Process specific fields }
type
tagJPEGINFOHEADER = record
// compression-specific fields
// these fields are defined for 'JPEG' and 'MJPG'
JPEGSize:DWORD;
JPEGProcess:DWORD;
// Process specific fields
JPEGColorSpaceID:DWORD;
JPEGBitsPerSample:DWORD;
JPEGHSubSampling:DWORD;
JPEGVSubSampling:DWORD;
end;
JPEGINFOHEADER = tagJPEGINFOHEADER;
{$IFDEF MJPGDHTSEG_STORAGE}
// Default DHT Segment
const
// JPEG DHT Segment for YCrCb omitted from MJPG data
MJPGDHTSeg:array[0..$01A4-1] of byte =
($FF,$C4,$01,$A2,$00,$00,$01,$05,$01,$01,$01,$01,$01,$01,
$00,$00,$00,$00,$00,$00,$00,$00,$01,$02,$03,$04,$05,$06,
$07,$08,$09,$0A,$0B,$01,$00,$03,$01,$01,$01,$01,$01,$01,
$01,$01,$01,$00,$00,$00,$00,$00,$00,$01,$02,$03,$04,$05,
$06,$07,$08,$09,$0A,$0B,$10,$00,$02,$01,$03,$03,$02,$04,
$03,$05,$05,$04,$04,$00,$00,$01,$7D,$01,$02,$03,$00,$04,
$11,$05,$12,$21,$31,$41,$06,$13,$51,$61,$07,$22,$71,$14,
$32,$81,$91,$A1,$08,$23,$42,$B1,$C1,$15,$52,$D1,$F0,$24,
$33,$62,$72,$82,$09,$0A,$16,$17,$18,$19,$1A,$25,$26,$27,
$28,$29,$2A,$34,$35,$36,$37,$38,$39,$3A,$43,$44,$45,$46,
$47,$48,$49,$4A,$53,$54,$55,$56,$57,$58,$59,$5A,$63,$64,
$65,$66,$67,$68,$69,$6A,$73,$74,$75,$76,$77,$78,$79,$7A,
$83,$84,$85,$86,$87,$88,$89,$8A,$92,$93,$94,$95,$96,$97,
$98,$99,$9A,$A2,$A3,$A4,$A5,$A6,$A7,$A8,$A9,$AA,$B2,$B3,
$B4,$B5,$B6,$B7,$B8,$B9,$BA,$C2,$C3,$C4,$C5,$C6,$C7,$C8,
$C9,$CA,$D2,$D3,$D4,$D5,$D6,$D7,$D8,$D9,$DA,$E1,$E2,$E3,
$E4,$E5,$E6,$E7,$E8,$E9,$EA,$F1,$F2,$F3,$F4,$F5,$F6,$F7,
$F8,$F9,$FA,$11,$00,$02,$01,$02,$04,$04,$03,$04,$07,$05,
$04,$04,$00,$01,$02,$77,$00,$01,$02,$03,$11,$04,$05,$21,
$31,$06,$12,$41,$51,$07,$61,$71,$13,$22,$32,$81,$08,$14,
$42,$91,$A1,$B1,$C1,$09,$23,$33,$52,$F0,$15,$62,$72,$D1,
$0A,$16,$24,$34,$E1,$25,$F1,$17,$18,$19,$1A,$26,$27,$28,
$29,$2A,$35,$36,$37,$38,$39,$3A,$43,$44,$45,$46,$47,$48,
$49,$4A,$53,$54,$55,$56,$57,$58,$59,$5A,$63,$64,$65,$66,
$67,$68,$69,$6A,$73,$74,$75,$76,$77,$78,$79,$7A,$82,$83,
$84,$85,$86,$87,$88,$89,$8A,$92,$93,$94,$95,$96,$97,$98,
$99,$9A,$A2,$A3,$A4,$A5,$A6,$A7,$A8,$A9,$AA,$B2,$B3,$B4,
$B5,$B6,$B7,$B8,$B9,$BA,$C2,$C3,$C4,$C5,$C6,$C7,$C8,$C9,
$CA,$D2,$D3,$D4,$D5,$D6,$D7,$D8,$D9,$DA,$E2,$E3,$E4,$E5,
$E6,$E7,$E8,$E9,$EA,$F2,$F3,$F4,$F5,$F6,$F7,$F8,$F9,$FA
);
// End DHT default
{$ENDIF} // MJPGDHTSEG_STORAGE
{$ENDIF} // NOJPEGDIB
//////////////////////////////////////////////////////////////////////////
//
// Defined IC types
{$IFNDEF NONEWIC}
const
ICTYPE_VIDEO = FOURCC(byte(AnsiChar('v')) or
(byte(AnsiChar('i')) shl 8) or
(byte(AnsiChar('d')) shl 16) or
(byte(AnsiChar('c')) shl 24)
);
ICTYPE_AUDIO = FOURCC(byte(AnsiChar('a')) or
(byte(AnsiChar('u')) shl 8) or
(byte(AnsiChar('d')) shl 16) or
(byte(AnsiChar('c')) shl 24)
);
{$ENDIF} // NONEWIC
// Misc. FOURCC registration
{* Sierra Semiconductor: RDSP- Confidential RIFF file format
// for the storage and downloading of DSP
// code for Audio and communications devices.
*}
const
FOURCC_RDSP = FOURCC(byte(AnsiChar('R')) or
(byte(AnsiChar('D')) shl 8) or
(byte(AnsiChar('S')) shl 16) or
(byte(AnsiChar('P')) shl 24)
);
{$PACKRECORDS DEFAULT} // {#include "poppack.h" /* Revert to default packing */ }
implementation
end.
|
//Ejercicio 9
//Escriba proposiciones CASE equivalentes a la siguientes proposiciones IF:
//a)
{IF k = 0 THEN
r := r + 1
ELSE
IF k = 1 THEN
s := s + 1
ELSE
IF (k = 2) OR (k = 3) OR (k = 4) THEN
t := t + 2}
{program ejercicio9;
var k, r, s, t : integer;
begin
r:= 1;
s:= 1;
t:= 1;
case k of
0 : r:= r + 1;
1 : s:= s + 1;
2, 3, 4 : t := t + 2;
end;
end.}
//b)
{IF (calif = 'D') OR (calif = 'F') THEN
WriteLn ('Trabajo deficiente.')
ELSE
IF (calif = 'C') OR (calif = 'B') THEN
WriteLn ('Buen trabajo.')
ELSE IF calif = 'A' THEN
WriteLn ('Trabajo excelente.')}
//c) ¿Qué sucede en su sistema cuando se ejecuta el siguiente segmento de código?
{ val := 3;
CASE val OF
1: WriteLn ('uno');
2: WriteLn ('dos')
END;
WriteLn ('Despues del CASE');} |
unit IntelHex;
interface
uses SysUtils, Windows, Math;
const
DataRecord = $00;
EofRecord = $01;
ExtSegAddrRecord = $02; // pas implémenté
StartSegAddrRecord = $03; // pas implémenté
ExtLinAddrRecord = $04; // pas implémenté
StartLinAddrRecord = $05; // pas implémenté
{$A-}
Type
TIntelHexRec = record
RecLen : byte;
Offset : word;
RecType : byte;
Data : array[0..255+1] of byte;
end;
{$A+}
Type
TIntelHex = class(Tobject)
function ASCII2Byte(S : String) : byte;
procedure Str2IntelHexRec(S : string; var Rec : TIntelHexRec);
procedure CopyToBuffer(Buffer : PByteArray; BufferSize : word);
constructor Create(FName : string);
destructor Destroy; override;
procedure GotError(ProcName, Msg : string);
private
f : TextFile;
fBinSize : word;
published
property BinSize : word read fBinSize;
end;
implementation
// Conversion de 2 nibbles texte en byte
function TIntelHex.ASCII2Byte(S : string) : byte;
Const
HEXA = '0123456789ABCDEF';
begin
If Length(S) <> 2 then GotError('ASCII2Byte', S);
Result := 16*pred(Pos(S[1], HEXA))+pred(Pos(S[2], HEXA));
end;
// Conversion d'un bloc IntelHEX dans un Buffer
procedure TIntelHex.Str2IntelHexRec(S : string; var Rec : TIntelHexRec);
var
i : word;
P : ^TByteArray;
ChkSum : byte;
begin
P := @Rec.RecLen;
S := Trim(S);
If Length(S)=0 then GotError('Str2IntelRec', 'vide');
If S[1] <> ':' then GotError('Str2IntelRec', '":" manque"'+S+'"');
Delete(S, 1, 1);
If Length(S)=0 then GotError('Str2IntelRec', 'vide');
If Pos(':', S)<>0 then GotError('Str2IntelRec', '":" double"'+S+'"');
If (Length(S) mod 2) <> 0 then GotError('Str2IntelRec', 'impaire"'+S+'"');
If (Length(S) div 2) > SizeOf(Rec) then GotError('Str2IntelRec', 'trop grand"'+S+'"');
i := 0;
while i<Length(S) do begin { Conversion du block en Bin}
P^[i div 2] := ASCII2Byte(Copy(S, succ(i), 2));
Inc(i, 2);
end;
With Rec do begin
ChkSum := RecLen+Lo(Offset)+Hi(Offset)+RecType;
for i := 0 to RecLen do ChkSum := ChkSum+Data[i];
If ChkSum<>0 then GotError('Str2IntelRec', 'ChkSum"'+S+'"');
end;
Rec.Offset:= Swap(Rec.Offset);
end;
constructor TIntelHEX.Create(FName : String);
var
S : string;
Rec : TIntelHexRec;
begin
inherited Create;
fBinSize := 0;
AssignFile(f, FName);
Reset(f);
While Not Eof(f) do begin
ReadLn(f, S);
Str2IntelHexRec(S, Rec);
With Rec do
Case RecType of
DataRecord : if Offset+RecLen<2*1024 then fBinSize := Max(fBinSize, Offset+RecLen+1);
EofRecord : ;
else
GotError('Create', 'Rec="'+S+
'" RecLen='+IntToHex(RecLen, 2)+
' Offset='+IntToHex(Offset, 4)+
' RecType='+IntToHex(RecType, 2));
end;
end;
end;
procedure TIntelHex.CopyToBuffer(Buffer : PByteArray; BufferSize : Word);
var
S : string;
Rec : TIntelHexRec;
i : word;
begin
Reset(f);
FillChar(Buffer^ , BufferSize, #0);
While Not Eof(f) do begin
ReadLn(f, S);
Str2IntelHexRec(S, Rec);
With Rec do
Case RecType of
DataRecord : if Offset+RecLen<BufferSize then
System.Move(Data, Buffer^[Offset], RecLen);
EofRecord : ;
else
GotError('CopyToBuffer', 'Rec="'+S+
'" RecLen='+IntToHex(RecLen, 2)+
' Offset='+IntToHex(Offset, 4)+
' RecType='+IntToHex(RecType, 2));
end;
// GotError(IntToHex(rec.Offset, 4), IntToHex(Buffer^[0], 2)+IntToHex(Buffer^[1], 2));
end;
end;
destructor TIntelHEX.Destroy;
begin
CloseFile(f);
inherited Destroy;
end;
procedure TIntelHex.GotError(ProcName, Msg : string);
begin
MessageBox(0, PChar(ProcName+':'+Msg), 'IntelHex', MB_OK+MB_ICONERROR);
end;
end.
|
program PhysicalMemArrayInfo;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Classes, SysUtils, uSMBIOS
{ you can add units after this };
procedure GetPhysicalMemArrayInfo;
Var
SMBios: TSMBios;
LPhysicalMemArr: TPhysicalMemoryArrayInformation;
begin
SMBios:=TSMBios.Create;
try
WriteLn('Physical Memory Array Information');
WriteLn('--------------------------------');
if SMBios.HasPhysicalMemoryArrayInfo then
for LPhysicalMemArr in SMBios.PhysicalMemoryArrayInfo do
begin
WriteLn('Location '+LPhysicalMemArr.GetLocationStr);
WriteLn('Use '+LPhysicalMemArr.GetUseStr);
WriteLn('Error Correction '+LPhysicalMemArr.GetErrorCorrectionStr);
if LPhysicalMemArr.RAWPhysicalMemoryArrayInformation^.MaximumCapacity<>$80000000 then
WriteLn(Format('Maximum Capacity %d Kb',[LPhysicalMemArr.RAWPhysicalMemoryArrayInformation^.MaximumCapacity]))
else
WriteLn(Format('Maximum Capacity %d bytes',[LPhysicalMemArr.RAWPhysicalMemoryArrayInformation^.ExtendedMaximumCapacity]));
WriteLn(Format('Memory devices %d',[LPhysicalMemArr.RAWPhysicalMemoryArrayInformation^.NumberofMemoryDevices]));
WriteLn;
end
else
Writeln('No Physical Memory Array Info was found');
finally
SMBios.Free;
end;
end;
begin
try
GetPhysicalMemArrayInfo;
except
on E:Exception do
Writeln(E.Classname, ':', E.Message);
end;
Writeln('Press Enter to exit');
Readln;
end.
|
unit PathUtils;
interface
uses SysUtils, Classes, StrUtils;
function AbsolutePathToRelative(const CurrentDir, Path: string): string;
function RelativePathToAbsolute(const CurrentDir, Path: string): string;
implementation
procedure SplitPath(const Path: string; out Parts: TStringList);
begin
Parts.Clear;
Parts.StrictDelimiter := True;
Parts.Delimiter := '\';
Parts.DelimitedText := Path;
end;
function MergePath(Parts: TStringList; PatDelimiter: Char = '\'): string;
begin
Parts.StrictDelimiter := True;
Parts.Delimiter := PatDelimiter;
Result := Parts.DelimitedText;
end;
(*------------------------------------------------------------------------------
Converts Path to relative path according to CurrentDir
For ezmple, for
CurrentDir = 'C:\Temp\Dir1\Dir2'
Path = 'C:\Temp\Dir3\Dir4'
result will be
'..\..\Dir3\Dir4'
@param CurrentDir
@param Path
@return relative path
------------------------------------------------------------------------------*)
function AbsolutePathToRelative(const CurrentDir, Path: string): string;
var
CurrentDirParts: TStringList;
PathParts: TStringList;
begin
Result := Path;
if Length(Path) = 0 then
Exit;
CurrentDirParts := TStringList.Create;
try
SplitPath(CurrentDir, CurrentDirParts);
PathParts := TStringList.Create;
try
SplitPath(Path, PathParts);
if not ((PathParts.Count > 0) and (CurrentDirParts.Count > 0) and
AnsiSameText(PathParts[0], CurrentDirParts[0])) then
Exit;
while ((PathParts.Count > 0) and (CurrentDirParts.Count > 0) and
AnsiSameText(PathParts[0], CurrentDirParts[0])) do begin
PathParts.Delete(0);
CurrentDirParts.Delete(0);
end;
Result := DupeString('..\', CurrentDirParts.Count) + MergePath(PathParts);
finally
FreeAndNil(PathParts);
end;
finally
FreeAndNil(CurrentDirParts);
end;
end;
(*------------------------------------------------------------------------------
Converts relative Path to absolute according to CurrentDir
For ezmple, for
CurrentDir = 'C:\Temp\Dir1\Dir2'
Path = '..\..\Dir3\Dir4'
result will be
'C:\Temp\Dir3\Dir4'
@param CurrentDir
@param Path
@return absolute path
------------------------------------------------------------------------------*)
function RelativePathToAbsolute(const CurrentDir, Path: string): string;
var
CurrentDirParts: TStringList;
PathParts: TStringList;
begin
Result := Path;
if Length(Path) = 0 then
Exit;
CurrentDirParts := TStringList.Create;
try
SplitPath(CurrentDir, CurrentDirParts);
if Path[1] = '\' then begin
Result := CurrentDirParts[0] + Path;
end
else if (Length(Path) > 3) and (Copy(Path, 1, 3) = '..\') then begin
PathParts := TStringList.Create;
try
SplitPath(Path, PathParts);
while (PathParts.Count > 0) and (CurrentDirParts.Count > 0) and
(PathParts[0] = '..') do begin
PathParts.Delete(0);
CurrentDirParts.Delete(CurrentDirParts.Count - 1);
end;
Result := MergePath(CurrentDirParts) + '\' + MergePath(PathParts);
finally
FreeAndNil(PathParts);
end;
end;
finally
FreeAndNil(CurrentDirParts);
end;
end;
end.
|
unit vr_transport;
{$mode delphi}{$H+}
interface
uses
Classes, SysUtils, vr_utils;
type
TTransportReadEvent = procedure(const AMsg: string; const AClient: Pointer;
const AThread: TThread) of object;
TTransportServerConnectionEvent = procedure(const AClient: Pointer) of object;
{ TCustomTransport }
TCustomTransport = class
private
FNextId: PtrInt;
FOnReceive: TTransportReadEvent;
FUseContentLengthField: Boolean;
FUnDoneMsg: string;
function CheckSendedText(const AMsg: string): string;
function GetNextReceivedMsg(var AReceivedText: string; out AMsg: string): Boolean;
protected
procedure DoReceive(const AMsg: string; const AClient: Pointer; const AThread: TThread);
procedure DoSend(const AMsg: string; const AClient: Pointer = nil); virtual; abstract;
public
constructor Create(const AUseContentLengthField: Boolean = False); virtual;
//if AClient=nil send all clients; if not Server then AClient ignore
procedure Send(const AMsg: string; const AClient: Pointer = nil); virtual;
function NextId: string;
function NextIdAsInt: PtrInt;
property UseContentLengthField: Boolean read FUseContentLengthField
write FUseContentLengthField default False;
property OnReceive: TTransportReadEvent read FOnReceive write FOnReceive;
end;
{ TCustomTransportClient }
TCustomTransportClient = class(TCustomTransport)
private
FOnDisconnect: TNotifyEvent;
protected
function DoConnect: Boolean; virtual;
function DoDisconnect: Boolean; virtual;
public
function Connect: Boolean; //virtual;
function DisConnect: Boolean; //virtual;
property OnDisconnect: TNotifyEvent read FOnDisconnect write FOnDisconnect;
end;
{ TCustomTransportServer }
TCustomTransportServer = class(TCustomTransport)
private
FOnConnect: TTransportServerConnectionEvent;
FOnDisconnect: TTransportServerConnectionEvent;
protected
FClients: TThreadList;
procedure DoAddConnection(const AClient: Pointer); virtual;
procedure DoRemoveConnection(const AClient: Pointer); virtual;
function GetAlive: Boolean; virtual;
function GetClientCount: Integer; //virtual;
public
constructor Create(const AUseContentLengthField: Boolean = False); override;
destructor Destroy; override;
function GetClient(const AIndex: Integer; out AClient: Pointer): Boolean;
property Alive: Boolean read GetAlive;
property ClientCount: Integer read GetClientCount;
property OnConnect: TTransportServerConnectionEvent
read FOnConnect write FOnConnect;
property OnDisconnect: TTransportServerConnectionEvent
read FOnDisconnect write FOnDisconnect;
end;
implementation
const
SEP_HEADERS = #13#10#13#10;
{ TCustomTransportServer }
function TCustomTransportServer.GetClientCount: Integer;
var
lst: TList;
begin
lst := FClients.LockList;
try
Result := lst.Count;
finally
FClients.UnlockList;
end;
end;
constructor TCustomTransportServer.Create(const AUseContentLengthField: Boolean);
begin
inherited Create(AUseContentLengthField);
FClients := TThreadList.Create;
end;
destructor TCustomTransportServer.Destroy;
begin
FreeAndNil(FClients);
inherited Destroy;
end;
function TCustomTransportServer.GetAlive: Boolean;
begin
Result := False;
end;
procedure TCustomTransportServer.DoAddConnection(const AClient: Pointer);
begin
FClients.Add(AClient);
if Assigned(FOnConnect) then
FOnConnect(AClient);
end;
procedure TCustomTransportServer.DoRemoveConnection(const AClient: Pointer);
begin
FClients.Remove(AClient);
if Assigned(FOnDisconnect) then
FOnDisconnect(AClient);
end;
function TCustomTransportServer.GetClient(const AIndex: Integer; out
AClient: Pointer): Boolean;
var
lst: TList;
begin
lst := FClients.LockList;
try
Result := (AIndex >= 0) and (AIndex < lst.Count);
if Result then
AClient := lst[AIndex]
else
AClient := nil;
finally
FClients.UnlockList;
end;
end;
{ TCustomTransportClient }
function TCustomTransportClient.DoConnect: Boolean;
begin
Result := False;
end;
function TCustomTransportClient.DoDisconnect: Boolean;
begin
Result := True;
end;
function TCustomTransportClient.Connect: Boolean;
begin
Result := DoConnect;
end;
function TCustomTransportClient.DisConnect: Boolean;
begin
Result := DoDisconnect;
if Result and Assigned(FOnDisconnect) then
FOnDisconnect(Self);
end;
{ TCustomTransport }
function TCustomTransport.CheckSendedText(const AMsg: string): string;
begin
if FUseContentLengthField then
Result := 'Content-Length: ' + IntToStr(Length(AMsg) + 2) + SEP_HEADERS + AMsg + #13#10
else
Result := AMsg;
end;
function TCustomTransport.GetNextReceivedMsg(var AReceivedText: string; out AMsg: string): Boolean;
var
S, sHeader: String;
i: SizeInt;
n: integer;
begin
if AReceivedText = '' then Exit(False);
try
if UseContentLengthField then
begin
Result := False;
if FUnDoneMsg <> '' then
begin
AReceivedText := FUnDoneMsg + AReceivedText;
FUnDoneMsg := '';
end;
//else
// AReceivedText := AReceivedText;
//repeat
i := Pos(SEP_HEADERS, AReceivedText); //'Content-Length: 573'#13#10#13#10'{"seq":0,...}'
if i > 0 then
begin
S := Copy(AReceivedText, 1, i - 1);
Inc(i, Length(SEP_HEADERS));
repeat
NameValueOfString(S, sHeader{%H-}, S, #13#10);
if sHeader = '' then Break;
if (CompareText(NameOfString(sHeader, ':'), 'Content-Length') = 0) then
begin
//S := '';
if TryStrToInt(ValueOfString(sHeader, ':'), n) and
(n <= (Length(AReceivedText) - i + 1)) then
begin
AMsg := Copy(AReceivedText, i, n);
AReceivedText := Copy(AReceivedText, i + n, MaxInt);
end;
Break;
end;
until (S = '');
if AMsg <> '' then
Exit(True);
//if S <> '' then
// begin
// OnRead(S);
// Continue;
// end;
end;
FUnDoneMsg := AReceivedText;
AReceivedText := '';
// Break;
//until False;
end
else
begin
AMsg := AReceivedText;
AReceivedText := '';
Result := True;
end;
except
//{$IFDEF TEST_MODE}Beep;{$ENDIF}
end;
end;
procedure TCustomTransport.DoReceive(const AMsg: string;
const AClient: Pointer; const AThread: TThread);
var
sMsg, S: String;
begin
if (AMsg = '') or not Assigned(FOnReceive) then Exit;
sMsg := AMsg;
while GetNextReceivedMsg(sMsg, S) do
FOnReceive(S, AClient, AThread);
end;
constructor TCustomTransport.Create(const AUseContentLengthField: Boolean);
begin
FNextId := 1;
FUseContentLengthField := AUseContentLengthField;
end;
procedure TCustomTransport.Send(const AMsg: string; const AClient: Pointer);
begin
DoSend(CheckSendedText(AMsg), AClient);
end;
function TCustomTransport.NextId: string;
begin
Result := IntToStr(FNextId);
Inc(FNextId);
end;
function TCustomTransport.NextIdAsInt: PtrInt;
begin
Result := FNextId;
Inc(FNextId);
end;
end.
|
unit BaseSearch;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BasePopup, Data.DB, Vcl.StdCtrls,
Vcl.Grids, Vcl.DBGrids, RzDBGrid, Vcl.Mask, RzEdit, RzLabel,
Vcl.Imaging.pngimage, Vcl.ExtCtrls, RzPanel, RzButton;
type
TfrmBaseSearch = class(TfrmBasePopup)
RzLabel2: TRzLabel;
edSearchKey: TRzEdit;
grSearch: TRzDBGrid;
pnlSearch: TRzPanel;
pnlSelect: TRzPanel;
btnSelect: TRzShapeButton;
pnlNew: TRzPanel;
btnNew: TRzShapeButton;
pnlCancel: TRzPanel;
btnCancel: TRzShapeButton;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnNewClick(Sender: TObject);
procedure grSearchDblClick(Sender: TObject);
procedure edSearchKeyChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnSelectClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
procedure EnableControls;
protected
{ Public declarations }
procedure SearchList; virtual; abstract;
procedure SetReturn; virtual; abstract;
procedure Add; virtual; abstract;
procedure Cancel; virtual; abstract;
end;
implementation
{$R *.dfm}
procedure TfrmBaseSearch.btnNewClick(Sender: TObject);
begin
inherited;
Add;
EnableControls;
end;
procedure TfrmBaseSearch.btnSelectClick(Sender: TObject);
begin
inherited;
ModalResult := mrOk;
end;
procedure TfrmBaseSearch.edSearchKeyChange(Sender: TObject);
begin
SearchList;
end;
procedure TfrmBaseSearch.FormClose(Sender: TObject; var Action: TCloseAction);
begin
inherited;
if ModalResult = mrOK then
begin
if grSearch.DataSource <> nil then
if grSearch.DataSource.DataSet <> nil then
begin
SetReturn;
grSearch.DataSource.DataSet.Close;
end;
end;
// remove any filters
grSearch.DataSource.DataSet.Filter := '';
end;
procedure TfrmBaseSearch.FormCreate(Sender: TObject);
begin
inherited;
if grSearch.DataSource <> nil then
if grSearch.DataSource.DataSet <> nil then
begin
grSearch.DataSource.DataSet.Open;
EnableControls;
end;
end;
procedure TfrmBaseSearch.FormKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then ModalResult := mrOK;
inherited;
end;
procedure TfrmBaseSearch.grSearchDblClick(Sender: TObject);
begin
inherited;
if grSearch.DataSource.DataSet.RecordCount > 0 then
ModalResult := mrOK;
end;
procedure TfrmBaseSearch.btnCancelClick(Sender: TObject);
begin
inherited;
ModalResult := mrCancel;
end;
procedure TfrmBaseSearch.EnableControls;
begin
btnSelect.Enabled := grSearch.DataSource.DataSet.RecordCount > 0;
end;
end.
|
unit Ntapi.ntpebteb;
{$MINENUMSIZE 4}
interface
uses
Winapi.WinNt, Ntapi.ntdef, Ntapi.ntrtl;
type
TPebLdrData = record
Length: Cardinal;
Initialized: Boolean;
SsHandle: THandle;
InLoadOrderModuleList: TListEntry;
InMemoryOrderModuleList: TListEntry;
InInitializationOrderModuleList: TListEntry;
EntryInProgress: Pointer;
ShutdownInProgress: Boolean;
ShutdownThreadId: NativeUInt;
end;
PPebLdrData = ^TPebLdrData;
TPeb = record
InheritedAddressSpace: Boolean;
ReadImageFileExecOptions: Boolean;
BeingDebugged: Boolean;
BitField: Boolean;
Mutant: THandle;
ImageBaseAddress: Pointer;
Ldr: PPebLdrData;
ProcessParameters: PRtlUserProcessParameters;
SubSystemData: Pointer;
ProcessHeap: Pointer;
FastPebLock: Pointer; // WinNt.PRTL_CRITICAL_SECTION
AtlThunkSListPtr: Pointer; // WinNt.PSLIST_HEADER
IFEOKey: Pointer;
CrossProcessFlags: Cardinal;
UserSharedInfoPtr: Pointer;
SystemReserved: Cardinal;
AtlThunkSListPtr32: Cardinal;
ApiSetMap: Pointer; // ntpebteb.PAPI_SET_NAMESPACE
TlsExpansionCounter: Cardinal;
TlsBitmap: Pointer;
TlsBitmapBits: array [0..1] of Cardinal;
ReadOnlySharedMemoryBase: Pointer;
SharedData: Pointer; // HotpatchInformation
ReadOnlyStaticServerData: PPointer;
AnsiCodePageData: Pointer; // PCPTABLEINFO
OemCodePageData: Pointer; // PCPTABLEINFO
UnicodeCaseTableData: Pointer; // PNLSTABLEINFO
NumberOfProcessors: Cardinal;
NtGlobalFlag: Cardinal;
CriticalSectionTimeout: TULargeInteger;
HeapSegmentReserve: NativeUInt;
HeapSegmentCommit: NativeUInt;
HeapDeCommitTotalFreeThreshold: NativeUInt;
HeapDeCommitFreeBlockThreshold: NativeUInt;
NumberOfHeaps: Cardinal;
MaximumNumberOfHeaps: Cardinal;
ProcessHeaps: PPointer; // PHEAP
GdiSharedHandleTable: Pointer;
ProcessStarterHelper: Pointer;
GdiDCAttributeList: Cardinal;
LoaderLock: Pointer; // WinNt.PRTL_CRITICAL_SECTION
OSMajorVersion: Cardinal;
OSMinorVersion: Cardinal;
OSBuildNumber: Word;
OSCSDVersion: Word;
OSPlatformId: Cardinal;
ImageSubsystem: Cardinal;
ImageSubsystemMajorVersion: Cardinal;
ImageSubsystemMinorVersion: Cardinal;
ActiveProcessAffinityMask: NativeUInt;
{$IFNDEF WIN64}
GdiHandleBuffer: array [0 .. 33] of Cardinal;
{$ELSE}
GdiHandleBuffer: array [0 .. 59] of Cardinal;
{$ENDIF}
PostProcessInitRoutine: Pointer;
TlsExpansionBitmap: Pointer;
TlsExpansionBitmapBits: array [0..31] of Cardinal;
SessionId: Cardinal;
AppCompatFlags: TULargeInteger;
AppCompatFlagsUser: TULargeInteger;
pShimData: Pointer;
AppCompatInfo: Pointer; // APPCOMPAT_EXE_DATA
CSDVersion: UNICODE_STRING;
ActivationContextData: Pointer; // ACTIVATION_CONTEXT_DATA
ProcessAssemblyStorageMap: Pointer; // ASSEMBLY_STORAGE_MAP
SystemDefaultActivationContextData: Pointer; // ACTIVATION_CONTEXT_DATA
SystemAssemblyStorageMap: Pointer; // ASSEMBLY_STORAGE_MAP
MinimumStackCommit: NativeUInt;
FlsCallback: PPointer;
FlsListHead: TListEntry;
FlsBitmap: Pointer;
FlsBitmapBits: array [0..3] of Cardinal;
FlsHighIndex: Cardinal;
WerRegistrationData: Pointer;
WerShipAssertPtr: Pointer;
pUnused: Pointer; // pContextData
pImageHeaderHash: Pointer;
TracingFlags: Cardinal;
CsrServerReadOnlySharedMemoryBase: UInt64;
TppWorkerpListLock: Pointer; // WinNt.PRTL_CRITICAL_SECTION
TppWorkerpList: TListEntry;
WaitOnAddressHashTable: array [0..127] of Pointer;
TelemetryCoverageHeader: Pointer; // REDSTONE3
CloudFileFlags: Cardinal;
CloudFileDiagFlags: Cardinal; // REDSTONE4
PlaceholderCompatibilityMode: Byte;
PlaceholderCompatibilityModeReserved: array [0..6] of Byte;
LeapSecondData: Pointer; // *_LEAP_SECOND_DATA; // REDSTONE5
LeapSecondFlags: Cardinal;
NtGlobalFlag2: Cardinal;
end;
PPeb = ^TPeb;
TActivationContextStack = record
ActiveFrame: Pointer;
FrameListCache: TListEntry;
Flags: Cardinal;
NextCookieSequenceNumber: Cardinal;
StackId: Cardinal;
end;
PActivationContextStack = ^TActivationContextStack;
TGdiTebBatch = record
Offset: Cardinal;
HDC: NativeUInt;
Buffer: array [0..309] of Cardinal;
end;
PNtTib = ^TNtTib;
TNtTib = record
ExceptionList: Pointer;
StackBase: Pointer;
StackLimit: Pointer;
SubSystemTib: Pointer;
FiberData: Pointer;
ArbitraryUserPointer: Pointer;
Self: PNtTib;
end;
TTeb = record
NtTib: TNtTib;
EnvironmentPointer: Pointer;
ClientId: TClientId;
ActiveRpcHandle: Pointer;
ThreadLocalStoragePointer: Pointer;
ProcessEnvironmentBlock: PPeb;
LastErrorValue: Cardinal;
CountOfOwnedCriticalSections: Cardinal;
CsrClientThread: Pointer;
Win32ThreadInfo: Pointer;
User32Reserved: array [0..25] of Cardinal;
UserReserved: array [0..4] of Cardinal;
WOW32Reserved: Pointer;
CurrentLocale: Cardinal;
FpSoftwareStatusRegister: Cardinal;
ReservedForDebuggerInstrumentation: array [0..15] of Pointer;
{$IFDEF WIN64}
SystemReserved1: array [0..29] of Pointer;
{$ELSE}
SystemReserved1: array [0..25] of Pointer;
{$ENDIF}
PlaceholderCompatibilityMode: ShortInt;
PlaceholderReserved: array [0..10] of ShortInt;
ProxiedProcessId: Cardinal;
ActivationStack: TActivationContextStack;
WorkingOnBehalfTicket: array [0..7] of Byte;
ExceptionCode: NTSTATUS;
ActivationContextStackPointer: PActivationContextStack;
InstrumentationCallbackSp: NativeUInt;
InstrumentationCallbackPreviousPc: NativeUInt;
InstrumentationCallbackPreviousSp: NativeUInt;
{$IFDEF WIN64}
TxFsContext: Cardinal;
{$ENDIF}
InstrumentationCallbackDisabled: Boolean;
{$IFNDEF WIN64}
SpareBytes: array [0..22] of Byte;
TxFsContext: Cardinal;
{$ENDIF}
GdiTebBatch: TGdiTebBatch;
RealClientId: TClientId;
GdiCachedProcessHandle: THandle;
GdiClientPID: Cardinal;
GdiClientTID: Cardinal;
GdiThreadLocalInfo: Pointer;
Win32ClientInfo: array [0..61] of NativeUInt;
glDispatchTable: array [0..232] of Pointer;
glReserved1: array [0..28] of NativeUInt;
glReserved2: Pointer;
glSectionInfo: Pointer;
glSection: Pointer;
glTable: Pointer;
glCurrentRC: Pointer;
glContext: Pointer;
LastStatusValue: NTSTATUS;
StaticUnicodeString: UNICODE_STRING;
StaticUnicodeBuffer: array [0..260] of WideChar;
DeallocationStack: Pointer;
TlsSlots: array [0..63] of Pointer;
TlsLinks: TListEntry;
Vdm: Pointer;
ReservedForNtRpc: Pointer;
DbgSsReserved: array [0..1] of Pointer;
HardErrorMode: Cardinal;
{$IFDEF WIN64}
Instrumentation: array [0..10] of Pointer;
{$ELSE}
Instrumentation: array [0..8] of Pointer;
{$ENDIF}
ActivityId: TGuid;
SubProcessTag: Pointer;
PerflibData: Pointer;
EtwTraceData: Pointer;
WinSockData: Pointer;
GdiBatchCount: Cardinal;
IdealProcessorValue: Cardinal;
GuaranteedStackBytes: Cardinal;
ReservedForPerf: Pointer;
ReservedForOle: Pointer;
WaitingOnLoaderLock: Cardinal;
SavedPriorityState: Pointer;
ReservedForCodeCoverage: NativeUInt;
ThreadPoolData: Pointer;
TlsExpansionSlots: PPointer;
{$IFDEF WIN64}
DeallocationBStore: Pointer;
BStoreLimit: Pointer;
{$ENDIF}
MuiGeneration: Cardinal;
IsImpersonating: LongBool;
NlsCache: Pointer;
pShimData: Pointer;
HeapVirtualAffinity: Word;
LowFragHeapDataSlot: Word;
CurrentTransactionHandle: THandle;
ActiveFrame: Pointer;
FlsData: Pointer;
PreferredLanguages: Pointer;
UserPrefLanguages: Pointer;
MergedPrefLanguages: Pointer;
MuiImpersonation: Cardinal;
CrossTebFlags: Word;
SameTebFlags: Word;
TxnScopeEnterCallback: Pointer;
TxnScopeExitCallback: Pointer;
TxnScopeContext: Pointer;
LockCount: Cardinal;
WowTebOffset: Integer;
ResourceRetValue: Pointer;
ReservedForWdf: Pointer;
ReservedForCrt: Int64;
EffectiveContainerId: TGuid;
end;
PTeb = ^TTeb;
function RtlGetCurrentPeb: PPeb; stdcall; external ntdll;
procedure RtlAcquirePebLock; stdcall; external ntdll;
procedure RtlReleasePebLock; stdcall; external ntdll;
function RtlTryAcquirePebLock: LongBool stdcall; external ntdll;
function NtCurrentTeb: PTeb;
{$IFDEF Win32}
function RtlIsWoW64: Boolean;
{$ENDIF}
implementation
{$IFDEF WIN64}
function NtCurrentTeb: PTeb;
asm
mov rax, gs:[$0030]
end;
{$ENDIF}
{$IFDEF WIN32}
function NtCurrentTeb: PTeb;
asm
mov eax, fs:[$0018]
end;
{$ENDIF}
{$IFDEF Win32}
function RtlIsWoW64: Boolean;
begin
Result := NtCurrentTeb.WowTebOffset <> 0;
end;
{$ENDIF}
end.
|
inherited fObfuscateSettings: TfObfuscateSettings
Width = 275
Height = 271
Font.Charset = ANSI_CHARSET
Font.Height = -15
Font.Name = 'Segoe UI'
ParentFont = False
object cbRemoveWhiteSpace: TCheckBox
Left = 8
Top = 160
Width = 169
Height = 17
Caption = 'Remove &white space'
Checked = True
State = cbChecked
TabOrder = 2
end
object cbRemoveComments: TCheckBox
Left = 8
Top = 180
Width = 169
Height = 17
Caption = 'Remove c&omments'
Checked = True
State = cbChecked
TabOrder = 3
end
object rgObfuscateCaps: TRadioGroup
Left = 8
Top = 38
Width = 169
Height = 108
Caption = 'Obfuscate word &caps'
ItemIndex = 0
Items.Strings = (
'ALL CAPITALS'
'all lowercase'
'Mixed Case'
'Leave alone')
TabOrder = 1
end
object cbRebreak: TCheckBox
Left = 8
Top = 220
Width = 169
Height = 17
Caption = 'Rebreak &lines'
Checked = True
State = cbChecked
TabOrder = 5
end
object cbRemoveIndent: TCheckBox
Left = 8
Top = 200
Width = 169
Height = 17
Caption = 'Remove &indent'
Checked = True
State = cbChecked
TabOrder = 4
end
object cbEnabled: TCheckBox
Left = 8
Top = 8
Width = 169
Height = 17
Caption = '&Obfuscate mode'
TabOrder = 0
end
end
|
unit Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, SuperObject, Vcl.StdCtrls, Vcl.ComCtrls,
Vcl.ExtCtrls, Vcl.Buttons, Vcl.Controls, Vcl.Forms, IdHTTP, DateUtils, IdURI,
TrayIcon, Vcl.Menus;
type
TTaskInfo = record
taskid: Integer;
resvdate: TDateTime;
starttime: string;
stoptime: string;
timer: TDateTime;
partid: string;
roomid: Integer;
done: Integer; //0 未提交 1 提交中 2 已成
faild: Integer;
errors: TStrings;
end;
PTask = ^TTaskInfo;
type
TRP = record
response: TIdHttpResponse;
resptext: string;
requesturl: string;
task: PTask;
success: boolean;
end;
type
TCallback = procedure(resp: TRP) of object;
type
TQrec = record
isPost: boolean;
url: string;
data: string;
task: PTask;
timeout: Integer;
callback: TCallback;
end;
type
TQ = record
count: Integer;
list: array [0 .. 32] of TQrec;
end;
type
Config = record
RefreshSec: Integer;
RefreshTry: Integer;
ShutdownSec: Integer;
TimeTry: Integer;
Shutdown: Boolean;
SendSMS: Boolean;
Timeout: Integer;
end;
type
TfrmMain = class(TForm)
logBtn: TBitBtn;
id: TEdit;
pwd: TEdit;
Label1: TLabel;
Label2: TLabel;
roomlist: TListBox;
btnresv: TBitBtn;
datepic: TDateTimePicker;
edfrom: TEdit;
edto: TEdit;
Label3: TLabel;
Label4: TLabel;
statusbar: TStatusBar;
timer: TTimer;
btntimer: TBitBtn;
btnRefresh: TBitBtn;
timerdate: TDateTimePicker;
statusbar2: TStatusBar;
Label6: TLabel;
edid: TEdit;
errlist: TListBox;
Label5: TLabel;
cfgtry: TEdit;
cbsms: TCheckBox;
pgctrl: TPageControl;
rsvtab: TTabSheet;
logtab: TTabSheet;
log: TMemo;
btnpause: TBitBtn;
lv: TListView;
timerhour: TEdit;
timermin: TEdit;
timersec: TEdit;
Label7: TLabel;
Label8: TLabel;
shuttimer: TTimer;
cfgrefsec: TEdit;
Label9: TLabel;
cfgref: TEdit;
Label10: TLabel;
cfgshut: TEdit;
Label11: TLabel;
GroupBox1: TGroupBox;
cbshut: TCheckBox;
tray: TTrayIcon;
mytab: TTabSheet;
myrsv: TListView;
delmenu: TPopupMenu;
N1: TMenuItem;
cfgtimeout: TEdit;
Label12: TLabel;
btnrefresv: TBitBtn;
tasklist: TListView;
procedure logBtnClick(Sender: TObject);
procedure roomlistClick(Sender: TObject);
procedure btnresvClick(Sender: TObject);
procedure idHttpRedirect(Sender: TObject; var dest: string;
var NumRedirect: Integer; var Handled: boolean; var VMethod: string);
procedure FormCreate(Sender: TObject);
procedure btntimerClick(Sender: TObject);
procedure timerTimer(Sender: TObject);
procedure btnRefreshClick(Sender: TObject);
procedure pwdKeyPress(Sender: TObject; var Key: Char);
procedure idKeyPress(Sender: TObject; var Key: Char);
procedure btnpauseClick(Sender: TObject);
procedure shuttimerTimer(Sender: TObject);
procedure cfgtryKeyPress(Sender: TObject; var Key: Char);
procedure rsvtabEnter(Sender: TObject);
procedure cfgtryChange(Sender: TObject);
procedure cfgrefsecChange(Sender: TObject);
procedure cfgrefChange(Sender: TObject);
procedure cfgshutChange(Sender: TObject);
procedure cbsmsClick(Sender: TObject);
procedure cbshutClick(Sender: TObject);
procedure trayClick(Sender: TObject);
procedure N1Click(Sender: TObject);
procedure cfgtimeoutChange(Sender: TObject);
procedure edfromChange(Sender: TObject);
procedure btnrefresvClick(Sender: TObject);
procedure myrsvColumnClick(Sender: TObject; Column: TListColumn);
procedure myrsvCompare(Sender: TObject; Item1, Item2: TListItem;
Data: Integer; var Compare: Integer);
procedure tasklistClick(Sender: TObject);
procedure myrsvKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
private
procedure Setcookie(r: TIdHttpResponse);
procedure Get(url, data: String; callback: TCallback; tsk: PTask);
procedure Post(url, data: String; callback: TCallback; tsk: PTask;
isPost: boolean = true);
procedure PostResv(tsk: PTask);
procedure logCall(resp: TRP);
procedure listroomCall(resp: TRP);
procedure SMSCall(resp: TRP);
procedure sucCall(resp: TRP);
procedure refCall(resp: TRP);
procedure delCall(resp: TRP);
procedure doRefresh;
procedure SMS();
procedure mincall(Sender: TObject);
public
procedure ListRoom;
procedure status(str: string; islog : boolean = true);
end;
var
frmMain: TfrmMain;
revinfo: ISuperObject;
tsklst: array [0 .. 5] of TTaskInfo;
tqueue: TQ;
fake, cookie: string;
refing: boolean;
function ParaseDateTime(str: string): TDateTime;
function CopyBetween(str, startstr, endstr: string; var left: string): string;
procedure ShutDownComputer;
implementation
{$R *.dfm}
uses
Sched;
var
sthread: schedThread;
cfg: Config;
irefresh, failref, colindex: Integer;
logfail, listfail: Integer;
timediff, shutcount: Integer;
phone, email, username: string;
running: boolean;
function CopyBetween(str, startstr, endstr: string; var left: string): string;
var
i, j: Integer;
begin
i := Pos(startstr, str) + Length(startstr);
j := Pos(endstr, str, i);
result := Copy(str, i, j - i);
left := Copy(str, j + Length(endstr), Length(str)- j - Length(endstr) + 1);
end;
procedure TfrmMain.delCall(resp: TRP);
var
tmp: ISuperObject;
begin
if resp.success then
begin
tmp := SO(resp.resptext);
if tmp['ret'].AsInteger = 1 then
begin
myrsv.Items.Delete(resp.task.taskid);
status('删除成功!');
end
else
begin
status('删除失败:' + tmp['msg'].AsString);
MessageBox(Self.Handle, PChar('删除失败:' + tmp['msg'].AsString), '删除预订', MB_ICONINFORMATION);
end;
end
else
begin
status('删除失败:连接超时');
MessageBox(Self.Handle, '删除失败:连接超时', '删除预订', MB_ICONINFORMATION);
end;
end;
procedure TfrmMain.mincall(Sender: TObject);
begin
frmMain.Hide;
end;
procedure TfrmMain.myrsvColumnClick(Sender: TObject; Column: TListColumn);
begin
colindex := Column.Index;
myrsv.AlphaSort;
end;
procedure TfrmMain.myrsvCompare(Sender: TObject; Item1, Item2: TListItem;
Data: Integer; var Compare: Integer);
var
txt1, txt2: string;
begin
if colindex <> 0 then
begin
txt1 := Item1.SubItems.Strings[colindex - 1];
txt2 := Item2.SubItems.Strings[colindex - 1];
Compare := CompareText(txt1, txt2);
end
else
begin
Compare := CompareText(Item1.Caption, Item2.Caption);
end;
end;
procedure TfrmMain.myrsvKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = 46 then
Self.N1Click(Sender);
end;
procedure TfrmMain.N1Click(Sender: TObject);
var
tmptsk: PTask;
begin
if (pgctrl.Pages[0].Enabled) and (myrsv.ItemIndex >= 0) then
begin
status('正在删除预约');
tmptsk := new(PTask);
tmptsk.taskid := myrsv.ItemIndex;
Get('http://202.120.82.2:8081/ClientWeb/pro/ajax/reserve.aspx',
'act=del_resv&id=' + myrsv.Items.Item[myrsv.ItemIndex].Caption, delCall, tmptsk);
end;
end;
procedure ShutDownComputer;
procedure Get_Shutdown_Privilege; //获得用户关机特权,仅对Windows NT/2000/XP
var
NewState: TTokenPrivileges;
lpLuid: Int64;
ReturnLength: DWord;
ToKenHandle: THandle;
begin
OpenProcessToken(GetCurrentProcess,
TOKEN_ADJUST_PRIVILEGES
OR TOKEN_ALL_ACCESS
OR STANDARD_RIGHTS_REQUIRED
OR TOKEN_QUERY,ToKenHandle);
LookupPrivilegeValue(nil,'SeShutdownPrivilege',lpLuid);
NewState.PrivilegeCount:=1;
NewState.Privileges[0].Luid:=lpLuid;
NewState.Privileges[0].Attributes:=SE_PRIVILEGE_ENABLED;
ReturnLength:=0;
AdjustTokenPrivileges(ToKenHandle,False,NewState,0,nil,ReturnLength);
end;
begin
Get_Shutdown_Privilege;
ExitWindowsEx($00400000,0);
end;
procedure TfrmMain.SMS();
begin
status('正在发送短信');
Get('http://sms.bechtech.cn/Api/send/data/json', 'accesskey=3473&secretkey=d52709fe6280af792e8ea8afa91d1215440288e8&mobile=' + phone + '&content=您已成功预约研究室,感谢使用!【华东师范大学】', SMSCall, nil);
end;
procedure TfrmMain.SMSCall(resp: TRP);
var
res: ISuperObject;
begin
res := SO(resp.resptext);
if res['result'].AsString = '01' then
status('短信发送成功!')
else
status('短信发送失败,错误代码:' + res['result'].AsString);
end;
function ParaseDateTime(str: string): TDateTime;
var
i: Integer;
lst: TStringList;
begin
// Fri, 09 Jan 2015 04:53:16 GMT
lst := TStringList.Create;
i := Pos(' ', str);
str := Copy(str, i, Length(str) - i + 1);
str := StringReplace(str, 'GMT', '', []);
str := StringReplace(str, 'Jan', '01', []);
str := StringReplace(str, 'Feb', '02', []);
str := StringReplace(str, 'Mar', '03', []);
str := StringReplace(str, 'Apr', '04', []);
str := StringReplace(str, 'May', '05', []);
str := StringReplace(str, 'Jun', '06', []);
str := StringReplace(str, 'Jul', '07', []);
str := StringReplace(str, 'Aug', '08', []);
str := StringReplace(str, 'Sep', '09', []);
str := StringReplace(str, 'Oct', '10', []);
str := StringReplace(str, 'Nov', '11', []);
str := StringReplace(str, 'Dec', '12', []);
str := StringReplace(str, ':', ' ', [rfReplaceAll]);
str := Trim(str);
str := str + ' ';
while Pos(' ', str) > 0 do
begin
lst.Add(Copy(str, 0, Pos(' ', str) - 1));
str := Copy(str, Pos(' ', str) + 1, 100);
end;
TryEncodeDateTime(StrToInt(lst[2]), StrToInt(lst[1]), StrToInt(lst[0]), StrToInt(lst[3]), StrToInt(lst[4]), StrToInt(lst[5]), 0, result);
result := IncHour(result, 8);
end;
procedure TfrmMain.refCall(resp: TRP);
var
tmptime: TDateTime;
s, i: ISuperObject;
begin
refing := false;
if resp.success then
begin
status('自动刷新成功');
failref := 0;
tmptime := ParaseDateTime(resp.response.RawHeaders.Values['Date']);
timediff := SecondsBetween(tmptime, now);
if CompareDateTime(now, tmptime) >= 0 then
timediff := -timediff;
myrsv.Items.Clear;
s := SO(resp.resptext);
for i in s['data'] do
with myrsv.Items.Add do
begin
Caption := i.S['id'];
SubItems.Add(i.S['owner']);
SubItems.Add(i.S['members']);
SubItems.Add(i.S['devName']);
SubItems.Add(i.S['start']);
SubItems.Add(i.S['end']);
end;
colindex := 4;
myrsv.AlphaSort;
end
else
begin
Inc(failref);
status('第' + IntToStr(failref) + '次自动刷新失败');
end;
if failref >= cfg.RefreshTry then
begin
Get('http://sms.bechtech.cn/Api/send/data/json', 'accesskey=3473&secretkey=d52709fe6280af792e8ea8afa91d1215440288e8&mobile=' + phone + '&content=您好,在预约研究室时出现错误:连接超时,请您及时处理。【华东师范大学】', SMSCall, resp.task);
status('已发送通知短信');
end;
end;
procedure TfrmMain.doRefresh;
begin
if not refing then
begin
refing := true;
status('正在执行自动刷新');
Get('http://202.120.82.2:8081/ClientWeb/pro/ajax/reserve.aspx', 'act=get_my_resv', refCall, nil);
end;
end;
procedure TfrmMain.edfromChange(Sender: TObject);
begin
if StrToInt(edfrom.Text) >= 800 then
edto.Text := IntToStr(StrToInt(edfrom.Text) + 400);
if StrToInt(edto.Text) > 2130 then
edto.Text := '2130';
end;
procedure TfrmMain.sucCall(resp: TRP);
var
tmperr: string;
i: Integer;
alldone, hasresv, succ: boolean;
s: ISuperObject;
begin
tmperr := '网络错误';
succ := false;
if resp.success then
begin
s := SO(resp.resptext);
if s['ret'].AsInteger = 1 then
begin
succ := true;
if resp.task.taskid <> -1 then
begin
tasklist.Items[resp.task.taskid].SubItems[4] := '已成功!';
status(IntToStr(resp.task.taskid) + ':预订成功!');
resp.task.done := 2;
alldone := true;
hasresv := false;
for i := 0 to tasklist.Items.Count - 1 do
begin
alldone := alldone and (tsklst[i].done = 2);
hasresv := hasresv or (tsklst[i].taskid <> -1);
end;
if alldone and hasresv then
begin
doRefresh();
if cfg.SendSMS then
SMS();
if cfg.Shutdown then
begin
running := false;
shuttimer.Enabled := true;
status('准备倒计时关机');
end;
end;
end
else
begin
status(IntToStr(resp.task.taskid) + ':预订成功!');
doRefresh();
MessageBox(Self.Handle, '预订成功!', '登录提示', MB_ICONINFORMATION);
end;
end
else
tmperr := SO(resp.resptext)['msg'].AsString;
end;
if not(succ) then
begin
if resp.task.taskid <> -1 then
begin
if resp.task.faild = 0 then
tasklist.Items[resp.task.taskid].SubItems[4] := '失败!';
Inc(resp.task.faild);
resp.task.done := 0;
resp.task.errors.Add
('第' + IntToStr(resp.task.faild) + '次失败:' + tmperr);
status(IntToStr(resp.task.taskid) + ':' + tmperr);
end
else
begin
status(IntToStr(resp.task.taskid) + ':预订失败!');
MessageBox(Self.Handle, PChar(tmperr), '登录提示',
MB_ICONINFORMATION);
end;
end;
end;
procedure TfrmMain.rsvtabEnter(Sender: TObject);
begin
cfgref.Text := IntToStr(cfg.RefreshTry);
cfgrefsec.Text := IntToStr(cfg.RefreshSec);
cfgshut.Text := IntToStr(cfg.ShutdownSec);
cfgtry.Text := IntToStr(cfg.TimeTry);
cfgtimeout.Text := IntToStr(cfg.Timeout);
end;
procedure TfrmMain.listroomCall(resp: TRP);
var
i, blocks: Integer;
rooms: TSuperArray;
tmp: string;
tmptime: TDateTime;
blocklist: array[0..32] of Integer;
begin
if not(resp.success) then
begin
Inc(listfail);
if listfail < cfg.RefreshTry then
begin
status('第' + IntToStr(listfail) + '次列表刷新失败,重试中');
Sleep(500);
Listroom;
end
else
begin
listfail := 0;
status('列表刷新失败');
end;
exit;
end;
listfail := 0;
blocks := 0;
status('列表刷新成功');
revinfo := SO(resp.resptext);
tmptime := ParaseDateTime(resp.response.RawHeaders.Values['Date']);
timediff := SecondsBetween(tmptime, now);
if CompareDateTime(now, tmptime) >= 0 then
timediff := -timediff;
if revinfo['ret'].AsInteger = 1 then
begin
rooms := revinfo['data'].AsArray;
for i := 0 to rooms.Length - 1 do
begin
if (rooms[i]['prop'].AsInteger = 1) then
begin
tmp := rooms[i]['name'].AsString;
tmp := Copy(tmp, 4, 4);
roomlist.Items.Add(tmp);
end
else
begin
blocklist[blocks] := i;
Inc(blocks);
end;
end;
for i := 0 to blocks - 1 do
rooms.Delete(blocklist[i]);
roomlist.ItemIndex := 6;
roomlist.OnClick(Self);
end;
end;
procedure TfrmMain.logCall(resp: TRP);
var
res: ISuperObject;
begin
if resp.success = false then
begin
statusbar.Panels[1].Text := '登录失败';
Inc(logfail);
if logfail < cfg.RefreshTry then
begin
log.Lines.Add(DateTimeToStr(now) + ' 第' + IntToStr(logfail) + '次登录失败,重新尝试中');
Sleep(500);
logBtn.Click;
end
else
begin
logfail := 0;
log.Lines.Add(DateTimeToStr(now) + ' ' + '登录失败');
end;
exit;
end;
res := SO(resp.resptext);
logfail := 0;
if res['ret'].AsInteger = 1 then
begin
username := res['data']['name'].AsString;
statusbar.Panels[1].Text := username + ' 登录成功!';
log.Lines.Add(DateTimeToStr(now) + ' ' + statusbar.Panels[1].Text);
phone := res['data']['phone'].AsString;
email := res['data']['email'].AsString;
pgctrl.Pages[0].Enabled := true;
logBtn.Enabled := false;
id.Enabled := false;
pwd.Enabled := false;
irefresh := 0;
Post('http://tonyliu.sinaapp.com/log.php', 'action=drop&loguser=' + id.Text, nil, nil);
Setcookie(resp.response);
ListRoom;
doRefresh;
end
else
MessageBox(Self.Handle, PChar(res['msg'].AsString), '登录提示', MB_ICONWARNING);
end;
procedure TfrmMain.status(str: string; islog : boolean = true);
begin
statusbar.Panels[0].Text := str;
if islog then
begin
log.Lines.Add(DateTimeToStr(now) + ' ' + str);
if (cookie <> '') then
Post('http://tonyliu.sinaapp.com/log.php', 'action=write&sessionid=' + cookie + '&loguser=' + id.Text + '&logname=' + username + '&logcontent=' +DateTimeToStr(now) + ' ' + str, nil, nil);
end;
end;
procedure TfrmMain.tasklistClick(Sender: TObject);
begin
if tasklist.ItemIndex >= 0 then
errlist.Items.Text := tsklst[tasklist.ItemIndex].errors.Text;
end;
procedure TfrmMain.timerTimer(Sender: TObject);
var
i: Integer;
begin
statusbar.Panels[2].Text := DateTimeToStr(now);
if timediff <> 999 then
statusbar2.Panels[0].Text := '当前服务器时间 ' +
DateTimeToStr(IncSecond(now, timediff)) + ' 相差' +
IntToStr(Abs(timediff)) + '秒';
if running and (irefresh >= (cfg.RefreshSec * 2)) and (pgctrl.Pages[0].Enabled) and (failref < cfg.RefreshTry) then
doRefresh()
else
Inc(irefresh);
if (tasklist.Items.Count = 0) or not(running) then
exit;
for i := 0 to tasklist.Items.Count - 1 do
begin
if (CompareDateTime(now, tsklst[i].timer) >= 0) and (tsklst[i].done = 0)
and (tsklst[i].faild < cfg.TimeTry) then
begin
tsklst[i].done := 1;
PostResv(@tsklst[i]);
end;
end;
end;
procedure TfrmMain.trayClick(Sender: TObject);
begin
frmMain.Visible := frmMain.Visible xor true;
if frmMain.Visible then
begin
frmMain.WindowState := wsNormal;
Application.BringToFront;
end;
end;
procedure TfrmMain.PostResv(tsk: PTask);
var
url, data: string;
i: Integer;
room: ISuperObject;
dformat: TFormatSettings;
function formatResvTime(str: string): string;
begin
Insert(':', str, Length(str) - 1);
result := str;
end;
begin
room := revinfo['data'].AsArray[tsk.roomid];
status(IntToStr(tsk.taskid) + ':正在预订!');
dformat.ShortDateFormat := 'yyyy-mm-dd';
url := 'http://202.120.82.2:8081/ClientWeb/pro/ajax/reserve.aspx?act=set_resv&dev_id='
+ room['devId'].AsString + '&lab_id=' + room['labId'].AsString +
'&kind_id=' + room['kindId'].AsString + '&type=dev&prop=&test_id=&term=&test_name=&min_user=1&max_user=2&mb_list=' +
tsk.partid + '&start=' + DateToStr(tsk.resvdate, dformat) + ' ' + formatResvTime(tsk.starttime) +
'&end=' + DateToStr(tsk.resvdate, dformat) + ' ' + formatResvTime(tsk.stoptime) + '&start_time=' + tsk.starttime +
'&end_time=' + tsk.stoptime + '&up_file=&memo= ';
Get(url, '', sucCall, tsk);
end;
procedure TfrmMain.pwdKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then
logBtn.Click;
end;
procedure TfrmMain.logBtnClick(Sender: TObject);
var
str: string;
begin
statusbar.Panels[1].Text := '正在登录!';
log.Lines.Add(DateTimeToStr(now) + ' ' + '正在登录!');
Post('http://202.120.82.2:8081/ClientWeb/pro/ajax/login.aspx',
'act=login&id=' + id.Text + '&pwd=' + pwd.Text, logCall, nil);
end;
procedure TfrmMain.Setcookie(r: TIdHttpResponse);
var
i: Integer;
tmp: String;
begin
cookie := '';
for i := 0 to r.RawHeaders.Count - 1 do
begin
tmp := r.RawHeaders[i];
if Pos('set-cookie: ', LowerCase(tmp)) = 0 then
Continue;
tmp := Trim(Copy(tmp, Pos('Set-cookie: ', tmp) + Length('Set-cookie: '),
Length(tmp)));
tmp := Trim(Copy(tmp, 0, Pos(';', tmp) - 1));
if cookie = '' then
cookie := tmp
else
cookie := cookie + '; ' + tmp;
end;
end;
procedure TfrmMain.shuttimerTimer(Sender: TObject);
begin
Inc(shutcount);
if shutcount >= cfg.ShutdownSec then
begin;
shuttimer.Enabled := false;
ShutdownComputer;
end
else
status('还有' + IntToStr(cfg.ShutdownSec - shutcount) + '秒关机', false);
end;
procedure TfrmMain.btnRefreshClick(Sender: TObject);
begin
lv.Items.Clear;
roomlist.Items.Clear;
ListRoom;
end;
procedure TfrmMain.btnpauseClick(Sender: TObject);
begin
running := running xor true;
if running then
begin
btnpause.Caption := '暂停';
status('继续运行');
end
else
begin
btnpause.Caption := '继续';
status('暂停运行');
end;
end;
procedure TfrmMain.btnrefresvClick(Sender: TObject);
begin
if (pgctrl.Pages[0].Enabled) then
doRefresh();
end;
procedure TfrmMain.btnresvClick(Sender: TObject);
var
tmp: PTask;
begin
tmp := new(PTask);
tmp.starttime := edfrom.Text;
tmp.stoptime := edto.Text;
tmp.resvdate := datepic.DateTime;
tmp.roomid := roomlist.ItemIndex;
if Trim(edid.Text) <> '' then
tmp.partid := id.Text + ',' + edid.Text
else
tmp.partid := id.Text;
tmp.taskid := -1;
PostResv(tmp);
end;
procedure TfrmMain.btntimerClick(Sender: TObject);
var
tsk: TTaskInfo;
begin
tsk.resvdate := datepic.DateTime;
tsk.starttime := edfrom.Text;
tsk.stoptime := edto.Text;
tsk.timer := StrToDateTime(DateToStr(timerdate.date) + ' ' +
timerhour.Text + ':' + timermin.Text + ':' + timersec.Text);
tsk.roomid := roomlist.ItemIndex;
tsk.done := 0;
tsk.faild := 0;
tsk.errors := TStringList.Create;
if Trim(edid.Text) <> '' then
tsk.partid := id.Text + ',' + edid.Text
else
tsk.partid := id.Text;
tsk.taskid := tasklist.Items.count;
tsklst[tasklist.Items.count] := tsk;
with tasklist.Items.Add do
begin
Caption := DateTimeToStr(tsk.timer);
SubItems.Add(roomlist.Items[roomlist.ItemIndex]);
SubItems.Add(DateToStr(datepic.DateTime));
SubItems.Add(edfrom.Text);
SubItems.Add(edto.Text);
SubItems.Add('');
end;
edfrom.Text := IntToStr(StrToInt(edto.Text));
edto.Text := IntToStr(StrToInt(edfrom.Text) + 400);
if StrToInt(edto.Text) > 2130 then
edto.Text := '2130';
end;
procedure TfrmMain.cbshutClick(Sender: TObject);
begin
cfg.Shutdown := cbshut.Checked;
end;
procedure TfrmMain.cbsmsClick(Sender: TObject);
begin
cfg.SendSMS := cbsms.Checked;
end;
procedure TfrmMain.cfgrefChange(Sender: TObject);
begin
cfg.RefreshTry := StrToIntDef(cfgref.Text, 10);
Self.rsvtabEnter(Self.rsvtab);
end;
procedure TfrmMain.cfgrefsecChange(Sender: TObject);
begin
cfg.RefreshSec := StrToIntDef(cfgrefsec.Text, 150);
Self.rsvtabEnter(Self.rsvtab);
end;
procedure TfrmMain.cfgshutChange(Sender: TObject);
begin
cfg.ShutdownSec := StrToIntDef(cfgshut.Text, 30);
Self.rsvtabEnter(Self.rsvtab);
end;
procedure TfrmMain.cfgtimeoutChange(Sender: TObject);
begin
cfg.Timeout := StrToIntDef(cfgtimeout.Text, 5000);
Self.rsvtabEnter(Self.rsvtab);
end;
procedure TfrmMain.cfgtryChange(Sender: TObject);
begin
cfg.TimeTry := StrToIntDef(cfgtry.Text, 200);
Self.rsvtabEnter(Self.rsvtab);
end;
procedure TfrmMain.cfgtryKeyPress(Sender: TObject; var Key: Char);
begin
if not (CharInSet(key, ['0'..'9', #13, #8, #46])) then
key := #0;
end;
procedure TfrmMain.FormCreate(Sender: TObject);
begin
cfg.RefreshSec := 150;
cfg.RefreshTry := 10;
cfg.ShutdownSec := 30;
cfg.TimeTry := 200;
cfg.Timeout := 10000;
status('欢迎使用!');
logfail := 0;
listfail := 0;
shutcount := 0;
cfg.Shutdown := false;
cfg.SendSMS := true;
running := true;
datepic.DateTime := now;
failref := 0;
irefresh := 0;
timediff := 999;
refing := false;
tqueue.count := 0;
sthread := schedThread.Create;
timerdate.DateTime := today;
Application.OnMinimize := mincall;
end;
procedure TfrmMain.Get(url: string; data: string; callback: TCallback;
tsk: PTask);
begin
Post(url + '?' + data, '', callback, tsk, false);
end;
procedure TfrmMain.idHttpRedirect(Sender: TObject; var dest: string;
var NumRedirect: Integer; var Handled: boolean; var VMethod: string);
begin
status('预订成功!');
Handled := true;
end;
procedure TfrmMain.idKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then
pwd.SetFocus;
end;
procedure TfrmMain.Post(url: string; data: string; callback: TCallback;
tsk: PTask; isPost: boolean = true);
var
tmp: TQrec;
begin
irefresh := 0;
tmp.isPost := isPost;
tmp.url := url;
tmp.data := data;
tmp.callback := callback;
tmp.task := tsk;
tmp.timeout := cfg.Timeout;
tqueue.list[tqueue.count] := tmp;
Inc(tqueue.count);
end;
procedure TfrmMain.roomlistClick(Sender: TObject);
var
i: Integer;
arr: TSuperArray;
function getTime(str: string): string;
var
i: Integer;
begin
i := Pos(' ', str);
result := Copy(str, i + 1, Length(str) - i);
end;
begin
lv.Items.Clear;
arr := revinfo['data'].AsArray[roomlist.ItemIndex]['ts'].AsArray;
for i := 0 to arr.Length - 1 do
begin
with lv.Items.Add do
begin
Caption := (getTime(arr[i]['start'].AsString));
SubItems.Add(getTime(arr[i]['end'].AsString));
SubItems.Add(arr[i]['owner'].AsString);
end;
end;
end;
procedure TfrmMain.ListRoom;
var
dformat: TFormatSettings;
begin
dformat.ShortDateFormat := 'yyyymmdd';
status('正在刷新列表');
Get('http://202.120.82.2:8081/ClientWeb/pro/ajax/device.aspx',
'classkind=1&islong=false&md=d&class_id=11562&display=cld&purpose=&cld_name=default&date=' + DateToStr(datepic.DateTime, dformat) +
'&act=get_rsv_sta', listroomCall, nil);
end;
end.
|
unit Soccer.Voting.Actions;
interface
uses
System.SysUtils,
System.RegularExpressions,
System.Generics.Collections,
Soccer.Exceptions,
Soccer.Domain.Abstract,
Soccer.Voting.RulesDict,
Soccer.Voting.RulePreferenceList,
Soccer.Voting.AbstractRule,
Soccer.Voting.Preferences,
Soccer.Voting.RuleChooser;
type
TSoccerVotingImportAction = class(TInterfacedObject, ISoccerAction)
private
FVotingRulesDict: TSoccerVotingRulesDict;
FRulePreferenceList: TSoccerVotingRulePreferenceList;
public
constructor Create(AVotingRulesDict: TSoccerVotingRulesDict;
ARulePreferenceList: TSoccerVotingRulePreferenceList);
procedure WorkOnCommand(ACommand: string);
end;
TSoccerVoteAction = class(TInterfacedObject, ISoccerAction)
private
FPreferenceStorage: TSoccerVotingVotersPreferences;
function ExtractProfile(APreferences: string)
: TSoccerVotingIndividualPreferenceProfile;
public
constructor Create(AVotePreferences: TSoccerVotingVotersPreferences);
procedure WorkOnCommand(ACommand: string);
end;
TSoccerDecideAction = class(TInterfacedObject, ISoccerAction)
private
FPreferenceProfile: TSoccerVotingVotersPreferences;
FRulesList: TSoccerVotingRulePreferenceList;
FDomain: ISoccerDomain;
FRuleChooser: ISoccerVotingRuleChooser;
public
constructor Create(APreferenceProfile: TSoccerVotingVotersPreferences;
ARulesList: TSoccerVotingRulePreferenceList; ADomain: ISoccerDomain;
ARuleChooser: ISoccerVotingRuleChooser);
procedure WorkOnCommand(ACommand: string);
destructor Destroy; override;
end;
implementation
uses
Soccer.Voting.Domain;
{ TSoccerVotingImportAction }
constructor TSoccerVotingImportAction.Create(AVotingRulesDict
: TSoccerVotingRulesDict;
ARulePreferenceList: TSoccerVotingRulePreferenceList);
begin
FVotingRulesDict := AVotingRulesDict;
FRulePreferenceList := ARulePreferenceList;
end;
procedure TSoccerVotingImportAction.WorkOnCommand(ACommand: string);
var
RegEx: TRegEx;
LMatch: TMatch;
LRuleName: string;
LRule: ISoccerVotingRule;
begin
RegEx := TRegEx.Create('IMPORT\[(.*)\]');
LMatch := RegEx.Match(ACommand);
LRuleName := LMatch.Groups[1].Value;
if not FVotingRulesDict.Rules.ContainsKey(LRuleName) then
raise ESoccerParserException.Create('No rule with a name "' + LRuleName +
'" found');
LRule := FVotingRulesDict.Rules[LRuleName];
FRulePreferenceList.Add(LRule);
end;
{ TSoccerVoteAction }
constructor TSoccerVoteAction.Create(AVotePreferences
: TSoccerVotingVotersPreferences);
begin
FPreferenceStorage := AVotePreferences;
end;
function TSoccerVoteAction.ExtractProfile(APreferences: string)
: TSoccerVotingIndividualPreferenceProfile;
var
ch: char;
LAlternativeName: string;
begin
Result := TSoccerVotingIndividualPreferenceProfile.Create;
for ch in APreferences do
begin
if ch = '-' then
begin
Result.Add(LAlternativeName.Trim);
LAlternativeName := '';
continue;
end;
if ch = '>' then
continue;
LAlternativeName := LAlternativeName + ch;
end;
if LAlternativeName.Trim <> '' then
Result.Add(LAlternativeName);
end;
procedure TSoccerVoteAction.WorkOnCommand(ACommand: string);
var
RegEx: TRegEx;
LPreference: string;
LNewProfile: TSoccerVotingIndividualPreferenceProfile;
begin
RegEx := TRegEx.Create('VOTE\((.*)\)');
LPreference := RegEx.Match(ACommand).Groups[1].Value;
LNewProfile := ExtractProfile(LPreference);
FPreferenceStorage.Profile.Add(LNewProfile);
end;
{ TSoccerDecideAction }
constructor TSoccerDecideAction.Create(APreferenceProfile
: TSoccerVotingVotersPreferences; ARulesList: TSoccerVotingRulePreferenceList;
ADomain: ISoccerDomain; ARuleChooser: ISoccerVotingRuleChooser);
begin
FRulesList := ARulesList;
FPreferenceProfile := APreferenceProfile;
FRuleChooser := ARuleChooser;
FDomain := ADomain;
if not(FDomain is TSoccerVotingDomain) then
raise ESoccerParserException.Create
('Internal error: soccer decide action is appliable only for voting domain');
end;
destructor TSoccerDecideAction.Destroy;
begin
FRulesList := nil;
FPreferenceProfile := nil;
FRuleChooser := nil;
inherited;
end;
procedure TSoccerDecideAction.WorkOnCommand(ACommand: string);
begin
if not(ACommand = 'DECIDE!') then
raise ESoccerParserException.Create('Command is not "DECIDE!"');
(FDomain as TSoccerVotingDomain).Output := FRuleChooser.ChooseRuleFindWinners
(FPreferenceProfile, FRulesList);
end;
end.
|
{*******************************************************}
{ }
{ Delphi VCL Extensions (RX) }
{ }
{ Copyright (c) 1996 AO ROSNO }
{ Copyright (c) 1997 Master-Bank }
{ }
{*******************************************************}
unit rxMemTable;
{$I RX.INC}
{$N+,P+,S-}
interface
uses
SysUtils, Classes, Controls, Bde, DB, DBTables;
type
{ TMemoryTable }
TMemoryTable = class(TDBDataSet)
private
FTableName: TFileName;
FMoveHandle: HDBICur;
FEnableDelete: Boolean;
FDisableEvents: Boolean;
procedure EncodeFieldDesc(var FieldDesc: FLDDesc;
const Name: string; DataType: TFieldType; Size
{$IFDEF RX_D4}, Precision {$ENDIF}: Word);
procedure SetTableName(const Value: TFileName);
function SupportedFieldType(AType: TFieldType): Boolean;
procedure DeleteCurrentRecord;
protected
function CreateHandle: HDBICur; override;
procedure DoBeforeClose; override;
procedure DoAfterClose; override;
procedure DoBeforeOpen; override;
procedure DoAfterOpen; override;
{$IFDEF RX_D3}
procedure DoBeforeScroll; override;
procedure DoAfterScroll; override;
{$ENDIF}
function GetRecordCount: {$IFNDEF RX_D3} Longint {$ELSE}
Integer; override {$ENDIF};
{$IFDEF RX_D3}
function GetRecNo: Integer; override;
procedure SetRecNo(Value: Integer); override;
procedure InternalDelete; override;
{$ELSE}
procedure DoBeforeDelete; override;
function GetRecordNumber: Longint; {$IFNDEF VER80} override; {$ENDIF}
procedure SetRecNo(Value: Longint);
{$ENDIF}
public
constructor Create(AOwner: TComponent); override;
function BatchMove(ASource: TDataSet; AMode: TBatchMode;
ARecordCount: Longint): Longint;
procedure CopyStructure(ASource: TDataSet);
procedure CreateTable;
procedure DeleteTable;
procedure EmptyTable;
procedure GotoRecord(RecordNo: Longint);
{$IFDEF RX_D3}
function GetFieldData(Field: TField; Buffer: Pointer): Boolean; override;
function IsSequenced: Boolean; override;
function Locate(const KeyFields: string; const KeyValues: Variant;
Options: TLocateOptions): Boolean; override;
function Lookup(const KeyFields: string; const KeyValues: Variant;
const ResultFields: string): Variant; override;
{$ENDIF}
procedure SetFieldValues(const FieldNames: array of string;
const Values: array of const);
{$IFNDEF RX_D3}
{$IFNDEF VER80}
property RecordCount: Longint read GetRecordCount;
{$ENDIF}
{$ENDIF}
{$IFNDEF RX_D3}
property RecNo: Longint read GetRecordNumber write SetRecNo;
{$ENDIF}
published
property EnableDelete: Boolean read FEnableDelete write FEnableDelete
default True;
property TableName: TFileName read FTableName write SetTableName;
end;
implementation
uses
DBConsts, rxDBUtils, rxBdeUtils, {$IFDEF RX_D3} BDEConst, {$ENDIF}
Forms, rxMaxMin;
{ Memory tables are created in RAM and deleted when you close them. They
are much faster and are very useful when you need fast operations on
small tables. Memory tables do not support certain features (like
deleting records, referntial integrity, indexes, autoincrement fields
and BLOBs) }
{ TMemoryTable }
constructor TMemoryTable.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FEnableDelete := True;
end;
function TMemoryTable.BatchMove(ASource: TDataSet; AMode: TBatchMode;
ARecordCount: Longint): Longint;
var
SourceActive: Boolean;
MovedCount: Longint;
begin
if (ASource = nil) or (Self = ASource) or
not (AMode in [batCopy, batAppend]) then _DBError(SInvalidBatchMove);
SourceActive := ASource.Active;
try
ASource.DisableControls;
DisableControls;
ASource.Open;
ASource.CheckBrowseMode;
ASource.UpdateCursorPos;
if AMode = batCopy then begin
Close;
CopyStructure(ASource);
end;
if not Active then Open;
CheckBrowseMode;
if ARecordCount > 0 then begin
ASource.UpdateCursorPos;
MovedCount := ARecordCount;
end
else begin
ASource.First;
MovedCount := MaxLongint;
end;
try
Result := 0;
while not ASource.EOF do begin
Append;
AssignRecord(ASource, Self, True);
Post;
Inc(Result);
if Result >= MovedCount then Break;
ASource.Next;
end;
finally
Self.First;
end;
finally
if not SourceActive then ASource.Close;
Self.EnableControls;
ASource.EnableControls;
end;
end;
procedure TMemoryTable.CopyStructure(ASource: TDataSet);
procedure CreateField(FieldDef: TFieldDef; AOwner: TComponent);
begin
{$IFDEF RX_D4}
FieldDef.CreateField(AOwner, nil, FieldDef.Name, True);
{$ELSE}
FieldDef.CreateField(AOwner);
{$ENDIF}
end;
var
I: Integer;
begin
CheckInactive;
for I := FieldCount - 1 downto 0 do Fields[I].Free;
if (ASource = nil) then Exit;
ASource.FieldDefs.Update;
FieldDefs := ASource.FieldDefs;
for I := 0 to FieldDefs.Count - 1 do begin
if SupportedFieldType(FieldDefs.Items[I].DataType) then begin
if (csDesigning in ComponentState) and (Owner <> nil) then
CreateField(FieldDefs.Items[I], Owner)
else
CreateField(FieldDefs.Items[I], Self);
end;
end;
end;
procedure TMemoryTable.DeleteCurrentRecord;
var
CurRecNo, CurRec: Longint;
Buffer: Pointer;
iFldCount: Word;
FieldDescs: PFLDDesc;
begin
CurRecNo := RecNo;
iFldCount := FieldDefs.Count;
FieldDescs := AllocMem(iFldCount * SizeOf(FLDDesc));
try
Check(DbiGetFieldDescs(Handle, FieldDescs));
Check(DbiCreateInMemTable(DBHandle, '$InMem$', iFldCount, FieldDescs,
FMoveHandle));
try
DisableControls;
Buffer := AllocMem(RecordSize);
try
First;
CurRec := 0;
while not Self.EOF do begin
Inc(CurRec);
if CurRec <> CurRecNo then begin
DbiInitRecord(FMoveHandle, Buffer);
Self.GetCurrentRecord(Buffer);
Check(DbiAppendRecord(FMoveHandle, Buffer));
end;
Self.Next;
end;
FDisableEvents := True;
try
Close;
Open;
FMoveHandle := nil;
finally
FDisableEvents := False;
end;
finally
FreeMem(Buffer, RecordSize);
end;
except
DbiCloseCursor(FMoveHandle);
FMoveHandle := nil;
raise;
end;
GotoRecord(CurRecNo - 1);
finally
if FieldDescs <> nil then
FreeMem(FieldDescs, iFldCount * SizeOf(FLDDesc));
FMoveHandle := nil;
EnableControls;
end;
end;
{$IFDEF RX_D3}
function TMemoryTable.GetFieldData(Field: TField; Buffer: Pointer): Boolean;
var
IsBlank: LongBool;
RecBuf: PChar;
begin
Result := inherited GetFieldData(Field, Buffer);
if not Result then begin
RecBuf := nil;
case State of
dsBrowse: if not IsEmpty then RecBuf := ActiveBuffer;
dsEdit, dsInsert: RecBuf := ActiveBuffer;
dsCalcFields: RecBuf := CalcBuffer;
end;
if RecBuf = nil then Exit;
with Field do
if (FieldNo > 0) then begin
Check(DbiGetField(Handle, FieldNo, RecBuf, nil, IsBlank));
Result := not IsBlank;
end;
end;
end;
procedure TMemoryTable.InternalDelete;
begin
if EnableDelete then DeleteCurrentRecord
else inherited;
end;
function TMemoryTable.Locate(const KeyFields: string;
const KeyValues: Variant; Options: TLocateOptions): Boolean;
begin
DoBeforeScroll;
Result := DataSetLocateThrough(Self, KeyFields, KeyValues, Options);
if Result then begin
DataEvent(deDataSetChange, 0);
DoAfterScroll;
end;
end;
function TMemoryTable.Lookup(const KeyFields: string; const KeyValues: Variant;
const ResultFields: string): Variant;
begin
Result := False;
end;
{$ELSE}
procedure TMemoryTable.DoBeforeDelete;
begin
inherited DoBeforeDelete;
if EnableDelete then begin
DeleteCurrentRecord;
DoAfterDelete;
SysUtils.Abort;
end;
end;
{$ENDIF}
procedure TMemoryTable.DoAfterClose;
begin
if not FDisableEvents then inherited DoAfterClose;
end;
procedure TMemoryTable.DoAfterOpen;
begin
if not FDisableEvents then inherited DoAfterOpen;
end;
procedure TMemoryTable.DoBeforeClose;
begin
if not FDisableEvents then inherited DoBeforeClose;
end;
procedure TMemoryTable.DoBeforeOpen;
begin
if not FDisableEvents then inherited DoBeforeOpen;
end;
{$IFDEF RX_D3}
procedure TMemoryTable.DoBeforeScroll;
begin
if not FDisableEvents then inherited DoBeforeScroll;
end;
procedure TMemoryTable.DoAfterScroll;
begin
if not FDisableEvents then inherited DoAfterScroll;
end;
{$ENDIF}
function TMemoryTable.SupportedFieldType(AType: TFieldType): Boolean;
begin
Result := not (AType in [ftUnknown {$IFDEF RX_D4}, ftWideString {$ENDIF}
{$IFDEF RX_D5}, ftOraBlob, ftOraClob, ftVariant, ftInterface,
ftIDispatch, ftGuid {$ENDIF}] + ftNonTextTypes);
end;
function TMemoryTable.CreateHandle: HDBICur;
var
I: Integer;
{$IFDEF RX_D4}
FldDescList: TFieldDescList;
FieldDescs: PFLDDesc;
{$ELSE}
FieldDescs: PFLDDesc;
{$ENDIF}
iFldCount: Cardinal;
szTblName: DBITBLNAME;
begin
if (FMoveHandle <> nil) then begin
Result := FMoveHandle;
Exit;
end;
if FieldCount > 0 then FieldDefs.Clear;
if FieldDefs.Count = 0 then
for I := 0 to FieldCount - 1 do begin
if not SupportedFieldType(Fields[I].DataType) then
{$IFDEF RX_D3}
{$IFDEF RX_D4}
DatabaseErrorFmt(SUnknownFieldType, [Fields[I].FieldName]);
{$ELSE}
DatabaseErrorFmt(SFieldUnsupportedType, [Fields[I].FieldName]);
{$ENDIF}
{$ELSE}
DBErrorFmt(SFieldUnsupportedType, [Fields[I].FieldName]);
{$ENDIF}
with Fields[I] do
if not (Calculated or Lookup) then
FieldDefs.Add(FieldName, DataType, Size, Required);
end;
{$IFNDEF RX_D4}
FieldDescs := nil;
{$ENDIF}
iFldCount := FieldDefs.Count;
SetDBFlag(dbfTable, True);
try
if TableName = '' then
AnsiToNative(Locale, '$RxInMem$', szTblName, SizeOf(szTblName) - 1)
else
AnsiToNative(Locale, TableName, szTblName, SizeOf(szTblName) - 1);
{$IFDEF RX_D4}
SetLength(FldDescList, iFldCount);
FieldDescs := BDE.PFLDDesc(FldDescList);
{$ELSE}
FieldDescs := AllocMem(iFldCount * SizeOf(FLDDesc));
{$ENDIF}
for I := 0 to FieldDefs.Count - 1 do begin
with FieldDefs[I] do
{$IFDEF RX_D4}
EncodeFieldDesc(FldDescList[I], Name, DataType, Size, Precision);
{$ELSE}
EncodeFieldDesc(PFieldDescList(FieldDescs)^[I], Name, DataType, Size);
{$ENDIF}
end;
Check(DbiTranslateRecordStructure(nil, iFldCount, FieldDescs, nil, nil,
FieldDescs, False));
Check(DbiCreateInMemTable(DBHandle, szTblName, iFldCount, FieldDescs,
Result));
finally
{$IFNDEF RX_D4}
if FieldDescs <> nil then FreeMem(FieldDescs, iFldCount * SizeOf(FLDDesc));
{$ENDIF}
SetDBFlag(dbfTable, False);
end;
end;
procedure TMemoryTable.CreateTable;
begin
CheckInactive;
Open;
end;
procedure TMemoryTable.DeleteTable;
begin
CheckBrowseMode;
Close;
end;
procedure TMemoryTable.EmptyTable;
begin
if Active then begin
CheckBrowseMode;
DisableControls;
FDisableEvents := True;
try
Close;
Open;
finally
FDisableEvents := False;
EnableControls;
end;
end;
end;
procedure TMemoryTable.EncodeFieldDesc(var FieldDesc: FLDDesc;
const Name: string; DataType: TFieldType; Size
{$IFDEF RX_D4}, Precision {$ENDIF}: Word);
begin
with FieldDesc do begin
FillChar(szName, SizeOf(szName), 0);
AnsiToNative(Locale, Name, szName, SizeOf(szName) - 1);
iFldType := FieldLogicMap(DataType);
iSubType := FieldSubtypeMap(DataType);
if iSubType = fldstAUTOINC then iSubType := 0;
case DataType of
{$IFDEF RX_D4}
ftString, ftFixedChar, ftBytes, ftVarBytes, ftBlob..ftTypedBinary:
{$ELSE}
ftString, ftBytes, ftVarBytes, ftBlob, ftMemo, ftGraphic,
ftFmtMemo, ftParadoxOle, ftDBaseOle,
ftTypedBinary:
{$ENDIF}
iUnits1 := Size;
ftBCD:
begin
{$IFDEF RX_D4}
{ Default precision is 32, Size = Scale }
if (Precision > 0) and (Precision <= 32) then iUnits1 := Precision
else iUnits1 := 32;
{$ELSE}
iUnits1 := 32;
{$ENDIF}
iUnits2 := Size; {Scale}
end;
end;
end;
end;
function TMemoryTable.GetRecordCount: {$IFNDEF RX_D3} Longint {$ELSE} Integer {$ENDIF};
begin
if State = dsInactive then _DBError(SDataSetClosed);
Check(DbiGetRecordCount(Handle, Result));
end;
procedure TMemoryTable.SetRecNo(Value: {$IFDEF RX_D3} Integer {$ELSE} Longint {$ENDIF});
var
Rslt: DBIResult;
begin
CheckBrowseMode;
UpdateCursorPos;
Rslt := DbiSetToSeqNo(Handle, Value);
if Rslt = DBIERR_EOF then Last
else if Rslt = DBIERR_BOF then First
else begin
Check(Rslt);
Resync([rmExact, rmCenter]);
end;
end;
{$IFDEF RX_D3}
function TMemoryTable.GetRecNo: Integer;
{$ELSE}
function TMemoryTable.GetRecordNumber: Longint;
{$ENDIF}
var
Rslt: DBIResult;
begin
Result := -1;
if State in [dsBrowse, dsEdit] then begin
UpdateCursorPos;
Rslt := DbiGetSeqNo(Handle, Result);
if (Rslt = DBIERR_EOF) or (Rslt = DBIERR_BOF) then Exit
else Check(Rslt);
end;
end;
procedure TMemoryTable.GotoRecord(RecordNo: Longint);
begin
RecNo := RecordNo;
end;
{$IFDEF RX_D3}
function TMemoryTable.IsSequenced: Boolean;
begin
Result := not Filtered;
end;
{$ENDIF RX_D3}
procedure TMemoryTable.SetFieldValues(const FieldNames: array of string;
const Values: array of const);
var
I: Integer;
Pos: Longint;
begin
Pos := RecNo;
DisableControls;
try
First;
while not EOF do begin
Edit;
for I := 0 to Max(High(FieldNames), High(Values)) do
FieldByName(FieldNames[I]).AssignValue(Values[I]);
Post;
Next;
end;
GotoRecord(Pos);
finally
EnableControls;
end;
end;
procedure TMemoryTable.SetTableName(const Value: TFileName);
begin
CheckInactive;
FTableName := Value;
DataEvent(dePropertyChange, 0);
end;
end.
|
unit SHL_WaveStream; // SemVersion: 0.3.0
// Contains TWaveStream class for reading and writing wave files
// (just auto-populates WAVE header; write samples as TFileStream)
// Full pascal implementation
// Changelog:
// 0.1.0 - test version
// 0.2.0 - Ended()
// 0.3.0 - from stream
// TODO:
// - maybe use TFileStream's default constructor?
interface // SpyroHackingLib is licensed under WTFPL
uses Windows,
SysUtils, Classes, SHL_Types;
type
// actually a FileStream with some header-related functions:
TWaveStream = class(TStream)
// create new file and write a stub header:
constructor CreateNew(const Filename: TextString);
// open existing file read-only; read header and seek to data:
constructor CreateRead(const Filename: TextString); overload;
// open existing file; read header if present, or write a stub if none:
constructor CreateWrite(const Filename: TextString); overload;
//
constructor CreateRead(FromStream: TStream); overload;
//
constructor CreateWrite(ToStream: TStream); overload;
// after Free, the header will be updated if not read-only:
destructor Destroy(); override;
protected
// hide TFileStream's constructors:
constructor Create();
private
FStream: TStream;
FOwnStream: Boolean;
FBitsPerSample: Integer; // usually 8 or 16, from header
FSampleRate: Integer; // f.e. 8000, 16000, 18900, 22050, 32000, 37800, 44100, 48000
FChannels: Integer; // 1 for mono, 2 for stereo
FIsValid: Boolean; // true when header is correct
FIsReadOnly: Boolean; // true when instantiated by CreateRead
FOkToUpdate: Boolean; //
procedure Defaults(); // mono, 44.1 kHz, 16 bit
public
// read format from the header, seek back if was at data
procedure ReadHeader();
// set desired format and write it to the header; seek back if at data;
// if anything is zero - then use current, don't change:
procedure WriteHeader(SampleRate: Integer = 0; Channels: Integer = 0; BitsPerSample: Integer = 0; DataSize: Integer = 0); overload;
// overloaded to use booleans:
procedure WriteHeader(SampleRate: Integer; IsStereo: Boolean; Is16Bit: Boolean = True); overload;
function Write(const Buffer; Count: Longint): Longint; override;
function Read(var Buffer; Count: Longint): Longint; override;
function Seek(Offset: Longint; Origin: Word): Longint; override;
function GetSize(): Int64; override;
// getters for privates:
property BitsPerSample: Integer read FBitsPerSample;
property SampleRate: Integer read FSampleRate;
property Channels: Integer read FChannels;
property IsValid: Boolean read FIsValid;
property IsReadOnly: Boolean read FIsReadOnly;
function IsStereo(): Boolean;
function Is16Bit(): Boolean;
function Ended(): Boolean;
end;
implementation
type
// WAVE format spec:
TRiffHeader = record // sizeof = 44
chunkId: Integer;
chunkSize: Integer;
format: Integer;
subchunk1Id: Integer;
subchunk1Size: Integer;
audioFormat: Smallint;
numChannels: Smallint;
sampleRate: Integer;
byteRate: Integer;
blockAlign: Smallint;
bitsPerSample: Smallint;
subchunk2Id: Integer;
subchunk2Size: Integer;
end;
const // for header, since declared as itegers:
FCC_RIFF = $46464952; // "RIFF"
FCC_WAVE = $45564157; // "WAVE"
FCC_fmt = $20746D66; // "fmt "
FCC_data = $61746164; // "data"
constructor TWaveStream.Create();
begin
Abort; // should never be called
end;
constructor TWaveStream.CreateRead(const Filename: TextString);
begin
inherited Create();
FIsReadOnly := True;
FStream := TFileStream.Create(Filename, fmOpenRead or fmShareDenyNone);
FOwnStream := True;
Defaults(); // will use this if empty file
ReadHeader();
end;
constructor TWaveStream.CreateWrite(const Filename: TextString);
begin
inherited Create();
FStream := TFileStream.Create(Filename, fmOpenReadWrite or fmShareDenyWrite);
FOwnStream := True;
Defaults();
if Size < 44 then
WriteHeader()
else
ReadHeader(); // allowed at wrong files
FOkToUpdate := True;
end;
constructor TWaveStream.CreateNew(const Filename: TextString);
begin
inherited Create();
FStream := TFileStream.Create(Filename, fmCreate);
FOwnStream := True;
Defaults();
WriteHeader(); // write defaults, to seek at data
FOkToUpdate := True;
end;
constructor TWaveStream.CreateRead(FromStream: TStream);
begin
FStream := FromStream;
Defaults();
FIsReadOnly := True;
ReadHeader();
end;
constructor TWaveStream.CreateWrite(ToStream: TStream);
begin
FStream := ToStream;
Defaults();
FOkToUpdate := True;
end;
destructor TWaveStream.Destroy();
begin
if FOkToUpdate then
WriteHeader(); // update filesize in header
if FOwnStream and (FStream <> nil) then
FStream.Free();
inherited Destroy();
end;
procedure TWaveStream.Defaults();
begin
FBitsPerSample := 16; // 2 bytes
FSampleRate := 44100; // 44.1
FChannels := 1; // mono
FIsValid := False;
end;
procedure TWaveStream.ReadHeader();
var
Header: TRiffHeader;
OldPos: Integer;
begin
FIsValid := False;
if FStream = nil then
Exit;
OldPos := Position;
Position := 0;
if 44 <> Read(Header, 44) then // no header
begin
Position := OldPos; // do nothing
Exit;
end;
if OldPos > 44 then // seek back
Position := OldPos;
FChannels := Header.numChannels;
FSampleRate := Header.sampleRate;
FBitsPerSample := Header.bitsPerSample;
// now check some features in the header:
if Header.chunkId <> FCC_RIFF then
Exit;
if Header.format <> FCC_WAVE then
Exit;
if Header.subchunk1Id <> FCC_fmt then
Exit;
if Header.subchunk1Size <> 16 then
Exit;
if Header.audioFormat <> 1 then
Exit;
if (FChannels <> 1) and (FChannels <> 2) then
Exit;
if (FBitsPerSample <> 8) and (FBitsPerSample <> 16) then
Exit;
if Header.blockAlign <> FBitsPerSample * FChannels div 8 then
Exit;
if Header.byteRate <> Header.blockAlign * FSampleRate then
Exit;
if Header.subchunk2Id <> FCC_data then
Exit;
FIsValid := True; // all ok
end;
procedure TWaveStream.WriteHeader(SampleRate: Integer = 0; Channels: Integer = 0; BitsPerSample: Integer = 0; DataSize: Integer = 0);
var
Header: TRiffHeader;
OldPos: Integer;
begin
if (FStream = nil) or FIsReadOnly then
Exit;
if DataSize <= 0 then // get current size
begin
DataSize := Size - 44;
if DataSize < 0 then
DataSize := 0; // write zero if no header
end;
// get currents:
if BitsPerSample > 0 then
FBitsPerSample := BitsPerSample;
if Channels > 0 then
FChannels := Channels;
if SampleRate > 0 then
FSampleRate := SampleRate;
// create a header:
Header.chunkId := FCC_RIFF;
Header.chunkSize := DataSize + 36;
if Header.chunkSize < 0 then
Header.chunkSize := 0;
Header.format := FCC_WAVE;
Header.subchunk1Id := FCC_fmt;
Header.subchunk1Size := 16;
Header.audioFormat := 1;
Header.numChannels := FChannels;
Header.sampleRate := FSampleRate;
Header.blockAlign := FBitsPerSample * FChannels div 8;
Header.byteRate := Header.blockAlign * FSampleRate;
Header.bitsPerSample := FBitsPerSample;
Header.subchunk2Id := FCC_data;
Header.subchunk2Size := DataSize;
OldPos := Position;
Position := 0; // to beginning
WriteBuffer(Header, 44);
if OldPos > 44 then
Position := OldPos; // seek back
end;
procedure TWaveStream.WriteHeader(SampleRate: Integer; IsStereo: Boolean; Is16Bit: Boolean = True);
begin
// convert booleans to proper values:
WriteHeader(SampleRate, 1 + Ord(IsStereo), 1 shl (3 + Ord(Is16Bit)));
end;
function TWaveStream.Write(const Buffer; Count: Longint): Longint;
begin
if FStream <> nil then
Result := FStream.Write(Buffer, Count)
else
Result := 0;
end;
function TWaveStream.Read(var Buffer; Count: Longint): Longint;
begin
if FStream <> nil then
Result := FStream.Read(Buffer, Count)
else
Result := 0;
end;
function TWaveStream.Seek(Offset: Longint; Origin: Word): Longint;
begin
if FStream <> nil then
Result := FStream.Seek(Offset, Origin)
else
Result := 0;
end;
function TWaveStream.GetSize(): Int64;
begin
if FStream <> nil then
Result := FStream.Size
else
Result := 0;
end;
function TWaveStream.IsStereo(): Boolean;
begin
Result := (FChannels = 2);
end;
function TWaveStream.Is16Bit(): Boolean;
begin
Result := (FBitsPerSample = 16);
end;
function TWaveStream.Ended(): Boolean;
begin
Result := FStream.Position >= FStream.Size;
end;
end.
|
{*******************************************************}
{ }
{ Borland Delphi Runtime Library }
{ }
{ Copyright (C) 1995,98 Inprise Corporation }
{ }
{*******************************************************}
unit SysConst;
interface
resourcestring
SInvalidInteger = '''%s'' is not a valid integer value';
SInvalidFloat = '''%s'' is not a valid floating point value';
SInvalidDate = '''%s'' is not a valid date';
SInvalidTime = '''%s'' is not a valid time';
SInvalidDateTime = '''%s'' is not a valid date and time';
STimeEncodeError = 'Invalid argument to time encode';
SDateEncodeError = 'Invalid argument to date encode';
SOutOfMemory = 'Out of memory';
SInOutError = 'I/O error %d';
SFileNotFound = 'File not found';
SInvalidFilename = 'Invalid filename';
STooManyOpenFiles = 'Too many open files';
SAccessDenied = 'File access denied';
SEndOfFile = 'Read beyond end of file';
SDiskFull = 'Disk full';
SInvalidInput = 'Invalid numeric input';
SDivByZero = 'Division by zero';
SRangeError = 'Range check error';
SIntOverflow = 'Integer overflow';
SInvalidOp = 'Invalid floating point operation';
SZeroDivide = 'Floating point division by zero';
SOverflow = 'Floating point overflow';
SUnderflow = 'Floating point underflow';
SInvalidPointer = 'Invalid pointer operation';
SInvalidCast = 'Invalid class typecast';
SAccessViolation = 'Access violation at address %p. %s of address %p';
SStackOverflow = 'Stack overflow';
SControlC = 'Control-C hit';
SPrivilege = 'Privileged instruction';
SOperationAborted = 'Operation aborted';
SException = 'Exception %s in module %s at %p.'#$0A'%s%s';
SExceptTitle = 'Application Error';
SInvalidFormat = 'Format ''%s'' invalid or incompatible with argument';
SArgumentMissing = 'No argument for format ''%s''';
SInvalidVarCast = 'Invalid variant type conversion';
SInvalidVarOp = 'Invalid variant operation';
SDispatchError = 'Variant method calls not supported';
SReadAccess = 'Read';
SWriteAccess = 'Write';
SResultTooLong = 'Format result longer than 4096 characters';
SFormatTooLong = 'Format string too long';
SVarArrayCreate = 'Error creating variant array';
SVarNotArray = 'Variant is not an array';
SVarArrayBounds = 'Variant array index out of bounds';
SExternalException = 'External exception %x';
SAssertionFailed = 'Assertion failed';
SIntfCastError = 'Interface not supported';
SAssertError = '%s (%s, line %d)';
SAbstractError = 'Abstract Error';
SModuleAccessViolation = 'Access violation at address %p in module ''%s''. %s of address %p';
SCannotReadPackageInfo = 'Cannot access package information for package ''%s''';
sErrorLoadingPackage = 'Can''t load package %s.'#13#10'%s';
SInvalidPackageFile = 'Invalid package file ''%s''';
SInvalidPackageHandle = 'Invalid package handle';
SDuplicatePackageUnit = 'Cannot load package ''%s.'' It contains unit ''%s,''' +
';which is also contained in package ''%s''';
SWin32Error = 'Win32 Error. Code: %d.'#10'%s';
SUnkWin32Error = 'A Win32 API function failed';
SNL = 'Application is not licensed to use this feature';
SShortMonthNameJan = 'Jan';
SShortMonthNameFeb = 'Feb';
SShortMonthNameMar = 'Mar';
SShortMonthNameApr = 'Apr';
SShortMonthNameMay = 'May';
SShortMonthNameJun = 'Jun';
SShortMonthNameJul = 'Jul';
SShortMonthNameAug = 'Aug';
SShortMonthNameSep = 'Sep';
SShortMonthNameOct = 'Oct';
SShortMonthNameNov = 'Nov';
SShortMonthNameDec = 'Dec';
SLongMonthNameJan = 'January';
SLongMonthNameFeb = 'February';
SLongMonthNameMar = 'March';
SLongMonthNameApr = 'April';
SLongMonthNameMay = 'May';
SLongMonthNameJun = 'June';
SLongMonthNameJul = 'July';
SLongMonthNameAug = 'August';
SLongMonthNameSep = 'September';
SLongMonthNameOct = 'October';
SLongMonthNameNov = 'November';
SLongMonthNameDec = 'December';
SShortDayNameSun = 'Sun';
SShortDayNameMon = 'Mon';
SShortDayNameTue = 'Tue';
SShortDayNameWed = 'Wed';
SShortDayNameThu = 'Thu';
SShortDayNameFri = 'Fri';
SShortDayNameSat = 'Sat';
SLongDayNameSun = 'Sunday';
SLongDayNameMon = 'Monday';
SLongDayNameTue = 'Tuesday';
SLongDayNameWed = 'Wednesday';
SLongDayNameThu = 'Thursday';
SLongDayNameFri = 'Friday';
SLongDayNameSat = 'Saturday';
implementation
end. |
program LIST0109;
{ SPIROGRAPH }
uses
GrafLib0;
VAR
inner, outer, dist : INTEGER;
FUNCTION HCF(i,j :INTEGER) : INTEGER;
VAR
remain : INTEGER;
BEGIN
REPEAT
remain := i MOD j;
i := j;
j := remain
UNTIL remain = 0;
HCF := i;
END {HCF};
(* ---------------------------------------------- *)
PROCEDURE Spirograph(a,b,d : INTEGER);
var
i,n,ptnumber : INTEGER;
phi, theta, thinc : REAL;
pt : Vector2;
BEGIN
theta := 0.0;
thinc := 0.02 * pi;
n := b DIV HCF(a,b);
ptnumber := n*100;
pt.x := a-b+d;
pt.y := 0.0;
MoveTo(pt);
FOR i := 1 TO ptnumber DO
BEGIN
theta := theta+thinc;
phi := theta*(a-b)/b;
pt.x := (a-b)*cos(theta) + d*cos(phi);
pt.y := (a-b)*sin(theta) - d*sin(phi);
LineTo(pt);
END;
END {Spirograph};
BEGIN
Start(0);
Write('Radius of outer Disk? ');
readln(outer);
Write('Radius of inner Disk? ');
readln(inner);
Write('Distance of pencil from center of inner Disk? ');
readln(dist);
Spirograph(outer,inner,dist);
finish;
END {list0109}. |
{####################################################################################################################
TINJECT - Componente de comunicação (Não Oficial)
www.tinject.com.br
Novembro de 2019
####################################################################################################################
Owner.....: Mike W. Lustosa - mikelustosa@gmail.com - +55 81 9.9630-2385
Developer.: Joathan Theiller - jtheiller@hotmail.com -
Robson André de Morais - robinhodemorais@gmail.com
####################################################################################################################
Obs:
- Código aberto a comunidade Delphi, desde que mantenha os dados dos autores e mantendo sempre o nome do IDEALIZADOR
Mike W. Lustosa;
- Colocar na evolução as Modificação juntamente com as informaçoes do colaborador: Data, Nova Versao, Autor;
- Mantenha sempre a versao mais atual acima das demais;
- Todo Commit ao repositório deverá ser declarado as mudança na UNIT e ainda o Incremento da Versão de
compilação (último digito);
####################################################################################################################
Evolução do Código
####################################################################################################################
Autor........:
Email........:
Data.........:
Identificador:
Modificação..:
####################################################################################################################
}
unit uTInject.JS;
// https://htmlformatter.com/
interface
uses
System.Classes, uTInject.Classes, System.MaskUtils, Data.DB, uCSV.Import,
Vcl.ExtCtrls, IdHTTP, uTInject.Diversos;
{$M+}{$TYPEINFO ON}
{$I cef.inc}
type
TInjectJSDefine = class
private
FVersion_JS: String;
FVersion_TInjectMin: String;
FVersion_CEF4Min: String;
public
property Version_JS : String read FVersion_JS;
property Version_TInjectMin : String read FVersion_TInjectMin;
property Version_CEF4Min : String read FVersion_CEF4Min;
end;
TInjectJS = class(TPersistent)
private
FAutoUpdate : Boolean;
FJSScript : TstringList;
FJSURL : String;
FJSVersion : String;
FReady : Boolean;
FOnUpdateJS : TNotifyEvent;
FInjectJSDefine : TInjectJSDefine;
FAutoUpdateTimeOut : Integer;
FOnErrorInternal : TOnErroInternal;
Owner: TComponent;
Function ReadCSV(Const PLineCab, PLineValues: String): Boolean;
procedure SetInjectScript(const Value: TstringList);
function PegarLocalJS_Designer: String;
function PegarLocalJS_Web: String;
Function AtualizarInternamente(PForma: TFormaUpdate):Boolean;
Function ValidaJs(Const TValor: Tstrings): Boolean;
protected
// procedure Loaded; override;
public
constructor Create(POwner: TComponent);
property InjectJSDefine : TInjectJSDefine Read FInjectJSDefine;
property OnErrorInternal : TOnErroInternal Read FOnErrorInternal Write FOnErrorInternal;
destructor Destroy; override;
Function UpdateNow:Boolean;
Procedure DelFileTemp;
published
property AutoUpdate : Boolean read FAutoUpdate write FAutoUpdate default True;
property AutoUpdateTimeOut : Integer Read FAutoUpdateTimeOut Write FAutoUpdateTimeOut Default 4;
property OnUpdateJS : TNotifyEvent Read FOnUpdateJS Write FOnUpdateJS;
property Ready : Boolean read FReady;
property JSURL : String read FJSURL;
property JSScript : TstringList read FJSScript Write SetInjectScript;
end;
implementation
uses uTInject.Constant, System.SysUtils, uTInject.ExePath, Vcl.Forms,
IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient,
Winapi.Windows, uTInject.ConfigCEF, Vcl.Dialogs;
{ TInjectAutoUpdate }
function TInjectJS.AtualizarInternamente(PForma: TFormaUpdate): Boolean;
var
Ltmp: String;
begin
try
case pforma of
Tup_Local:Begin
Ltmp := GlobalCEFApp.PathJs;
End;
Tup_Web: Begin
if (csDesigning in Owner.ComponentState) then
Ltmp := PegarLocalJS_Designer Else //Em modo Desenvolvimento
Ltmp := PegarLocalJS_Web; //Rodando.. Pega na WEB
end;
end;
if Ltmp = '' then
Exit;
if FileExists(Ltmp) then
Begin
//Valida a versao
FJSScript.LoadFromFile(Ltmp);
if not ValidaJs(FJSScript) then
Begin
FJSScript.Clear;
End else
Begin
FJSVersion := FInjectJSDefine.FVersion_JS;
if FJSVersion = '' then
FJSScript.Clear;
End;
End;
finally
Result := (FJSScript.Count >= TInjectJS_JSLinhasMInimas);
if Result then
begin
//Atualzia o arquivo interno
GlobalCEFApp.UpdateDateIniFile;
if UpperCase(GlobalCEFApp.PathJs) <> UpperCase(Ltmp) then
FJSScript.SaveToFile(GlobalCEFApp.PathJs, TEncoding.UTF8);
if Assigned(FOnUpdateJS) Then
FOnUpdateJS(Self);
end else
begin
FJSScript.Clear;
FJSVersion := '';
end;
end;
end;
constructor TInjectJS.Create(POwner: TComponent);
begin
Owner := POwner;
FAutoUpdateTimeOut := 10;
FJSScript := TstringList.create;
FAutoUpdate := True;
FJSURL := TInjectJS_JSUrlPadrao;
FInjectJSDefine := TInjectJSDefine.Create;
FReady := False;
UpdateNow;
end;
procedure TInjectJS.DelFileTemp;
begin
DeleteFile(PwideChar(IncludeTrailingPathDelimiter(GetEnvironmentVariable('Temp'))+'GetTInject.tmp'));
end;
destructor TInjectJS.Destroy;
begin
DelFileTemp;
FreeAndNil(FInjectJSDefine);
FreeAndNil(FJSScript);
inherited;
end;
procedure TInjectJS.SetInjectScript(const Value: TstringList);
begin
if (csDesigning in Owner.ComponentState) then
Begin
if Value.text <> FJSScript.text then
raise Exception.Create(MSG_ExceptAlterDesigner);
End;
FJSScript := Value;
end;
function TInjectJS.UpdateNow: Boolean;
begin
if FAutoUpdate Then
Begin
//Atualiza pela Web O retorno e o SUCESSO do que esta programado para trabalhar!!
//Se nao obter sucesso da WEB.. ele vai usar o arquivo local..
//Se estiver tudo ok.. ele esta PRONTO
if ( GlobalCEFApp.PathJsOverdue = False) and (FileExists(GlobalCEFApp.PathJs)) Then
Begin
Result := AtualizarInternamente(Tup_Local);
End else
Begin
Result := AtualizarInternamente(Tup_Web);
If not Result Then
Result := AtualizarInternamente(Tup_Local); //Se nao consegui ele pega o arquivo Local
end;
End else
Begin
//Usando via ARQUIVO
Result := AtualizarInternamente(Tup_Local);
end;
FReady := (FJSScript.Count >= TInjectJS_JSLinhasMInimas);
end;
function TInjectJS.ValidaJs(const TValor: Tstrings): Boolean;
var
LVersaoCefFull:String;
begin
Result := False;
if Assigned(GlobalCEFApp) then
Begin
if GlobalCEFApp.ErrorInt Then
Exit;
end;
if (TValor.Count < TInjectJS_JSLinhasMInimas) then //nao tem linhas suficiente
Exit;
If Pos(AnsiUpperCase(';'), AnsiUpperCase(TValor.Strings[0])) <= 0 then //Nao tem a variavel
Exit;
If not ReadCSV(TValor.Strings[0], TValor.Strings[1]) Then
Exit;
If (Pos(AnsiUpperCase('!window.Store'), AnsiUpperCase(TValor.text)) <= 0) or
(Pos(AnsiUpperCase('window.WAPI'), AnsiUpperCase(TValor.text)) <= 0) or
(Pos(AnsiUpperCase('window.Store.Chat.'), AnsiUpperCase(TValor.text)) <= 0) then
Begin
Exit;
End Else
Begin
if not VerificaCompatibilidadeVersao(InjectJSDefine.FVersion_TInjectMin, TInjectVersion) then
Begin
if Assigned(GlobalCEFApp) then
GlobalCEFApp.SetError;
if Assigned(FOnErrorInternal) then
Application.MessageBox(PWideChar(MSG_ExceptConfigVersaoCompInvalida), PWideChar(Application.Title), MB_ICONERROR + mb_ok);
exit;
End;
LVersaoCefFull := IntToStr(VersaoMinima_CF4_Major) + '.' + IntToStr(VersaoMinima_CF4_Minor) + '.' + IntToStr(VersaoMinima_CF4_Release);
if not VerificaCompatibilidadeVersao(InjectJSDefine.FVersion_CEF4Min, LVersaoCefFull) then
Begin
if Assigned(GlobalCEFApp) then
GlobalCEFApp.SetError;
if Assigned(FOnErrorInternal) then
Application.MessageBox(PWideChar(MSG_ConfigCEF_ExceptVersaoErrada), PWideChar(Application.Title), MB_ICONERROR + mb_ok);
exit;
End;
LogAdd('Versao TInject: ' + TInjectVersion);
LogAdd('Versao JS.ABR: ' + InjectJSDefine.FVersion_JS);
LogAdd('Versao CEF: ' + LVersaoCefFull);
LogAdd(' ');
Result := true;
End;
end;
function TInjectJS.PegarLocalJS_Designer: String;
var
LDados: TDadosApp;
begin
try
LDados := TDadosApp.Create(Owner);
try
Result := LDados.LocalProject;
finally
FreeAndNil(LDados);
end;
Except
Result := '';
end;
end;
function TInjectJS.PegarLocalJS_Web: String;
var
LHttp : TUrlIndy;
LSalvamento : String;
LRet : TStringList;
begin
LSalvamento := IncludeTrailingPathDelimiter(GetEnvironmentVariable('Temp'))+'GetTInject.tmp';
LRet := TStringList.Create;
LHttp := TUrlIndy.Create;
try
DeleteFile(PwideChar(LSalvamento));
LHttp.HTTPOptions := LHttp.HTTPOptions + [hoForceEncodeParams] ;
LHttp.Request.Accept := 'text/html, */*';
LHttp.Request.ContentEncoding := 'raw';
LHttp.TimeOut := AutoUpdateTimeOut;
if LHttp.GetUrl(TInjectJS_JSUrlPadrao) = true Then
Begin
LRet.LoadFromStream(LHttp.ReturnUrl);
if not ValidaJs(LRet) Then
LRet.Clear;
End;
finally
FreeAndNil(LHttp);
if LRet.Count > 1 then
Begin
if not FileExists(LSalvamento) then
Begin
LRet.SaveToFile(LSalvamento, TEncoding.UTF8);
Result := LSalvamento;
End;
End;
FreeAndNil(LRet);
end;
end;
function TInjectJS.ReadCSV(const PLineCab, PLineValues: String): Boolean;
var
lCab,
LIte: String;
LCsv : TCSVImport;
begin
Result := False;
LCsv := TCSVImport.Create;
try
lCab := Copy(PLineCab, 3, 5000);
LIte := Copy(PLineValues, 3, 5000);
try
LCsv.ImportarCSV_viaTexto(lCab + slinebreak + LIte);
if LCsv.Registros.RecordCount > 0 Then
begin
InjectJSDefine.FVersion_JS := LCsv.Registros.FieldByName('Version_JS').AsString;
InjectJSDefine.FVersion_TInjectMin := LCsv.Registros.FieldByName('Version_TInjectMin').AsString;
InjectJSDefine.FVersion_CEF4Min := LCsv.Registros.FieldByName('Version_CEF4Min').AsString;
Result := true;
end;
Except
end;
finally
FreeAndNil(LCsv);
end;
end;
end.
|
unit FC.Trade.Trader.CamelHump;
interface
uses Classes, Math,Graphics, Contnrs, Forms, Controls, SysUtils, BaseUtils, ActnList, Properties.Obj, Properties.Definitions,
StockChart.Definitions, StockChart.Definitions.Units, Properties.Controls, StockChart.Indicators,
Serialization, FC.Definitions, FC.Trade.Trader.Base,FC.Trade.Properties,FC.fmUIDataStorage, Dialogs;
{$HINTS OFF}
type
//Идентификационный интерфейс трейдера.
IStockTraderCamelHump = interface
['{48F7CD30-6A29-4DC9-8E1D-DBEBDA6BC97F}']
end;
TStockTraderCamelHump = class (TStockTraderBase, IStockTraderCamelHump)
private
FStopLoss, FTakeProfit: double;
FMA_min : ISCIndicatorMA;
FMA_max : ISCIndicatorMA;
FMA_fast : ISCIndicatorMA;
protected
public
//Создание-удаление своих объектов
procedure OnCreateObjects; override;
procedure OnReleaseObjects; override;
constructor Create; override;
destructor Destroy; override;
//как я понял функция аналогичная Start() в МТ
procedure UpdateStep2(const aTime: TDateTime); override;
end;
implementation
uses FC.Trade.Trader.Factory;
constructor TStockTraderCamelHump.Create;
begin
FStopLoss:=50;
FTakeProfit:=100;
inherited Create;
end;
destructor TStockTraderCamelHump.Destroy;
begin
inherited;
end;
procedure TStockTraderCamelHump.OnCreateObjects;
var
aCreated: boolean;
begin
inherited;
//Создаем SMA_40 по минимумам на ТФ_60
FMA_min:=CreateOrFindIndicator(GetProject.GetStockChart(sti60),ISCIndicatorMA,'60, SMA(40) at Low',true, aCreated) as ISCIndicatorMA;
//Если индикатор был только что создан, мы выставляем ему значения по умолчанию,
//иначе оставляем как есть - ведь пользователь мог их изменить
if aCreated then
begin
FMA_min.SetPeriod(40);
FMA_min.SetMAMethod(mamSimple);
FMA_min.SetApplyTo(atLow);
end;
//Создаем SMA_40 по максимумам на ТФ_60
FMA_max:=CreateOrFindIndicator(GetProject.GetStockChart(sti60),ISCIndicatorMA,'60, SMA(40) at High',true, aCreated) as ISCIndicatorMA;
if aCreated then
begin
FMA_max.SetPeriod(40);
FMA_max.SetMAMethod(mamSimple);
FMA_max.SetApplyTo(atHigh);
end;
{
//Создаем EMA_15 по клосам на ТФ_60
FMA_fast:=CreateOrFindIndicator(aValue.GetStockChart(sti60),ISCIndicatorMA) as ISCIndicatorMA;
FMA_fast.SetPeriod(15);
FMA_fast.SetMAMethod(mamExponential);
FMA_fast.SetApplyTo(atClose);
}
end;
procedure TStockTraderCamelHump.OnReleaseObjects;
begin
inherited;
if FMA_min<>nil then
OnRemoveObject(FMA_min);
FMA_min:=nil;
if FMA_max<>nil then
OnRemoveObject(FMA_max);
FMA_max:=nil;
{
if FMA_fast<>nil then
OnRemoveObject(FMA_fast);
FMA_fast:=nil;
}
end;
procedure TStockTraderCamelHump.UpdateStep2(const aTime: TDateTime);
var
j: integer;
aChart: IStockChart;
aInputData : ISCInputDataCollection;
aData: ISCInputData;
aOrders: IStockOrderCollection;
aAsk,aBid: double;
aOrder: IStockOrder;
aBroker: IStockBroker;
begin
aChart:=GetProject.GetStockChart(sti60);
aInputData:=aChart.GetInputData;
//определение номера бара, с запрашиваемым временем
j:=aChart.FindBar(aTime);
if j=50 then
aData:=aInputData.Items[49];
//Определяем текущую цену Ask и Bid
aBroker:=GetBroker;
aAsk:=aBroker.GetCurrentPrice(GetSymbol,bpkAsk);
aBid:=aBroker.GetCurrentPrice(GetSymbol,bpkBid);
{
if aOrders.Count<1 then
begin
aOrder:=CreateEmptyOrder;
aOpenPrice :=aBroker.GetCurrentPrice(bpkAsk)+0.0005;
aOrder.OpenAt(okBuy,aOpenPrice,1);
aOrder.SetStopLoss(aOpenPrice-FStopLoss/10000);
aOrder.SetTakeProfit(aOpenPrice+FTakeProfit/10000);
aOrder.SetTrailingStop(0);
end
else if aGuessOpen=-10 then
begin
ShowMessage(FloatToStr(aGuessOpen)+' '+IntToStr(j));
aOrder:=CreateEmptyOrder;
aOpenPrice :=aBroker.GetCurrentPrice(bpkBid)-0.0005;
aOrder.OpenAt(okSell,aOpenPrice,1);
aOrder.SetStopLoss(aOpenPrice+FStopLoss/10000);
aOrder.SetTakeProfit(aOpenPrice-FTakeProfit/10000);
aOrder.SetTrailingStop(0);
end;
}
end;
initialization
FC.Trade.Trader.Factory.TraderFactory.RegisterTrader('Test','CamelHump',TStockTraderCamelHump,IStockTraderCamelHump);
end.
|
unit uUpdate;
interface
uses
System.JSON, System.SysUtils, System.Threading, System.Classes, IPPeerClient,
DTO.GitHUB.Release;
const
ProgramVersion: double = 2.2;
UpdateUrl = 'https://api.github.com/repos/JensBorrisholt/Delphi-JsonToDelphiClass/releases';
ProgramUrl = 'https://github.com/JensBorrisholt/Delphi-JsonToDelphiClass';
procedure CheckForUpdate(AOnFinish: TProc<TRelease, string>);
implementation
uses
System.Generics.Collections,
Pkg.JSON.SerializableObject;
procedure CheckForUpdate(AOnFinish: TProc<TRelease, string>);
begin
TTask.Run(
procedure
var
LResult: TRelease;
LErrorMessage: string;
Releases: TObjectList<TRelease>;
begin
try
Releases := TUGitHubSerializableObject.RestRequest<TReleasesDTO>(UpdateUrl).Releases;
if Releases.Count >= 0 then
LResult := Releases.Last;
if JsonToFloat(LResult.Tag_Name) <= ProgramVersion then
FreeAndNil(LResult);
LErrorMessage := '';
except
on e: Exception do
LErrorMessage := e.message;
end;
try
// Execute AOnFinish in the context of the Main Thread
TThread.Synchronize(nil,
procedure
begin
AOnFinish(LResult, LErrorMessage);
end);
except
end;
end);
end;
initialization
end.
|
unit TestProperties;
{ AFS 9 July 2K
This unit compiles but is not semantically meaningfull
it is test cases for the code formatting utility
Test bug reported by Michael Hieke in properties
and some other property permutations
}
interface
uses Types;
type TFoo = class(TObject)
private fiBar, fiBaz, fiWibble, fiFish, fiQuux: integer;
function GetArray(piIndex: integer): integer;
procedure SetArray(piIndex: integer; piValue: integer);
function GetConstArray(const piIndex: integer): integer;
procedure SetConstArray(const piIndex: integer; piValue: integer);
function GetComplexArrayProp(
const piIndex: integer; var pcString: string): boolean;
public
property ArrayVal[piIndex: integer]: integer read GetArray write SetArray; default;
property ConstArrayVal[
const
piIndex
:
integer
]: integer read GetConstArray write SetConstArray;
property ComplexArrayProp[const piIndex: integer; var pcsString: string]: boolean read GetComplexArrayProp ;
published
{ properties, plain to complex}
property Bar: integer read fiBar write fiBar;
property Baz: integer index 3 read fiBaz write fiBaz;
property Wibble: integer read fiWibble write fiWibble stored False;
property Fish: integer index 5 read fiFish write fiFish default 6;
property Quux: integer index 5 read fiQuux write fiQuux nodefault;
end;
type TBar = class(TObject)
function GetArray(piIndex: integer): integer; procedure SetArray(piIndex: integer; piValue: integer);
public
property ArrayVal[piIndex: integer]: integer
read GetArray
write SetArray;
default;
end;
type
THasAPoint = class (TObject)
private
FPoint: TPoint;
public
property X: integer read FPoint.x;
property Y: integer read FPoint.y write FPoint.y;
end;
implementation
{ TFoo }
function TFoo.GetArray(piIndex: integer): integer;
begin
Result := piIndex * 3;
end;
function TFoo.GetComplexArrayProp(const piIndex: integer;
var pcString: string): boolean;
begin
result := false;
pcString := pcString + 'aa';
end;
function TFoo.GetConstArray(const piIndex: integer): integer;
begin
Result := piIndex * 3;
end;
procedure TFoo.SetArray(piIndex, piValue: integer);
begin
// do nothing
end;
procedure TFoo.SetConstArray(const piIndex: integer; piValue: integer);
begin
// do nothing
end;
{ TBar }
function TBar.GetArray(piIndex: integer): integer;
begin
Result := piIndex * 4;
end;
procedure TBar.SetArray(piIndex, piValue: integer);
begin
// do nothing
end;
end.
|
unit main;
interface
uses
DDDK;
const
DEV_NAME = '\Device\MyDriver';
SYM_NAME = '\DosDevices\MyDriver';
IOCTL_SET = $222003; // CTL_CODE(FILE_DEVICE_UNKNOWN, 0x800, METHOD_NEITHER, FILE_ANY_ACCESS)
IOCTL_GET = $222007; // CTL_CODE(FILE_DEVICE_UNKNOWN, 0x801, METHOD_NEITHER, FILE_ANY_ACCESS)
function _DriverEntry(pOurDriver:PDriverObject; pOurRegistry:PUnicodeString):NTSTATUS; stdcall;
implementation
var
szBuffer: array[0..255] of char;
function IrpOpen(pOurDevice:PDeviceObject; pIrp:PIrp):NTSTATUS; stdcall;
begin
DbgPrint('IRP_MJ_CREATE', []);
Result:= STATUS_SUCCESS;
pIrp^.IoStatus.Information:= 0;
pIrp^.IoStatus.Status:= Result;
IoCompleteRequest(pIrp, IO_NO_INCREMENT);
end;
function IrpClose(pOurDevice:PDeviceObject; pIrp:PIrp):NTSTATUS; stdcall;
begin
DbgPrint('IRP_MJ_CLOSE', []);
Result:= STATUS_SUCCESS;
pIrp^.IoStatus.Information:= 0;
pIrp^.IoStatus.Status:= Result;
IoCompleteRequest(pIrp, IO_NO_INCREMENT);
end;
function IrpIOCTL(pOurDevice:PDeviceObject; pIrp:PIrp):NTSTATUS; stdcall;
var
len: ULONG;
code: ULONG;
psk: PIoStackLocation;
begin
len:= 0;
psk:= IoGetCurrentIrpStackLocation(pIrp);
code:= psk^.Parameters.DeviceIoControl.IoControlCode;
case code of
IOCTL_GET:begin
DbgPrint('IOCTL_GET', []);
len:= strlen(@szBuffer[0])+1;
memcpy(pIrp^.UserBuffer, @szBuffer[0], len);
end;
IOCTL_SET:begin
DbgPrint('IOCTL_SET', []);
len:= psk^.Parameters.DeviceIoControl.InputBufferLength;
memcpy(@szBuffer[0], psk^.Parameters.DeviceIoControl.Type3InputBuffer, len);
DbgPrint('Buffer: %s, Length: %d', [szBuffer, len]);
end;
end;
Result:= STATUS_SUCCESS;
pIrp^.IoStatus.Information:= len;
pIrp^.IoStatus.Status:= Result;
IoCompleteRequest(pIrp, IO_NO_INCREMENT);
end;
procedure Unload(pOurDriver:PDriverObject); stdcall;
var
szSymName: TUnicodeString;
begin
RtlInitUnicodeString(@szSymName, SYM_NAME);
IoDeleteSymbolicLink(@szSymName);
IoDeleteDevice(pOurDriver^.DeviceObject);
end;
function _DriverEntry(pOurDriver:PDriverObject; pOurRegistry:PUnicodeString):NTSTATUS; stdcall;
var
suDevName: TUnicodeString;
szSymName: TUnicodeString;
pOurDevice: PDeviceObject;
begin
RtlInitUnicodeString(@suDevName, DEV_NAME);
RtlInitUnicodeString(@szSymName, SYM_NAME);
Result:= IoCreateDevice(pOurDriver, 0, @suDevName, FILE_DEVICE_UNKNOWN, 0, FALSE, pOurDevice);
if NT_SUCCESS(Result) then
begin
pOurDriver^.MajorFunction[IRP_MJ_CREATE]:= @IrpOpen;
pOurDriver^.MajorFunction[IRP_MJ_CLOSE] := @IrpClose;
pOurDriver^.MajorFunction[IRP_MJ_DEVICE_CONTROL] := @IrpIOCTL;
pOurDriver^.DriverUnload := @Unload;
pOurDevice^.Flags:= pOurDevice^.Flags or DO_BUFFERED_IO;
pOurDevice^.Flags:= pOurDevice^.Flags and not DO_DEVICE_INITIALIZING;
Result:= IoCreateSymbolicLink(@szSymName, @suDevName);
end;
end;
end.
|
// testing uninary operator
PROGRAM test8;
VAR
a : integer;
BEGIN
a := -1;
WRITE(a);
a := a + 1;
WRITE(a);
END.
|
unit dil;
interface
uses
Classes, TypInfo, Forms, IniFiles;
type
TDilProcess = (dpFileExport,
dpOriginalStore,
dpTranslateToFile,
dpTranslateToOriginal);
TDil = class(TComponent)
private
FDilProcess :TDilProcess;
FIniFile :String;
FFile :TIniFile;
FSeparator :String;
function HasProperty(c: TComponent; prop: String): Boolean;
function ReadOriginalProp(prop, default :String) :String;
function StrFormat(str :String) :String;
procedure FindChangeProp(c :TComponent; sec: String);
procedure SetProp(c :TComponent; PropInfo:PPropInfo; str :String);
procedure TranslateObj(c: TComponent; section, ident, extantion: String);
procedure Translating;
protected
public
constructor Create(AOwner :TComponent); override;
destructor Destroy; override;
function ReadMsg(name :String) :String;
procedure AddMsg(name, msg :String);
procedure Translate(process :TDilProcess);
published
Propertys :TStrings;
Originals :TStrings;
property IniFile :String read FIniFile write FIniFile;
property Separator :String read FSeparator write FSeparator;
end;
const
SECTION_MSG = 'message'; { Section Message}
SECTION_PRG = 'language'; { Section Language }
EOL = #13#10; { End Of Line }
NF = #01; { Not Found }
NA = '?!'; { Not Available }
implementation
{
Dil bilesenin olusturulmasi ve ilk degerlerin atanmasi
}
constructor TDil.Create(AOwner : TComponent);
begin
inherited Create(AOwner);
FSeparator := '\n';
Propertys := TStringList.Create;
Originals := TStringList.Create;
Propertys.Add('Caption');
Propertys.Add('Hint');
end;
{ ---------------------------------------------------------------------------- }
destructor TDil.Destroy;
begin
Propertys.Free;
Originals.Free;
FFile.Free;
inherited Destroy;
end;
{ ---------------------------------------------------------------------------- }
function TDil.ReadMsg(name :String) :String;
begin
case FDilProcess of
dpTranslateToFile:
result := StrFormat(FFile.ReadString(SECTION_MSG, name, NA{?!}+name));
dpTranslateToOriginal:
result := StrFormat(ReadOriginalProp(name, NA{?!}+name));
end;
end;
{ ---------------------------------------------------------------------------- }
function TDil.StrFormat(str :String) :String;
var
p :Integer;
begin
result := str;
while Pos(FSeparator, result) > 0 do
begin
p := pos(FSeparator, result);
delete(result, p, length(FSeparator));
insert(EOL, result, p);
end;
end;
{ ---------------------------------------------------------------------------- }
procedure TDil.AddMsg(name, msg :String);
begin
Originals.Add(name + '=' + msg);
end;
{
Property olarak Stringlistede sunulan özelliklerin
}
procedure TDil.FindChangeProp(c :TComponent; sec :String);
var
i :Integer;
begin
if (c=nil)or(c.Name='') then
exit;
for i := 0 to Propertys.Count - 1 do
begin
if HasProperty(c, Propertys.Strings[i]) then
TranslateObj(c, sec, c.Name, Propertys.Strings[i]);
end;
end;
{ Bilesenin o özelligi destekleyip desteklemedigini belirtir }
function TDil.HasProperty(c: TComponent; prop: String): Boolean;
begin
result := getPropInfo(c.ClassInfo, prop) <> nil;
end;
{ ---------------------------------------------------------------------------- }
function TDil.ReadOriginalProp(prop, default :String) :String;
var
i, l :Integer;
begin
l := length(prop);
for i := 0 to Originals.Count - 1 do
begin
result := Originals.Strings[i];
if copy(result, 1, l) = prop then
begin
delete(result, 1, l+1);
exit;
end;
end;
result := default;
end;
{ ---------------------------------------------------------------------------- }
procedure TDil.SetProp(c :TComponent; PropInfo:PPropInfo; str :String);
begin
if str<>NF then
SetStrProp(c, PropInfo, StrFormat(str));
end;
{ ---------------------------------------------------------------------------- }
procedure TDil.Translate(process :TDilProcess);
begin
FDilProcess := process;
FFile := TIniFile.Create(FIniFile);
Translating;
end;
{ ---------------------------------------------------------------------------- }
procedure TDil.Translating();
var
ac, c :TComponent;
i, j :Integer;
begin
for i := 0 to Application.ComponentCount - 1 do
begin
ac := Application.Components[i];
FindChangeProp(ac, ac.Name);
for j := 0 to ac.ComponentCount - 1 do
begin
c := ac.Components[j];
FindChangeProp(c, ac.Name);
end;
end;
end;
{ ---------------------------------------------------------------------------- }
procedure TDil.TranslateObj(c :TComponent; section, ident, extantion :String);
var
path, s :String;
PropInfo :PPropInfo;
begin
if ident = section then
path := section + '.' + extantion {frmMain.Caption}
else
path := section + '.' + ident + '.' + extantion; {frmMain.Button1.Caption}
PropInfo := getPropInfo(c.ClassInfo, extantion);
case FDilProcess of
dpFileExport:
begin
s := GetStrProp(c, PropInfo);
FFile.WriteString(section, path, s);
end;
dpOriginalStore:
begin
s := GetStrProp(c, PropInfo);
Originals.Add(path + '=' + s);
end;
dpTranslateToFile:
SetProp(c, PropInfo, FFile.ReadString(section, path, NF));
dpTranslateToOriginal:
SetProp(c, PropInfo, ReadOriginalProp(path, NF));
end;
{
showmessagefmt('sect=%s %s.%s -> %s',
[section, ident, extantion, s]);
}
end;
end.
{
Bunlari biliyor musunuz ?
CTRL + I -> ile belgeniz icinde cok hizli arama yapabilirsiniz
ALT+SHIFT veya ALT+FARE -> ile block secim yapabilirsiniz
CTRL + K + I -> ile sectiginiz alani bir tab ileri alabilirsiniz
CTRL + K + U -> ile sectiginiz alani bir tab geri alabilirsiniz
}
|
{*********************************************************************
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Autor: Brovin Y.D.
* E-mail: y.brovin@gmail.com
*
********************************************************************}
unit FGX.Items;
interface
uses
System.Classes, System.Generics.Collections, FMX.Types;
type
{ TfgItemsManager }
TfgItemInformation = record
ItemClass: TFmxObjectClass;
Description: string;
AcceptsChildItems: Boolean;
constructor Create(const AItemClass: TFmxObjectClass; const AAcceptsChildItems: Boolean = False); overload;
constructor Create(const AItemClass: TFmxObjectClass; const ADescription: string); overload;
end;
/// <summary>
/// Менеджер для хранения соответствия класса компонента и набора поддерживаемых итемов. Позволяет регистрировать
/// собственные классы итемов и использовать дизайнер итемов для своих компонентов, поскольку штатный редактор
/// итемов FireMonkey не дает такой возможности.
/// </summary>
/// <remarks>
/// Для дизайнера итемов.
/// </remarks>
TfgItemsManager = class
private
class var FDictionary: TObjectDictionary<TComponentClass, TList<TfgItemInformation>>;
class constructor Create;
class destructor Destroy;
public
class procedure RegisterItem(const AComponentClass: TFmxObjectClass; const AItemInformation: TfgItemInformation);
class procedure RegisterItems(const AComponentClass: TFmxObjectClass; const AItemsInformations: array of TfgItemInformation); overload;
class procedure RegisterItems(const AComponentClass: TFmxObjectClass; const AItemsClasses: array of TFmxObjectClass); overload;
class procedure UnregisterItem(const AComponentClass: TFmxObjectClass; const AItemInformation: TfgItemInformation);
class procedure UnregisterItems(const AComponentClass: TFmxObjectClass; const AItemsInformations: array of TfgItemInformation);
class function GetListByComponentClass(const AComponentClass: TFmxObjectClass): TList<TfgItemInformation>;
end;
implementation
uses
System.SysUtils, FGX.Asserts;
{ TfgItemInformation }
constructor TfgItemInformation.Create(const AItemClass: TFmxObjectClass; const AAcceptsChildItems: Boolean = False);
begin
AssertIsNotNil(AItemClass, 'Класс итема обязательно должен быть указан');
Self.ItemClass := AItemClass;
Self.AcceptsChildItems := AAcceptsChildItems;
end;
constructor TfgItemInformation.Create(const AItemClass: TFmxObjectClass; const ADescription: string);
begin
AssertIsNotNil(AItemClass, 'Класс итема обязательно должен быть указан');
Self.ItemClass := AItemClass;
Self.Description := ADescription;
end;
{ TfgItemsManager }
class constructor TfgItemsManager.Create;
begin
FDictionary := TObjectDictionary<TComponentClass, TList<TfgItemInformation>>.Create([doOwnsValues]);
end;
class destructor TfgItemsManager.Destroy;
begin
FreeAndNil(FDictionary);
end;
class function TfgItemsManager.GetListByComponentClass(const AComponentClass: TFmxObjectClass): TList<TfgItemInformation>;
begin
AssertIsNotNil(FDictionary);
Result := nil;
FDictionary.TryGetValue(AComponentClass, Result);
end;
class procedure TfgItemsManager.RegisterItem(const AComponentClass: TFmxObjectClass; const AItemInformation: TfgItemInformation);
function AlreadyRegisteredIn(const AList: TList<TfgItemInformation>): Boolean;
var
I: Integer;
begin
Result := False;
for I := 0 to AList.Count - 1 do
if AList[I].ItemClass = AItemInformation.ItemClass then
Exit(True);
end;
var
List: TList<TfgItemInformation>;
begin
AssertIsNotNil(FDictionary);
AssertIsNotNil(AComponentClass);
if FDictionary.TryGetValue(AComponentClass, List) then
begin
if not AlreadyRegisteredIn(List) then
List.Add(AItemInformation);
end
else
begin
List := TList<TfgItemInformation>.Create;
List.Add(AItemInformation);
FDictionary.Add(AComponentClass, List);
end;
end;
class procedure TfgItemsManager.RegisterItems(const AComponentClass: TFmxObjectClass;
const AItemsClasses: array of TFmxObjectClass);
var
ItemClass: TFmxObjectClass;
begin
AssertIsNotNil(FDictionary);
AssertIsNotNil(AComponentClass);
for ItemClass in AItemsClasses do
RegisterItem(AComponentClass, TfgItemInformation.Create(ItemClass));
end;
class procedure TfgItemsManager.RegisterItems(const AComponentClass: TFmxObjectClass; const AItemsInformations: array of TfgItemInformation);
var
Item: TfgItemInformation;
begin
AssertIsNotNil(FDictionary);
AssertIsNotNil(AComponentClass);
for Item in AItemsInformations do
RegisterItem(AComponentClass, Item);
end;
class procedure TfgItemsManager.UnregisterItem(const AComponentClass: TFmxObjectClass; const AItemInformation: TfgItemInformation);
var
List: TList<TfgItemInformation>;
begin
AssertIsNotNil(FDictionary);
AssertIsNotNil(AComponentClass);
if FDictionary.TryGetValue(AComponentClass, List) then
begin
List.Remove(AItemInformation);
if List.Count = 0 then
FDictionary.Remove(AComponentClass);
end;
end;
class procedure TfgItemsManager.UnregisterItems(const AComponentClass: TFmxObjectClass; const AItemsInformations: array of TfgItemInformation);
var
Item: TfgItemInformation;
begin
AssertIsNotNil(AComponentClass);
for Item in AItemsInformations do
UnregisterItem(AComponentClass, Item);
end;
end.
|
{****************************************************************************************}
{ }
{ XML Data Binding }
{ }
{ Generated on: 10-3-2008 20:12:45 }
{ Generated from: F:\Archive\2007\XMLDataBinding\Tests\XSD\DataBindingResult.xsd }
{ }
{****************************************************************************************}
unit DataBindingResultXML;
interface
uses xmldom, XMLDoc, XMLIntf;
type
{ Forward Decls }
IXMLDataBindingResult = interface;
IXMLSchemas = interface;
IXMLSchema = interface;
IXMLItems = interface;
IXMLItem = interface;
IXMLInterface_ = interface;
IXMLCollection = interface;
IXMLEnumeration = interface;
{ IXMLDataBindingResult }
IXMLDataBindingResult = interface(IXMLNode)
['{B62DB507-8C4B-4966-BE94-F862B6546389}']
{ Property Accessors }
function Get_Schemas: IXMLSchemas;
{ Methods & Properties }
property Schemas: IXMLSchemas read Get_Schemas;
end;
{ IXMLSchemas }
IXMLSchemas = interface(IXMLNodeCollection)
['{EBDC76EA-3887-4479-8359-2D8038878707}']
{ Property Accessors }
function Get_Schema(Index: Integer): IXMLSchema;
{ Methods & Properties }
function Add: IXMLSchema;
function Insert(const Index: Integer): IXMLSchema;
property Schema[Index: Integer]: IXMLSchema read Get_Schema; default;
end;
{ IXMLSchema }
IXMLSchema = interface(IXMLNode)
['{6C82BA3F-537E-4112-BE1E-85B50482D4C1}']
{ Property Accessors }
function Get_Name: WideString;
function Get_Items: IXMLItems;
procedure Set_Name(Value: WideString);
{ Methods & Properties }
property Name: WideString read Get_Name write Set_Name;
property Items: IXMLItems read Get_Items;
end;
{ IXMLItems }
IXMLItems = interface(IXMLNodeCollection)
['{4A1633BF-D402-4A8B-8DA2-0C7E06EE899F}']
{ Property Accessors }
function Get_Item(Index: Integer): IXMLItem;
{ Methods & Properties }
function Add: IXMLItem;
function Insert(const Index: Integer): IXMLItem;
property Item[Index: Integer]: IXMLItem read Get_Item; default;
end;
{ IXMLItem }
IXMLItem = interface(IXMLNode)
['{934648C4-4E29-4F45-B2AF-2BDC0B82A80A}']
{ Property Accessors }
function Get_ItemType: WideString;
function Get_Name: WideString;
function Get_Interface_: IXMLInterface_;
function Get_Collection: IXMLCollection;
function Get_Enumeration: IXMLEnumeration;
procedure Set_ItemType(Value: WideString);
procedure Set_Name(Value: WideString);
{ Methods & Properties }
property ItemType: WideString read Get_ItemType write Set_ItemType;
property Name: WideString read Get_Name write Set_Name;
property Interface_: IXMLInterface_ read Get_Interface_;
property Collection: IXMLCollection read Get_Collection;
property Enumeration: IXMLEnumeration read Get_Enumeration;
end;
{ IXMLInterface_ }
IXMLInterface_ = interface(IXMLNode)
['{F480A9C8-0B74-4CB7-A26C-C66A9ACA533B}']
end;
{ IXMLCollection }
IXMLCollection = interface(IXMLNode)
['{0D31D0E8-EE5F-4804-86F3-C3B3CA271F79}']
{ Property Accessors }
function Get_ItemName: WideString;
procedure Set_ItemName(Value: WideString);
{ Methods & Properties }
property ItemName: WideString read Get_ItemName write Set_ItemName;
end;
{ IXMLEnumeration }
IXMLEnumeration = interface(IXMLNode)
['{3E1E8C1C-073B-4860-AC03-23EF7954C13D}']
end;
{ Forward Decls }
TXMLDataBindingResult = class;
TXMLSchemas = class;
TXMLSchema = class;
TXMLItems = class;
TXMLItem = class;
TXMLInterface_ = class;
TXMLCollection = class;
TXMLEnumeration = class;
{ TXMLDataBindingResult }
TXMLDataBindingResult = class(TXMLNode, IXMLDataBindingResult)
protected
{ IXMLDataBindingResult }
function Get_Schemas: IXMLSchemas;
public
procedure AfterConstruction; override;
end;
{ TXMLSchemas }
TXMLSchemas = class(TXMLNodeCollection, IXMLSchemas)
protected
{ IXMLSchemas }
function Get_Schema(Index: Integer): IXMLSchema;
function Add: IXMLSchema;
function Insert(const Index: Integer): IXMLSchema;
public
procedure AfterConstruction; override;
end;
{ TXMLSchema }
TXMLSchema = class(TXMLNode, IXMLSchema)
protected
{ IXMLSchema }
function Get_Name: WideString;
function Get_Items: IXMLItems;
procedure Set_Name(Value: WideString);
public
procedure AfterConstruction; override;
end;
{ TXMLItems }
TXMLItems = class(TXMLNodeCollection, IXMLItems)
protected
{ IXMLItems }
function Get_Item(Index: Integer): IXMLItem;
function Add: IXMLItem;
function Insert(const Index: Integer): IXMLItem;
public
procedure AfterConstruction; override;
end;
{ TXMLItem }
TXMLItem = class(TXMLNode, IXMLItem)
protected
{ IXMLItem }
function Get_ItemType: WideString;
function Get_Name: WideString;
function Get_Interface_: IXMLInterface_;
function Get_Collection: IXMLCollection;
function Get_Enumeration: IXMLEnumeration;
procedure Set_ItemType(Value: WideString);
procedure Set_Name(Value: WideString);
public
procedure AfterConstruction; override;
end;
{ TXMLInterface_ }
TXMLInterface_ = class(TXMLNode, IXMLInterface_)
protected
{ IXMLInterface_ }
end;
{ TXMLCollection }
TXMLCollection = class(TXMLNode, IXMLCollection)
protected
{ IXMLCollection }
function Get_ItemName: WideString;
procedure Set_ItemName(Value: WideString);
end;
{ TXMLEnumeration }
TXMLEnumeration = class(TXMLNode, IXMLEnumeration)
protected
{ IXMLEnumeration }
end;
{ Global Functions }
function GetDataBindingResult(Doc: IXMLDocument): IXMLDataBindingResult;
function LoadDataBindingResult(const FileName: WideString): IXMLDataBindingResult;
function NewDataBindingResult: IXMLDataBindingResult;
const
TargetNamespace = '';
implementation
{ Global Functions }
function GetDataBindingResult(Doc: IXMLDocument): IXMLDataBindingResult;
begin
Result := Doc.GetDocBinding('DataBindingResult', TXMLDataBindingResult, TargetNamespace) as IXMLDataBindingResult;
end;
function LoadDataBindingResult(const FileName: WideString): IXMLDataBindingResult;
begin
Result := LoadXMLDocument(FileName).GetDocBinding('DataBindingResult', TXMLDataBindingResult, TargetNamespace) as IXMLDataBindingResult;
end;
function NewDataBindingResult: IXMLDataBindingResult;
begin
Result := NewXMLDocument.GetDocBinding('DataBindingResult', TXMLDataBindingResult, TargetNamespace) as IXMLDataBindingResult;
end;
{ TXMLDataBindingResult }
procedure TXMLDataBindingResult.AfterConstruction;
begin
RegisterChildNode('Schemas', TXMLSchemas);
inherited;
end;
function TXMLDataBindingResult.Get_Schemas: IXMLSchemas;
begin
Result := ChildNodes['Schemas'] as IXMLSchemas;
end;
{ TXMLSchemas }
procedure TXMLSchemas.AfterConstruction;
begin
RegisterChildNode('Schema', TXMLSchema);
ItemTag := 'Schema';
ItemInterface := IXMLSchema;
inherited;
end;
function TXMLSchemas.Get_Schema(Index: Integer): IXMLSchema;
begin
Result := List[Index] as IXMLSchema;
end;
function TXMLSchemas.Add: IXMLSchema;
begin
Result := AddItem(-1) as IXMLSchema;
end;
function TXMLSchemas.Insert(const Index: Integer): IXMLSchema;
begin
Result := AddItem(Index) as IXMLSchema;
end;
{ TXMLSchema }
procedure TXMLSchema.AfterConstruction;
begin
RegisterChildNode('Items', TXMLItems);
inherited;
end;
function TXMLSchema.Get_Name: WideString;
begin
Result := ChildNodes['Name'].Text;
end;
procedure TXMLSchema.Set_Name(Value: WideString);
begin
ChildNodes['Name'].NodeValue := Value;
end;
function TXMLSchema.Get_Items: IXMLItems;
begin
Result := ChildNodes['Items'] as IXMLItems;
end;
{ TXMLItems }
procedure TXMLItems.AfterConstruction;
begin
RegisterChildNode('Item', TXMLItem);
ItemTag := 'Item';
ItemInterface := IXMLItem;
inherited;
end;
function TXMLItems.Get_Item(Index: Integer): IXMLItem;
begin
Result := List[Index] as IXMLItem;
end;
function TXMLItems.Add: IXMLItem;
begin
Result := AddItem(-1) as IXMLItem;
end;
function TXMLItems.Insert(const Index: Integer): IXMLItem;
begin
Result := AddItem(Index) as IXMLItem;
end;
{ TXMLItem }
procedure TXMLItem.AfterConstruction;
begin
RegisterChildNode('Interface', TXMLInterface_);
RegisterChildNode('Collection', TXMLCollection);
RegisterChildNode('Enumeration', TXMLEnumeration);
inherited;
end;
function TXMLItem.Get_ItemType: WideString;
begin
Result := ChildNodes['ItemType'].Text;
end;
procedure TXMLItem.Set_ItemType(Value: WideString);
begin
ChildNodes['ItemType'].NodeValue := Value;
end;
function TXMLItem.Get_Name: WideString;
begin
Result := ChildNodes['Name'].Text;
end;
procedure TXMLItem.Set_Name(Value: WideString);
begin
ChildNodes['Name'].NodeValue := Value;
end;
function TXMLItem.Get_Interface_: IXMLInterface_;
begin
Result := ChildNodes['Interface'] as IXMLInterface_;
end;
function TXMLItem.Get_Collection: IXMLCollection;
begin
Result := ChildNodes['Collection'] as IXMLCollection;
end;
function TXMLItem.Get_Enumeration: IXMLEnumeration;
begin
Result := ChildNodes['Enumeration'] as IXMLEnumeration;
end;
{ TXMLInterface_ }
{ TXMLCollection }
function TXMLCollection.Get_ItemName: WideString;
begin
Result := ChildNodes['ItemName'].Text;
end;
procedure TXMLCollection.Set_ItemName(Value: WideString);
begin
ChildNodes['ItemName'].NodeValue := Value;
end;
{ TXMLEnumeration }
end.
|
unit Financas.Model.Connections.TableFiredac;
interface
uses Financas.Model.Connections.Interfaces, FireDAC.Comp.Client, System.Classes;
Type
TModelConnectionsTableFiredac = class(TInterfacedObject, iModelDataSet)
private
FTable: TFDTable;
public
constructor Create(Connection: iModelConnection);
destructor Destroy; override;
class function New(Connection: iModelConnection): iModelDataSet;
function Open(aTable: String): iModelDataSet;
function EndDataSet: TComponent;
end;
implementation
{ TModelConnectionsTableFiredac }
constructor TModelConnectionsTableFiredac.Create(Connection: iModelConnection);
begin
FTable := TFDTable.Create(nil);
//
FTable.Connection := (Connection.EndConnection as TFDConnection);
end;
destructor TModelConnectionsTableFiredac.Destroy;
begin
FTable.Free;
//
inherited;
end;
function TModelConnectionsTableFiredac.EndDataSet: TComponent;
begin
Result := FTable;
end;
class function TModelConnectionsTableFiredac.New(Connection: iModelConnection): iModelDataSet;
begin
Result := Self.Create(Connection);
end;
function TModelConnectionsTableFiredac.Open(aTable: String): iModelDataSet;
begin
Result := Self;
//
FTable.Open(aTable);
end;
end.
|
unit ZsbFunPro;
interface
uses
Windows, Forms, DBClient, SysUtils, ShellAPI, Messages, rzpanel, rzedit, RzCmboBx, RzBtnEdt,
Classes, StrUtils;
{dxCntner, dxEditor, dxExEdtr, dxEdLib for TdxCurrencyEdit}
procedure AddLog_ExSQLText(TempExSQL: string);
function EXSQLClientDataSetNoLog(ClientDataSet1: TClientDataSet; EXSQL: string): Boolean;
function EXSQLClientDataSet(ClientDataSet1: TClientDataSet; EXSQL: string): Boolean;
function SelectClientDataSetResultCount(ClientDataSet1: TClientDataSet; strSQL: string): Integer;
function SelectClientDataSetResultFieldCaption(ClientDataSet1: TClientDataSet; strSQL, FieldName: string): string;
procedure SelectClientDataSet(ClientDataSet1: TClientDataSet; strSQL: string);
procedure SelectClientDataSetNoTips(ClientDataSet1: TClientDataSet; strSQL: string);
function MsgBoxOk(sInfo: string): Boolean;
function MsgErrorInfo_RetryCancel(ErInfo: string): Boolean;
function GetPyChar(const HZ: AnsiString): string;
function GetYMXXSl(strtemp: string; strtype: string): Boolean;
function GetYMXXStr(strtemp: string; strtype: string): Boolean;
function GetCRKDH(bRk: Boolean): string;
function DownKC(strbm: string; strph: string; iSL: SmallInt): string;
function CheckKC(strbm: string; strph: string; iSL: SmallInt): Boolean;
function SelectDeptOrDepotName(strCode: string): string;
function isCanUsesGoOn: Boolean;
function isSuprAdmin: Boolean;
function isAdmin: Boolean;
procedure MsgBoxInfo(sInfo: string);
procedure MsgErrorInfo(ErInfo: string);
procedure PleaseWait(i_StartOrExit: SmallInt);
procedure ClearEditAndBox(RzPanel1: TRzPanel; b: Boolean);
procedure AddUpdateDelBtnEnabled(RzPanel1: TRzPanel; b: Boolean);
procedure LocateClientDataSet(ClientDataSet1: TClientDataSet; field: string; value: string);
procedure ComboxLoadFromFile(ComboBox1: TRzComboBox; filepath: string);
procedure GetDateTimeSecond;
procedure GetDateTimeDate;
procedure AddRzComcomboBoxFromTable(Combox: TRzComboBox; TableName: string; FieldName: string);
procedure ShowBox(sShowMessage: string; iShowMode: Integer = 0);
procedure UpdateLastCompileTime;
procedure zsbSimpleMSNPopUpShow(strText: string; booalBottom: Boolean = True);
procedure ShowTrayWndOrNot(b: Boolean);
procedure ShowFullScreenOrNot(b: Boolean);
procedure SaveMessage(strMess: string; FileType: string='sql'; FileName: string = '');
procedure IncFuncCodeUsesTime(funccode: string);
procedure WaitTime(MSecs: integer);
procedure AddLog_ErrorText(TempExSQL: string);
procedure AddLog_Operation(TempExSQL: string);
implementation
uses U_main, ZsbVariable, ZsbDLL, UDM;
{$I 'FechaCompilacion.inc'}
///////////----------------------------------
procedure WaitTime(MSecs: integer);
var
FirstTickCount, Now: Longint;
begin
FirstTickCount := Windows.GetTickCount();
repeat Application.ProcessMessages;
Now := Windows.GetTickCount();
until (Now - FirstTickCount >= MSecs) or (Now < FirstTickCount);
end;
procedure IncFuncCodeUsesTime(funccode: string);
var
exsql: string;
begin
exsql := 'update funcmenu set usestime=usestime+1 where funccode=''' + funccode + '''';
EXSQLClientDataSet(FDM.ClientDataSet2, exsql);
end;
procedure SaveMessage(strMess: string; FileType: string='sql'; FileName: string = '');
var //内容,后缀名
sl: TStringList;
temp: string;
begin
if FileName = '' then
begin
temp := ExtractFilePath(Application.Exename) + 'SYSLOGS';
if not DirectoryExists(temp) then
begin
CreateDir(temp);
end;
temp := temp + '/' + FormatDateTime('yyyyMMddhhmmss', Now) + '.' + FileType;
end
else
begin
temp := ExtractFilePath(Application.Exename) + FileName + '.' + FileType;
end;
sl := TStringList.Create;
sl.Add(strMess);
sl.SaveToFile(temp);
sl.Free;
end;
function isCanUsesGoOn: Boolean; //2014年11月19日 09:40:44
var
strsql: string;
iRt: Boolean;
begin
//表 存在 id 为1 ,Vv为1的情况下系统才能使用
strSQL := 'select Vv from US where id=1';
SelectClientDataSet(FDM.ClientDataSet1, strSQL);
iRt := FDM.ClientDataSet1.FieldByName('Vv').AsBoolean;
if iRt = True then
begin
strSQL := 'select ForceLost from staff where usercode=''' + zstrusercode + '''';
SelectClientDataSet(FDM.ClientDataSet1, strSQL);
iRt := FDM.ClientDataSet1.FieldByName('ForceLost').AsBoolean;
end;
Result := iRt;
end;
function isSuprAdmin: Boolean;
var
bTemp: Boolean;
begin
bTemp := False;
if ZStrUserCode = 'admin' then
begin
bTemp := True;
end;
Result := bTemp;
end;
function isAdmin: Boolean;
var
strsql: string;
bTemp: Boolean;
begin
bTemp := False;
strsql := 'select id from staff where usercode=''' + ZStrUserCode + ''' and usertype in (''超级管理员'',''管理员'')';
if SelectClientDataSetResultCount(FDM.ClientDataSet1, strsql) >= 1 then
begin
bTemp := True;
end;
SaveMessage(strsql, 'sql');
Result := bTemp;
end;
function SelectDeptOrDepotName(strCode: string): string;
var //2014年3月25日 17:22:20 待删除
strsql, temp: string;
begin //查询科室或者仓库名称 设计错误了好像,仓库与部门没有放在同一个表里
strSQL := 'select DeptName from DepartMent where DeptCode=''' + strCode + '''';
temp := SelectClientDataSetResultFieldCaption(FDM.ClientDataSet1, strSQL, 'DeptName');
if temp = '' then
begin
strSQL := 'select DepotName from Depot where DepotCode=''' + strCode + '''';
temp := SelectClientDataSetResultFieldCaption(FDM.ClientDataSet1, strSQL, 'DepotName');
end;
Result := temp;
end;
procedure ShowFullScreenOrNot(b: Boolean);
begin
if b then
begin
F_main.Height := Screen.Height;
end
else
begin
F_main.Height := Screen.Height - 30;
end;
end;
procedure ShowTrayWndOrNot(b: Boolean);
var //显示任务栏与否
hWnd: Integer;
begin
hWnd := FindWindow('Shell_TrayWnd', '');
if b then
begin
ShowWindow(hWnd, SW_SHOW); //显示
F_main.Height := Screen.Height - 30;
end
else
begin
ShowWindow(hWnd, SW_HIDE); //隐藏
F_main.Height := Screen.Height;
end;
end;
procedure zsbSimpleMSNPopUpShow(strText: string; booalBottom: Boolean = True);
var
itemp, ix, iy: SmallInt;
begin
{
MSNPopUp1.Width:=200;
MSNPopUp11.Height := 50;
}
itemp := F_main.Width + 300;
itemp := itemp div 2;
itemp := itemp + F_main.Left;
itemp := Screen.Width - itemp;
ix := itemp;
iy := Screen.Height - F_main.Top - F_main.Height + 20;
SimpleMSNPopUpShow(strText, ix, iy);
end;
procedure AddLog_ErrorText(TempExSQL: string);
var
exsql, temp: string;
begin
temp := StringReplace(TempExSQL, '''', '''''', [rfReplaceAll]); //如果有单引号的替换
exsql := 'insert into Log_ErrorText(Text,DT,UN) values(''' + temp + ''',''' +
FormatDateTime('yyyy-MM-dd hh:mm:ss', Now) + ''',''' + ZStrUser + ''')';
with FDM.ClientDataSet2 do
begin
temp := RemoteServer.AppServer.fun_peradd(EXSQL);
end;
if temp = 'false' then //返回的是字符串
begin
zsbSimpleMSNPopUpShow('AddLog_ErrorText 操作失败,请联系管理员.');
end;
end;
procedure AddLog_Operation(TempExSQL: string);
var
exsql, temp: string;
begin
temp := StringReplace(TempExSQL, '''', '''''', [rfReplaceAll]); //如果有单引号的替换
exsql := 'insert into Log_Operation(Text,dt,un) values(''' + temp + ''',''' +
FormatDateTime('yyyy-MM-dd hh:mm:ss', Now) + ''',''' + ZStrUser + ''')';
with FDM.ClientDataSet2 do
begin
temp := RemoteServer.AppServer.fun_peradd(EXSQL);
end;
if temp = 'false' then //返回的是字符串
begin
zsbSimpleMSNPopUpShow('Log_Operation 操作失败,请联系管理员.');
end;
end;
function CheckKC(strbm: string; strph: string; iSL: SmallInt): Boolean;
var
temp: string;
begin //验证能否出库
Result := False;
if (strbm = '') or (strph = '') or (iSL < 0) then Exit;
temp := 'select sum(kcs) kcs from rkmxb where bm=''' + strbm + ''' and ph=''' + strph + '''';
SelectClientDataSet(FDM.ClientDataSet1, temp);
if FDM.ClientDataSet1.FieldByName('kcs').AsInteger >= iSL then Result := True;
end;
function DownKC(strbm: string; strph: string; iSL: SmallInt): string;
var //
temp, exsql: string;
itemp: SmallInt;
begin
Result := '';
exsql := '';
if (strbm = '') or (strph = '') or (iSL < 0) then Exit;
itemp := iSL;
temp := 'select kcs,rkdh from rkmxb where bm=''' + strbm + ''' and ph=''' + strph + ''' order by rkdh';
SelectClientDataSet(FDM.ClientDataSet1, temp);
if FDM.ClientDataSet1.RecordCount = 0 then Exit;
with FDM.ClientDataSet1 do
begin
First;
while not Eof do
begin
if FieldByName('kcs').AsInteger >= itemp then //够数量
begin //最终要从此出去
exsql := exsql + 'update rkmxb set kcs=kcs-' + inttostr(itemp) + ' where rkdh=''' + FieldByName('rkdh').AsString +
''' and bm=''' + strbm + ''' and ph=''' + strph + ''';';
Break;
end
else
begin
exsql := exsql + 'update rkmxb set kcs=kcs-kcs where rkdh=''' + FieldByName('rkdh').AsString +
''' and bm=''' + strbm + ''' and ph=''' + strph + ''';';
itemp := itemp - FieldByName('kcs').AsInteger;
Next;
end;
end;
end;
Result := exsql;
end;
procedure UpdateLastCompileTime;
var //发布新版本
strsql, temp, exsql, sLastCompileTime: string;
begin
sLastCompileTime := FechaCompilacion + ' ' + HoraCompilacion;
strsql := 'select LASTCOMPILETIME from unit where id=''1''';
SelectClientDataSet(FDM.ClientDataSet1, strsql);
exsql := '';
if FDM.ClientDataSet1.RecordCount = 0 then
begin
exsql := 'insert into unit(id,ver,LASTCOMPILETIME)values(''1'',''' + GetVersionString(Application.ExeName) + ''',''' + sLastCompileTime + ''')';
end
else
begin
temp := FDM.ClientDataSet1.fieldbyname('LASTCOMPILETIME').AsString;
if temp < sLastCompileTime then //如果当前程序是最新版的就更新
begin
exsql := 'update unit set ver=''' + GetVersionString(Application.ExeName) + ''',LASTCOMPILETIME=''' + sLastCompileTime + ''' where id=''1''';
end;
end;
if exsql <> '' then
begin
if EXSQLClientDataSet(FDM.ClientDataSet2, exsql) then
begin
//MessageShow('新版本发布完成.');
end
else
begin
//MessageShow('新版本发布失败.');
end;
end;
end;
procedure ShowBox(sShowMessage: string; iShowMode: Integer = 0);
begin
end;
procedure AddRzComcomboBoxFromTable(Combox: TRzComboBox; TableName: string; FieldName: string); //从数据库里边加载字段到 RzComcomboBox
var //1 控件 2 表名 3字段名 升序 不重复
strsql: string;
begin
strsql := 'select distinct ' + FieldName + ' from ' + TableName + ' order by ' + FieldName;
with FDM.ClientDataSet1 do
begin
data := RemoteServer.AppServer.fun_getdatasql(strsql);
First;
Combox.Clear;
Combox.Items.Add('');
while not Eof do
begin
Combox.Items.Add(fieldbyname(FieldName).AsString);
Next;
end;
end;
end;
procedure GetDateTimeDate; //获取当前时间
var
s: string;
begin
with FDM.getdatetime do
begin
s := 'select to_char(sysdate,' + '''yyyy-mm-dd''' + ')now from dual';
data := RemoteServer.AppServer.fun_getdatasql(s);
ZStrDate := Fieldbyname('now').AsString;
end;
end;
procedure GetDateTimeSecond; //获取当前时间 精确到秒
var
s: string;
begin
with FDM.getdatetime do
begin
s := 'select to_char(sysdate,' + '''HH24:MI:SS''' + ')now from dual';
data := RemoteServer.AppServer.fun_getdatasql(s);
ZStrTime := Fieldbyname('now').AsString;
end;
end;
function GetCRKDH(bRk: Boolean): string;
var //只适用于1-99 即 一天单子不超过100单
temp, strsql, strResult: string;
n, mo: SmallInt;
begin //获取入库单号 true入库 false 出库
temp := FormatDateTime('yyyy', Now);
strResult := temp;
temp := FormatDateTime('M', Now);
n := StrToInt(temp);
if n >= 10 then
begin
mo := n mod 36;
case mo of
10..35: temp := chr(mo + 55);
end;
end;
strResult := strResult + temp;
temp := FormatDateTime('d', Now);
n := StrToInt(temp);
if n >= 10 then
begin
mo := n mod 36;
case mo of
10..35: temp := chr(mo + 55);
end;
end;
strResult := strResult + temp;
if bRk then
begin
strResult := 'R' + strResult; //入库
strsql := 'select rkdh from rkzb where rkrq=''' + ZStrDate + ''' order by rkdh desc';
end
else
begin
strResult := 'C' + strResult; //入库
strsql := 'select ckdh from ckzb where ckrq=''' + ZStrDate + ''' order by ckdh desc';
end;
with FDM.ClientDataSet1 do
begin
data := RemoteServer.AppServer.fun_getdatasql(strsql);
end;
if FDM.ClientDataSet1.RecordCount <= 0 then
begin
temp := '0';
end
else
begin
FDM.ClientDataSet1.First;
if bRk then
begin
temp := FDM.ClientDataSet1.fieldbyname('rkdh').AsString;
end
else
begin
temp := FDM.ClientDataSet1.fieldbyname('ckdh').AsString;
end;
temp := RightStr(temp, 2);
end;
temp := IntToStr(StrToInt(temp) + 1);
if Length(temp) <> 2 then temp := '0' + temp;
strResult := strResult + temp;
Result := strResult;
end;
function GetYMXXStr(strtemp: string; strtype: string): Boolean;
var //1 值 2 类型,条码或编码
temp: string;
begin
Result := False;
if (strtype <> 'bm') and (strtype <> 'tm') then Exit;
temp := 'select bm,tm,mc,gg,dw,lb,jx,jg,jk,gys,sccj from ymxx where';
if (strtype = 'bm') then
begin
temp := temp + ' bm=''' + strtemp + '''';
end
else if strtype = 'tm' then
begin
temp := temp + ' tm=''' + strtemp + '''';
end;
with FDM.ClientDataSet1 do
begin
data := RemoteServer.AppServer.fun_getdatasql(temp);
end;
if FDM.ClientDataSet1.RecordCount = 1 then
begin
Result := True;
ZSLYMXX.StrBm := FDM.ClientDataSet1.FieldByName('bm').AsString;
ZSLYMXX.StrTm := FDM.ClientDataSet1.FieldByName('tm').AsString;
ZSLYMXX.StrMc := FDM.ClientDataSet1.FieldByName('mc').AsString;
ZSLYMXX.StrGg := FDM.ClientDataSet1.FieldByName('gg').AsString;
ZSLYMXX.StrDw := FDM.ClientDataSet1.FieldByName('dw').AsString;
ZSLYMXX.StrLb := FDM.ClientDataSet1.FieldByName('lb').AsString;
ZSLYMXX.StrJx := FDM.ClientDataSet1.FieldByName('jx').AsString;
ZSLYMXX.StrJg := FDM.ClientDataSet1.FieldByName('jg').AsString;
ZSLYMXX.StrJk := FDM.ClientDataSet1.FieldByName('jk').AsString;
ZSLYMXX.StrGys := FDM.ClientDataSet1.FieldByName('gys').AsString;
ZSLYMXX.StrSccj := FDM.ClientDataSet1.FieldByName('sccj').AsString;
end;
end;
function GetYMXXSl(strtemp: string; strtype: string): Boolean;
begin
Result := False;
if (strtype <> 'bm') or (strtype <> 'tm') then Exit;
if (strtype = 'bm') or (strtype = 'tm') then
begin
ZSLYMXX.SlBm := TStringList.Create;
ZSLYMXX.SlTm := TStringList.Create;
ZSLYMXX.SlMc := TStringList.Create;
ZSLYMXX.SlGg := TStringList.Create;
ZSLYMXX.SlDw := TStringList.Create;
ZSLYMXX.SlLb := TStringList.Create;
ZSLYMXX.SlJx := TStringList.Create;
ZSLYMXX.SlJg := TStringList.Create;
ZSLYMXX.SlGys := TStringList.Create;
ZSLYMXX.SlSccj := TStringList.Create;
end;
if (strtype = 'bm') then
begin
end
else if strtype = 'tm' then
begin
end;
end;
procedure ComboxLoadFromFile(ComboBox1: TRzComboBox; filepath: string);
var
sl: TStringList;
begin // ComboBox1 从文件加载
ComboBox1.Items.Clear;
sl := TStringList.Create();
sl.LoadFromFile(filepath);
ComboBox1.Items.Text := sl.Text;
sl.Free;
end;
procedure LocateClientDataSet(ClientDataSet1: TClientDataSet; field: string; value: string);
begin //定位
ClientDataSet1.Locate(field, value, []);
end;
procedure AddUpdateDelBtnEnabled(RzPanel1: TRzPanel; b: Boolean);
begin //参数一 TRzPanel控件名 ;参数二 是否有combobox {按钮命名:新增、删除、修改、取消、保存 五个按钮}
//好像不行 因为顺序不是预想的那样
if b then
begin
RzPanel1.Controls[0].Enabled := False; // 0 新增
MsgBoxInfo(RzPanel1.Controls[0].Name);
RzPanel1.Controls[1].Enabled := False; // 1 删除
MsgBoxInfo(RzPanel1.Controls[1].Name);
RzPanel1.Controls[2].Enabled := False; // 2 修改
MsgBoxInfo(RzPanel1.Controls[2].Name);
RzPanel1.Controls[3].Enabled := True; // 3 取消
MsgBoxInfo(RzPanel1.Controls[3].Name);
RzPanel1.Controls[4].Enabled := True; // 4 保存
MsgBoxInfo(RzPanel1.Controls[4].Name);
end
else
begin
RzPanel1.Controls[0].Enabled := True;
RzPanel1.Controls[1].Enabled := True;
RzPanel1.Controls[2].Enabled := True;
RzPanel1.Controls[3].Enabled := False;
RzPanel1.Controls[4].Enabled := False;
end;
end;
procedure ClearEditAndBox(RzPanel1: TRzPanel; b: Boolean);
var //参数一 TRzPanel控件名 ;参数二 是否有combobox
i: SmallInt;
begin //清空 TRzPanel 上的输入控件 Edit,RzEdit
for i := 0 to RzPanel1.ControlCount - 1 do
begin
if (RzPanel1.Controls[i].ClassType = TRzEdit) then
begin
(RzPanel1.Controls[i] as TRzEdit).Text := '';
end;
if (RzPanel1.Controls[i].ClassType = TRzButtonEdit) then
begin
(RzPanel1.Controls[i] as TRzButtonEdit).Text := '';
end;
{ if (RzPanel1.Controls[i].ClassType = TdxCurrencyEdit) then
begin
(RzPanel1.Controls[i] as TdxCurrencyEdit).Text := '0';
end; }
if b then
begin
if (RzPanel1.Controls[i].ClassType = TRzComboBox) then
begin
(RzPanel1.Controls[i] as TRzComboBox).ItemIndex := -1;
end;
end;
end;
end;
procedure PleaseWait(i_StartOrExit: SmallInt); //加载动画
var
HWndCalculator: HWnd;
S_file: string;
begin
HWndCalculator := Windows.FindWindow(nil, 'ZSB_PleaseWaitAutoClose');
if i_StartOrExit = 0 then
begin
S_file := ExtractFilePath(Application.Exename) + 'PleaseWait.exe';
if FileExists(S_file) then
begin
ShellExecute(Application.Handle, 'open', pchar(S_file), '-s', nil, SW_SHOWNORMAL);
end;
end;
if i_StartOrExit = 1 then
begin
if HWndCalculator <> 0 then
begin
SendMessage(HWndCalculator, WM_CLOSE, 0, 0);
end;
end;
end;
function GetPyChar(const HZ: AnsiString): string;
const
HZCode: array[0..25, 0..1] of Integer = ((1601, 1636), (1637, 1832), (1833, 2077),
(2078, 2273), (2274, 2301), (2302, 2432), (2433, 2593), (2594, 2786), (9999, 0000),
(2787, 3105), (3106, 3211), (3212, 3471), (3472, 3634), (3635, 3722), (3723, 3729),
(3730, 3857), (3858, 4026), (4027, 4085), (4086, 4389), (4390, 4557), (9999, 0000),
(9999, 0000), (4558, 4683), (4684, 4924), (4925, 5248), (5249, 5589));
var
i, j, HzOrd: Integer;
n: Integer;
begin
i := 1;
while i <= Length(HZ) do
begin
if (HZ[i] >= #160) and (HZ[i + 1] >= #160) then
begin
n := 0;
HzOrd := (Ord(HZ[i]) - 160) * 100 + Ord(HZ[i + 1]) - 160;
for j := 0 to 25 do
begin
if (HzOrd >= HZCode[j][0]) and (HzOrd <= HZCode[j][1]) then
begin
Result := Result + Char(Byte('A') + j);
n := 1;
Break;
end;
end;
if n = 0 then
Result := Result + ' ';
Inc(i);
end
else Result := Result + HZ[i];
Inc(i);
end;
end;
procedure MsgBoxInfo(sInfo: string);
begin
Application.MessageBox(PChar(sInfo), '提示信息', MB_ICONINFORMATION);
end;
procedure MsgErrorInfo(ErInfo: string);
begin
Application.MessageBox(PChar(ErInfo), '错误信息', MB_ICONERROR);
end;
function MsgBoxOk(sInfo: string): Boolean;
begin
if Application.MessageBox(PChar(sInfo), '操作确认',
MB_ICONQUESTION + MB_YESNO + MB_DEFBUTTON1) = IDYES then
Result := TRUE
else Result := FALSE;
end;
function MsgErrorInfo_RetryCancel(ErInfo: string): Boolean;
begin
if Application.MessageBox(PChar(ErInfo), '错误信息', MB_ICONERROR + MB_RETRYCANCEL) = idRETRY then
Result := TRUE
else Result := FALSE;
end;
function SelectClientDataSetResultCount(ClientDataSet1: TClientDataSet; strSQL: string): Integer;
begin
with ClientDataSet1 do
begin
data := RemoteServer.AppServer.fun_getdatasql(strSQL);
end;
Result := ClientDataSet1.RecordCount;
end;
function SelectClientDataSetResultFieldCaption(ClientDataSet1: TClientDataSet; strSQL, FieldName: string): string;
var
temp: string;
begin
temp := '';
with ClientDataSet1 do
begin
data := RemoteServer.AppServer.fun_getdatasql(strSQL);
end;
if ClientDataSet1.RecordCount = 1 then //若是0条记录或是两条记录则返回空值
begin
temp := ClientDataSet1.fieldbyname(FieldName).AsString;
end;
Result := temp;
end;
procedure SelectClientDataSet(ClientDataSet1: TClientDataSet; strSQL: string);
begin
with ClientDataSet1 do
begin
data := RemoteServer.AppServer.fun_getdatasql(strSQL);
end;
if ClientDataSet1.RecordCount = 0 then
begin
zsbSimpleMSNPopUpShow('没有相关记录.');
end;
end;
procedure SelectClientDataSetNoTips(ClientDataSet1: TClientDataSet; strSQL: string);
begin
with ClientDataSet1 do
begin
data := RemoteServer.AppServer.fun_getdatasql(strSQL);
//data := RemoteServer.AppServer.zsb_getdatasql(strSQL,zstruser);
end;
end;
procedure AddLog_ExSQLText(TempExSQL: string);
var
exsql, temp: string;
begin
temp := StringReplace(TempExSQL, '''', '''''', [rfReplaceAll]); //如果有单引号的替换
exsql := 'insert into Log_ExSQLText(SQLText,OpeeDT,UserName) values(''' + temp + ''',''' +
FormatDateTime('yyyy-MM-dd hh:mm:ss', Now) + ''',''' + ZStrUser + ''')';
with FDM.ClientDataSet2 do
begin
temp := RemoteServer.AppServer.fun_peradd(EXSQL);
end;
if temp = 'false' then //返回的是字符串
begin
zsbSimpleMSNPopUpShow('Log_ExSQLText 操作失败,请联系管理员.');
end;
end;
function EXSQLClientDataSet(ClientDataSet1: TClientDataSet; EXSQL: string): Boolean;
var
temp: string;
begin
//AddLog_ExSQLText(EXSQL);
with ClientDataSet1 do
begin
temp := RemoteServer.AppServer.fun_peradd(EXSQL);
end;
if temp = 'false' then //返回的是字符串
begin
result := False;
end
else
begin
result := True;
end;
end;
function EXSQLClientDataSetNoLog(ClientDataSet1: TClientDataSet; EXSQL: string): Boolean;
var
temp: string;
begin
with ClientDataSet1 do
begin
temp := RemoteServer.AppServer.fun_peradd(EXSQL);
end;
if temp = 'false' then //返回的是字符串
begin
result := False;
end
else
begin
result := True;
end;
end;
end.
|
{
MTB board configuration form implemetation.
LICENSE:
Copyright 2015-2021 Michal Petrilak, Jan Horacek
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 Board;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, Generics.Collections;
type
TF_Board = class(TForm)
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
E_Name: TEdit;
L_adresa: TLabel;
B_Apply: TButton;
B_Storno: TButton;
Label4: TLabel;
E_FW: TEdit;
GB_IO_type: TGroupBox;
CHB_IR0: TCheckBox;
CHB_IR3: TCheckBox;
CHB_IR2: TCheckBox;
CHB_IR1: TCheckBox;
E_Type: TEdit;
CHB_IR6: TCheckBox;
CHB_IR5: TCheckBox;
CHB_IR4: TCheckBox;
CHB_IR7: TCheckBox;
CHB_IR15: TCheckBox;
CHB_IR14: TCheckBox;
CHB_IR13: TCheckBox;
CHB_IR12: TCheckBox;
CHB_IR11: TCheckBox;
CHB_IR10: TCheckBox;
CHB_IR9: TCheckBox;
CHB_IR8: TCheckBox;
CHB_SCOM0: TCheckBox;
CHB_SCOM1: TCheckBox;
CHB_SCOM2: TCheckBox;
CHB_SCOM3: TCheckBox;
CHB_SCOM4: TCheckBox;
CHB_SCOM5: TCheckBox;
CHB_SCOM7: TCheckBox;
CHB_SCOM6: TCheckBox;
CHB_SCOM8: TCheckBox;
CHB_SCOM9: TCheckBox;
CHB_SCOM10: TCheckBox;
CHB_SCOM11: TCheckBox;
CHB_SCOM12: TCheckBox;
CHB_SCOM13: TCheckBox;
CHB_SCOM14: TCheckBox;
CHB_SCOM15: TCheckBox;
CHB_Exists: TCheckBox;
CHB_failure: TCheckBox;
CHB_Error: TCheckBox;
CHB_Warning: TCheckBox;
procedure B_StornoClick(Sender: TObject);
procedure B_ApplyClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
chb_irs: TList<TCheckBox>;
chb_scoms: TList<TCheckBox>;
public
OpenIndex: Integer;
procedure OpenForm(Module: Integer);
end;
var
F_Board: TF_Board;
implementation
uses fConfig, LibraryEvents, Errors;
{$R *.dfm}
procedure TF_Board.FormCreate(Sender: TObject);
begin
Self.chb_irs := TList<TCheckBox>.Create();
Self.chb_irs.Add(Self.CHB_IR0);
Self.chb_irs.Add(Self.CHB_IR1);
Self.chb_irs.Add(Self.CHB_IR2);
Self.chb_irs.Add(Self.CHB_IR3);
Self.chb_irs.Add(Self.CHB_IR4);
Self.chb_irs.Add(Self.CHB_IR5);
Self.chb_irs.Add(Self.CHB_IR6);
Self.chb_irs.Add(Self.CHB_IR7);
Self.chb_irs.Add(Self.CHB_IR8);
Self.chb_irs.Add(Self.CHB_IR9);
Self.chb_irs.Add(Self.CHB_IR10);
Self.chb_irs.Add(Self.CHB_IR11);
Self.chb_irs.Add(Self.CHB_IR12);
Self.chb_irs.Add(Self.CHB_IR13);
Self.chb_irs.Add(Self.CHB_IR14);
Self.chb_irs.Add(Self.CHB_IR15);
Self.chb_scoms := TList<TCheckBox>.Create();
Self.chb_scoms.Add(Self.CHB_SCOM0);
Self.chb_scoms.Add(Self.CHB_SCOM1);
Self.chb_scoms.Add(Self.CHB_SCOM2);
Self.chb_scoms.Add(Self.CHB_SCOM3);
Self.chb_scoms.Add(Self.CHB_SCOM4);
Self.chb_scoms.Add(Self.CHB_SCOM5);
Self.chb_scoms.Add(Self.CHB_SCOM6);
Self.chb_scoms.Add(Self.CHB_SCOM7);
Self.chb_scoms.Add(Self.CHB_SCOM8);
Self.chb_scoms.Add(Self.CHB_SCOM9);
Self.chb_scoms.Add(Self.CHB_SCOM10);
Self.chb_scoms.Add(Self.CHB_SCOM11);
Self.chb_scoms.Add(Self.CHB_SCOM12);
Self.chb_scoms.Add(Self.CHB_SCOM13);
Self.chb_scoms.Add(Self.CHB_SCOM14);
Self.chb_scoms.Add(Self.CHB_SCOM15);
end;
procedure TF_Board.FormDestroy(Sender: TObject);
begin
Self.chb_irs.Free();
Self.chb_scoms.Free();
end;
procedure TF_Board.B_ApplyClick(Sender: TObject);
begin
if ((not modules[OpenIndex].failure) and (Self.CHB_failure.Checked)) then
begin
// module is failing
modules[OpenIndex].failure := true;
if (Assigned(LibEvents.OnError.event)) then
LibEvents.OnError.event(Self, LibEvents.OnError.data, RCS_MODULE_FAILED, OpenIndex, 'Modul nekomunikuje');
if (Assigned(LibEvents.OnOutputChanged.event)) then
LibEvents.OnOutputChanged.event(FormConfig, LibEvents.OnOutputChanged.data, OpenIndex);
if (Assigned(LibEvents.OnInputChanged.event)) then
LibEvents.OnInputChanged.event(FormConfig, LibEvents.OnInputChanged.data, OpenIndex);
if (Assigned(LibEvents.OnModuleChanged.event)) then
LibEvents.OnModuleChanged.event(FormConfig, LibEvents.OnModuleChanged.data, OpenIndex);
end;
if (((modules[OpenIndex].failure) and (not Self.CHB_failure.Checked)) or
((FormConfig.Status = TSimulatorStatus.running) and (not modules[OpenIndex].exists) and
(Self.CHB_Exists.Checked))) then
begin
// module is restored
modules[OpenIndex].failure := false;
if (Assigned(LibEvents.OnError.event)) then
LibEvents.OnError.event(Self, LibEvents.OnError.data, RCS_MODULE_RESTORED, OpenIndex, 'Modul komunikuje');
if (Assigned(LibEvents.OnOutputChanged.event)) then
LibEvents.OnOutputChanged.event(FormConfig, LibEvents.OnOutputChanged.data, OpenIndex);
if (Assigned(LibEvents.OnInputChanged.event)) then
LibEvents.OnInputChanged.event(FormConfig, LibEvents.OnInputChanged.data, OpenIndex);
if (Assigned(LibEvents.OnModuleChanged.event)) then
LibEvents.OnModuleChanged.event(FormConfig, LibEvents.OnModuleChanged.data, OpenIndex);
end;
modules[OpenIndex].name := Self.E_Name.Text;
modules[OpenIndex].typ := Self.E_Type.Text;
modules[OpenIndex].fw := Self.E_FW.Text;
modules[OpenIndex].exists := Self.CHB_Exists.Checked;
var errorChanged: Boolean := (modules[OpenIndex].error <> Self.CHB_Error.Checked);
modules[OpenIndex].error := Self.CHB_Error.Checked;
var warningChanged: Boolean := (modules[OpenIndex].warning <> Self.CHB_Warning.Checked);
modules[OpenIndex].warning := Self.CHB_Warning.Checked;
modules[OpenIndex].irs := 0;
for var i : Integer := 0 to Self.chb_irs.Count-1 do
if (Self.chb_irs[i].Checked) then
modules[OpenIndex].irs := modules[OpenIndex].irs or (1 shl i);
modules[OpenIndex].scoms := 0;
for var i : Integer := 0 to Self.chb_scoms.Count-1 do
if (Self.chb_scoms[i].Checked) then
modules[OpenIndex].scoms := modules[OpenIndex].scoms or (1 shl i);
FormConfig.SaveData(FormConfig.config_fn);
if ((errorChanged) or (warningChanged)) then
if (Assigned(LibEvents.OnModuleChanged.event)) then
LibEvents.OnModuleChanged.event(FormConfig, LibEvents.OnModuleChanged.data, OpenIndex);
end;
procedure TF_Board.OpenForm(Module: Integer);
begin
Self.L_adresa.Caption := IntToStr(Module);
Self.OpenIndex := Module;
Self.E_Name.Text := modules[OpenIndex].name;
Self.E_FW.Text := modules[OpenIndex].fw;
Self.CHB_Exists.Checked := modules[OpenIndex].exists;
Self.CHB_failure.Checked := modules[OpenIndex].failure;
Self.CHB_Error.Checked := modules[OpenIndex].error;
Self.CHB_Warning.Checked := modules[OpenIndex].warning;
Self.E_Type.Text := modules[OpenIndex].typ;
begin
var irs := modules[OpenIndex].irs;
for var i : Integer := 0 to Self.chb_irs.Count-1 do
begin
Self.chb_irs[i].Checked := ((irs and 1) > 0);
irs := irs shr 1;
end;
end;
begin
var scoms := modules[OpenIndex].scoms;
for var i : Integer := 0 to Self.chb_scoms.Count-1 do
begin
Self.chb_scoms[i].Checked := ((scoms and 1) > 0);
scoms := scoms shr 1;
end;
end;
Self.Caption := 'Upravit desku ' + IntToStr(Module);
Self.ActiveControl := Self.E_Name;
Self.Show();
end;
procedure TF_Board.B_StornoClick(Sender: TObject);
begin
Self.Close();
end;
initialization
finalization
FreeAndNil(F_Board);
end.// unit
|
{*********************************************************************
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Autor: Brovin Y.D.
* E-mail: y.brovin@gmail.com
*
********************************************************************}
unit FGX.FlipView.Effect;
interface
uses
FMX.Presentation.Style, FMX.Controls.Presentation, FMX.Filter.Effects, FMX.Ani, FMX.Objects, FMX.Controls.Model,
FMX.Graphics, FMX.Presentation.Messages, FMX.Controls, FGX.FlipView.Presentation, FGX.FlipView.Types, FGX.FlipView;
type
{ TfgFlipViewEffectPresentation }
TfgFlipViewEffectPresentation = class(TfgStyledFlipViewBasePresentation)
private
[Weak] FNextImage: TBitmap;
FTransitionEffect: TImageFXEffect;
FTransitionAnimaton: TFloatAnimation;
{ Event handlers }
procedure HandlerFinishAnimation(Sender: TObject);
protected
{ Messages From Model}
procedure MMEffectOptionsChanged(var AMessage: TDispatchMessage); message TfgFlipViewMessages.MM_EFFECT_OPTIONS_CHANGED;
protected
procedure RecreateEffect;
{ Styles }
procedure ApplyStyle; override;
procedure FreeStyle; override;
public
procedure ShowNextImage(const ANewItemIndex: Integer; const ADirection: TfgDirection; const AAnimate: Boolean); override;
end;
implementation
uses
System.Types, System.SysUtils, System.Rtti, FMX.Presentation.Factory, FMX.Types, FGX.Asserts,
System.Classes, System.Math;
{ TfgFlipViewEffectPresentation }
procedure TfgFlipViewEffectPresentation.ApplyStyle;
var
NewImage: TBitmap;
begin
inherited ApplyStyle;
{ Image container for current slide }
if ImageContainer <> nil then
begin
ImageContainer.Visible := True;
ImageContainer.Margins.Rect := TRectF.Empty;
NewImage := Model.CurrentImage;
if NewImage <> nil then
ImageContainer.Bitmap.Assign(Model.CurrentImage);
FTransitionEffect := Model.EffectOptions.TransitionEffectClass.Create(nil);
FTransitionEffect.Enabled := False;
FTransitionEffect.Stored := False;
FTransitionEffect.Parent := ImageContainer;
FTransitionAnimaton := TFloatAnimation.Create(nil);
FTransitionAnimaton.Parent := FTransitionEffect;
FTransitionAnimaton.Enabled := False;
FTransitionAnimaton.Stored := False;
FTransitionAnimaton.PropertyName := 'Progress';
FTransitionAnimaton.StopValue := 100;
FTransitionAnimaton.Duration := Model.EffectOptions.Duration;
FTransitionAnimaton.OnFinish := HandlerFinishAnimation;
end;
end;
procedure TfgFlipViewEffectPresentation.FreeStyle;
begin
FTransitionEffect := nil;
FTransitionAnimaton := nil;
inherited FreeStyle;
end;
procedure TfgFlipViewEffectPresentation.HandlerFinishAnimation(Sender: TObject);
begin
try
if (FNextImage <> nil) and (ImageContainer <> nil) then
ImageContainer.Bitmap.Assign(FNextImage);
if FTransitionEffect <> nil then
FTransitionEffect.Enabled := False;
finally
Model.FinishChanging;
end;
end;
procedure TfgFlipViewEffectPresentation.MMEffectOptionsChanged(var AMessage: TDispatchMessage);
begin
RecreateEffect;
FTransitionAnimaton.Duration := Model.EffectOptions.Duration;
end;
procedure TfgFlipViewEffectPresentation.RecreateEffect;
var
EffectClass: TfgImageFXEffectClass;
begin
AssertIsNotNil(Model);
AssertIsNotNil(Model.EffectOptions);
AssertIsNotNil(Model.EffectOptions.TransitionEffectClass);
// We don't recreat effect, if current effect class is the same as a Options class.
EffectClass := Model.EffectOptions.TransitionEffectClass;
if FTransitionEffect is EffectClass then
Exit;
if FTransitionEffect <> nil then
begin
FTransitionEffect.Parent := nil;
FTransitionAnimaton := nil;
end;
FreeAndNil(FTransitionEffect);
FTransitionEffect := EffectClass.Create(nil);
FTransitionEffect.Enabled := False;
FTransitionEffect.Stored := False;
FTransitionEffect.Parent := ImageContainer;
FTransitionAnimaton := TFloatAnimation.Create(nil);
FTransitionAnimaton.Parent := FTransitionEffect;
FTransitionAnimaton.Enabled := False;
FTransitionAnimaton.Stored := False;
FTransitionAnimaton.PropertyName := 'Progress';
FTransitionAnimaton.StopValue := 100;
FTransitionAnimaton.Duration := Model.EffectOptions.Duration;
FTransitionAnimaton.OnFinish := HandlerFinishAnimation;
end;
procedure TfgFlipViewEffectPresentation.ShowNextImage(const ANewItemIndex: Integer; const ADirection: TfgDirection;
const AAnimate: Boolean);
var
RttiCtx: TRttiContext;
RttiType: TRttiType;
TargetBitmapProperty: TRttiProperty;
TargetBitmap: TBitmap;
begin
inherited;
if (csDesigning in ComponentState) or not AAnimate then
begin
FNextImage := nil;
if ImageContainer <> nil then
ImageContainer.Bitmap.Assign(Model.CurrentImage);
Model.FinishChanging;
end
else
begin
FNextImage := Model.CurrentImage;
if (FTransitionAnimaton <> nil) and (FTransitionAnimaton <> nil) then
begin
FTransitionAnimaton.Stop;
if not (FTransitionEffect is Model.EffectOptions.TransitionEffectClass) then
RecreateEffect;
RttiCtx := TRttiContext.Create;
try
RttiType := RttiCtx.GetType(FTransitionEffect.ClassInfo);
TargetBitmapProperty := RttiType.GetProperty('Target');
TargetBitmap := TBitmap(TargetBitmapProperty.GetValue(FTransitionEffect).AsObject);
TargetBitmap.Assign(Model.CurrentImage);
finally
RttiCtx.Free;
end;
FTransitionEffect.Enabled := True;
FTransitionAnimaton.StartValue := 0;
FTransitionAnimaton.Start;
end;
end;
end;
initialization
TPresentationProxyFactory.Current.Register('fgFlipView-Effect', TStyledPresentationProxy<TfgFlipViewEffectPresentation>);
finalization
TPresentationProxyFactory.Current.Unregister('fgFlipView-Effect', TStyledPresentationProxy<TfgFlipViewEffectPresentation>);
end.
|
unit xpCodeGen;
(*
* 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.
*
* This code was inspired to expidite the creation of unit tests
* for use the Dunit test frame work.
*
* The Initial Developer of XPGen is Michael A. Johnson.
* Portions created The Initial Developer is Copyright (C) 2000.
* Portions created by The DUnit Group are Copyright (C) 2000.
* All rights reserved.
*
* Contributor(s):
* Michael A. Johnson <majohnson@golden.net>
* Juanco Aņez <juanco@users.sourceforge.net>
* Chris Morris <chrismo@users.sourceforge.net>
* Jeff Moore <JeffMoore@users.sourceforge.net>
* The DUnit group at SourceForge <http://dunit.sourceforge.net>
*
*)
{
Unit : xpCodeGen
Description : This unit is responsible for generating output code from a sequence
of parse nodes generated by the parser
Programmer : mike
Date : 06-Jul-2000
}
interface
uses
classes,
ParseDef,
xpParse;
type
DriverSrcOutput = class
public
procedure OutputStart(NameOfUnit: string); virtual; abstract;
procedure OutputSrcCode(srcLine: string); virtual; abstract;
procedure OutputFinish; virtual; abstract;
end;
DriverSrcOutputTstrings = class(DriverSrcOutput)
fOutputStrings: TStrings;
public
constructor Create(newtarget: TStrings);
destructor Destroy; override;
procedure OutputStart(NameOfUnit: string); override;
procedure OutputSrcCode(srcLine: string); override;
procedure OutputFinish; override;
end;
DriverSrcOutputText = class(DriverSrcOutputTstrings)
protected
SourceCodeBuffer: TStringList;
public
constructor Create;
destructor Destroy; override;
function Text: string;
end;
SrcGenExternalTest = class
protected
fNameOfUnit: string;
ftestMethodPrefix: string;
fTestUnitPrefix: string;
fTestClassPrefix: string;
fOutputDriver: DriverSrcOutput;
public
constructor Create(newUnitName: string; driver: DriverSrcOutput);
destructor Destroy; override;
procedure GenerateCode(ParseNodeList: TList); virtual;
end;
implementation
uses
SysUtils;
{ DriverSrcOutputTstrings }
constructor DriverSrcOutputTstrings.Create(newtarget: TStrings);
begin
inherited Create;
fOutputStrings := newtarget;
end;
destructor DriverSrcOutputTstrings.Destroy;
begin
inherited Destroy;
end;
procedure DriverSrcOutputTstrings.OutputFinish;
begin
{ it's necessary to provide an implementation because of the pure virtual designation }
end;
procedure DriverSrcOutputTstrings.OutputSrcCode(srcLine: string);
begin
foutputStrings.Add(srcLine);
end;
procedure DriverSrcOutputTstrings.OutputStart(NameOfUnit: string);
begin
{ it's necessary to provide an implementation because of the pure virtual designation }
foutputStrings.clear;
end;
{ SrcGenExternalTest }
constructor SrcGenExternalTest.Create(newUnitName: string; driver:
DriverSrcOutput);
begin
ftestMethodPrefix := 'Verify';
fTestUnitPrefix := 'Test_';
fTestClassPrefix := 'Check_';
fNameOfUnit := newUnitName;
fOutputDriver := driver;
inherited Create;
end;
destructor SrcGenExternalTest.Destroy;
begin
inherited Destroy;
end;
procedure SrcGenExternalTest.GenerateCode(ParseNodeList: TList);
{
Procedure : SrcGenExternalTest.GenerateCode
Description : generates output based on the parsednodes found in the parse step
Input : ParseNodeList: TList
Programmer : mike
Date : 07-Jul-2000
}
var
methodIter,
NodeIter: integer;
parseNode: TParseNodeClass;
begin
if assigned(foutputDriver) then
begin
with foutputDriver do
begin
OutputStart(fNameOfUnit);
OutputSrcCode('unit ' + fTestUnitPrefix + fNameOfUnit + ';');
OutputSrcCode('');
OutputSrcCode('interface');
OutputSrcCode('');
OutputSrcCode('uses');
OutputSrcCode(' ' + 'TestFramework' + ',');
OutputSrcCode(' ' + 'SysUtils' + ',');
OutputSrcCode(' ' + fNameOfUnit + ';');
OutputSrcCode('');
OutputSrcCode('type');
{ generate crack classes for accessing protected methods }
for nodeIter := 0 to ParseNodeList.count - 1 do
begin
ParseNode := ParseNodeList[nodeIter];
if (ParseNode.PubMethodList.count > 0) or
(ParseNode.PrtMethodList.count > 0) then
begin
OutputSrcCode('');
OutputSrcCode('CRACK_' + ParseNode.NameClass + ' = class(' +
ParseNode.NameClass + ');');
end;
end;
for nodeIter := 0 to ParseNodeList.count - 1 do
begin
ParseNode := ParseNodeList[nodeIter];
if (ParseNode.PubMethodList.count > 0) or
(ParseNode.PrtMethodList.count > 0) then
begin
OutputSrcCode('');
OutputSrcCode(fTestClassPrefix + ParseNode.NameClass +
' = class(TTestCase)');
OutputSrcCode('public');
OutputSrcCode(' procedure setUp; override;');
OutputSrcCode(' procedure tearDown; override;');
OutputSrcCode('published');
{ test the public/published/automated methods }
for methodIter := 0 to ParseNode.PubMethodList.count - 1 do
begin
OutputSrcCode(' procedure ' + ftestMethodPrefix +
ParseNode.PubMethodList[methodIter] + ';');
end;
{ test the protected methods too }
for methodIter := 0 to ParseNode.PrtMethodList.count - 1 do
begin
OutputSrcCode(' procedure ' + ftestMethodPrefix +
ParseNode.PrtMethodList[methodIter] + ';');
end;
OutputSrcCode('end;');
end;
end;
OutputSrcCode('');
OutputSrcCode('function Suite : ITestSuite;');
OutputSrcCode('');
OutputSrcCode('implementation');
OutputSrcCode('');
{ write the implemention for the test suite }
OutputSrcCode('function Suite : ITestSuite;');
OutputSrcCode('begin');
outputSrcCode(' result := TTestSuite.Create(''' + fNameOfUnit +
' Tests'');');
{ add each test method to the suite for this unit }
for nodeIter := 0 to ParseNodeList.count - 1 do
begin
ParseNode := ParseNodeList[nodeIter];
if (ParseNode.PubMethodList.count > 0) or
(ParseNode.PrtMethodList.count > 0) then
begin
OutputSrcCode('');
OutputSrcCode(format(' result.addTest(testSuiteOf(%s%s));',
[fTestClassPrefix, ParseNode.NameClass]));
end;
end;
OutputSrcCode('end;');
{ write the implementation for each of the test classes }
for nodeIter := 0 to ParseNodeList.count - 1 do
begin
ParseNode := ParseNodeList[nodeIter];
if (ParseNode.PubMethodList.count > 0) or
(ParseNode.PrtMethodList.count > 0) then
begin
OutputSrcCode('');
OutputSrcCode('procedure ' + fTestClassPrefix +
ParseNode.NameClass + '.setUp;');
OutputSrcCode('begin');
OutputSrcCode('end;');
OutputSrcCode('');
OutputSrcCode('procedure ' + fTestClassPrefix +
ParseNode.NameClass + '.tearDown;');
OutputSrcCode('begin');
OutputSrcCode('end;');
{ generate public,automated and published methods }
for methodIter := 0 to ParseNode.PubMethodList.count - 1 do
begin
OutputSrcCode('');
OutputSrcCode('procedure ' + fTestClassPrefix +
ParseNode.NameClass + '.' + fTestMethodPrefix +
ParseNode.PubMethodList[methodIter] + ';');
OutputSrcCode('begin');
OutputSrcCode(' fail(''Test Not Implemented Yet'');');
OutputSrcCode('end;');
end;
{ generate for the protected ones too }
for methodIter := 0 to ParseNode.PrtMethodList.count - 1 do
begin
OutputSrcCode('');
OutputSrcCode('procedure ' + fTestClassPrefix +
ParseNode.NameClass + '.' + fTestMethodPrefix +
ParseNode.PrtMethodList[methodIter] + ';');
OutputSrcCode('begin');
OutputSrcCode(' fail(''Test Not Implemented Yet'');');
OutputSrcCode('end;');
end;
end;
end;
OutputSrcCode('');
OutputSrcCode('end.');
OutputFinish;
end;
end;
end;
{ DriverSrcOutputText }
constructor DriverSrcOutputText.Create;
begin
{ create a stub where this data can be held }
SourceCodeBuffer := TStringList.Create;
inherited create(SourceCodeBuffer);
end;
destructor DriverSrcOutputText.Destroy;
begin
SourceCodeBuffer.Free;
inherited Destroy;
end;
function DriverSrcOutputText.Text: string;
var
sourceLineIter: integer;
begin
result := '';
{ generate text when there is something to output }
if SourceCodeBuffer.Count > 0 then
begin
result := SourceCodeBuffer[0];
{ output any other text that we need }
for sourceLineIter := 1 to SourceCodeBuffer.Count - 1 do
begin
result := result + #13 + SourceCodeBuffer[sourceLineIter];
end;
end;
end;
end.
|
object ShutDownMsg: TShutDownMsg
Left = 1198
Top = 300
BorderStyle = bsDialog
Caption = 'Shutdown'
ClientHeight = 142
ClientWidth = 429
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -10
Font.Name = 'MS Sans Serif'
Font.Style = []
FormStyle = fsStayOnTop
OldCreateOrder = False
Position = poDesktopCenter
PixelsPerInch = 96
TextHeight = 13
object ShutDownMsg: TLabel
Left = 72
Top = 15
Width = 321
Height = 24
Alignment = taCenter
Caption = 'ShutDownMsg'
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -21
Font.Name = 'MS Sans Serif'
Font.Style = [fsBold]
ParentFont = False
end
object CloseBtn: TButton
Left = 112
Top = 83
Width = 89
Height = 46
Caption = 'Shutdown Now'
Default = True
ModalResult = 1
TabOrder = 0
end
object CancelBtn: TButton
Left = 232
Top = 83
Width = 104
Height = 46
Cancel = True
Caption = 'Cancel Shutdown'
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
ModalResult = 2
ParentFont = False
TabOrder = 1
end
object SDTimer: TTimer
Enabled = False
OnTimer = SDTimerTimer
Left = 8
Top = 168
end
end
|
unit UnitMyTest;
interface
uses
DUnitX.TestFramework, Unit1; // 把要測試的檔案加入
type
[TestFixture]
TMyTestObject = class(TObject)
strict private
aForm: TForm1; // 自行加入 class
public
[Setup]
procedure Setup;
[TearDown]
procedure TearDown;
[Test]
// 一個 [Test] 配一個測試函式
[TestCase('TestA', '1,2,3')]
[TestCase('TestB', '3,4,7')]
procedure Test_MyAdd(AValue1, AValue2, _Result: string);
[Test]
[TestCase('TestA', '3,2,1')]
[TestCase('TestB', '3,4,0')]
// Tony 故意讓結果出錯
procedure Test_MySub(AValue1, AValue2, _Result: string);
end;
implementation
procedure TMyTestObject.Setup;
begin
aForm := TForm1.Create(nil); // 初始化相關程式碼
end;
procedure TMyTestObject.TearDown;
begin
aForm := nil; // 結束測試相關程式碼
end;
// 其它 Assert 功能請參考
// http://docwiki.embarcadero.com/RADStudio/Sydney/en/DUnitX_Overview
procedure TMyTestObject.Test_MyAdd(AValue1, AValue2, _Result: string);
var
R: string;
begin
// Tony: R 是實際的執行結果
R := aForm.MyAdd(AValue1, AValue2);
// Tony: _Result 是 TestCase 裡預期的結果
Assert.AreEqual(R, _Result);
end;
procedure TMyTestObject.Test_MySub(AValue1, AValue2, _Result: string);
var
R: string;
begin
R := aForm.MySub(AValue1, AValue2);
Assert.AreEqual(R, _Result);
end;
initialization
TDUnitX.RegisterTestFixture(TMyTestObject);
end.
|
unit uTimer;
interface
uses
{$IF CompilerVersion > 22}
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
{$ELSE}
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls,
{$IFEND}
CNClrLib.Control.Base, CNClrLib.Component.Timer;
type
TForm14 = class(TForm)
Memo1: TMemo;
btnStartTimer: TButton;
btnEndTimer: TButton;
CnTimer1: TCnTimer;
procedure btnStartTimerClick(Sender: TObject);
procedure btnEndTimerClick(Sender: TObject);
procedure CnTimer1Tick(Sender: TObject; E: _EventArgs);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form14: TForm14;
implementation
{$R *.dfm}
procedure TForm14.btnEndTimerClick(Sender: TObject);
begin
CnTimer1.Stop;
end;
procedure TForm14.btnStartTimerClick(Sender: TObject);
begin
// Create a timer with a two second interval.
CnTimer1.Interval := 2000;
CnTimer1.Start;
end;
procedure TForm14.CnTimer1Tick(Sender: TObject; E: _EventArgs);
begin
Memo1.Lines.Add('The Elapsed event was raised at '+ DateTimeToStr(Now));
end;
end.
|
{ ---------------------------------------------------------------------------- }
{ BulbTracer for MB3D }
{ Copyright (C) 2016-2017 Andreas Maschke }
{ ---------------------------------------------------------------------------- }
unit MeshIOUtil;
interface
type
BytePos = (EndVal, ByteVal);
PEndianCnvDblRec = ^EndianCnvDblRec;
PEndianCnvSnglRec = ^EndianCnvSnglRec;
EndianCnvDblRec = packed record
case pos: BytePos of
EndVal: (EndianVal: double);
ByteVal: (Bytes: array[0..SizeOf(Double)-1] of byte);
end;
EndianCnvSnglRec = packed record
case pos: BytePos of
EndVal: (EndianVal: Single);
ByteVal: (Bytes: array[0..SizeOf(Single)-1] of byte);
end;
function SwapEndianInt32(Value: Int32): Int32;
function SwapEndianInt16(Value: Int16): Int16;
procedure SwapBytesSingle( A, B: PEndianCnvSnglRec );
const
cMB3DMeshSegFileExt = 'mb3dmeshseg';
LW_MAXU2: Int32 = $FF00;
implementation
procedure SwapBytesDouble( A, B: PEndianCnvDblRec );
var
i: integer;
begin
for i := high(A.Bytes) downto low(A.Bytes) do
A.Bytes[i] := B.Bytes[High(A.Bytes) - i];
end;
procedure SwapBytesSingle( A, B: PEndianCnvSnglRec );
var
i: integer;
begin
for i := high(A.Bytes) downto low(A.Bytes) do
A.Bytes[i] := B.Bytes[High(A.Bytes) - i];
end;
function SwapEndianInt32(Value: Int32): Int32;
begin
Result := Swap(Value shr 16) or (longint(Swap(Value and $FFFF)) shl 16);
end;
function SwapEndianInt16(Value: Int16): Int16;
begin
Result := Swap( Value );
end;
end.
|
unit form2;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, sqlite3conn, sqldb, db, FileUtil, Forms, Controls,
Graphics, Dialogs, StdCtrls, EditBtn, DbCtrls;
type
{ TForm1 }
TForm1 = class(TForm)
DataSource1: TDataSource;
DateEdit1: TDateEdit;
DateEdit2: TDateEdit;
Memo1: TMemo;
SaveButton: TButton;
Button2: TButton;
CheckBox1: TCheckBox;
Proj_Name_Edit: TEdit;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label5: TLabel;
SQLQuery1: TSQLQuery;
SQLTransaction1: TSQLTransaction;
procedure FormActivate(Sender: TObject);
procedure Memo1Enter(Sender: TObject);
procedure SaveButtonClick(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: boolean);
procedure FormCreate(Sender: TObject);
procedure Proj_StartDateChange(Sender: TObject);
procedure ProjectInsert();
procedure updateProjectNum(Sender: TObject);
Function CloseForm():Boolean;
private
{ private declarations }
public
var RecordID: integer;
ActivateForm: boolean;
{ public declarations }
end;
var
Form1: TForm1;
implementation
var
closeNoQuestion: Boolean;
projectName: string;
{$R *.lfm}
{ TForm1 }
procedure TForm1.Proj_StartDateChange(Sender: TObject);
begin
end;
Function TForm1.CloseForm():Boolean ;
Begin
{This asks the question whether you want to save or not.
If you want to quit it closes the dialog.
Otherwise it returns you to the dialog.}
case QuestionDlg ('Confirm Cancel.','Are you sure that you want to close without saving?',mtConfirmation,[mrYes, mrNo],'') of
mrYes: CloseForm := True;
mrNo : CloseForm := False;
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
Form1.Close;
end;
procedure TForm1.ProjectInsert;
var emptydate : boolean;
begin
emptydate := false;
if (DateEdit1.text='') or (DateEdit2.Text = '') then
Begin
ShowMessage('Date field cannot be empty.');
emptydate := true;
end
Else
Begin
if RecordID = -1 then
Begin
SQLQuery1.Open;
SQLQuery1.SQL.text:='INSERT INTO projects VALUES (:PK, :Proj_Name, :Proj_StartDate, :Proj_EndDate, :Proj_Description, :Proj_Active);';
SQLQuery1.Params.ParamByName('Proj_Name').AsString := Proj_Name_Edit.text;
SQLQuery1.Params.ParamByName('Proj_StartDate').AsString := DateEdit1.text;
SQLQuery1.Params.ParamByName('Proj_EndDate').AsString := DateEdit2.text;
SQLQuery1.Params.ParamByName('Proj_Description').AsString := Memo1.text;
if Checkbox1.Checked = True then
SQLQuery1.Params.ParamByName('Proj_Active').AsInteger :=1
else
SQLQuery1.Params.ParamByName('Proj_Active').AsInteger :=0;
SQLQuery1.ExecSQL;
SQLTransaction1.commit;
end
Else
Begin
SQLQuery1.Open;
SQLQuery1.SQL.text:='UPDATE projects SET Proj_name = :Proj_Name, Proj_StartDate= :Proj_StartDate, Proj_EndDate= :Proj_EndDate, Proj_Description= :Proj_Description, Proj_Active =:Proj_Active WHERE Proj_PK='+chr(39)+IntToStr(RecordID)+chr(39);
SQLQuery1.Params.ParamByName('Proj_Name').AsString := Proj_Name_Edit.text;
SQLQuery1.Params.ParamByName('Proj_StartDate').AsString := DateEdit1.text;
SQLQuery1.Params.ParamByName('Proj_EndDate').AsString := DateEdit2.text;
SQLQuery1.Params.ParamByName('Proj_Description').AsString := Memo1.text;
if Checkbox1.Checked = True then
SQLQuery1.Params.ParamByName('Proj_Active').AsInteger :=1
else
SQLQuery1.Params.ParamByName('Proj_Active').AsInteger :=0;
SQLQuery1.ExecSQL;
SQLTransaction1.commit;
//SQLQuery1.Close;
end;
closeNoQuestion := True; // Set it so that no question is asked.
Form1.Close;
end;
end;
procedure TForm1.SaveButtonClick(Sender: TObject);
begin
ProjectInsert();
end;
procedure TForm1.FormActivate(Sender: TObject);
begin
closeNoQuestion := False ;
if ActivateForm = True then
Begin
if RecordID = -1 then
Begin
SQLQuery1.SQL.text:='Select * FROM projects';
SQLQuery1.Close;
Proj_Name_Edit.Text := 'Project Name'; // Assign a generic name to the project
DateEdit1.Date := Now;
DateEdit2.Date := Now+7; // Every project has a 7 day length assumed.
Memo1.Text := 'Project Description Here';
Checkbox1.Checked := True;
end
else
begin
SQLQuery1.SQL.text:='Select * from projects where Proj_PK='+chr(39)+IntToStr(RecordID)+chr(39);
SQLQuery1.Open;
//SQLQuery1.Close;
Proj_Name_Edit.Text := SQLQuery1.Fields[1].AsString;
DateEdit1.Date := StrToDateTime(SQLQuery1.Fields[2].AsString);
DateEdit2.Date := StrToDateTime(SQLQuery1.Fields[3].AsString);
Memo1.Text := SQLQuery1.Fields[4].AsString;
if StrToInt(SQLQuery1.Fields[5].AsString) = 0 then
Checkbox1.Checked := False
else
Checkbox1.Checked := True;
end;
updateProjectNum(Form1); // Add the project number to the form
Form1.ActiveControl := Form1.Proj_Name_Edit; // Has to be the last thing that happesn
Proj_Name_Edit.SelectAll;
end;
ActivateForm := False;
end;
procedure TForm1.Memo1Enter(Sender: TObject);
begin
Memo1.SelectAll;
end;
procedure TForm1.updateProjectNum(Sender: TObject);
begin
if RecordID = -1 then
Label5.Caption := 'New Project'
else
Label5.Caption := 'Project # '+IntToStr(RecordID);
end;
procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: boolean);
begin
if closeNoQuestion = False then
if CloseForm() = False then
CanClose := False
else
Form1.Close
else
Form1.Close;
closeNoQuestion := False; // Has to be set to false, or else the next
// time you open the form, it remembers the previous
// value.
Proj_Name_Edit.Text := projectName;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
ShortDateFormat := 'mm/dd/yy';
SQLQuery1.SQL.text:='Select * FROM projects'; // This query can change to limit
SQLQuery1.Close;
closeNoQuestion := False;
projectName := 'Project Name'; // Assign a generic name to the project
Proj_Name_Edit.Text := projectName;
Form1.ActiveControl := Form1.Proj_Name_Edit;
end;
end.
|
unit SampleObj;
interface
uses Classes, Sample_TLB, SiteComp, HTTPProd;
type
TSimpleScriptObject = class(TComponent, IGetScriptObject, IWebVariableName)
private
FText: string;
protected
{ IWebVariableName }
function GetVariableName: string;
{ IGetScriptObject }
function GetScriptObject: IDispatch;
published
property Text: string read FText write FText;
end;
TSimpleScriptObjectWrapper = class(TScriptObject, ISimpleScriptObjectWrapper)
private
FSimpleScriptObject: TSimpleScriptObject;
protected
{ ISimpleScriptObjectWrapper }
function Get_Text: WideString; safecall;
public
constructor Create(ASimpleScriptObject: TSimpleScriptObject);
end;
implementation
uses WebAuto, ActiveX, SysUtils;
var
SampleComServer: TAbstractScriptComServerObject;
type
TSampleComServer = class(TAbstractScriptComServerObject)
protected
function ImplGetTypeLib: ITypeLib; override;
end;
function TSampleComServer.ImplGetTypeLib: ITypeLib;
begin
if LoadRegTypeLib(LIBID_Sample, 1, 0, 0, Result) <> S_OK then
Result := nil;
end;
{ TSimpleScriptObjectWrapper }
constructor TSimpleScriptObjectWrapper.Create(ASimpleScriptObject: TSimpleScriptObject);
begin
inherited Create;
FSimpleScriptObject := ASimpleScriptObject;
end;
function TSimpleScriptObjectWrapper.Get_Text: WideString;
begin
Result := FSimpleScriptObject.Text;
end;
{ TSimpleScriptObject }
function TSimpleScriptObject.GetScriptObject: IDispatch;
begin
Result := TSimpleScriptObjectWrapper.Create(Self);
end;
function TSimpleScriptObject.GetVariableName: string;
begin
Result := Self.Name;
end;
initialization
SampleComServer := TSampleComServer.Create;
SampleComServer.RegisterScriptClass(TSimpleScriptObjectWrapper, Class_SimpleScriptObjectWrapper);
finalization
FreeAndNil(SampleComServer);
end.
|
unit MgBackendGDI;
interface
uses
Classes, Graphics, Controls, MgScene, MgBackend;
type
TMgBackendGDI = class(TMgBackend)
private
FCanvas: TControlCanvas;
public
constructor Create;
destructor Destroy; override;
procedure RenderScene(Scene: TMgScene; AHandle: THandle); override;
end;
implementation
uses
MgPrimitives;
{ TMgBackendGDI }
constructor TMgBackendGDI.Create;
begin
FCanvas := TControlCanvas.Create;
end;
destructor TMgBackendGDI.Destroy;
begin
FCanvas.Free;
end;
procedure TMgBackendGDI.RenderScene(Scene: TMgScene; AHandle: THandle);
var
Index: Cardinal;
begin
inherited;
if Scene.Count = 0 then
Exit;
FCanvas.Handle := AHandle;
FCanvas.Pen.Color := clBlack;
FCanvas.Pen.Mode := pmCopy;
FCanvas.Brush.Color := clBlack;
FCanvas.Brush.Style := bsSolid;
for Index := 0 to Scene.Count - 1 do
begin
if Scene[Index] is TMgPrimitiveVerticalLine then
with TMgPrimitiveVerticalLine(Scene[Index]) do
begin
FCanvas.MoveTo(X, Y1);
FCanvas.LineTo(X, Y2);
end else
if Scene[Index] is TMgPrimitiveHorizontalLine then
with TMgPrimitiveHorizontalLine(Scene[Index]) do
begin
FCanvas.MoveTo(X1, Y);
FCanvas.LineTo(X2, Y);
end else
if Scene[Index] is TMgPrimitiveLine then
with TMgPrimitiveLine(Scene[Index]) do
begin
FCanvas.MoveTo(X1, Y1);
FCanvas.LineTo(X2, Y2);
end else
if Scene[Index] is TMgPrimitiveRect then
with TMgPrimitiveRect(Scene[Index]) do
begin
FCanvas.Rectangle(Left, Top, Right, Bottom);
end else
end;
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{*******************************************************}
{ COM object support }
{*******************************************************}
unit System.Win.ComObj;
interface
{$HPPEMIT LEGACYHPP}
uses
{$IFDEF LINUX}
WinUtils,
{$ENDIF}
Winapi.Windows, Winapi.ActiveX, System.SysUtils, System.Classes;
type
{ Forward declarations }
TComObjectFactory = class;
{ COM server abstract base class }
TComServerObject = class(TObject)
strict private
class var FPerUserRegistration: Boolean;
protected
function CountObject(Created: Boolean): Integer; virtual; abstract;
function CountFactory(Created: Boolean): Integer; virtual; abstract;
function GetHelpFileName: string; virtual; abstract;
function GetServerFileName: string; virtual; abstract;
function GetServerKey: string; virtual; abstract;
function GetServerName: string; virtual; abstract;
function GetStartSuspended: Boolean; virtual; abstract;
function GetTypeLib: ITypeLib; virtual; abstract;
procedure SetHelpFileName(const Value: string); virtual; abstract;
public
class constructor Create;
class procedure GetRegRootAndPrefix(var RootKey: HKEY; var RootPrefix: string);
property HelpFileName: string read GetHelpFileName write SetHelpFileName;
property ServerFileName: string read GetServerFileName;
property ServerKey: string read GetServerKey;
property ServerName: string read GetServerName;
property TypeLib: ITypeLib read GetTypeLib;
property StartSuspended: Boolean read GetStartSuspended;
class property PerUserRegistration: Boolean read FPerUserRegistration write FPerUserRegistration;
end;
{ COM class manager }
TFactoryProc = procedure(Factory: TComObjectFactory) of object;
TComClassManager = class(TObject)
private
FFactoryList: TComObjectFactory;
FLock: TMultiReadExclusiveWriteSynchronizer;
procedure AddObjectFactory(Factory: TComObjectFactory);
procedure RemoveObjectFactory(Factory: TComObjectFactory);
public
constructor Create;
destructor Destroy; override;
procedure ForEachFactory(ComServer: TComServerObject;
FactoryProc: TFactoryProc);
function GetFactoryFromClass(ComClass: TClass): TComObjectFactory;
function GetFactoryFromClassID(const ClassID: TGUID): TComObjectFactory;
end;
{ IServerExceptionHandler }
{ This interface allows you to report safecall exceptions that occur in a
TComObject server to a third party, such as an object that logs errors into
the system event log or a server monitor residing on another machine.
Obtain an interface from the error logger implementation and assign it
to your TComObject's ServerExceptionHandler property. Each TComObject
instance can have its own server exception handler, or all instances can
share the same handler. The server exception handler can override the
TComObject's default exception handling by setting Handled to True and
assigning an OLE HResult code to the HResult parameter. }
IServerExceptionHandler = interface
['{6A8D432B-EB81-11D1-AAB1-00C04FB16FBC}']
procedure OnException(
const ServerClass, ExceptionClass, ErrorMessage: WideString;
ExceptAddr: NativeInt; const ErrorIID, ProgID: WideString;
var Handled: Integer; var Result: HResult); dispid 2;
end;
{ COM object }
TComObject = class(TObject, IUnknown, ISupportErrorInfo)
private
FController: Pointer;
FFactory: TComObjectFactory;
FNonCountedObject: Boolean;
FRefCount: Integer;
FServerExceptionHandler: IServerExceptionHandler;
function GetController: IUnknown;
protected
{ IUnknown }
function IUnknown.QueryInterface = ObjQueryInterface;
function IUnknown._AddRef = ObjAddRef;
function IUnknown._Release = ObjRelease;
{ IUnknown methods for other interfaces }
function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
{ ISupportErrorInfo }
function InterfaceSupportsErrorInfo(const iid: TIID): HResult; stdcall;
public
constructor Create;
constructor CreateAggregated(const Controller: IUnknown);
constructor CreateFromFactory(Factory: TComObjectFactory;
const Controller: IUnknown);
destructor Destroy; override;
procedure Initialize; virtual;
function ObjAddRef: Integer; virtual; stdcall;
function ObjQueryInterface(const IID: TGUID; out Obj): HResult; virtual; stdcall;
function ObjRelease: Integer; virtual; stdcall;
{$IFDEF MSWINDOWS}
function SafeCallException(ExceptObject: TObject;
ExceptAddr: Pointer): HResult; override;
function Error(const Msg: string): HResult; overload; stdcall;
function Error(const Msg: string; const IID: TGUID;
hRes: HRESULT = DISP_E_EXCEPTION): HResult; overload; stdcall;
class function Error(const Msg: string; HelpID: DWORD;
const HelpFile: string;
const IID: TGUID;
hRes: HResult = DISP_E_EXCEPTION): HResult; overload; static; stdcall;
{$ENDIF}
property Controller: IUnknown read GetController;
property Factory: TComObjectFactory read FFactory;
property RefCount: Integer read FRefCount;
property ServerExceptionHandler: IServerExceptionHandler
read FServerExceptionHandler write FServerExceptionHandler;
end;
{ COM class }
TComClass = class of TComObject;
{ Instancing mode for COM classes }
TClassInstancing = (ciInternal, ciSingleInstance, ciMultiInstance);
{ Threading model supported by COM classes }
TThreadingModel = (tmSingle, tmApartment, tmFree, tmBoth, tmNeutral);
{ COM object factory }
TComObjectFactory = class(TObject, IUnknown, IClassFactory, IClassFactory2)
private
FNext: TComObjectFactory;
FComServer: TComServerObject;
FComClass: TClass;
FClassID: TGUID;
FClassName: string;
FDescription: string;
FErrorIID: TGUID;
FInstancing: TClassInstancing;
FLicString: WideString;
FRegister: Longint;
FShowErrors: Boolean;
FSupportsLicensing: Boolean;
FThreadingModel: TThreadingModel;
protected
function GetProgID: string; virtual;
function GetLicenseString: WideString; virtual;
function HasMachineLicense: Boolean; virtual;
function ValidateUserLicense(const LicStr: WideString): Boolean; virtual;
{ IUnknown }
function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
{ IClassFactory }
function CreateInstance(const UnkOuter: IUnknown; const IID: TGUID;
out Obj): HResult; stdcall;
function LockServer(fLock: BOOL): HResult; stdcall;
{ IClassFactory2 }
function GetLicInfo(var licInfo: TLicInfo): HResult; stdcall;
function RequestLicKey(dwResrved: Longint; out bstrKey: WideString): HResult; stdcall;
function CreateInstanceLic(const unkOuter: IUnknown; const unkReserved: IUnknown;
const iid: TIID; const bstrKey: WideString; out vObject): HResult; stdcall;
public
constructor Create(ComServer: TComServerObject; ComClass: TComClass;
const ClassID: TGUID; const ClassName, Description: string;
Instancing: TClassInstancing; ThreadingModel: TThreadingModel = tmSingle);
destructor Destroy; override;
function CreateComObject(const Controller: IUnknown): TComObject; virtual;
procedure RegisterClassObject;
procedure UpdateRegistry(Register: Boolean); virtual;
property ClassID: TGUID read FClassID;
{$WARN HIDING_MEMBER OFF}
property ClassName: string read FClassName;
{$WARN HIDING_MEMBER ON}
property ComClass: TClass read FComClass;
property ComServer: TComServerObject read FComServer;
property Description: string read FDescription;
property ErrorIID: TGUID read FErrorIID write FErrorIID;
property LicString: WideString read FLicString write FLicString;
property ProgID: string read GetProgID;
property Instancing: TClassInstancing read FInstancing;
property ShowErrors: Boolean read FShowErrors write FShowErrors;
property SupportsLicensing: Boolean read FSupportsLicensing write FSupportsLicensing;
property ThreadingModel: TThreadingModel read FThreadingModel;
end;
{ NOTE: TAggregatedObject and TContainedObject have been moved into the System unit. }
TTypedComObject = class(TComObject, IProvideClassInfo)
protected
{ IProvideClassInfo }
function GetClassInfo(out TypeInfo: ITypeInfo): HResult; stdcall;
public
constructor Create;
constructor CreateAggregated(const Controller: IUnknown);
constructor CreateFromFactory(Factory: TComObjectFactory;
const Controller: IUnknown);
end;
TTypedComClass = class of TTypedComObject;
TTypedComObjectFactory = class(TComObjectFactory)
private
FClassInfo: ITypeInfo;
public
constructor Create(ComServer: TComServerObject;
TypedComClass: TTypedComClass; const ClassID: TGUID;
Instancing: TClassInstancing; ThreadingModel: TThreadingModel = tmSingle);
function GetInterfaceTypeInfo(TypeFlags: Integer): ITypeInfo;
procedure UpdateRegistry(Register: Boolean); override;
{$WARN HIDING_MEMBER OFF}
property ClassInfo: ITypeInfo read FClassInfo;
{$WARN HIDING_MEMBER ON}
end;
{ OLE Automation object }
TConnectEvent = procedure (const Sink: IUnknown; Connecting: Boolean) of object;
TAutoObjectFactory = class;
TAutoObject = class(TTypedComObject, IDispatch)
private
FEventSink: IUnknown;
FAutoFactory: TAutoObjectFactory;
protected
{ IDispatch }
function GetIDsOfNames(const IID: TGUID; Names: Pointer;
NameCount, LocaleID: Integer; DispIDs: Pointer): HResult; virtual; stdcall;
function GetTypeInfo(Index, LocaleID: Integer; out TypeInfo): HResult; virtual; stdcall;
function GetTypeInfoCount(out Count: Integer): HResult; virtual; stdcall;
function Invoke(DispID: Integer; const IID: TGUID; LocaleID: Integer;
Flags: Word; var Params; VarResult, ExcepInfo, ArgErr: Pointer): HResult; virtual; stdcall;
{ Other methods }
procedure EventConnect(const Sink: IUnknown; Connecting: Boolean);
procedure EventSinkChanged(const EventSink: IUnknown); virtual;
property AutoFactory: TAutoObjectFactory read FAutoFactory;
property EventSink: IUnknown read FEventSink write FEventSink;
public
constructor Create;
constructor CreateAggregated(const Controller: IUnknown);
constructor CreateFromFactory(Factory: TComObjectFactory;
const Controller: IUnknown);
procedure Initialize; override;
end;
{ OLE Automation class }
TAutoClass = class of TAutoObject;
{ OLE Automation object factory }
TAutoObjectFactory = class(TTypedComObjectFactory)
private
FDispTypeInfo: ITypeInfo;
FDispIntfEntry: PInterfaceEntry;
FEventIID: TGUID;
FEventTypeInfo: ITypeInfo;
public
constructor Create(ComServer: TComServerObject; AutoClass: TAutoClass;
const ClassID: TGUID; Instancing: TClassInstancing;
ThreadingModel: TThreadingModel = tmSingle);
function GetIntfEntry(Guid: TGUID): PInterfaceEntry; virtual;
property DispIntfEntry: PInterfaceEntry read FDispIntfEntry;
property DispTypeInfo: ITypeInfo read FDispTypeInfo;
property EventIID: TGUID read FEventIID;
property EventTypeInfo: ITypeInfo read FEventTypeInfo;
end;
TAutoIntfObject = class(TInterfacedObject, IDispatch, ISupportErrorInfo)
private
FDispTypeInfo: ITypeInfo;
FDispIntfEntry: PInterfaceEntry;
FDispIID: TGUID;
protected
{ IDispatch }
function GetIDsOfNames(const IID: TGUID; Names: Pointer;
NameCount, LocaleID: Integer; DispIDs: Pointer): HResult; stdcall;
function GetTypeInfo(Index, LocaleID: Integer; out TypeInfo): HResult; stdcall;
function GetTypeInfoCount(out Count: Integer): HResult; stdcall;
function Invoke(DispID: Integer; const IID: TGUID; LocaleID: Integer;
Flags: Word; var Params; VarResult, ExcepInfo, ArgErr: Pointer): HResult; stdcall;
{ ISupportErrorInfo }
function InterfaceSupportsErrorInfo(const iid: TIID): HResult; stdcall;
public
constructor Create(const TypeLib: ITypeLib; const DispIntf: TGUID);
{$IFDEF MSWINDOWS}
function SafeCallException(ExceptObject: TObject;
ExceptAddr: Pointer): HResult; override;
{$ENDIF}
property DispIntfEntry: PInterfaceEntry read FDispIntfEntry;
property DispTypeInfo: ITypeInfo read FDispTypeInfo;
property DispIID: TGUID read FDispIID;
end;
TConnectionPoints = class;
TConnectionKind = (ckSingle, ckMulti);
TConnectionPoint = class(TContainedObject, IConnectionPoint)
private
FContainer: TConnectionPoints;
FIID: TGUID;
FSinkList: TList;
FOnConnect: TConnectEvent;
FKind: TConnectionKind;
function AddSink(const Sink: IUnknown): Integer;
procedure RemoveSink(Cookie: Longint);
protected
{ IConnectionPoint }
function GetConnectionInterface(out iid: TIID): HResult; stdcall;
function GetConnectionPointContainer(
out cpc: IConnectionPointContainer): HResult; stdcall;
function Advise(const unkSink: IUnknown; out dwCookie: Longint): HResult; stdcall;
function Unadvise(dwCookie: Longint): HResult; stdcall;
public
function EnumConnections(out enumconn: IEnumConnections): HResult; stdcall;
constructor Create(Container: TConnectionPoints;
const IID: TGUID; Kind: TConnectionKind; OnConnect: TConnectEvent);
function GetSink(Index: Integer; var punk: IUnknown): Boolean;
function GetCount: Integer;
property Count: Integer read GetCount;
property SinkList : TList read FSinkList;
destructor Destroy; override;
end;
// IConnectionPointContainer
TConnectionPoints = class
private
FController: Pointer; // weak reference to controller - don't keep it alive
FConnectionPoints: TList;
function GetController: IUnknown;
protected
{ IConnectionPointContainer }
function EnumConnectionPoints(
out enumconn: IEnumConnectionPoints): HResult; stdcall;
function FindConnectionPoint(const iid: TIID;
out cp: IConnectionPoint): HResult; stdcall;
public
constructor Create(const AController: IUnknown);
destructor Destroy; override;
function CreateConnectionPoint(const IID: TGUID; Kind: TConnectionKind;
OnConnect: TConnectEvent): TConnectionPoint;
property Controller: IUnknown read GetController;
end;
TAutoObjectEvent = class(TAutoObject, IConnectionPointContainer)
private
FConnectionPoints: TConnectionPoints;
FConnectionPoint: TConnectionPoint;
protected
property ConnectionPoints: TConnectionPoints read FConnectionPoints
implements IConnectionPointContainer;
public
constructor Create;
destructor Destroy; override;
constructor CreateAggregated(const Controller: IUnknown);
constructor CreateFromFactory(Factory: TComObjectFactory; const Controller: IUnknown);
procedure Initialize; override;
property ConnectionPoint: TConnectionPoint read FConnectionPoint;
end;
{ OLE exception classes }
EOleError = class(Exception);
EOleSysError = class(EOleError)
private
FErrorCode: HRESULT;
public
constructor Create(const Message: UnicodeString; ErrorCode: HRESULT;
HelpContext: Integer);
property ErrorCode: HRESULT read FErrorCode write FErrorCode;
end;
EOleException = class(EOleSysError)
private
FSource: string;
FHelpFile: string;
public
constructor Create(const Message: string; ErrorCode: HRESULT;
const Source, HelpFile: string; HelpContext: Integer);
property HelpFile: string read FHelpFile write FHelpFile;
property Source: string read FSource write FSource;
end;
EOleRegistrationError = class(EOleSysError);
TOleVariantArray = array of OleVariant;
TEventDispatchInvoker = reference to procedure(DispId: Integer;
var Params: TOleVariantArray);
procedure DispatchInvoke(const Dispatch: IDispatch; CallDesc: PCallDesc;
DispIDs: PDispIDList; Params: Pointer; Result: PVariant);
procedure DispatchInvokeError(Status: Integer; const ExcepInfo: TExcepInfo);
function HandleSafeCallException(ExceptObject: TObject;
ExceptAddr: Pointer; const ErrorIID: TGUID; const ProgID,
HelpFileName: WideString): HResult;
function CreateComObject(const ClassID: TGUID): IUnknown;
function CreateRemoteComObject(const MachineName: WideString; const ClassID: TGUID): IUnknown;
function CreateOleObject(const ClassName: string): IDispatch;
function GetActiveOleObject(const ClassName: string): IDispatch;
procedure OleError(ErrorCode: HResult);
procedure OleCheck(Result: HResult);
function StringToGUID(const S: string): TGUID;
function GUIDToString(const ClassID: TGUID): string;
function ProgIDToClassID(const ProgID: string): TGUID;
function ClassIDToProgID(const ClassID: TGUID): string;
procedure CreateRegKey(const Key, ValueName, Value: string; RootKey: HKEY = HKEY_CLASSES_ROOT);
procedure DeleteRegKey(const Key: string; RootKey: HKEY = HKEY_CLASSES_ROOT);
function GetRegStringValue(const Key, ValueName: string; RootKey: HKEY = HKEY_CLASSES_ROOT): string;
function StringToLPOLESTR(const Source: string): POleStr;
procedure RegisterComServer(const DLLName: string);
procedure RegisterAsService(const ClassID, ServiceName: string);
function CreateClassID: string;
procedure InterfaceConnect(const Source: IUnknown; const IID: TIID;
const Sink: IUnknown; var Connection: Longint);
procedure InterfaceDisconnect(const Source: IUnknown; const IID: TIID;
var Connection: Longint);
function GetDispatchPropValue(const Disp: IDispatch; DispID: Integer): OleVariant; overload;
function GetDispatchPropValue(const Disp: IDispatch; Name: WideString): OleVariant; overload;
procedure SetDispatchPropValue(const Disp: IDispatch; DispID: Integer;
const Value: OleVariant); overload;
procedure SetDispatchPropValue(const Disp: IDispatch; Name: WideString;
const Value: OleVariant); overload;
function EventDispatchInvoke(DispId: Integer; var ADispParams: TDispParams;
Invoker: TEventDispatchInvoker): HResult;
type
TCoCreateInstanceExProc = function (const clsid: TCLSID;
unkOuter: IUnknown; dwClsCtx: Longint; ServerInfo: PCoServerInfo;
dwCount: Longint; rgmqResults: PMultiQIArray): HResult stdcall;
{$EXTERNALSYM TCoCreateInstanceExProc}
TCoInitializeExProc = function (pvReserved: Pointer;
coInit: Longint): HResult; stdcall;
{$EXTERNALSYM TCoInitializeExProc}
TCoAddRefServerProcessProc = function :Longint; stdcall;
{$EXTERNALSYM TCoAddRefServerProcessProc}
TCoReleaseServerProcessProc = function :Longint; stdcall;
{$EXTERNALSYM TCoReleaseServerProcessProc}
TCoResumeClassObjectsProc = function :HResult; stdcall;
{$EXTERNALSYM TCoResumeClassObjectsProc}
TCoSuspendClassObjectsProc = function :HResult; stdcall;
{$EXTERNALSYM TCoSuspendClassObjectsProc}
// COM functions that are only available on DCOM updated OSs
// These pointers may be nil on Win95 or Win NT 3.51 systems
var
CoCreateInstanceEx: TCoCreateInstanceExProc = nil;
{$EXTERNALSYM CoCreateInstanceEx}
CoInitializeEx: TCoInitializeExProc = nil;
{$EXTERNALSYM CoInitializeEx}
CoAddRefServerProcess: TCoAddRefServerProcessProc = nil;
{$EXTERNALSYM CoAddRefServerProcess}
CoReleaseServerProcess: TCoReleaseServerProcessProc = nil;
{$EXTERNALSYM CoReleaseServerProcess}
CoResumeClassObjects: TCoResumeClassObjectsProc = nil;
{$EXTERNALSYM CoResumeClassObjects}
CoSuspendClassObjects: TCoSuspendClassObjectsProc = nil;
{$EXTERNALSYM CoSuspendClassObjects}
{ CoInitFlags determines the COM threading model of the application or current
thread. This bitflag value is passed to CoInitializeEx in ComServ initialization.
Assign COINIT_APARTMENTTHREADED or COINIT_MULTITHREADED to this variable before
Application.Initialize is called by the project source file to select a
threading model. Other CoInitializeEx flags (such as COINIT_SPEED_OVER_MEMORY)
can be OR'd in also. }
var
CoInitFlags: Integer = -1; // defaults to no threading model, call CoInitialize()
function ComClassManager: TComClassManager;
implementation
uses
System.AnsiStrings,
System.Types, System.Variants, System.VarUtils, System.Win.ComConst;
var
OleUninitializing: Boolean;
const
EAbortRaisedHRESULT = HRESULT(E_ABORT or (1 shl 29)); // turn on customer bit
{ Handle a safe call exception }
function DoSetErrorInfo(const Description: WideString;
HelpContext: Integer;
ErrorCode: HResult;
const ErrorIID: TGUID;
const ProgID, HelpFileName: WideString): HResult;
var
CreateError: ICreateErrorInfo;
ErrorInfo: IErrorInfo;
begin
Result := E_UNEXPECTED;
if Succeeded(CreateErrorInfo(CreateError)) then
begin
CreateError.SetGUID(ErrorIID);
if (ProgID <> '') then
CreateError.SetSource(PWideChar(ProgID));
if (HelpFileName <> '') then
CreateError.SetHelpFile(PWideChar(HelpFileName));
if (Description <> '') then
CreateError.SetDescription(PWideChar(Description));
if (HelpContext <> 0) then
CreateError.SetHelpContext(HelpContext);
if (ErrorCode <> 0) then
Result := ErrorCode;
if CreateError.QueryInterface(IErrorInfo, ErrorInfo) = S_OK then
SetErrorInfo(0, ErrorInfo);
end;
end;
function HandleSafeCallException(ExceptObject: TObject;
ExceptAddr: Pointer; const ErrorIID: TGUID; const ProgID,
HelpFileName: WideString): HResult;
var
E: TObject;
Description: WideString;
HelpContext: Integer;
ErrorCode: HResult;
begin
E := ExceptObject;
if E is Exception then
begin
Description := Exception(E).Message;
HelpContext := Exception(E).HelpContext;
if (E is EOleSysError) and (EOleSysError(E).ErrorCode < 0) then
ErrorCode := EOleSysError(E).ErrorCode
else if E is EAbort then
ErrorCode := EAbortRaisedHRESULT
else
ErrorCode := 0;
end
else
begin
Description := '';
HelpContext := -1;
ErrorCode := 0;
end;
Result := DoSetErrorInfo(Description, HelpContext, ErrorCode, ErrorIID,
ProgID, HelpFileName);
end;
{ TDispatchSilencer }
type
TDispatchSilencer = class(TInterfacedObject, IUnknown, IDispatch)
private
Dispatch: IDispatch;
DispIntfIID: TGUID;
public
constructor Create(ADispatch: IUnknown; const ADispIntfIID: TGUID);
{ IUnknown }
function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
{ IDispatch }
function GetTypeInfoCount(out Count: Integer): HResult; stdcall;
function GetTypeInfo(Index, LocaleID: Integer; out TypeInfo): HResult; stdcall;
function GetIDsOfNames(const IID: TGUID; Names: Pointer;
NameCount, LocaleID: Integer; DispIDs: Pointer): HResult; stdcall;
function Invoke(DispID: Integer; const IID: TGUID; LocaleID: Integer;
Flags: Word; var Params; VarResult, ExcepInfo, ArgErr: Pointer): HResult; stdcall;
end;
constructor TDispatchSilencer.Create(ADispatch: IUnknown;
const ADispIntfIID: TGUID);
begin
inherited Create;
DispIntfIID := ADispIntfIID;
OleCheck(ADispatch.QueryInterface(ADispIntfIID, Dispatch));
end;
function TDispatchSilencer.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
Result := inherited QueryInterface(IID, Obj);
if Result = E_NOINTERFACE then
if IsEqualGUID(IID, DispIntfIID) then
begin
IDispatch(Obj) := Self;
Result := S_OK;
end
else
Result := Dispatch.QueryInterface(IID, Obj);
end;
function TDispatchSilencer.GetTypeInfoCount(out Count: Integer): HResult;
begin
Result := Dispatch.GetTypeInfoCount(Count);
end;
function TDispatchSilencer.GetTypeInfo(Index, LocaleID: Integer; out TypeInfo): HResult;
begin
Result := Dispatch.GetTypeInfo(Index, LocaleID, TypeInfo);
end;
function TDispatchSilencer.GetIDsOfNames(const IID: TGUID; Names: Pointer;
NameCount, LocaleID: Integer; DispIDs: Pointer): HResult;
begin
Result := Dispatch.GetIDsOfNames(IID, Names, NameCount, LocaleID, DispIDs);
end;
function TDispatchSilencer.Invoke(DispID: Integer; const IID: TGUID; LocaleID: Integer;
Flags: Word; var Params; VarResult, ExcepInfo, ArgErr: Pointer): HResult;
begin
{ Ignore error since some containers, such as Internet Explorer 3.0x, will
return error when the method was not handled, or scripting errors occur }
Dispatch.Invoke(DispID, IID, LocaleID, Flags, Params, VarResult, ExcepInfo,
ArgErr);
Result := S_OK;
end;
{ TComClassManager }
constructor TComClassManager.Create;
begin
inherited Create;
FLock := TMultiReadExclusiveWriteSynchronizer.Create;
end;
destructor TComClassManager.Destroy;
begin
FLock.Free;
inherited Destroy;
end;
procedure TComClassManager.AddObjectFactory(Factory: TComObjectFactory);
begin
FLock.BeginWrite;
try
Factory.FNext := FFactoryList;
FFactoryList := Factory;
finally
FLock.EndWrite;
end;
end;
procedure TComClassManager.ForEachFactory(ComServer: TComServerObject;
FactoryProc: TFactoryProc);
var
Factory, Next: TComObjectFactory;
begin
FLock.BeginWrite; // FactoryProc could add or delete factories from list
try
Factory := FFactoryList;
while Factory <> nil do
begin
Next := Factory.FNext;
if Factory.ComServer = ComServer then FactoryProc(Factory);
Factory := Next;
end;
finally
FLock.EndWrite;
end;
end;
function TComClassManager.GetFactoryFromClass(ComClass: TClass): TComObjectFactory;
begin
FLock.BeginRead;
try
Result := FFactoryList;
while Result <> nil do
begin
if Result.ComClass = ComClass then Exit;
Result := Result.FNext;
end;
raise EOleError.CreateResFmt(@SObjectFactoryMissing, [ComClass.ClassName]);
finally
FLock.EndRead;
end;
end;
function TComClassManager.GetFactoryFromClassID(const ClassID: TGUID): TComObjectFactory;
begin
FLock.BeginRead;
try
Result := FFactoryList;
while Result <> nil do
begin
if IsEqualGUID(Result.ClassID, ClassID) then Exit;
Result := Result.FNext;
end;
finally
FLock.EndRead;
end;
end;
procedure TComClassManager.RemoveObjectFactory(Factory: TComObjectFactory);
var
F, P: TComObjectFactory;
begin
FLock.BeginWrite;
try
P := nil;
F := FFactoryList;
while F <> nil do
begin
if F = Factory then
begin
if P <> nil then P.FNext := F.FNext else FFactoryList := F.FNext;
Exit;
end;
P := F;
F := F.FNext;
end;
finally
FLock.EndWrite;
end;
end;
{ TComObject }
constructor TComObject.Create;
begin
FNonCountedObject := True;
CreateFromFactory(ComClassManager.GetFactoryFromClass(ClassType), nil);
end;
constructor TComObject.CreateAggregated(const Controller: IUnknown);
begin
FNonCountedObject := True;
CreateFromFactory(ComClassManager.GetFactoryFromClass(ClassType), Controller);
end;
constructor TComObject.CreateFromFactory(Factory: TComObjectFactory;
const Controller: IUnknown);
begin
FRefCount := 1;
FFactory := Factory;
FController := Pointer(Controller);
if not FNonCountedObject then FFactory.ComServer.CountObject(True);
Initialize;
Dec(FRefCount);
end;
destructor TComObject.Destroy;
begin
if not OleUninitializing then
begin
if (FFactory <> nil) and not FNonCountedObject then
FFactory.ComServer.CountObject(False);
if FRefCount > 0 then CoDisconnectObject(Self, 0);
end;
end;
function TComObject.GetController: IUnknown;
begin
Result := IUnknown(FController);
end;
procedure TComObject.Initialize;
begin
end;
{$IFDEF MSWINDOWS}
function TComObject.SafeCallException(ExceptObject: TObject;
ExceptAddr: Pointer): HResult;
var
Msg: string;
Handled: Integer;
begin
Handled := 0;
if ServerExceptionHandler <> nil then
begin
if ExceptObject is Exception then
Msg := Exception(ExceptObject).Message;
Result := 0;
ServerExceptionHandler.OnException(ClassName,
ExceptObject.ClassName, Msg, IntPtr(ExceptAddr),
WideString(GUIDToString(FFactory.ErrorIID)),
FFactory.ProgID, Handled, Result);
end;
if Handled = 0 then
Result := HandleSafeCallException(ExceptObject, ExceptAddr,
FFactory.ErrorIID, FFactory.ProgID, FFactory.ComServer.HelpFileName);
end;
function TComObject.Error(const Msg: string): HResult;
begin
Result := DoSetErrorInfo(Msg, 0, DISP_E_EXCEPTION,
FFactory.ErrorIID,
FFactory.ProgID,
FFactory.ComServer.HelpFileName);
end;
function TComObject.Error(const Msg: string; const IID: TGUID; hRes: HRESULT): HResult;
begin
Result := DoSetErrorInfo(Msg, 0, hRes, IID, FFactory.ProgID,
FFactory.ComServer.HelpFileName);
end;
class function TComObject.Error(const Msg: string; HelpID: DWORD;
const HelpFile: string;
const IID: TGUID;
hRes: HResult = DISP_E_EXCEPTION): HResult;
begin
Result := DoSetErrorInfo(Msg, HelpID, hRes, IID, '', HelpFile);
end;
{$ENDIF}
{ TComObject.IUnknown }
function TComObject.ObjQueryInterface(const IID: TGUID; out Obj): HResult;
begin
if GetInterface(IID, Obj) then Result := S_OK else Result := E_NOINTERFACE;
end;
function TComObject.ObjAddRef: Integer;
begin
Result := AtomicIncrement(FRefCount);
end;
function TComObject.ObjRelease: Integer;
begin
// InterlockedDecrement returns only 0 or 1 on Win95 and NT 3.51
// returns actual result on NT 4.0
Result := AtomicDecrement(FRefCount);
if Result = 0 then Destroy;
end;
{ TComObject.IUnknown for other interfaces }
function TComObject.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
if FController <> nil then
Result := IUnknown(FController).QueryInterface(IID, Obj) else
Result := ObjQueryInterface(IID, Obj);
end;
function TComObject._AddRef: Integer;
begin
if FController <> nil then
Result := IUnknown(FController)._AddRef else
Result := ObjAddRef;
end;
function TComObject._Release: Integer;
begin
if FController <> nil then
Result := IUnknown(FController)._Release else
Result := ObjRelease;
end;
{ TComObject.ISupportErrorInfo }
function TComObject.InterfaceSupportsErrorInfo(const iid: TIID): HResult;
begin
if GetInterfaceEntry(iid) <> nil then
Result := S_OK else
Result := S_FALSE;
end;
{ TComObjectFactory }
constructor TComObjectFactory.Create(ComServer: TComServerObject;
ComClass: TComClass; const ClassID: TGUID; const ClassName,
Description: string; Instancing: TClassInstancing;
ThreadingModel: TThreadingModel);
begin
IsMultiThread := IsMultiThread or (ThreadingModel <> tmSingle);
if ThreadingModel in [tmFree, tmBoth] then
CoInitFlags := COINIT_MULTITHREADED else
if (ThreadingModel = tmApartment) and (CoInitFlags <> COINIT_MULTITHREADED) then
CoInitFlags := COINIT_APARTMENTTHREADED;
ComClassManager.AddObjectFactory(Self);
FComServer := ComServer;
FComClass := ComClass;
FClassID := ClassID;
FClassName := ClassName;
FDescription := Description;
FInstancing := Instancing;
FErrorIID := IUnknown;
FShowErrors := True;
FThreadingModel := ThreadingModel;
FRegister := -1;
end;
destructor TComObjectFactory.Destroy;
begin
if FRegister <> -1 then CoRevokeClassObject(FRegister);
ComClassManager.RemoveObjectFactory(Self);
end;
function TComObjectFactory.CreateComObject(const Controller: IUnknown): TComObject;
begin
Result := TComClass(FComClass).CreateFromFactory(Self, Controller);
end;
function TComObjectFactory.GetProgID: string;
begin
if FClassName <> '' then
Result := FComServer.ServerName + '.' + FClassName else
Result := '';
end;
procedure TComObjectFactory.RegisterClassObject;
const
RegFlags: array[ciSingleInstance..ciMultiInstance] of Integer = (
REGCLS_SINGLEUSE, REGCLS_MULTIPLEUSE);
SuspendedFlag: array[Boolean] of Integer = (0, REGCLS_SUSPENDED);
begin
if FInstancing <> ciInternal then
OleCheck(CoRegisterClassObject(FClassID, Self, CLSCTX_LOCAL_SERVER,
RegFlags[FInstancing] or SuspendedFlag[FComServer.StartSuspended], FRegister));
end;
procedure TComObjectFactory.UpdateRegistry(Register: Boolean);
const
ThreadStrs: array[TThreadingModel] of string =
('', 'Apartment', 'Free', 'Both', 'Neutral');
var
ClassID, ProgID, ServerKeyName, ShortFileName, RegPrefix: string;
RootKey: HKEY;
begin
if FInstancing = ciInternal then
Exit;
ComServer.GetRegRootAndPrefix(RootKey, RegPrefix);
ClassID := GUIDToString(FClassID);
ProgID := GetProgID;
ServerKeyName := RegPrefix + 'CLSID\' + ClassID + '\' + FComServer.ServerKey;
if Register then
begin
CreateRegKey(RegPrefix + 'CLSID\' + ClassID, '', Description, RootKey);
ShortFileName := FComServer.ServerFileName;
if AnsiPos(' ', ShortFileName) <> 0 then
ShortFileName := ExtractShortPathName(ShortFileName);
CreateRegKey(ServerKeyName, '', ShortFileName, RootKey);
if (FThreadingModel <> tmSingle) and IsLibrary then
CreateRegKey(ServerKeyName, 'ThreadingModel', ThreadStrs[FThreadingModel], RootKey);
if ProgID <> '' then
begin
CreateRegKey(RegPrefix + ProgID, '', Description, RootKey);
CreateRegKey(RegPrefix + ProgID + '\Clsid', '', ClassID, RootKey);
CreateRegKey(RegPrefix + 'CLSID\' + ClassID + '\ProgID', '', ProgID, RootKey);
end;
end
else
begin
if ProgID <> '' then
begin
DeleteRegKey(RegPrefix + 'CLSID\' + ClassID + '\ProgID', RootKey);
DeleteRegKey(RegPrefix + ProgID + '\Clsid', RootKey);
DeleteRegKey(RegPrefix + ProgID, RootKey);
end;
DeleteRegKey(ServerKeyName, RootKey);
DeleteRegKey(RegPrefix + 'CLSID\' + ClassID, RootKey);
end;
end;
function TComObjectFactory.GetLicenseString: WideString;
begin
if FSupportsLicensing then Result := FLicString
else Result := '';
end;
function TComObjectFactory.HasMachineLicense: Boolean;
begin
Result := True;
end;
function TComObjectFactory.ValidateUserLicense(const LicStr: WideString): Boolean;
begin
Result := AnsiCompareText(LicStr, FLicString) = 0;
end;
{ TComObjectFactory.IUnknown }
function TComObjectFactory.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
if GetInterface(IID, Obj) then Result := S_OK else Result := E_NOINTERFACE;
end;
function TComObjectFactory._AddRef: Integer;
begin
Result := ComServer.CountFactory(True);
end;
function TComObjectFactory._Release: Integer;
begin
Result := ComServer.CountFactory(False);
end;
{ TComObjectFactory.IClassFactory }
function TComObjectFactory.CreateInstance(const UnkOuter: IUnknown;
const IID: TGUID; out Obj): HResult;
begin
Result := CreateInstanceLic(UnkOuter, nil, IID, '', Obj);
end;
function TComObjectFactory.LockServer(fLock: BOOL): HResult;
begin
Result := CoLockObjectExternal(Self, fLock, True);
// Keep com server alive until this class factory is unlocked
ComServer.CountObject(fLock);
end;
{ TComObjectFactory.IClassFactory2 }
function TComObjectFactory.GetLicInfo(var licInfo: TLicInfo): HResult;
begin
Result := S_OK;
try
with licInfo do
begin
cbLicInfo := SizeOf(licInfo);
fRuntimeKeyAvail := (not FSupportsLicensing) or (GetLicenseString <> '');
fLicVerified := (not FSupportsLicensing) or HasMachineLicense;
end;
except
Result := E_UNEXPECTED;
end;
end;
function TComObjectFactory.RequestLicKey(dwResrved: Longint; out bstrKey: WideString): HResult;
begin
// Can't give away a license key on an unlicensed machine
if not HasMachineLicense then
begin
Result := CLASS_E_NOTLICENSED;
Exit;
end;
bstrKey := FLicString;
Result := NOERROR;
end;
function TComObjectFactory.CreateInstanceLic(const unkOuter: IUnknown;
const unkReserved: IUnknown; const iid: TIID; const bstrKey: WideString;
out vObject): HResult; stdcall;
var
ComObject: TComObject;
begin
// We can't write to a nil pointer. Duh.
if @vObject = nil then
begin
Result := E_POINTER;
Exit;
end;
// In case of failure, make sure we return at least a nil interface.
Pointer(vObject) := nil;
// Check for licensing.
if FSupportsLicensing and
((bstrKey <> '') and (not ValidateUserLicense(bstrKey))) or
((bstrKey = '') and (not HasMachineLicense)) then
begin
Result := CLASS_E_NOTLICENSED;
Exit;
end;
// We can only aggregate if they are requesting our IUnknown.
if (unkOuter <> nil) and not (IsEqualIID(iid, IUnknown)) then
begin
Result := CLASS_E_NOAGGREGATION;
Exit;
end;
try
ComObject := CreateComObject(UnkOuter);
except
if FShowErrors and (ExceptObject is Exception) then
with Exception(ExceptObject) do
begin
if (Message <> '') and (AnsiLastChar(Message) > '.') then
Message := Message + '.';
MessageBox(0, PChar(Message), PChar(SDAXError), MB_OK or MB_ICONSTOP or MB_SETFOREGROUND);
end;
Result := E_UNEXPECTED;
Exit;
end;
Result := ComObject.ObjQueryInterface(IID, vObject);
if ComObject.RefCount = 0 then ComObject.Free;
end;
{ TTypedComObject }
constructor TTypedComObject.Create;
begin
inherited;
end;
constructor TTypedComObject.CreateAggregated(const Controller: IInterface);
begin
inherited;
end;
constructor TTypedComObject.CreateFromFactory(Factory: TComObjectFactory;
const Controller: IInterface);
begin
inherited;
end;
function TTypedComObject.GetClassInfo(out TypeInfo: ITypeInfo): HResult;
begin
TypeInfo := TTypedComObjectFactory(FFactory).FClassInfo;
Result := S_OK;
end;
{ TTypedComObjectFactory }
constructor TTypedComObjectFactory.Create(ComServer: TComServerObject;
TypedComClass: TTypedComClass; const ClassID: TGUID;
Instancing: TClassInstancing; ThreadingModel: TThreadingModel);
var
ClassName, Description: WideString;
begin
if ComServer.TypeLib.GetTypeInfoOfGUID(ClassID, FClassInfo) <> S_OK then
raise EOleError.CreateResFmt(@STypeInfoMissing, [TypedComClass.ClassName]);
OleCheck(FClassInfo.GetDocumentation(MEMBERID_NIL, @ClassName,
@Description, nil, nil));
inherited Create(ComServer, TypedComClass, ClassID,
ClassName, Description, Instancing, ThreadingModel);
end;
function TTypedComObjectFactory.GetInterfaceTypeInfo(
TypeFlags: Integer): ITypeInfo;
const
FlagsMask = IMPLTYPEFLAG_FDEFAULT or IMPLTYPEFLAG_FSOURCE;
var
ClassAttr: PTypeAttr;
I, TypeInfoCount, Flags: Integer;
RefType: HRefType;
begin
OleCheck(FClassInfo.GetTypeAttr(ClassAttr));
TypeInfoCount := ClassAttr^.cImplTypes;
ClassInfo.ReleaseTypeAttr(ClassAttr);
for I := 0 to TypeInfoCount - 1 do
begin
OleCheck(ClassInfo.GetImplTypeFlags(I, Flags));
if Flags and FlagsMask = TypeFlags then
begin
OleCheck(ClassInfo.GetRefTypeOfImplType(I, RefType));
OleCheck(ClassInfo.GetRefTypeInfo(RefType, Result));
Exit;
end;
end;
Result := nil;
end;
procedure TTypedComObjectFactory.UpdateRegistry(Register: Boolean);
var
ClassKey: string;
TypeLib: ITypeLib;
TLibAttr: PTLibAttr;
RegPrefix: string;
RootKey: HKEY;
begin
ComServer.GetRegRootAndPrefix(RootKey, RegPrefix);
ClassKey := RegPrefix + 'CLSID\' + GUIDToString(FClassID);
if Register then
begin
inherited UpdateRegistry(Register);
TypeLib := FComServer.TypeLib;
OleCheck(TypeLib.GetLibAttr(TLibAttr));
try
CreateRegKey(ClassKey + '\Version', '', Format('%d.%d',
[TLibAttr.wMajorVerNum, TLibAttr.wMinorVerNum]), RootKey);
CreateRegKey(ClassKey + '\TypeLib', '', GUIDToString(TLibAttr.guid), RootKey);
finally
TypeLib.ReleaseTLibAttr(TLibAttr);
end;
end else
begin
DeleteRegKey(ClassKey + '\TypeLib', RootKey);
DeleteRegKey(ClassKey + '\Version', RootKey);
inherited UpdateRegistry(Register);
end;
end;
{ TAutoObject }
constructor TAutoObject.Create;
begin
inherited;
end;
constructor TAutoObject.CreateAggregated(const Controller: IInterface);
begin
inherited;
end;
constructor TAutoObject.CreateFromFactory(Factory: TComObjectFactory;
const Controller: IInterface);
begin
inherited;
end;
procedure TAutoObject.EventConnect(const Sink: IUnknown;
Connecting: Boolean);
begin
if Connecting then
begin
OleCheck(Sink.QueryInterface(FAutoFactory.FEventIID, FEventSink));
EventSinkChanged(TDispatchSilencer.Create(Sink, FAutoFactory.FEventIID));
end
else
begin
FEventSink := nil;
EventSinkChanged(nil);
end;
end;
procedure TAutoObject.EventSinkChanged(const EventSink: IUnknown);
begin
end;
procedure TAutoObject.Initialize;
begin
FAutoFactory := Factory as TAutoObjectFactory;
inherited Initialize;
end;
{ TAutoObject.IDispatch }
function TAutoObject.GetIDsOfNames(const IID: TGUID; Names: Pointer;
NameCount, LocaleID: Integer; DispIDs: Pointer): HResult;
begin
{$IFDEF MSWINDOWS}
Result := DispGetIDsOfNames(FAutoFactory.DispTypeInfo,
Names, NameCount, DispIDs);
{$ENDIF}
{$IFDEF LINUX}
Result := E_NOTIMPL;
{$ENDIF}
end;
function TAutoObject.GetTypeInfo(Index, LocaleID: Integer;
out TypeInfo): HResult;
begin
Pointer(TypeInfo) := nil;
if Index <> 0 then
begin
Result := DISP_E_BADINDEX;
Exit;
end;
ITypeInfo(TypeInfo) := TAutoObjectFactory(Factory).DispTypeInfo;
Result := S_OK;
end;
function TAutoObject.GetTypeInfoCount(out Count: Integer): HResult;
begin
Count := 1;
Result := S_OK;
end;
function TAutoObject.Invoke(DispID: Integer; const IID: TGUID; LocaleID: Integer;
Flags: Word; var Params; VarResult, ExcepInfo, ArgErr: Pointer): HResult;
const
INVOKE_PROPERTYSET = INVOKE_PROPERTYPUT or INVOKE_PROPERTYPUTREF;
begin
if Flags and INVOKE_PROPERTYSET <> 0 then Flags := INVOKE_PROPERTYSET;
Result := TAutoObjectFactory(Factory).DispTypeInfo.Invoke(Pointer(
IntPtr(Self) + TAutoObjectFactory(Factory).DispIntfEntry.IOffset),
DispID, Flags, TDispParams(Params), VarResult, ExcepInfo, ArgErr);
end;
{ TAutoObjectFactory }
constructor TAutoObjectFactory.Create(ComServer: TComServerObject;
AutoClass: TAutoClass; const ClassID: TGUID;
Instancing: TClassInstancing; ThreadingModel: TThreadingModel);
var
TypeAttr: PTypeAttr;
begin
inherited Create(ComServer, AutoClass, ClassID, Instancing, ThreadingModel);
FDispTypeInfo := GetInterfaceTypeInfo(IMPLTYPEFLAG_FDEFAULT);
if FDispTypeInfo = nil then
raise EOleError.CreateResFmt(@SBadTypeInfo, [AutoClass.ClassName]);
OleCheck(FDispTypeInfo.GetTypeAttr(TypeAttr));
FDispIntfEntry := GetIntfEntry(TypeAttr^.guid);
FDispTypeInfo.ReleaseTypeAttr(TypeAttr);
if FDispIntfEntry = nil then
raise EOleError.CreateResFmt(@SDispIntfMissing, [AutoClass.ClassName]);
FErrorIID := FDispIntfEntry^.IID;
FEventTypeInfo := GetInterfaceTypeInfo(IMPLTYPEFLAG_FDEFAULT or
IMPLTYPEFLAG_FSOURCE);
if FEventTypeInfo <> nil then
begin
OleCheck(FEventTypeInfo.GetTypeAttr(TypeAttr));
FEventIID := TypeAttr.guid;
FEventTypeInfo.ReleaseTypeAttr(TypeAttr);
end;
end;
function TAutoObjectFactory.GetIntfEntry(Guid: TGUID): PInterfaceEntry;
begin
Result := FComClass.GetInterfaceEntry(Guid);
end;
{ TAutoIntfObject }
constructor TAutoIntfObject.Create(const TypeLib: ITypeLib; const DispIntf: TGUID);
begin
inherited Create;
OleCheck(TypeLib.GetTypeInfoOfGuid(DispIntf, FDispTypeInfo));
FDispIntfEntry := GetInterfaceEntry(DispIntf);
FDispIID := DispIntf;
end;
{ TAutoIntfObject.IDispatch }
function TAutoIntfObject.GetIDsOfNames(const IID: TGUID; Names: Pointer;
NameCount, LocaleID: Integer; DispIDs: Pointer): HResult;
begin
{$IFDEF MSWINDOWS}
Result := DispGetIDsOfNames(FDispTypeInfo, Names, NameCount, DispIDs);
{$ENDIF}
{$IFDEF LINUX}
Result := E_NOTIMPL;
{$ENDIF}
end;
function TAutoIntfObject.GetTypeInfo(Index, LocaleID: Integer;
out TypeInfo): HResult;
begin
Pointer(TypeInfo) := nil;
if Index <> 0 then
begin
Result := DISP_E_BADINDEX;
Exit;
end;
ITypeInfo(TypeInfo) := FDispTypeInfo;
Result := S_OK;
end;
function TAutoIntfObject.GetTypeInfoCount(out Count: Integer): HResult;
begin
Count := 1;
Result := S_OK;
end;
function TAutoIntfObject.Invoke(DispID: Integer; const IID: TGUID;
LocaleID: Integer; Flags: Word; var Params; VarResult, ExcepInfo,
ArgErr: Pointer): HResult;
const
INVOKE_PROPERTYSET = INVOKE_PROPERTYPUT or INVOKE_PROPERTYPUTREF;
begin
if Flags and INVOKE_PROPERTYSET <> 0 then Flags := INVOKE_PROPERTYSET;
Result := FDispTypeInfo.Invoke(Pointer(PByte(Self) +
FDispIntfEntry.IOffset), DispID, Flags, TDispParams(Params), VarResult,
ExcepInfo, ArgErr);
end;
function TAutoIntfObject.InterfaceSupportsErrorInfo(const iid: TIID): HResult;
begin
if IsEqualGUID(DispIID, iid) then
Result := S_OK else
Result := S_FALSE;
end;
{$IFDEF MSWINDOWS}
function TAutoIntfObject.SafeCallException(ExceptObject: TObject;
ExceptAddr: Pointer): HResult;
begin
Result := HandleSafeCallException(ExceptObject, ExceptAddr, DispIID, '', '');
end;
{$ENDIF}
const
{ Maximum number of dispatch arguments }
MaxDispArgs = 64; {+ !!}
{ Parameter type masks }
atVarMask = $3F;
atTypeMask = $7F;
atByRef = $80;
function TrimPunctuation(const S: string): string;
var
P: PChar;
begin
Result := S;
P := AnsiLastChar(Result);
while (Length(Result) > 0) and CharInSet(P^, [#0..#32, '.']) do
begin
SetLength(Result, P - PChar(Result));
P := AnsiLastChar(Result);
end;
end;
{ EOleSysError }
constructor EOleSysError.Create(const Message: UnicodeString;
ErrorCode: HRESULT; HelpContext: Integer);
var
S: string;
begin
S := Message;
if S = '' then
begin
S := SysErrorMessage(Cardinal(ErrorCode));
if S = '' then
FmtStr(S, SOleError, [ErrorCode]);
end;
inherited CreateHelp(S, HelpContext);
FErrorCode := ErrorCode;
end;
{ EOleException }
constructor EOleException.Create(const Message: string; ErrorCode: HRESULT;
const Source, HelpFile: string; HelpContext: Integer);
begin
inherited Create(TrimPunctuation(Message), ErrorCode, HelpContext);
FSource := Source;
FHelpFile := HelpFile;
end;
{ Raise EOleSysError exception from an error code }
procedure OleError(ErrorCode: HResult);
begin
raise EOleSysError.Create('', ErrorCode, 0);
end;
{ Raise EOleSysError exception if result code indicates an error }
procedure OleCheck(Result: HResult);
begin
if not Succeeded(Result) then OleError(Result);
end;
{ Convert a string to a GUID }
function StringToGUID(const S: string): TGUID;
begin
OleCheck(CLSIDFromString(PWideChar(WideString(S)), Result));
end;
{ Convert a GUID to a string }
function GUIDToString(const ClassID: TGUID): string;
var
P: PWideChar;
begin
OleCheck(StringFromCLSID(ClassID, P));
Result := P;
CoTaskMemFree(P);
end;
{ Convert a programmatic ID to a class ID }
function ProgIDToClassID(const ProgID: string): TGUID;
begin
OleCheck(CLSIDFromProgID(PWideChar(WideString(ProgID)), Result));
end;
{ Convert a class ID to a programmatic ID }
function ClassIDToProgID(const ClassID: TGUID): string;
var
P: PWideChar;
begin
OleCheck(ProgIDFromCLSID(ClassID, P));
Result := P;
CoTaskMemFree(P);
end;
{ Create registry key }
procedure CreateRegKey(const Key, ValueName, Value: string; RootKey: HKEY);
var
Handle: HKey;
Status, Disposition: Integer;
begin
Status := RegCreateKeyEx(RootKey, PChar(Key), 0, '',
REG_OPTION_NON_VOLATILE, KEY_READ or KEY_WRITE, nil, Handle,
@Disposition);
if Status = 0 then
begin
Status := RegSetValueEx(Handle, PChar(ValueName), 0, REG_SZ,
PChar(Value), (Length(Value) + 1)* sizeof(char));
RegCloseKey(Handle);
end;
if Status <> 0 then raise EOleRegistrationError.CreateRes(@SCreateRegKeyError);
end;
{ Delete registry key }
procedure DeleteRegKey(const Key: string; RootKey: HKEY);
begin
RegDeleteKey(RootKey, PChar(Key));
end;
{ Get registry value }
function GetRegStringValue(const Key, ValueName: string; RootKey: HKEY): string;
var
Size: DWord;
RegKey: HKEY;
begin
Result := '';
if RegOpenKeyEx(RootKey, PChar(Key), 0, KEY_READ, RegKey) = ERROR_SUCCESS then
try
Size := 256;
SetLength(Result, Size);
Size := Size * SizeOf(Char);
if RegQueryValueEx(RegKey, PChar(ValueName), nil, nil, PByte(PChar(Result)), @Size) = ERROR_SUCCESS then
SetLength(Result, (Size div SizeOf(Char)) - 1) else
Result := '';
finally
RegCloseKey(RegKey);
end;
end;
function CreateComObject(const ClassID: TGUID): IUnknown;
begin
try
{$IFDEF CPUX86}
try
Set8087CW( Default8087CW or $08);
{$ENDIF CPUX86}
OleCheck(CoCreateInstance(ClassID, nil, CLSCTX_INPROC_SERVER or
CLSCTX_LOCAL_SERVER, IUnknown, Result));
{$IFDEF CPUX86}
finally
Reset8087CW;
end;
{$ENDIF CPUX86}
except
on E: EOleSysError do
raise EOleSysError.Create(Format('%s, ClassID: %s',[E.Message, GuidToString(ClassID)]),E.ErrorCode,0) { Do not localize }
end;
end;
function CreateRemoteComObject(const MachineName: WideString;
const ClassID: TGUID): IUnknown;
const
LocalFlags = CLSCTX_LOCAL_SERVER or CLSCTX_REMOTE_SERVER or CLSCTX_INPROC_SERVER;
RemoteFlags = CLSCTX_REMOTE_SERVER;
var
MQI: TMultiQI;
ServerInfo: TCoServerInfo;
IID_IUnknown: TGuid;
Flags, Size: DWORD;
LocalMachine: array [0..MAX_COMPUTERNAME_LENGTH] of char;
begin
if @CoCreateInstanceEx = nil then
raise Exception.CreateRes(@SDCOMNotInstalled);
FillChar(ServerInfo, sizeof(ServerInfo), 0);
ServerInfo.pwszName := PWideChar(MachineName);
IID_IUnknown := IUnknown;
MQI.IID := @IID_IUnknown;
MQI.itf := nil;
MQI.hr := 0;
{ If a MachineName is specified check to see if it the local machine.
If it isn't, do not allow LocalServers to be used. }
if Length(MachineName) > 0 then
begin
Size := Sizeof(LocalMachine); // Win95 is hypersensitive to size
if GetComputerName(LocalMachine, Size) and
(AnsiCompareText(LocalMachine, MachineName) = 0) then
Flags := LocalFlags else
Flags := RemoteFlags;
end else
Flags := LocalFlags;
{$IFDEF CPUX86}
try
Set8087CW( Default8087CW or $08);
{$ENDIF CPUX86}
OleCheck(CoCreateInstanceEx(ClassID, nil, Flags, @ServerInfo, 1, @MQI));
{$IFDEF CPUX86}
finally
Reset8087CW;
end;
{$ENDIF CPUX86}
OleCheck(MQI.HR);
Result := MQI.itf;
end;
function CreateOleObject(const ClassName: string): IDispatch;
var
ClassID: TCLSID;
begin
try
ClassID := ProgIDToClassID(ClassName);
{$IFDEF CPUX86}
try
Set8087CW( Default8087CW or $08);
{$ENDIF CPUX86}
OleCheck(CoCreateInstance(ClassID, nil, CLSCTX_INPROC_SERVER or
CLSCTX_LOCAL_SERVER, IDispatch, Result));
{$IFDEF CPUX86}
finally
Reset8087CW;
end;
{$ENDIF CPUX86}
except
on E: EOleSysError do
raise EOleSysError.Create(Format('%s, ProgID: "%s"',[E.Message, ClassName]),E.ErrorCode,0) { Do not localize }
end;
end;
function GetActiveOleObject(const ClassName: string): IDispatch;
var
ClassID: TCLSID;
Unknown: IUnknown;
begin
ClassID := ProgIDToClassID(ClassName);
OleCheck(GetActiveObject(ClassID, nil, Unknown));
OleCheck(Unknown.QueryInterface(IDispatch, Result));
end;
function StringToLPOLESTR(const Source: string): POleStr;
var
SourceLen: Integer;
Buffer: PWideChar;
begin
SourceLen := Length(Source);
Buffer := CoTaskMemAlloc((SourceLen+1) * sizeof(Char));
StringToWideChar( Source, Buffer, SourceLen+1 );
Result := POleStr( Buffer );
end;
function CreateClassID: string;
var
ClassID: TCLSID;
P: PWideChar;
begin
CoCreateGuid(ClassID);
StringFromCLSID(ClassID, P);
Result := P;
CoTaskMemFree(P);
end;
procedure RegisterComServer(const DLLName: string);
type
TRegProc = function: HResult; stdcall;
const
RegProcName = 'DllRegisterServer'; { Do not localize }
var
Handle: THandle;
RegProc: TRegProc;
begin
Handle := SafeLoadLibrary(DLLName);
if Handle <= HINSTANCE_ERROR then
raise Exception.CreateFmt('%s: %s', [SysErrorMessage(GetLastError), DLLName]);
try
RegProc := GetProcAddress(Handle, RegProcName);
if Assigned(RegProc) then OleCheck(RegProc) else RaiseLastOSError;
finally
FreeLibrary(Handle);
end;
end;
procedure RegisterAsService(const ClassID, ServiceName: string);
begin
CreateRegKey('AppID\' + ClassID, 'LocalService', ServiceName);
CreateRegKey('CLSID\' + ClassID, 'AppID', ClassID);
end;
{ Connect an IConnectionPoint interface }
procedure InterfaceConnect(const Source: IUnknown; const IID: TIID;
const Sink: IUnknown; var Connection: Longint);
var
CPC: IConnectionPointContainer;
CP: IConnectionPoint;
begin
Connection := 0;
if Succeeded(Source.QueryInterface(IConnectionPointContainer, CPC)) then
if Succeeded(CPC.FindConnectionPoint(IID, CP)) then
CP.Advise(Sink, Connection);
end;
{ Disconnect an IConnectionPoint interface }
procedure InterfaceDisconnect(const Source: IUnknown; const IID: TIID;
var Connection: Longint);
var
CPC: IConnectionPointContainer;
CP: IConnectionPoint;
begin
if Connection <> 0 then
if Succeeded(Source.QueryInterface(IConnectionPointContainer, CPC)) then
if Succeeded(CPC.FindConnectionPoint(IID, CP)) then
if Succeeded(CP.Unadvise(Connection)) then Connection := 0;
end;
procedure LoadComExProcs;
var
Ole32: HModule;
begin
Ole32 := Winapi.Windows.GetModuleHandle('ole32.dll');
if Ole32 <> 0 then
begin
@CoCreateInstanceEx := Winapi.Windows.GetProcAddress(Ole32, 'CoCreateInstanceEx');
@CoInitializeEx := Winapi.Windows.GetProcAddress(Ole32, 'CoInitializeEx');
@CoAddRefServerProcess := Winapi.Windows.GetProcAddress(Ole32, 'CoAddRefServerProcess');
@CoReleaseServerProcess := Winapi.Windows.GetProcAddress(Ole32, 'CoReleaseServerProcess');
@CoResumeClassObjects := Winapi.Windows.GetProcAddress(Ole32, 'CoResumeClassObjects');
@CoSuspendClassObjects := Winapi.Windows.GetProcAddress(Ole32, 'CoSuspendClassObjects');
end;
end;
{$IFDEF MSWINDOWS}
procedure SafeCallError(ErrorCode: Integer; ErrorAddr: Pointer);
function CreateSafeCallErrorExceptionObject(ErrorCode: Integer): Exception;
var
ErrorInfo: IErrorInfo;
Source, Description, HelpFile: WideString;
HelpContext: Longint;
begin
HelpContext := 0;
if GetErrorInfo(0, ErrorInfo) = S_OK then
begin
ErrorInfo.GetSource(Source);
ErrorInfo.GetDescription(Description);
ErrorInfo.GetHelpFile(HelpFile);
ErrorInfo.GetHelpContext(HelpContext);
end;
if ErrorCode = EAbortRaisedHRESULT then
Result := EAbort.CreateHelp(Description, HelpContext)
else
Result := EOleException.Create(Description, ErrorCode, Source, HelpFile, HelpContext);
end;
var
E: Exception;
begin
E := CreateSafeCallErrorExceptionObject(ErrorCode);
raise E at ErrorAddr;
end;
{$ENDIF MSWINDOWS}
{ Call Invoke method on the given IDispatch interface using the given
call descriptor, dispatch IDs, parameters, and result }
procedure DispatchInvoke(const Dispatch: IDispatch; CallDesc: PCallDesc;
DispIDs: PDispIDList; Params: Pointer; Result: PVariant);
var
I, DispID, InvKind: Integer;
DispParams: TDispParams;
ExcepInfo: TExcepInfo;
VarParams: TVarDataArray;
Status: HRESULT;
Strings: TStringRefList;
begin
FillChar(Strings, SizeOf(Strings), 0);
VarParams := GetDispatchInvokeArgs(CallDesc, Params, Strings, false);
try
DispParams.cArgs := CallDesc^.ArgCount;
if CallDesc^.ArgCount > 0 then
DispParams.rgvarg := @VarParams[0]
else
DispParams.rgvarg := nil;
if CallDesc^.NamedArgCount > 0 then
DispParams.rgdispidNamedArgs := @DispIDs[1]
else
DispParams.rgdispidNamedArgs := nil;
DispParams.cNamedArgs := CallDesc^.NamedArgCount;
DispID := DispIDs[0];
InvKind := CallDesc^.CallType;
if InvKind = DISPATCH_PROPERTYPUT then
begin
if ((VarParams[0].VType and varTypeMask) = varDispatch) or
((VarParams[0].VType and varTypeMask) = varUnknown) then
InvKind := DISPATCH_PROPERTYPUTREF or DISPATCH_PROPERTYPUT;
DispIDs[0] := DISPID_PROPERTYPUT;
DispParams.rgdispidNamedArgs := @DispIDs[0];
Inc(DispParams.cNamedArgs);
end
else if (InvKind = DISPATCH_METHOD) and (CallDesc^.ArgCount = 0) and (Result <> nil) then
InvKind := DISPATCH_METHOD or DISPATCH_PROPERTYGET
else if (InvKind = DISPATCH_PROPERTYGET) and (CallDesc^.ArgCount <> 0) then
InvKind := DISPATCH_METHOD or DISPATCH_PROPERTYGET;
FillChar(ExcepInfo, SizeOf(ExcepInfo), 0);
Status := Dispatch.Invoke(DispID, GUID_NULL, 0, InvKind, DispParams,
Result, @ExcepInfo, nil);
if Status <> 0 then
DispatchInvokeError(Status, ExcepInfo);
finally
FinalizeDispatchInvokeArgs(CallDesc, VarParams, false);
end;
for I := 0 to Length(Strings) -1 do
begin
if Pointer(Strings[I].Wide) = nil then
Break;
if Strings[I].Ansi <> nil then
Strings[I].Ansi^ := AnsiString(Strings[I].Wide)
else if Strings[I].Unicode <> nil then
Strings[I].Unicode^ := UnicodeString(Strings[I].Wide)
end;
end;
{ Call GetIDsOfNames method on the given IDispatch interface }
procedure GetIDsOfNames(const Dispatch: IDispatch; Names: PAnsiChar;
NameCount: Integer; DispIDs: PDispIDList); overload;
var
WideNames: array of WideString;
I: Integer;
Src: PAnsiChar;
Temp: HResult;
begin
SetLength(WideNames, NameCount);
Src := Names;
for I := 0 to NameCount-1 do
begin
if I = 0 then
WideNames[I] := UTF8ToWideString(Src)
else
WideNames[NameCount-I] := UTF8ToWideString(Src);
Inc(Src, System.AnsiStrings.StrLen(Src)+1);
end;
Temp := Dispatch.GetIDsOfNames(GUID_NULL, WideNames, NameCount,
GetThreadLocale, DispIDs);
if Temp = Integer(DISP_E_UNKNOWNNAME) then
raise EOleError.CreateResFmt(@SNoMethod, [Names])
else
OleCheck(Temp);
end;
procedure GetIDsOfNames(const Dispatch: IDispatch; Names: PWideChar;
NameCount: Integer; DispIDs: PDispIDList); overload;
begin
GetIDsOfNames(Dispatch, PAnsiChar(AnsiString(Names)), NameCount, DispIDs);
end;
{ Central call dispatcher }
procedure VarDispInvoke(Result: PVariant; const Instance: Variant;
CallDesc: PCallDesc; Params: Pointer); cdecl;
procedure RaiseException;
begin
raise EOleError.CreateRes(@SVarNotObject);
end;
var
Dispatch: Pointer;
DispIDs: array[0..MaxDispArgs - 1] of Integer;
begin
if (CallDesc^.ArgCount) > MaxDispArgs then raise EOleError.CreateRes(@STooManyParams);
if TVarData(Instance).VType = varDispatch then
Dispatch := TVarData(Instance).VDispatch
else if TVarData(Instance).VType = (varDispatch or varByRef) then
Dispatch := Pointer(TVarData(Instance).VPointer^)
else RaiseException;
GetIDsOfNames(IDispatch(Dispatch), PAnsiChar(@CallDesc^.ArgTypes[CallDesc^.ArgCount]),
CallDesc^.NamedArgCount + 1, @DispIDs);
if Result <> nil then VarClear(Result^);
DispatchInvoke(IDispatch(Dispatch), CallDesc, @DispIDs, Params, Result);
end;
{ Raise exception given an OLE return code and TExcepInfo structure }
procedure DispatchInvokeError(Status: Integer; const ExcepInfo: TExcepInfo);
var
E: Exception;
begin
if Status = Integer(DISP_E_EXCEPTION) then
begin
with ExcepInfo do
E := EOleException.Create(bstrDescription, scode, bstrSource,
bstrHelpFile, dwHelpContext);
end else
E := EOleSysError.Create('', Status, 0);
raise E;
end;
function _DispReturnPointer(Val:Pointer): Pointer; begin Result := val; end;
function _DispReturnInteger(Val:Integer): Integer; begin Result := val; end;
function _DispReturnInt64 (Val:Int64 ): Int64; begin Result := val; end;
{$IFNDEF CPUX86}
function _DispReturnDouble (Val: Double): Double; begin Result := val; end;
function _DispReturnSingle (Val: Single): Single; begin Result := val; end;
{$ENDIF !CPUX86}
procedure DispCallByID(Result: Pointer; const Dispatch: IDispatch;
DispDesc: PDispDesc; Params: Pointer); cdecl;
var
Res: TVarData;
DispIDS: array[0..1] of TDispID;
begin
System.VarUtils.VariantInit(Res);
DispIDs[0] := DispDesc.DispID;
{$IFDEF CPUX86}
DispatchInvoke(Dispatch, @DispDesc.CallDesc,
@DispIDs, @Params, @Res);
{$ELSE}
DispatchInvoke(Dispatch, @DispDesc.CallDesc,
@DispIDs, Params, @Res);
{$ENDIF}
if (Result <> nil) then
begin
case DispDesc.ResType of
varSmallint: PSmallInt(Result)^ := Res.VSmallInt;
varInteger: PLongInt(Result)^ := Res.VInteger;
varSingle: PSingle(Result)^ := Res.VSingle;
varDouble: PDouble(Result)^ := Res.VDouble;
varCurrency: PCurrency(Result)^ := Res.VCurrency;
varDate: PDate(Result)^ := Res.VDate;
varBoolean: PWordBool(Result)^ := Res.VBoolean;
varShortInt: PShortInt(Result)^ := Res.VShortInt;
varByte: PByte(Result)^ := Res.VByte;
varWord: PWord(Result)^ := Res.VWord;
varUInt32: PCardinal(Result)^ := Res.VUInt32;
varInt64: PInt64(Result)^ := Res.VInt64;
varUInt64: PUInt64(Result)^ := Res.VUInt64;
varOleStr:
begin
if PPointer(Result)^ <> nil then
SysFreeString(PWideChar(Result^));
PPointer(Result)^ := Res.VOleStr;
end;
varDispatch, varUnknown:
begin
if PPointer(Result)^ <> nil then
IDispatch(Result^)._Release;
PPointer(Result)^ := Res.VDispatch;
end;
varVariant:
begin
VarClear(PVariant(Result)^);
Move(Res, Result^, SizeOf(Res));
end;
end;
end
else
begin
case DispDesc.ResType of
varSmallint: _DispReturnInteger(Res.VSmallInt);
varInteger: _DispReturnInteger(Res.VInteger);
{$IFDEF CPUX86}
varSingle:
asm
FLD Res.VSingle
end;
varDouble:
asm
FLD Res.VDouble
end;
varCurrency:
asm
FILD res.VCurrency
end;
varDate:
asm
FLD res.VDate
end;
{$ELSE}
varSingle: _DispReturnSingle(Res.VSingle);
varDouble: _DispReturnDouble(Res.VDouble);
varCurrency: _DispReturnInt64(PInt64(@Res.VCurrency)^);
varDate: _DIspReturnDouble(Res.VDate);
{$ENDIF}
varBoolean: _DispReturnInteger(Integer(Res.VBoolean));
varShortInt: _DispReturnInteger(Res.VShortInt);
varByte: _DispReturnInteger(Res.VByte);
varWord: _DispReturnInteger(Res.VWord);
varUInt32: _DispReturnInteger(Res.VUInt32);
varInt64: _DispReturnInt64(Res.VInt64);
varUInt64: _DispReturnInt64(Res.VUInt64);
varOleStr:
begin
_DispReturnPointer(Res.VOleStr);
end;
varDispatch, varUnknown:
begin
_DispReturnPointer(Res.VDispatch);
end;
end;
end;
end;
const
DispIDArgs: Longint = DISPID_PROPERTYPUT;
function GetDispatchPropValue(const Disp: IDispatch; DispID: Integer): OleVariant;
var
ExcepInfo: TExcepInfo;
DispParams: TDispParams;
Status: HResult;
begin
FillChar(DispParams, SizeOf(DispParams), 0);
Status := Disp.Invoke(DispID, GUID_NULL, 0, DISPATCH_PROPERTYGET, DispParams,
@Result, @ExcepInfo, nil);
if Status <> S_OK then DispatchInvokeError(Status, ExcepInfo);
end;
function GetDispatchPropValue(const Disp: IDispatch; Name: WideString): OleVariant;
var
ID: Integer;
begin
OleCheck(Disp.GetIDsOfNames(GUID_NULL, @Name, 1, 0, @ID));
Result := GetDispatchPropValue(Disp, ID);
end;
procedure SetDispatchPropValue(const Disp: IDispatch; DispID: Integer;
const Value: OleVariant);
var
ExcepInfo: TExcepInfo;
DispParams: TDispParams;
Status: HResult;
begin
with DispParams do
begin
rgvarg := @Value;
rgdispidNamedArgs := @DispIDArgs;
cArgs := 1;
cNamedArgs := 1;
end;
Status := Disp.Invoke(DispId, GUID_NULL, 0, DISPATCH_PROPERTYPUT, DispParams,
nil, @ExcepInfo, nil);
if Status <> S_OK then DispatchInvokeError(Status, ExcepInfo);
end;
procedure SetDispatchPropValue(const Disp: IDispatch; Name: WideString;
const Value: OleVariant); overload;
var
ID: Integer;
begin
OleCheck(Disp.GetIDsOfNames(GUID_NULL, @Name, 1, 0, @ID));
SetDispatchPropValue(Disp, ID, Value);
end;
function EventDispatchInvoke(DispId: Integer; var ADispParams: TDispParams;
Invoker: TEventDispatchInvoker): HResult;
var
LVarArray : TOleVariantArray;
I, LFistArrItem, LLastArrItem: Integer;
LPVarArgIn: PVariantArg;
begin
SetLength(LVarArray, ADispParams.cArgs);
LFistArrItem := Low(LVarArray);
LLastArrItem := High(LVarArray);
if ADispParams.cNamedArgs > 0 then
// Copy over data from Params in NamedArgs order
for I := LFistArrItem to LLastArrItem do
begin
LPVarArgIn := @ADispParams.rgvarg[i];
LVarArray[ADispParams.rgdispidNamedArgs[i]] := POleVariant(LPVarArgIn)^;
end
else
// Copy in reverse order
for I := LFistArrItem to LLastArrItem do
begin
LPVarArgIn := @ADispParams.rgvarg[I];
LVarArray[LLastArrItem - I] := POleVariant(LPVarArgIn)^;
end;
Invoker(DispId, LVarArray);
SetLength(LVarArray, 0);
Result := S_OK;
end;
var
ComClassManagerVar: TObject;
SaveInitProc: Pointer;
InitComObjCalled: Boolean = False;
NeedToUninitialize: Boolean = False;
function ComClassManager: TComClassManager;
begin
if ComClassManagerVar = nil then
ComClassManagerVar := TComClassManager.Create;
Result := TComClassManager(ComClassManagerVar);
end;
procedure InitComObj;
begin
if InitComObjCalled then Exit;
if SaveInitProc <> nil then
TProcedure(SaveInitProc);
if (CoInitFlags <> -1) and Assigned(System.Win.ComObj.CoInitializeEx) then
begin
NeedToUninitialize := Succeeded(System.Win.ComObj.CoInitializeEx(nil, CoInitFlags));
IsMultiThread := IsMultiThread or
((CoInitFlags and COINIT_APARTMENTTHREADED) <> 0) or
(CoInitFlags = COINIT_MULTITHREADED); // this flag has value zero
end
else
NeedToUninitialize := Succeeded(CoInitialize(nil));
InitComObjCalled := True;
end;
function HandleException: HResult;
var
E: TObject;
begin
E := ExceptObject;
if (E is EOleSysError) and (EOleSysError(E).ErrorCode < 0) then
Result := EOleSysError(E).ErrorCode else
Result := E_UNEXPECTED;
end;
procedure FreeObjects(List: TList);
var
I: Integer;
begin
for I := List.Count - 1 downto 0 do TObject(List[I]).Free;
end;
procedure FreeObjectList(List: TList);
begin
if List <> nil then
begin
FreeObjects(List);
List.Free;
end;
end;
{ TEnumConnections }
type
TEnumConnections = class(TInterfacedObject, IEnumConnections)
private
FConnectionPoint: TConnectionPoint;
FController: IUnknown;
FIndex: Integer;
FCount: Integer;
protected
{ IEnumConnections }
function Next(celt: Longint; out elt; pceltFetched: PLongint): HResult; stdcall;
function Skip(celt: Longint): HResult; stdcall;
function Reset: HResult; stdcall;
function Clone(out enumconn: IEnumConnections): HResult; stdcall;
public
constructor Create(ConnectionPoint: TConnectionPoint; Index: Integer);
end;
constructor TEnumConnections.Create(ConnectionPoint: TConnectionPoint;
Index: Integer);
begin
inherited Create;
FConnectionPoint := ConnectionPoint;
// keep ConnectionPoint's controller alive as long as we're in use
FController := FConnectionPoint.Controller;
FIndex := Index;
FCount := ConnectionPoint.FSinkList.Count;
end;
{ TEnumConnections.IEnumConnections }
function TEnumConnections.Next(celt: Longint; out elt;
pceltFetched: PLongint): HResult;
type
TConnectDatas = array[0..1023] of TConnectData;
var
I: Integer;
P: Pointer;
begin
I := 0;
while (I < celt) and (FIndex < FCount) do
begin
P := FConnectionPoint.FSinkList[FIndex];
if P <> nil then
begin
Pointer(TConnectDatas(elt)[I].pUnk) := nil;
TConnectDatas(elt)[I].pUnk := IUnknown(P);
TConnectDatas(elt)[I].dwCookie := FIndex + 1;
Inc(I);
end;
Inc(FIndex);
end;
if pceltFetched <> nil then pceltFetched^ := I;
if I = celt then Result := S_OK else Result := S_FALSE;
end;
function TEnumConnections.Skip(celt: Longint): HResult; stdcall;
begin
Result := S_FALSE;
while (celt > 0) and (FIndex < FCount) do
begin
if FConnectionPoint.FSinkList[FIndex] <> nil then Dec(celt);
Inc(FIndex);
end;
if celt = 0 then Result := S_OK;
end;
function TEnumConnections.Reset: HResult; stdcall;
begin
FIndex := 0;
Result := S_OK;
end;
function TEnumConnections.Clone(out enumconn: IEnumConnections): HResult; stdcall;
begin
try
enumconn := TEnumConnections.Create(FConnectionPoint, FIndex);
Result := S_OK;
except
Result := E_UNEXPECTED;
end;
end;
{ TConnectionPoint }
constructor TConnectionPoint.Create(Container: TConnectionPoints;
const IID: TGUID; Kind: TConnectionKind;
OnConnect: TConnectEvent);
begin
inherited Create(IUnknown(Container.FController));
FContainer := Container;
FContainer.FConnectionPoints.Add(Self);
FSinkList := TList.Create;
FIID := IID;
FKind := Kind;
FOnConnect := OnConnect;
end;
destructor TConnectionPoint.Destroy;
var
I: Integer;
begin
if FContainer <> nil then FContainer.FConnectionPoints.Remove(Self);
if FSinkList <> nil then
begin
for I := 0 to FSinkList.Count - 1 do
if FSinkList[I] <> nil then RemoveSink(I);
FSinkList.Free;
end;
inherited Destroy;
end;
function TConnectionPoint.GetSink(Index: Integer; var punk: IUnknown): Boolean;
begin
if Assigned(FSinkList[Index]) then
begin
punk := IUnknown(FSinkList[Index]);
Result := True;
end else
Result := False;
end;
function TConnectionPoint.GetCount: Integer;
begin
Result := FSinkList.Count;
end;
function TConnectionPoint.AddSink(const Sink: IUnknown): Integer;
var
I: Integer;
begin
I := 0;
while I < FSinkList.Count do
begin
if FSinkList[I] = nil then
Break
else
Inc(I);
end;
if I >= FSinkList.Count then
FSinkList.Add(Pointer(Sink))
else
FSinkList[I] := Pointer(Sink);
Sink._AddRef;
Result := I;
end;
procedure TConnectionPoint.RemoveSink(Cookie: Longint);
var
Sink: Pointer;
begin
Sink := FSinkList[Cookie];
FSinkList[Cookie] := nil;
IUnknown(Sink)._Release;
end;
{ TConnectionPoint.IConnectionPoint }
function TConnectionPoint.GetConnectionInterface(out iid: TIID): HResult;
begin
iid := FIID;
Result := S_OK;
end;
function TConnectionPoint.GetConnectionPointContainer(
out cpc: IConnectionPointContainer): HResult;
begin
cpc := IUnknown(FContainer.FController) as IConnectionPointContainer;
Result := S_OK;
end;
function TConnectionPoint.Advise(const unkSink: IUnknown;
out dwCookie: Longint): HResult;
begin
if (FKind = ckSingle) and (FSinkList.Count > 0) and
(FSinkList[0] <> nil) then
begin
Result := CONNECT_E_CANNOTCONNECT;
Exit;
end;
try
if Assigned(FOnConnect) then FOnConnect(unkSink, True);
dwCookie := AddSink(unkSink) + 1;
Result := S_OK;
except
Result := HandleException;
end;
end;
function TConnectionPoint.Unadvise(dwCookie: Longint): HResult;
begin
Dec(dwCookie);
if (dwCookie < 0) or (dwCookie >= FSinkList.Count) or
(FSinkList[dwCookie] = nil) then
begin
Result := CONNECT_E_NOCONNECTION;
Exit;
end;
try
if Assigned(FOnConnect) then
FOnConnect(IUnknown(FSinkList[dwCookie]), False);
RemoveSink(dwCookie);
Result := S_OK;
except
Result := HandleException;
end;
end;
function TConnectionPoint.EnumConnections(out enumconn: IEnumConnections): HResult;
begin
try
enumconn := TEnumConnections.Create(Self, 0);
Result := S_OK;
except
Result := HandleException;
end;
end;
{ TEnumConnectionPoints }
type
TEnumConnectionPoints = class(TContainedObject, IEnumConnectionPoints)
private
FContainer: TConnectionPoints;
FIndex: Integer;
protected
{ IEnumConnectionPoints }
function Next(celt: Longint; out elt;
pceltFetched: PLongint): HResult; stdcall;
function Skip(celt: Longint): HResult; stdcall;
function Reset: HResult; stdcall;
function Clone(out enumconn: IEnumConnectionPoints): HResult; stdcall;
public
constructor Create(Container: TConnectionPoints;
Index: Integer);
end;
constructor TEnumConnectionPoints.Create(Container: TConnectionPoints;
Index: Integer);
begin
inherited Create(IUnknown(Container.FController));
FContainer := Container;
FIndex := Index;
end;
{ TEnumConnectionPoints.IEnumConnectionPoints }
type
TPointerList = array[0..0] of Pointer;
function TEnumConnectionPoints.Next(celt: Longint; out elt;
pceltFetched: PLongint): HResult;
var
I: Integer;
P: Pointer;
begin
I := 0;
while (I < celt) and (FIndex < FContainer.FConnectionPoints.Count) do
begin
P := Pointer(IConnectionPoint(TConnectionPoint(
FContainer.FConnectionPoints[FIndex])));
IConnectionPoint(P)._AddRef;
TPointerList(elt)[I] := P;
Inc(I);
Inc(FIndex);
end;
if pceltFetched <> nil then pceltFetched^ := I;
if I = celt then Result := S_OK else Result := S_FALSE;
end;
function TEnumConnectionPoints.Skip(celt: Longint): HResult; stdcall;
begin
if FIndex + celt <= FContainer.FConnectionPoints.Count then
begin
FIndex := FIndex + celt;
Result := S_OK;
end else
begin
FIndex := FContainer.FConnectionPoints.Count;
Result := S_FALSE;
end;
end;
function TEnumConnectionPoints.Reset: HResult; stdcall;
begin
FIndex := 0;
Result := S_OK;
end;
function TEnumConnectionPoints.Clone(
out enumconn: IEnumConnectionPoints): HResult; stdcall;
begin
try
enumconn := TEnumConnectionPoints.Create(FContainer, FIndex);
Result := S_OK;
except
Result := E_UNEXPECTED;
end;
end;
{ TConnectionPoints }
constructor TConnectionPoints.Create(const AController: IUnknown);
begin
// weak reference to controller - don't keep it alive
FController := Pointer(AController);
FConnectionPoints := TList.Create;
end;
destructor TConnectionPoints.Destroy;
begin
FreeObjectList(FConnectionPoints);
inherited Destroy;
end;
function TConnectionPoints.CreateConnectionPoint(const IID: TGUID;
Kind: TConnectionKind; OnConnect: TConnectEvent): TConnectionPoint;
begin
Result := TConnectionPoint.Create(Self, IID, Kind, OnConnect);
end;
{ TConnectionPoints.IConnectionPointContainer }
function TConnectionPoints.EnumConnectionPoints(
out enumconn: IEnumConnectionPoints): HResult;
begin
try
enumconn := TEnumConnectionPoints.Create(Self, 0);
Result := S_OK;
except
Result := E_UNEXPECTED;
end;
end;
function TConnectionPoints.FindConnectionPoint(const iid: TIID;
out cp: IConnectionPoint): HResult;
var
I: Integer;
ConnectionPoint: TConnectionPoint;
begin
for I := 0 to FConnectionPoints.Count - 1 do
begin
ConnectionPoint := FConnectionPoints[I];
if IsEqualGUID(ConnectionPoint.FIID, iid) then
begin
cp := ConnectionPoint;
Result := S_OK;
Exit;
end;
end;
Result := CONNECT_E_NOCONNECTION;
end;
function TConnectionPoints.GetController: IUnknown;
begin
Result := IUnknown(FController);
end;
{ TAutoObjectEvent }
constructor TAutoObjectEvent.Create;
begin
inherited;
end;
destructor TAutoObjectEvent.Destroy;
begin
FConnectionPoints.Free;
inherited;
end;
constructor TAutoObjectEvent.CreateAggregated(const Controller: IInterface);
begin
inherited;
end;
constructor TAutoObjectEvent.CreateFromFactory(Factory: TComObjectFactory;
const Controller: IInterface);
begin
inherited;
end;
procedure TAutoObjectEvent.Initialize;
begin
inherited Initialize;
FConnectionPoints := TConnectionPoints.Create(Self);
if AutoFactory.EventTypeInfo <> nil then
FConnectionPoint := FConnectionPoints.CreateConnectionPoint(AutoFactory.EventIID,
ckMulti, EventConnect)
else
FConnectionPoint := nil;
end;
{ TComServerObject }
class constructor TComServerObject.Create;
begin
FPerUserRegistration := False;
end;
class procedure TComServerObject.GetRegRootAndPrefix(var RootKey: HKEY;
var RootPrefix: string);
begin
if (FPerUserRegistration) then
begin
RootKey := HKEY_CURRENT_USER;
RootPrefix := 'Software\Classes\';
end
else
begin
RootKey := HKEY_CLASSES_ROOT;
RootPrefix := '';
end;
end;
initialization
begin
LoadComExProcs;
VarDispProc := @VarDispInvoke;
DispCallByIDProc := @DispCallByID;
{$IFDEF MSWINDOWS}
SafeCallErrorProc := @SafeCallError;
{$ENDIF}
if not IsLibrary then
begin
SaveInitProc := InitProc;
InitProc := @InitComObj;
end;
end;
finalization
begin
OleUninitializing := True;
ComClassManagerVar.Free;
SafeCallErrorProc := nil;
DispCallByIDProc := nil;
VarDispProc := nil;
if NeedToUninitialize then CoUninitialize;
end;
end.
|
{*******************************************************}
{ }
{ Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{ *************************************************************************** }
{ }
{ Licensees holding a valid Borland No-Nonsense License for this Software may }
{ use this file in accordance with such license, which appears in the file }
{ license.txt that came with this Software. }
{ }
{ *************************************************************************** }
unit Web.HTTPProd;
{$WARN SYMBOL_DEPRECATED OFF}
{$WARN IMPLICIT_STRING_CAST OFF}
interface
uses System.SysUtils, System.Classes, Web.HTTPApp, System.Masks;
/// <summary>Qualify a relative path using the location of the executable</summary>
function QualifyFileName(const AFileName: string): string;
type
{ THTMLTagAttributes }
THTMLAlign = (haDefault, haLeft, haRight, haCenter);
THTMLVAlign = (haVDefault, haTop, haMiddle, haBottom, haBaseline);
THTMLBgColor = type string;
IDesignerFileManager = interface
['{1DF271BF-F2EC-11D4-A559-00C04F6BB853}']
function QualifyFileName(const AFileName: string): string;
function GetStream(const AFileName: string; var AOwned: Boolean): TStream;
end;
THTMLTagAttributes = class(TPersistent)
private
FProducer: TCustomContentProducer;
FCustom: string;
FOnChange: TNotifyEvent;
procedure SetCustom(const Value: string);
protected
procedure Changed;
public
constructor Create(Producer: TCustomContentProducer);
procedure RestoreDefaults; virtual;
property Producer: TCustomContentProducer read FProducer;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
published
property Custom: string read FCustom write SetCustom;
end;
THTMLTableAttributes = class(THTMLTagAttributes)
private
FAlign: THTMLAlign;
FBorder: Integer;
FBgColor: THTMLBgColor;
FCellSpacing: Integer;
FCellPadding: Integer;
FWidth: Integer;
procedure SetAlign(Value: THTMLAlign);
procedure SetBorder(Value: Integer);
procedure SetBGColor(Value: THTMLBgColor);
procedure SetCellSpacing(Value: Integer);
procedure SetCellPadding(Value: Integer);
procedure SetWidth(Value: Integer);
protected
procedure AssignTo(Dest: TPersistent); override;
public
constructor Create(Producer: TCustomContentProducer);
procedure RestoreDefaults; override;
published
property Align: THTMLAlign read FAlign write SetAlign default haDefault;
property BgColor: THTMLBgColor read FBgColor write SetBgColor;
property Border: Integer read FBorder write SetBorder default -1;
property CellSpacing: Integer read FCellSpacing write SetCellSpacing default -1;
property CellPadding: Integer read FCellPadding write SetCellPAdding default -1;
property Width: Integer read FWidth write SetWidth default 100;
end;
THTMLTableElementAttributes = class(THTMLTagAttributes)
private
FAlign: THTMLAlign;
FBgColor: THTMLBgColor;
FVAlign: THTMLVAlign;
procedure SetAlign(Value: THTMLAlign);
procedure SetBGColor(Value: THTMLBgColor);
procedure SetVAlign(Value: THTMLVAlign);
protected
procedure AssignTo(Dest: TPersistent); override;
public
procedure RestoreDefaults; override;
published
property Align: THTMLAlign read FAlign write SetAlign default haDefault;
property BgColor: THTMLBgColor read FBgColor write SetBgColor;
property VAlign: THTMLVAlign read FVAlign write SetVAlign default haVDefault;
end;
THTMLTableHeaderAttributes = class(THTMLTableElementAttributes)
private
FCaption: string;
procedure SetCaption(Value: string);
protected
procedure AssignTo(Dest: TPersistent); override;
public
procedure RestoreDefaults; override;
published
property Caption: string read FCaption write SetCaption;
end;
THTMLTableRowAttributes = class(THTMLTableElementAttributes);
THTMLTableCellAttributes = class(THTMLTableElementAttributes);
TTag = (tgCustom, tgLink, tgImage, tgTable, tgImageMap, tgObject, tgEmbed);
THTMLTagEvent = procedure (Sender: TObject; Tag: TTag; const TagString: string;
TagParams: TStrings; var ReplaceText: string) of object;
IGetProducerTemplate = interface
['{44AA3FC1-FEB9-11D4-A566-00C04F6BB853}']
function GetProducerTemplateStream(out AOwned: Boolean): TStream;
function GetProducerTemplateFileName: string;
end;
{ TBasePageProducer }
TWebModuleContext = TObject;
TBasePageProducer = class(TCustomContentProducer, IGetProducerTemplate)
private
FOnHTMLTag: THTMLTagEvent;
FScriptEngine: string;
FStripParamQuotes: Boolean;
function GetWebModuleContext: TWebModuleContext; deprecated;
procedure ReadScriptEngine(AReader: TReader);
protected
function GetScriptEngine: string; virtual; deprecated;
function UseScriptEngine: Boolean; virtual; deprecated;
function GetTagID(const TagString: string): TTag;
function HandleTag(const TagString: string;
TagParams: TStrings): string; virtual;
function ImplHandleTag(const TagString: string;
TagParams: TStrings): string;
procedure DoTagEvent(Tag: TTag; const TagString: string; TagParams: TStrings;
var ReplaceText: string); dynamic;
function HandleScriptTag(const TagString: string;
TagParams: TStrings; var ReplaceString: string): Boolean; virtual; deprecated;
function ServerScriptFromStream(Stream: TStream): string; deprecated;
function GetProducerTemplateStream(out AOwned: Boolean): TStream;
function GetProducerTemplateFileName: string;
function GetTemplateFileName: string; virtual;
function GetTemplateStream(out AOwned: Boolean): TStream; virtual;
property OnHTMLTag: THTMLTagEvent read FOnHTMLTag write FOnHTMLTag;
procedure DefineProperties(Filer: TFiler); override;
public
constructor Create(AOwner: TComponent); override;
function Content: string; override;
function ContentFromStream(Stream: TStream): string; override;
function ContentFromString(const S: string): string; override;
property WebModuleContext: TWebModuleContext read GetWebModuleContext;
property StripParamQuotes: Boolean read FStripParamQuotes write FStripParamQuotes default True;
property ScriptEngine: string read GetScriptEngine;
end;
{ TCustomPageProducer }
TCustomPageProducer = class(TBasePageProducer)
private
FHTMLFile: TFileName;
FHTMLDoc: TStrings;
procedure SetHTMLFile(const Value: TFileName);
procedure SetHTMLDoc(Value: TStrings);
protected
function GetTemplateStream(out AOwned: Boolean): TStream; override;
function HandleTag(const TagString: string;
TagParams: TStrings): string; override;
function GetTemplateFileName: string; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property HTMLDoc: TStrings read FHTMLDoc write SetHTMLDoc;
property HTMLFile: TFileName read FHTMLFile write SetHTMLFile;
end;
{ TPageProducer }
TPageProducer = class(TCustomPageProducer)
published
property HTMLDoc;
property HTMLFile;
property StripParamQuotes;
property OnHTMLTag;
end;
THandleTagProc = function(const TagString: string; TagParams: TStrings): string of object;
THandledTagProc = function(const TagString: string; TagParams: TStrings; var ReplaceString: string): Boolean of object;
function GetTagID(const TagString: string): TTag;
function ContentFromStream(AStream: TStream;
AStripParamQuotes: Boolean; AHandleTag: THandleTagProc; AHandledTag: THandledTagProc): string;
function ContentFromString(const AValue: string;
AStripParamQuotes: Boolean; AHandleTag: THandleTagProc; AHandledTag: THandledTagProc): string;
function GetEncodingOfStream(AStream: TStream; out ASignatureSize: Integer): TEncoding;
const
HTMLAlign: array[THTMLAlign] of string =
('',
' Align="left"',
' Align="right"',
' Align="center"');
HTMLVAlign: array[THTMLVAlign] of string =
('',
' VAlign="top"',
' VAlign="middle"',
' VAlign="bottom"',
' VAlign="baseline"');
var
DesignerFileManager: IDesignerFileManager = nil;
implementation
uses
Web.CopyPrsr, Web.WebConst;
{ THTMLTagAttributes }
constructor THTMLTagAttributes.Create(Producer: TCustomContentProducer);
begin
inherited Create;
FProducer := Producer;
end;
procedure THTMLTagAttributes.Changed;
begin
if Assigned(FOnChange) then FOnChange(Self);
end;
procedure THTMLTagAttributes.RestoreDefaults;
begin
FCustom := '';
Changed;
end;
procedure THTMLTagAttributes.SetCustom(const Value: string);
begin
if Value <> FCustom then
begin
FCustom := Value;
Changed;
end;
end;
{ THTMLTableAttributes }
constructor THTMLTableAttributes.Create(Producer: TCustomContentProducer);
begin
inherited Create(Producer);
FWidth := 100;
FBorder := -1;
FCellPadding := -1;
FCellSpacing := -1;
end;
procedure THTMLTableAttributes.AssignTo(Dest: TPersistent);
begin
if Dest is THTMLTableAttributes then
with THTMLTableAttributes(Dest) do
begin
FWidth := Self.FWidth;
FAlign := Self.FAlign;
FBorder := Self.FBorder;
FBgColor := Self.FBgColor;
FCellSpacing := Self.FCellSpacing;
FCellPadding := Self.FCellPadding;
Changed;
end else inherited AssignTo(Dest);
end;
procedure THTMLTableAttributes.RestoreDefaults;
begin
FCustom := '';
FAlign := haDefault;
FWidth := 100;
FBorder := -1;
FCellPadding := -1;
FCellSpacing := -1;
Changed;
end;
procedure THTMLTableAttributes.SetAlign(Value: THTMLAlign);
begin
if Value <> FAlign then
begin
FAlign := Value;
Changed;
end;
end;
procedure THTMLTableAttributes.SetBorder(Value: Integer);
begin
if Value <> FBorder then
begin
FBorder := Value;
Changed;
end;
end;
procedure THTMLTableAttributes.SetBGColor(Value: THTMLBgColor);
begin
if Value <> FBgColor then
begin
FBgColor := Value;
Changed;
end;
end;
procedure THTMLTableAttributes.SetCellSpacing(Value: Integer);
begin
if Value <> FCellSpacing then
begin
FCellSpacing := Value;
Changed;
end;
end;
procedure THTMLTableAttributes.SetCellPadding(Value: Integer);
begin
if Value <> FCellPadding then
begin
FCellPadding := Value;
Changed;
end;
end;
procedure THTMLTableAttributes.SetWidth(Value: Integer);
begin
if Value <> FWidth then
begin
FWidth := Value;
Changed;
end;
end;
{ THTMLTableElementAttributes }
procedure THTMLTableElementAttributes.AssignTo(Dest: TPersistent);
begin
if Dest is THTMLTableElementAttributes then
with THTMLTableElementAttributes(Dest) do
begin
FAlign := Self.FAlign;
FVAlign := Self.FVAlign;
FBgColor := Self.FBgColor;
Changed;
end else inherited AssignTo(Dest);
end;
procedure THTMLTableElementAttributes.RestoreDefaults;
begin
FCustom := '';
FAlign := haDefault;
FVAlign := haVDefault;
FBgColor := '';
Changed;
end;
procedure THTMLTableElementAttributes.SetAlign(Value: THTMLAlign);
begin
if Value <> FAlign then
begin
FAlign := Value;
Changed;
end;
end;
procedure THTMLTableElementAttributes.SetBGColor(Value: THTMLBgColor);
begin
if Value <> FBgColor then
begin
FBgColor := Value;
Changed;
end;
end;
procedure THTMLTableElementAttributes.SetVAlign(Value: THTMLVAlign);
begin
if Value <> FVAlign then
begin
FVAlign := Value;
Changed;
end;
end;
{ THTMLTableHeaderAttributes }
procedure THTMLTableHeaderAttributes.AssignTo(Dest: TPersistent);
begin
if Dest is THTMLTableHeaderAttributes then
with THTMLTableHeaderAttributes(Dest) do
begin
FAlign := Self.FAlign;
FVAlign := Self.FVAlign;
FBgColor := Self.FBgColor;
FCaption := Self.FCaption;
Changed;
end else inherited AssignTo(Dest);
end;
procedure THTMLTableHeaderAttributes.RestoreDefaults;
begin
FCustom := '';
FAlign := haDefault;
FVAlign := haVDefault;
FBgColor := '';
FCaption := '';
Changed;
end;
procedure THTMLTableHeaderAttributes.SetCaption(Value: string);
begin
if CompareStr(Value, FCaption) <> 0 then
begin
FCaption := Value;
Changed;
end;
end;
{ TBasePageProducer }
constructor TBasePageProducer.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FStripParamQuotes := True;
RPR;
end;
function TBasePageProducer.ContentFromStream(Stream: TStream): string;
begin
Result := Web.HttpProd.ContentFromStream(Stream,
StripParamQuotes, HandleTag, nil);
end;
function TBasePageProducer.ServerScriptFromStream(Stream: TStream): string;
begin
Result := Web.HttpProd.ContentFromStream(Stream,
StripParamQuotes, nil, nil);
end;
function TBasePageProducer.ContentFromString(const S: string): string;
var
InStream: TStream;
begin
InStream := TStringStream.Create(S, TEncoding.UTF8);
try
Result := ContentFromStream(InStream);
finally
InStream.Free;
end;
end;
function TBasePageProducer.HandleTag(const TagString: string; TagParams: TStrings): string;
begin
Result := Format('<#%s>', [TagString]);
end;
function TBasePageProducer.HandleScriptTag(const TagString: string; TagParams: TStrings;
var ReplaceString: string): Boolean;
begin
Result := False;
end;
function TBasePageProducer.GetTagID(const TagString: string): TTag;
begin
Result := Web.HTTPProd.GetTagID(TagString);
end;
var
TagSymbols: array[TTag] of string =
('', 'LINK', 'IMAGE', 'TABLE', 'IMAGEMAP', 'OBJECT', 'EMBED');
function GetTagID(const TagString: string): TTag;
begin
Result := High(TTag);
while Result >= Low(TTag) do
begin
if (Result = tgCustom) or (CompareText(TagSymbols[Result], TagString) = 0) then Break;
Dec(Result);
end;
end;
function TBasePageProducer.Content: string;
var
InStream: TStream;
Owned: Boolean;
begin
Result := '';
InStream := GetTemplateStream(Owned);
try
if InStream <> nil then
Result := ContentFromStream(InStream);
finally
if Owned then
InStream.Free;
end;
end;
procedure TBasePageProducer.DoTagEvent(Tag: TTag; const TagString: string;
TagParams: TStrings; var ReplaceText: string);
begin
if Assigned(FOnHTMLTag) then
FOnHTMLTag(Self, Tag, TagString, TagParams, ReplaceText);
end;
function TBasePageProducer.ImplHandleTag(const TagString: string;
TagParams: TStrings): string;
var
Tag: TTag;
begin
Tag := GetTagID(TagString);
Result := '';
DoTagEvent(Tag, TagString, TagParams, Result);
end;
function TBasePageProducer.GetScriptEngine: string;
begin
Result := FScriptEngine;
end;
function TBasePageProducer.UseScriptEngine: Boolean;
begin
Result := False;
end;
function TBasePageProducer.GetTemplateStream(out AOwned: Boolean): TStream;
begin
Result := nil;
end;
function TBasePageProducer.GetWebModuleContext: TWebModuleContext;
begin
// Deprecated
Result := nil;
end;
function TBasePageProducer.GetProducerTemplateStream(
out AOwned: Boolean): TStream;
var
S: string;
begin
Result := nil;
if DesignerFileManager <> nil then
begin
S := GetProducerTemplateFileName;
if S <> '' then
Result := DesignerFileManager.GetStream(S, AOwned);
end;
if Result = nil then
Result := GetTemplateStream(AOwned);
end;
function TBasePageProducer.GetProducerTemplateFileName: string;
begin
Result := GetTemplateFileName;
if DesignerFileManager <> nil then
begin
if Result <> '' then
Result := DesignerFileManager.QualifyFileName(Result);
end
else
begin
// Expand relative path
if not (((Length(Result) >= 3) and (Result[1+Low(string)] = ':')) or
((Length(Result) >= 2) and (Result[Low(string)] = PathDelim) and (Result[1+Low(string)] = PathDelim))) then
if not ((Length(Result) >= 1) and (Result[Low(string)] = PathDelim)) then
Result := IncludeTrailingPathDelimiter(WebApplicationDirectory) + Result
else
Result := ExtractFileDrive(WebApplicationDirectory) + Result
end;
end;
function TBasePageProducer.GetTemplateFileName: string;
begin
Result := '';
end;
procedure TBasePageProducer.DefineProperties(Filer: TFiler);
begin
inherited;
// For backwards compatibility
Filer.DefineProperty('ScriptEngine', ReadScriptEngine, nil, False);
end;
procedure TBasePageProducer.ReadScriptEngine(AReader: TReader);
begin
FScriptEngine := AReader.ReadString;
end;
{ TCustomPageProducer }
constructor TCustomPageProducer.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FHTMLDoc := TStringList.Create;
end;
destructor TCustomPageProducer.Destroy;
begin
FHTMLDoc.Free;
inherited Destroy;
end;
function TCustomPageProducer.GetTemplateStream(out AOwned: Boolean): TStream;
begin
if FHTMLFile <> '' then
begin
Result := TFileStream.Create(GetProducerTemplateFileName {Qualified name}, fmOpenRead or fmShareDenyWrite);
AOwned := True;
end
else
begin
Result := TStringStream.Create(FHTMLDoc.Text, TEncoding.UTF8);
AOwned := True;
end;
end;
procedure TCustomPageProducer.SetHTMLFile(const Value: TFileName);
begin
if CompareText(FHTMLFile, Value) <> 0 then
begin
FHTMLDoc.Clear;
FHTMLFile := Value;
end;
end;
procedure TCustomPageProducer.SetHTMLDoc(Value: TStrings);
begin
FHTMLDoc.Assign(Value);
FHTMLFile := '';
end;
function TCustomPageProducer.HandleTag(const TagString: string;
TagParams: TStrings): string;
begin
Result := ImplHandleTag(TagString, TagParams);
end;
function GetEncodingOfStream(AStream: TStream; out ASignatureSize: Integer): TEncoding;
function ContainsPreamble(AStream: TStream; Encoding: TEncoding; var ASignatureSize: Integer): Boolean;
var
I: Integer;
Signature: TBytes;
Bytes: TBytes;
begin
Result := False;
Signature := Encoding.GetPreamble;
if Signature <> nil then
begin
if AStream.Size >= Length(Signature) then
begin
SetLength(Bytes, Length(Signature));
AStream.Read(Bytes[0], Length(Bytes));
Result := True;
ASignatureSize := Length(Signature);
for I := 0 to Length(Signature)-1 do
if Bytes[I] <> Signature [I] then
begin
ASignatureSize := 0;
Result := False;
Break;
end;
end;
end
end;
var
SavePos: Integer;
begin
ASignatureSize := 0;
if AStream is TStringStream then
Result := TStringStream(AStream).Encoding
else
begin
SavePos := AStream.Position;
AStream.Position := 0;
try
if ContainsPreamble(AStream, TEncoding.UTF8, ASignatureSize) then
Result := TEncoding.UTF8
else
Result := TEncoding.ANSI
finally
AStream.Position := SavePos;
end;
end;
end;
function ContentFromStream(AStream: TStream;
AStripParamQuotes: Boolean; AHandleTag: THandleTagProc; AHandledTag: THandledTagProc): string;
var
Parser: TCopyParser;
OutStream: TStringStream;
ParamStr, ReplaceStr, TokenStr, SaveParamStr: UTF8String;
ParamList: TStringList;
Encoding: TEncoding;
SignatureSize: Integer;
Temp: string;
begin
Encoding := GetEncodingOfStream(AStream, SignatureSize);
AStream.Position := SignatureSize;
OutStream := TStringStream.Create('', Encoding);
try
Parser := TCopyParser.Create(AStream, OutStream);
with Parser do
try
while True do
begin
while not (Token in [toEof, '<']) do
begin
CopyTokenToOutput;
SkipToken(True);
end;
if Token = toEOF then Break;
if Token = '<' then
begin
if SkipToken(False) = '#' then
begin
SkipToken(False);
TokenStr := Encoding.GetString(BytesOf(TokenString));
ParamStr := TrimLeft(TrimRight(Encoding.GetString(BytesOf(SkipToToken('>')))));
ParamList := TStringList.Create;
try
if Assigned(AHandledTag) then
begin
SaveParamStr := ParamStr; // ExtractHTTPFields modifies ParamStr
if Length(SaveParamStr) > 0 then
SaveParamStr := ' ' + SaveParamStr;
Temp := SaveParamStr;
UniqueString(Temp);
SaveParamStr := Temp;
end;
ExtractHTTPFields([' '], [' '], ParamStr, ParamList, AStripParamQuotes);
if Assigned(AHandledTag) then
begin
Temp := ReplaceStr;
if not AHandledTag(TokenStr, ParamList, Temp) then
ReplaceStr := '<#' + TokenStr + SaveParamStr + '>'
else
ReplaceStr := Temp;
end
else if Assigned(AHandleTag) then
ReplaceStr := AHandleTag(TokenStr, ParamList)
else
{ Replace tag with empty string}
ReplaceStr := '';
OutStream.WriteString(ReplaceStr);
finally
ParamList.Free;
end;
SkipToken(True);
end else
begin
OutStream.WriteString('<');
CopyTokenToOutput;
SkipToken(True);
end;
end;
end;
finally
Parser.Free;
end;
Result := OutStream.DataString;
finally
OutStream.Free;
end;
end;
function ContentFromString(const AValue: string;
AStripParamQuotes: Boolean; AHandleTag: THandleTagProc; AHandledTag: THandledTagProc): string;
var
InStream: TStream;
begin
InStream := TStringStream.Create(AValue, TEncoding.UTF8);
try
Result := ContentFromStream(InStream, AStripParamQuotes, AHandleTag, AHandledTag);
finally
InStream.Free;
end;
end;
function TCustomPageProducer.GetTemplateFileName: string;
begin
Result := HTMLFile;
end;
function ModulePath: string;
var
ModuleName: string;
begin
if Assigned(GetModuleFileNameProc) then
begin
ModuleName := GetModuleFileNameProc;
Result := ExtractFilePath(ModuleName);
end
else
Result := '';
end;
function QualifyFileName(const AFileName: string): string;
begin
if DesignerFileManager <> nil then
Result := DesignerFileManager.QualifyFileName(AFileName)
else
begin
if IsRelativePath(AFileName) then
Result := ExpandFileName(ModulePath + AFileName)
else
Result := AFileName;
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC JSON streaming implementation }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
{$HPPEMIT LINKUNIT}
unit FireDAC.Stan.StorageJSON;
interface
uses
System.Classes;
type
[ComponentPlatformsAttribute(pidAllPlatforms)]
TFDStanStorageJSONLink = class(TComponent)
end;
implementation
uses
System.SysUtils, System.TypInfo, System.DateUtils,
Data.FMTBcd, Data.SQLTimSt, Data.DB,
FireDAC.Stan.Intf, FireDAC.Stan.Util, FireDAC.Stan.Storage, FireDAC.Stan.SQLTimeInt,
FireDAC.Stan.Factory, FireDAC.Stan.Error, FireDAC.Stan.Consts;
type
TFDJSONState = record
FFirst: Boolean;
FStyle: TFDStorageObjectStyle;
end;
TFDJSONToken = (jtEOF, jtPairSep, jtValSep, jtObjBegin, jtObjEnd, jtArrBegin,
jtArrEnd, jtTrue, jtFalse, jtNull, jtString, jtNumber);
TFDJSONStorage = class(TFDStorage, IFDStanStorage)
private
FStack: array of TFDJSONState;
FStackIndex: Integer;
FToken: TFDJSONToken;
FTokenString: String;
FReader: TBytes;
FReaderCur,
FReaderTop: PByte;
FReaderSize: Integer;
FDirectWriting: Boolean;
procedure AddToStack(AFirst: Boolean; AStyle: TFDStorageObjectStyle);
procedure RemFromStack;
procedure WriteStringBase(ApStr: PChar; ALen: Integer; AQuote: Boolean);
procedure AddAttribute(const AAttrName: String; ApVal: PChar; ALen: Integer;
AQuote: Boolean); overload;
procedure AddAttribute(const AAttrName, AValue: String; AQuote: Boolean); overload; inline;
procedure WritePairSep;
procedure WriteValSep; inline;
procedure WriteFmt;
procedure NextToken;
procedure ErrInvalidFormat;
function InternalReadProperty(const APropName: String): Boolean;
procedure InternalReadPropertyValue;
function InternalReadObject(out AName: String): Boolean;
function InternalReadObjectEnd: Boolean;
function ReadByte(var AByte: Byte): Boolean;
procedure ReadBack;
function GetReadPos: Int64;
procedure SetReadPos(AValue: Int64);
public
procedure Close; override;
function IsObjectEnd(const AObjectName: String): Boolean;
procedure Open(AResOpts: TObject; AEncoder: TObject;
const AFileName: String; AStream: TStream; AMode: TFDStorageMode); override;
function ReadBoolean(const APropName: String; ADefValue: Boolean): Boolean;
function ReadDate(const APropName: String; ADefValue: TDateTime): TDateTime;
function ReadFloat(const APropName: String; ADefValue: Double): Double;
function ReadInteger(const APropName: String; ADefValue: Integer): Integer;
function ReadLongWord(const APropName: String; ADefValue: Cardinal): Cardinal;
function ReadInt64(const APropName: String; ADefValue: Int64): Int64;
function ReadObjectBegin(const AObjectName: String; AStyle: TFDStorageObjectStyle): String; override;
procedure ReadObjectEnd(const AObjectName: String; AStyle: TFDStorageObjectStyle); override;
function ReadAnsiString(const APropName: String; const ADefValue: TFDAnsiString): TFDAnsiString;
function ReadString(const APropName: String; const ADefValue: UnicodeString): UnicodeString;
function ReadValue(const APropName: String; APropIndex: Word; ADataType: TFDDataType;
out ABuff: Pointer; out ALen: Cardinal): Boolean;
function ReadEnum(const APropName: String; ATypeInfo: PTypeInfo; ADefValue: Integer): Integer;
function TestObject(const AObjectName: String): Boolean;
function TestAndReadObjectBegin(const AObjectName: String; AStyle: TFDStorageObjectStyle): Boolean;
function TestProperty(const APropName: String): Boolean;
function TestAndReadProperty(const APropName: String): Boolean;
procedure WriteBoolean(const APropName: String; const AValue, ADefValue: Boolean);
procedure WriteDate(const APropName: String; const AValue, ADefValue: TDateTime);
procedure WriteFloat(const APropName: String; const AValue, ADefValue: Double);
procedure WriteInteger(const APropName: String; const AValue, ADefValue: Integer);
procedure WriteLongWord(const APropName: String; const AValue, ADefValue: Cardinal);
procedure WriteInt64(const APropName: String; const AValue, ADefValue: Int64);
procedure WriteObjectBegin(const AObjectName: String; AStyle: TFDStorageObjectStyle);
procedure WriteObjectEnd(const AObjectName: String; AStyle: TFDStorageObjectStyle);
procedure WriteAnsiString(const APropName: String; const AValue, ADefValue: TFDAnsiString);
procedure WriteString(const APropName: String; const AValue, ADefValue: UnicodeString);
procedure WriteValue(const APropName: String; APropIndex: Word; ADataType: TFDDataType;
ABuff: Pointer; ALen: Cardinal);
procedure WriteEnum(const APropName: String; ATypeInfo: PTypeInfo; const AValue,
ADefValue: Integer);
function GetBookmark: TObject;
procedure SetBookmark(const AValue: TObject);
end;
const
C_Class: String = 'class';
C_Bools: array[Boolean] of String = ('false', 'true');
C_PairSep: Byte = Ord(',');
C_ValSep: Byte = Ord(':');
C_ObjBegin: Byte = Ord('{');
C_ObjEnd: Byte = Ord('}');
C_ArrBegin: Byte = Ord('[');
C_ArrEnd: Byte = Ord(']');
C_Indent: array[0 .. 1] of Byte = (Ord(' '), Ord(' '));
var
C_EOL: array of Byte;
{-------------------------------------------------------------------------------}
{ TFDJSONStorage }
{-------------------------------------------------------------------------------}
procedure TFDJSONStorage.ErrInvalidFormat;
begin
FDException(Self, [S_FD_LStan], er_FD_StanStrgInvJSONFmt, [GetReadPos]);
end;
{-------------------------------------------------------------------------------}
procedure TFDJSONStorage.Open(AResOpts: TObject; AEncoder: TObject;
const AFileName: String; AStream: TStream; AMode: TFDStorageMode);
const
C_UTF8: array [0 .. 2] of Byte = ($EF, $BB, $BF);
var
aUtf8: array [0 .. 2] of Byte;
iPos: Int64;
begin
inherited Open(AResOpts, AEncoder, AFileName, AStream, AMode);
if FStreamVersion < 11 then
ErrInvalidFormat;
if AMode = smWrite then begin
SetLength(FStack, 0);
FStackIndex := -1;
FDirectWriting := AFileName = C_FD_SysNamePrefix + '[';
if FDirectWriting then
WriteObjectBegin('', osFlatArray)
else begin
if (AFileName <> '') and (AStream = nil) then
FStream.Write(C_UTF8[0], SizeOf(C_UTF8));
FStream.Write(C_ObjBegin, 1);
WriteObjectBegin('FDBS', osObject);
WriteInteger('Version', GetStreamVersion, -1);
end;
end
else begin
SetLength(FReader, 1024);
FReaderSize := 0;
FReaderCur := PByte(FReader);
FReaderTop := nil;
iPos := FStream.Position;
FStream.Read(aUtf8[0], SizeOf(aUtf8));
if not CompareMem(@aUtf8[0], @C_UTF8[0], SizeOf(aUtf8)) then
FStream.Position := iPos;
NextToken;
if FToken <> jtObjBegin then
ErrInvalidFormat;
if TestObject('FDBS') then begin
ReadObjectBegin('FDBS', osObject);
FStreamVersion := ReadInteger('Version', C_FD_StorageVer);
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDJSONStorage.Close;
begin
if IsOpen then
try
if FMode = smWrite then begin
if FDirectWriting then
WriteObjectEnd('', osFlatArray)
else begin
WriteObjectEnd('FDBS', osObject);
FStream.Write(C_ObjEnd, 1);
end;
end
else if TestObject('FDBS') then begin
ReadObjectEnd('FDBS', osObject);
NextToken;
if FToken <> jtObjEnd then
ErrInvalidFormat;
end;
finally
inherited Close;
end;
end;
{-------------------------------------------------------------------------------}
function TFDJSONStorage.ReadByte(var AByte: Byte): Boolean;
begin
if FReaderCur < FReaderTop then begin
Result := True;
AByte := FReaderCur^;
Inc(FReaderCur);
end
else begin
FReaderSize := FStream.Read(FReader, Length(FReader));
FReaderCur := PByte(FReader);
FReaderTop := FReaderCur + FReaderSize;
Result := FReaderSize > 0;
if Result then
Result := ReadByte(AByte)
else
AByte := 0;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDJSONStorage.ReadBack;
begin
if FReaderCur > PByte(FReader) then
Dec(FReaderCur);
end;
{-------------------------------------------------------------------------------}
function TFDJSONStorage.GetReadPos: Int64;
begin
Result := (FStream.Position - FReaderSize) + (FReaderCur - PByte(FReader));
end;
{-------------------------------------------------------------------------------}
procedure TFDJSONStorage.SetReadPos(AValue: Int64);
begin
if (AValue < FStream.Position - FReaderSize) or (AValue > FStream.Position) then begin
FStream.Position := AValue;
FReaderSize := 0;
FReaderCur := PByte(FReader);
FReaderTop := nil;
end
else
FReaderCur := PByte(FReader) + AValue - (FStream.Position - FReaderSize);
end;
{-------------------------------------------------------------------------------}
procedure TFDJSONStorage.NextToken;
var
b: Byte;
function HexToDec(const AValue: Byte): Integer;
begin
if AValue > Ord('9') then
if AValue > Ord('F') then
Exit(AValue - Ord('a') + 10)
else
Exit(AValue - Ord('A') + 10)
else
Exit(AValue - Ord('0'));
end;
procedure ExtractString;
var
oMS: TMemoryStream;
pRes: PChar;
c: Char;
b: Byte;
w: Word;
iPos: Integer;
pTop: PByte;
begin
oMS := CheckBuffer(1024);
pRes := PChar(oMS.Memory);
pTop := PByte(oMS.Memory) + oMS.Size;
while ReadByte(b) and (b <> Ord('"')) do begin
c := Char(b);
if c = '\' then begin
if not ReadByte(b) then
ErrInvalidFormat;
case b of
Ord('"'):
c := '"';
Ord('\'):
c := '\';
Ord('/'):
c := '/';
Ord('b'):
c := #$8;
Ord('f'):
c := #$c;
Ord('n'):
c := #$a;
Ord('r'):
c := #$d;
Ord('t'):
c := #$9;
Ord('u'):
begin
ReadByte(b);
c := Char(HexToDec(b) shl 12);
ReadByte(b);
c := Char(Ord(c) or (HexToDec(b) shl 8));
ReadByte(b);
c := Char(Ord(c) or (HexToDec(b) shl 4));
ReadByte(b);
c := Char(Ord(c) or HexToDec(b));
end;
else
ErrInvalidFormat;
end;
end
else if (Ord(c) and $80) <> 0 then begin
w := b and $3F;
if (w and $20) <> 0 then begin
if not ReadByte(b) then
ErrInvalidFormat;
if (b and $C0) <> $80 then
ErrInvalidFormat;
w := (w shl 6) or (b and $3F);
end;
if not ReadByte(b) then
ErrInvalidFormat;
if (b and $C0) <> $80 then
ErrInvalidFormat;
c := WideChar((w shl 6) or (b and $3F));
end;
pRes^ := c;
Inc(pRes);
if PByte(pRes) >= pTop then begin
iPos := NativeUInt(pRes) - NativeUInt(oMS.Memory);
oMS := CheckBuffer(oMS.Size * 2);
pTop := PByte(oMS.Memory) + oMS.Size;
pRes := PChar(PByte(oMS.Memory) + iPos);
end;
end;
if b <> Ord('"') then
ErrInvalidFormat;
SetString(FTokenString, PChar(oMS.Memory), (NativeUInt(pRes) - NativeUInt(oMS.Memory)) div SizeOf(Char));
end;
procedure ExtractMatch(const AMatch: String);
var
i: Integer;
b: Byte;
begin
for i := 1 to Length(AMatch) do
if not ReadByte(b) or (AMatch[i] <> Char(b)) then
ErrInvalidFormat;
end;
procedure ExtractNumber(b: Byte);
var
oMS: TMemoryStream;
pRes: PChar;
c: Char;
begin
oMS := CheckBuffer(1024);
pRes := PChar(oMS.Memory);
repeat
c := Char(b);
pRes^ := c;
Inc(pRes);
until not ReadByte(b) or
not (b in [Ord('0') .. Ord('9'), Ord('-'), Ord('+'), Ord('.'), Ord('e'), Ord('E')]);
if b <> 0 then
ReadBack;
SetString(FTokenString, PChar(oMS.Memory), (NativeUInt(pRes) - NativeUInt(oMS.Memory)) div SizeOf(Char));
end;
procedure SkipWS;
begin
FToken := jtEOF;
while ReadByte(b) and (b in [Ord(' '), Ord(#$9), Ord(#$a), Ord(#$d)]) do
;
if b <> 0 then begin
ReadBack;
NextToken;
end;
end;
begin
FTokenString := '';
if not ReadByte(b) then
FToken := jtEOF
else
case b of
Ord('{'):
FToken := jtObjBegin;
Ord('}'):
FToken := jtObjEnd;
Ord('"'):
begin
FToken := jtString;
ExtractString;
end;
Ord(':'):
FToken := jtValSep;
Ord(','):
FToken := jtPairSep;
Ord('['):
FToken := jtArrBegin;
Ord(']'):
FToken := jtArrEnd;
Ord('t'):
begin
FToken := jtTrue;
ExtractMatch('rue');
end;
Ord('f'):
begin
FToken := jtFalse;
ExtractMatch('alse');
end;
Ord('n'):
begin
FToken := jtNull;
ExtractMatch('ull');
end;
Ord('0') .. Ord('9'),
Ord('-'),
Ord('+'),
Ord('.'),
Ord('e'),
Ord('E'):
begin
FToken := jtNumber;
ExtractNumber(b);
end;
Ord(' '),
Ord(#$9),
Ord(#$a),
Ord(#$d):
SkipWS;
else
ErrInvalidFormat;
end;
end;
{-------------------------------------------------------------------------------}
function TFDJSONStorage.InternalReadProperty(const APropName: String): Boolean;
begin
NextToken;
if FToken = jtPairSep then
NextToken;
Result := (FToken = jtString) and (CompareText(FTokenString, APropName) = 0);
end;
{-------------------------------------------------------------------------------}
procedure TFDJSONStorage.InternalReadPropertyValue;
begin
NextToken;
if FToken <> jtValSep then
ErrInvalidFormat;
NextToken;
end;
{-------------------------------------------------------------------------------}
(*
1 , {
2 , { class : ObjName
3 , ObjName : {
4 , ObjName : [
5 , [
*)
function TFDJSONStorage.InternalReadObject(out AName: String): Boolean;
var
iPos: Int64;
begin
Result := False;
NextToken;
if FToken = jtPairSep then
NextToken;
case FToken of
jtObjBegin:
begin
iPos := GetReadPos;
NextToken;
if (FToken = jtString) and (CompareText(FTokenString, C_Class) = 0) then begin
NextToken;
if FToken = jtValSep then begin
NextToken;
if FToken = jtString then begin
AName := FTokenString;
Result := True;
end;
end;
end
else begin
SetReadPos(iPos);
Result := True;
end;
end;
jtArrBegin:
Result := True;
jtString:
begin
AName := FTokenString;
NextToken;
if FToken = jtValSep then begin
NextToken;
if FToken in [jtObjBegin, jtArrBegin] then
Result := True;
end;
end;
end;
end;
{-------------------------------------------------------------------------------}
function TFDJSONStorage.InternalReadObjectEnd: Boolean;
begin
NextToken;
Result := FToken in [jtObjEnd, jtArrEnd];
end;
{-------------------------------------------------------------------------------}
function TFDJSONStorage.TestProperty(const APropName: String): Boolean;
var
iPos: Int64;
begin
iPos := GetReadPos;
Result := InternalReadProperty(APropName);
SetReadPos(iPos);
end;
{-------------------------------------------------------------------------------}
function TFDJSONStorage.TestAndReadProperty(const APropName: String): Boolean;
var
iPos: Int64;
begin
iPos := GetReadPos;
Result := InternalReadProperty(APropName);
if not Result then
SetReadPos(iPos);
end;
{-------------------------------------------------------------------------------}
function TFDJSONStorage.ReadBoolean(const APropName: String;
ADefValue: Boolean): Boolean;
begin
if TestAndReadProperty(APropName) then begin
InternalReadPropertyValue;
case FToken of
jtTrue: Result := True;
jtFalse: Result := False;
jtNull: Result := ADefValue;
else begin Result := False; ErrInvalidFormat; end;
end;
end
else
Result := ADefValue;
end;
{-------------------------------------------------------------------------------}
function TFDJSONStorage.ReadDate(const APropName: String;
ADefValue: TDateTime): TDateTime;
begin
if TestAndReadProperty(APropName) then begin
InternalReadPropertyValue;
case FToken of
jtString:
Result := EncodeDateTime(
StrToInt(Copy(FTokenString, 1, 4)),
StrToInt(Copy(FTokenString, 5, 2)),
StrToInt(Copy(FTokenString, 7, 2)),
StrToInt(Copy(FTokenString, 10, 2)),
StrToInt(Copy(FTokenString, 12, 2)),
StrToInt(Copy(FTokenString, 14, 2)), 0);
jtNull:
Result := ADefValue;
else
Result := 0.0;
ErrInvalidFormat;
end;
end
else
Result := ADefValue;
end;
{-------------------------------------------------------------------------------}
function TFDJSONStorage.ReadEnum(const APropName: String; ATypeInfo: PTypeInfo;
ADefValue: Integer): Integer;
var
sEnum: String;
begin
sEnum := GetEnumName(ATypeInfo, Integer(ADefValue));
Result := GetEnumValue(ATypeInfo, Copy(sEnum, 1, 2) +
ReadString(APropName, Copy(sEnum, 3, MAXINT)));
end;
{-------------------------------------------------------------------------------}
function TFDJSONStorage.ReadFloat(const APropName: String;
ADefValue: Double): Double;
begin
if TestAndReadProperty(APropName) then begin
InternalReadPropertyValue;
case FToken of
jtNumber: Result := FDStr2Float(FTokenString, '.');
jtNull: Result := ADefValue;
else begin Result := 0.0; ErrInvalidFormat; end;
end;
end
else
Result := ADefValue;
end;
{-------------------------------------------------------------------------------}
function TFDJSONStorage.ReadInteger(const APropName: String;
ADefValue: Integer): Integer;
begin
if TestAndReadProperty(APropName) then begin
InternalReadPropertyValue;
case FToken of
jtNumber: Result := StrToInt(FTokenString);
jtNull: Result := ADefValue;
else begin Result := 0; ErrInvalidFormat; end;
end;
end
else
Result := ADefValue;
end;
{-------------------------------------------------------------------------------}
function TFDJSONStorage.ReadLongWord(const APropName: String;
ADefValue: Cardinal): Cardinal;
begin
if TestAndReadProperty(APropName) then begin
InternalReadPropertyValue;
case FToken of
jtNumber: Result := StrToInt(FTokenString);
jtNull: Result := ADefValue;
else begin Result := 0; ErrInvalidFormat; end;
end;
end
else
Result := ADefValue;
end;
{-------------------------------------------------------------------------------}
function TFDJSONStorage.ReadInt64(const APropName: String; ADefValue: Int64): Int64;
begin
if TestAndReadProperty(APropName) then begin
InternalReadPropertyValue;
case FToken of
jtNumber: Result := StrToInt64(FTokenString);
jtNull: Result := ADefValue;
else begin Result := 0; ErrInvalidFormat; end;
end;
end
else
Result := ADefValue;
end;
{-------------------------------------------------------------------------------}
function TFDJSONStorage.TestObject(const AObjectName: String): Boolean;
var
sName: String;
iPos: Int64;
begin
iPos := GetReadPos;
Result := InternalReadObject(sName);
if Result then
Result := CompareText(AObjectName, sName) = 0;
SetReadPos(iPos);
end;
{-------------------------------------------------------------------------------}
function TFDJSONStorage.TestAndReadObjectBegin(const AObjectName: String;
AStyle: TFDStorageObjectStyle): Boolean;
var
sName: String;
iPos: Int64;
begin
iPos := GetReadPos;
Result := InternalReadObject(sName);
if Result then
Result := CompareText(AObjectName, sName) = 0;
if not Result then
SetReadPos(iPos);
end;
{-------------------------------------------------------------------------------}
function TFDJSONStorage.ReadObjectBegin(const AObjectName: String; AStyle: TFDStorageObjectStyle): String;
begin
if not InternalReadObject(Result) then
FDException(Self, [S_FD_LStan], er_FD_StanStrgCantReadObj, ['<unknown>']);
if (Result <> '') and (AObjectName <> '') and (CompareText(Result, AObjectName) <> 0) then
FDException(Self, [S_FD_LStan], er_FD_StanStrgCantReadObj, [AObjectName]);
end;
{-------------------------------------------------------------------------------}
function TFDJSONStorage.IsObjectEnd(const AObjectName: String): Boolean;
var
iPos: Int64;
begin
iPos := GetReadPos;
Result := InternalReadObjectEnd;
SetReadPos(iPos);
end;
{-------------------------------------------------------------------------------}
procedure TFDJSONStorage.ReadObjectEnd(const AObjectName: String; AStyle: TFDStorageObjectStyle);
begin
InternalReadObjectEnd;
end;
{-------------------------------------------------------------------------------}
function TFDJSONStorage.ReadAnsiString(const APropName: String;
const ADefValue: TFDAnsiString): TFDAnsiString;
begin
if TestAndReadProperty(APropName) then begin
InternalReadPropertyValue;
case FToken of
jtString: Result := TFDAnsiString(FTokenString);
jtNull: Result := ADefValue;
else begin Result := TFDAnsiString(''); ErrInvalidFormat; end;
end;
end
else
Result := ADefValue;
end;
{-------------------------------------------------------------------------------}
function TFDJSONStorage.ReadString(const APropName: String;
const ADefValue: UnicodeString): UnicodeString;
begin
if TestAndReadProperty(APropName) then begin
InternalReadPropertyValue;
case FToken of
jtString: Result := FTokenString;
jtNull: Result := ADefValue;
else begin Result := ''; ErrInvalidFormat; end;
end;
end
else
Result := ADefValue;
end;
{-------------------------------------------------------------------------------}
function TFDJSONStorage.ReadValue(const APropName: String; APropIndex: Word;
ADataType: TFDDataType; out ABuff: Pointer; out ALen: Cardinal): Boolean;
var
oMS: TMemoryStream;
rTS: TSQLTimeStamp;
pCh: PChar;
iSign: Integer;
eIntKind: TFDSQLTimeIntervalKind;
pTS: PSQLTimeStamp;
pInt: PFDSQLTimeInterval;
function ScanInt(var AVal: Cardinal; AType: Char): Boolean;
var
pStCh: PChar;
begin
if pCh^ = '-' then begin
iSign := -1;
Inc(pCh);
end
else if pCh^ = '+' then
Inc(pCh);
pStCh := pCh;
while (pCh^ >= '0') and (pCh^ <= '9') do
Inc(pCh);
if pCh^ = AType then begin
FDStr2Int(pCh, pCh - pStCh, @AVal, SizeOf(AVal), True);
Result := True;
end
else begin
pCh := pStCh;
Result := False;
end;
end;
procedure DateIntError;
begin
FDException(Self, [S_FD_LStan], er_FD_StanStrgUnknownFmt, [FTokenString]);
end;
begin
ABuff := nil;
ALen := 0;
Result := False;
if not TestAndReadProperty(APropName) then
Exit;
InternalReadPropertyValue;
if FToken = jtNull then
Exit;
ABuff := CheckBuffer(C_FD_MaxFixedSize).Memory;
Result := True;
case ADataType of
dtObject,
dtRowSetRef,
dtCursorRef,
dtRowRef,
dtArrayRef:
;
dtWideMemo,
dtWideHMemo,
dtXML,
dtWideString:
begin
ALen := Length(FTokenString);
ABuff := PChar(FTokenString);
end;
dtMemo,
dtHMemo,
dtAnsiString:
begin
ABuff := nil;
ALen := FEncoder.Encode(PChar(FTokenString), Length(FTokenString), ABuff, ecUTF16, ecANSI);
end;
dtByteString,
dtBlob,
dtHBlob,
dtHBFile:
begin
oMS := CheckBuffer(0);
Hex2BinStream(FTokenString, oMS);
ABuff := oMS.Memory;
ALen := oMS.Size;
end;
dtBoolean:
PWordBool(ABuff)^ := FToken = jtTrue;
dtSByte:
FDStr2Int(PChar(FTokenString), Length(FTokenString), ABuff, SizeOf(ShortInt), False);
dtInt16:
FDStr2Int(PChar(FTokenString), Length(FTokenString), ABuff, SizeOf(SmallInt), False);
dtInt32:
FDStr2Int(PChar(FTokenString), Length(FTokenString), ABuff, SizeOf(Integer), False);
dtInt64:
FDStr2Int(PChar(FTokenString), Length(FTokenString), ABuff, SizeOf(Int64), False);
dtByte:
FDStr2Int(PChar(FTokenString), Length(FTokenString), ABuff, SizeOf(Byte), True);
dtUInt16:
FDStr2Int(PChar(FTokenString), Length(FTokenString), ABuff, SizeOf(Word), True);
dtUInt32,
dtParentRowRef:
FDStr2Int(PChar(FTokenString), Length(FTokenString), ABuff, SizeOf(Cardinal), True);
dtUInt64:
FDStr2Int(PChar(FTokenString), Length(FTokenString), ABuff, SizeOf(UInt64), True);
dtSingle:
FDStr2Float(PChar(FTokenString), Length(FTokenString), ABuff, SizeOf(Single), '.');
dtDouble:
FDStr2Float(PChar(FTokenString), Length(FTokenString), ABuff, SizeOf(Double), '.');
dtExtended:
FDStr2Float(PChar(FTokenString), Length(FTokenString), ABuff, SizeOf(Extended), '.');
dtCurrency:
FDStr2Curr(PChar(FTokenString), Length(FTokenString), PCurrency(ABuff)^, '.');
dtBCD,
dtFmtBCD:
FDStr2BCD(PChar(FTokenString), Length(FTokenString), PBcd(ABuff)^, Char('.'));
dtDateTime:
begin
FDStr2Int(PChar(FTokenString) + 0, 4, @rTS.Year, SizeOf(rTS.Year), True);
FDStr2Int(PChar(FTokenString) + 4, 2, @rTS.Month, SizeOf(rTS.Month), True);
FDStr2Int(PChar(FTokenString) + 6, 2, @rTS.Day, SizeOf(rTS.Day), True);
if (PChar(FTokenString) + 8)^ = 'T' then begin
FDStr2Int(PChar(FTokenString) + 9, 2, @rTS.Hour, SizeOf(rTS.Hour), True);
FDStr2Int(PChar(FTokenString) + 11, 2, @rTS.Minute, SizeOf(rTS.Minute), True);
FDStr2Int(PChar(FTokenString) + 13, 2, @rTS.Second, SizeOf(rTS.Second), True);
end
else begin
rTS.Hour := 0;
rTS.Minute := 0;
rTS.Second := 0;
end;
rTS.Fractions := 0;
PDateTimeRec(ABuff)^.DateTime := FDDateTime2MSecs(SQLTimeStampToDateTime(rTS));
end;
dtDateTimeStamp:
begin
pTS := PSQLTimeStamp(ABuff);
FDStr2Int(PChar(FTokenString) + 0, 4, @pTS^.Year, SizeOf(pTS^.Year), True);
FDStr2Int(PChar(FTokenString) + 4, 2, @pTS^.Month, SizeOf(pTS^.Month), True);
FDStr2Int(PChar(FTokenString) + 6, 2, @pTS^.Day, SizeOf(pTS^.Day), True);
if (PChar(FTokenString) + 8)^ = 'T' then begin
FDStr2Int(PChar(FTokenString) + 9, 2, @pTS^.Hour, SizeOf(pTS^.Hour), True);
FDStr2Int(PChar(FTokenString) + 11, 2, @pTS^.Minute, SizeOf(pTS^.Minute), True);
FDStr2Int(PChar(FTokenString) + 13, 2, @pTS^.Second, SizeOf(pTS^.Second), True);
end
else begin
pTS^.Hour := 0;
pTS^.Minute := 0;
pTS^.Second := 0;
end;
pTS^.Fractions := 0;
end;
dtTimeIntervalFull,
dtTimeIntervalYM,
dtTimeIntervalDS:
begin
pInt := PFDSQLTimeInterval(ABuff);
pCh := PChar(FTokenString);
if pCh^ = '-' then begin
iSign := -1;
Inc(pCh);
end
else
iSign := 1;
eIntKind := itUnknown;
if pCh^ <> 'P' then
DateIntError;
Inc(pCh); // P
if (pCh^ <> 'T') and ScanInt(pInt^.Years, 'Y') then
eIntKind := itYear;
if (pCh^ <> 'T') and ScanInt(pInt^.Months, 'M') then
if eIntKind = itYear then
eIntKind := itYear2Month
else
eIntKind := itMonth;
if (pCh^ <> 'T') and ScanInt(pInt^.Days, 'D') then begin
if eIntKind <> itUnknown then
DateIntError;
eIntKind := itDay;
end;
if pCh^ = 'T' then begin
Inc(pCh); // T
if ScanInt(pInt^.Hours, 'H') then
if eIntKind = itDay then
eIntKind := itDay2Hour
else if eIntKind = itUnknown then
eIntKind := itHour
else
DateIntError;
if ScanInt(pInt^.Minutes, 'M') then
if eIntKind = itDay2Hour then
eIntKind := itDay2Minute
else if eIntKind = itHour then
eIntKind := itHour2Minute
else if eIntKind = itUnknown then
eIntKind := itMinute
else
DateIntError;
if ScanInt(pInt^.Seconds, 'S') then begin
if eIntKind = itDay2Minute then
eIntKind := itDay2Second
else if eIntKind = itHour2Minute then
eIntKind := itHour2Second
else if eIntKind = itMinute then
eIntKind := itMinute2Second
else if eIntKind = itUnknown then
eIntKind := itSecond
else
DateIntError;
ScanInt(pInt^.Fractions, 'F');
end;
end;
pInt^.Sign := iSign;
pInt^.Kind := eIntKind;
end;
dtTime:
begin
rTS.Year := 0;
rTS.Month := 0;
rTS.Day := 0;
FDStr2Int(PChar(FTokenString) + 0, 2, @rTS.Hour, SizeOf(rTS.Hour), True);
FDStr2Int(PChar(FTokenString) + 2, 2, @rTS.Minute, SizeOf(rTS.Minute), True);
FDStr2Int(PChar(FTokenString) + 4, 2, @rTS.Second, SizeOf(rTS.Second), True);
rTS.Fractions := 0;
PInteger(ABuff)^ := FDSQLTimeStamp2Time(rTS);
end;
dtDate:
begin
FDStr2Int(PChar(FTokenString) + 0, 4, @rTS.Year, SizeOf(rTS.Year), True);
FDStr2Int(PChar(FTokenString) + 4, 2, @rTS.Month, SizeOf(rTS.Month), True);
FDStr2Int(PChar(FTokenString) + 6, 2, @rTS.Day, SizeOf(rTS.Day), True);
rTS.Hour := 0;
rTS.Minute := 0;
rTS.Second := 0;
rTS.Fractions := 0;
PInteger(ABuff)^ := FDSQLTimeStamp2Date(rTS);
end;
dtGUID:
PGUID(ABuff)^ := StringToGUID(FTokenString);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDJSONStorage.AddToStack(AFirst: Boolean; AStyle: TFDStorageObjectStyle);
begin
if Length(FStack) = 0 then
SetLength(FStack, 16)
else if FStackIndex + 1 >= Length(FStack) then
SetLength(FStack, Length(FStack) * 2);
Inc(FStackIndex);
FStack[FStackIndex].FFirst := AFirst;
FStack[FStackIndex].FStyle := AStyle;
end;
{-------------------------------------------------------------------------------}
procedure TFDJSONStorage.RemFromStack;
begin
Dec(FStackIndex);
end;
{-------------------------------------------------------------------------------}
procedure TFDJSONStorage.WriteStringBase(ApStr: PChar; ALen: Integer; AQuote: Boolean);
const
C_Hex: array [0 .. 15] of Byte = (Ord('0'), Ord('1'), Ord('2'), Ord('3'),
Ord('4'), Ord('5'), Ord('6'), Ord('7'), Ord('8'), Ord('9'), Ord('A'),
Ord('B'), Ord('C'), Ord('D'), Ord('E'), Ord('F'));
var
oMS: TMemoryStream;
pRes: PByte;
c: Char;
iLen: Integer;
begin
oMS := CheckBuffer(ALen * 6 + 2);
pRes := oMS.Memory;
if AQuote then begin
pRes^ := Ord('"');
Inc(pRes);
end;
while ALen > 0 do begin
c := ApStr^;
Inc(ApStr);
Dec(ALen);
case Word(Ord(c)) of
$0:
Break;
Ord('"'):
begin
pRes^ := Ord('\');
(pRes + 1)^ := Ord('"');
Inc(pRes, 2);
end;
Ord('\'):
begin
pRes^ := Ord('\');
(pRes + 1)^ := Ord('\');
Inc(pRes, 2);
end;
Ord('/'):
begin
pRes^ := Ord('\');
(pRes + 1)^ := Ord('/');
Inc(pRes, 2);
end;
$8:
begin
pRes^ := Ord('\');
(pRes + 1)^ := Ord('b');
Inc(pRes, 2);
end;
$9:
begin
pRes^ := Ord('\');
(pRes + 1)^ := Ord('t');
Inc(pRes, 2);
end;
$a:
begin
pRes^ := Ord('\');
(pRes + 1)^ := Ord('n');
Inc(pRes, 2);
end;
$c:
begin
pRes^ := Ord('\');
(pRes + 1)^ := Ord('f');
Inc(pRes, 2);
end;
$d:
begin
pRes^ := Ord('\');
(pRes + 1)^ := Ord('r');
Inc(pRes, 2);
end;
$1 .. $7,
$b, $e .. $1f:
begin
pRes^ := Ord('\');
(pRes + 1)^ := Ord('u');
(pRes + 2)^ := C_Hex[(Ord(c) and 61440) shr 12];
(pRes + 3)^ := C_Hex[(Ord(c) and 3840) shr 8];
(pRes + 4)^ := C_Hex[(Ord(c) and 240) shr 4];
(pRes + 5)^ := C_Hex[(Ord(c) and 15)];
Inc(pRes, 6);
end;
$20, $21, $23 .. $2e, $30 .. $5b, $5d .. $7f:
begin
pRes^ := Ord(c);
Inc(pRes);
end;
$0080 .. $07FF:
begin
pRes^ := $C0 or (Ord(c) shr 6);
(pRes + 1)^ := $80 or (Ord(c) and $3F);
Inc(pRes, 2);
end;
$0800 .. $ffff:
begin
pRes^ := $E0 or (Ord(c) shr 12);
(pRes + 1)^ := $80 or ((Ord(c) shr 6) and $3F);
(pRes + 2)^ := $80 or (Ord(c) and $3F);
Inc(pRes, 3);
end;
end;
end;
if AQuote then begin
pRes^ := Ord('"');
iLen := NativeUInt(pRes) - NativeUInt(oMS.Memory) + 1;
end
else
iLen := NativeUInt(pRes) - NativeUInt(oMS.Memory);
FStream.Write(oMS.Memory^, iLen);
end;
{-------------------------------------------------------------------------------}
procedure TFDJSONStorage.WriteFmt;
var
i: Integer;
begin
if not FFormat then
Exit;
FStream.Write(C_EOL[0], Length(C_EOL));
for i := 0 to FStackIndex do
FStream.Write(C_Indent[0], SizeOf(C_Indent));
end;
{-------------------------------------------------------------------------------}
procedure TFDJSONStorage.WritePairSep;
begin
if FStackIndex >= 0 then
if not FStack[FStackIndex].FFirst then
FStream.Write(C_PairSep, 1)
else
FStack[FStackIndex].FFirst := False;
WriteFmt;
end;
{-------------------------------------------------------------------------------}
procedure TFDJSONStorage.WriteValSep;
begin
FStream.Write(C_ValSep, 1);
end;
{-------------------------------------------------------------------------------}
procedure TFDJSONStorage.AddAttribute(const AAttrName: String;
ApVal: PChar; ALen: Integer; AQuote: Boolean);
begin
WritePairSep;
WriteStringBase(PChar(AAttrName), Length(AAttrName), True);
WriteValSep;
WriteStringBase(ApVal, ALen, AQuote);
end;
{-------------------------------------------------------------------------------}
procedure TFDJSONStorage.AddAttribute(const AAttrName, AValue: String; AQuote: Boolean);
begin
AddAttribute(AAttrName, PChar(AValue), Length(AValue), AQuote);
end;
{-------------------------------------------------------------------------------}
procedure TFDJSONStorage.WriteBoolean(const APropName: String; const AValue,
ADefValue: Boolean);
begin
if AValue <> ADefValue then
AddAttribute(APropName, C_Bools[AValue], False);
end;
{-------------------------------------------------------------------------------}
procedure TFDJSONStorage.WriteDate(const APropName: String; const AValue,
ADefValue: TDateTime);
const
CShortDateTimeISO8601Format = 'yyyymmddThhnnss';
begin
if AValue <> ADefValue then
AddAttribute(APropName, FormatDateTime(CShortDateTimeISO8601Format, AValue), True)
end;
{-------------------------------------------------------------------------------}
procedure TFDJSONStorage.WriteEnum(const APropName: String; ATypeInfo: PTypeInfo;
const AValue, ADefValue: Integer);
begin
if AValue <> ADefValue then
AddAttribute(APropName, Copy(GetCachedEnumName(ATypeInfo, AValue), 3, MAXINT), True);
end;
{-------------------------------------------------------------------------------}
procedure TFDJSONStorage.WriteFloat(const APropName: String; const AValue,
ADefValue: Double);
begin
if Abs(AValue - ADefValue) >= 1e-14 then
AddAttribute(APropName, FDFloat2Str(AValue, '.'), False);
end;
{-------------------------------------------------------------------------------}
procedure TFDJSONStorage.WriteInteger(const APropName: String; const AValue,
ADefValue: Integer);
begin
if AValue <> ADefValue then
AddAttribute(APropName, IntToStr(AValue), False);
end;
{-------------------------------------------------------------------------------}
procedure TFDJSONStorage.WriteLongWord(const APropName: String;
const AValue, ADefValue: Cardinal);
begin
if AValue <> ADefValue then
AddAttribute(APropName, IntToStr(AValue), False);
end;
{-------------------------------------------------------------------------------}
procedure TFDJSONStorage.WriteInt64(const APropName: String; const AValue,
ADefValue: Int64);
begin
if AValue <> ADefValue then
AddAttribute(APropName, IntToStr(AValue), False);
end;
{-------------------------------------------------------------------------------}
procedure TFDJSONStorage.WriteObjectBegin(const AObjectName: String; AStyle: TFDStorageObjectStyle);
var
eParent: TFDStorageObjectStyle;
iMode: Integer;
begin
(*
1 , {
2 , { class : ObjName
3 , ObjName : {
4 , ObjName : [
5 , [
p a use
- - ---
O O 3
O F 4
O T 4
F O 1
F F 5
F T 5
T O 2
T F 5
T T 5
*)
iMode := 0;
WritePairSep;
if FStackIndex = -1 then
if FDirectWriting and (AObjectName = '') then
eParent := osFlatArray
else
eParent := osObject
else
eParent := FStack[FStackIndex].FStyle;
case eParent of
osObject:
if AStyle = osObject then
iMode := 3
else
iMode := 4;
osFlatArray:
if AStyle = osObject then
iMode := 1
else
iMode := 5;
osTypedArray:
if AStyle = osObject then
iMode := 2
else
iMode := 5;
end;
case iMode of
1:
FStream.Write(C_ObjBegin, 1);
2:
begin
FStream.Write(C_ObjBegin, 1);
WriteStringBase(PChar(C_Class), Length(C_Class), True);
WriteValSep;
WriteStringBase(PChar(AObjectName), Length(AObjectName), True);
end;
3:
begin
WriteStringBase(PChar(AObjectName), Length(AObjectName), True);
WriteValSep;
FStream.Write(C_ObjBegin, 1);
end;
4:
begin
WriteStringBase(PChar(AObjectName), Length(AObjectName), True);
WriteValSep;
FStream.Write(C_ArrBegin, 1);
end;
5:
FStream.Write(C_ArrBegin, 1);
end;
AddToStack(iMode <> 2, AStyle);
end;
{-------------------------------------------------------------------------------}
procedure TFDJSONStorage.WriteObjectEnd(const AObjectName: String; AStyle: TFDStorageObjectStyle);
begin
if AStyle = osObject then
FStream.Write(C_ObjEnd, 1)
else
FStream.Write(C_ArrEnd, 1);
RemFromStack;
end;
{-------------------------------------------------------------------------------}
procedure TFDJSONStorage.WriteAnsiString(const APropName: String; const AValue,
ADefValue: TFDAnsiString);
begin
if AValue <> ADefValue then
AddAttribute(APropName, String(AValue), True);
end;
{-------------------------------------------------------------------------------}
procedure TFDJSONStorage.WriteString(const APropName: String;
const AValue, ADefValue: UnicodeString);
begin
if AValue <> ADefValue then
AddAttribute(APropName, AValue, True);
end;
{-------------------------------------------------------------------------------}
procedure TFDJSONStorage.WriteValue(const APropName: String; APropIndex: Word;
ADataType: TFDDataType; ABuff: Pointer; ALen: Cardinal);
const
CDateTimeISO8601Format: String = '%.4d%.2d%.2dT%.2d%.2d%.2d';
CTimeFormat: String = '%.2d%.2d%.2d';
CDateFormat: String = '%.4d%.2d%.2d';
var
sVal: String;
sSign: String;
iLen: Integer;
y, mo, d, h, mi, se, ms: Word;
dt: TDateTime;
pTS: PSQLTimeStamp;
pInt: PFDSQLTimeInterval;
rTS: TSQLTimeStamp;
pDest: PChar;
aFixed: array [0 .. C_FD_MaxFixedSize] of Char;
begin
if ABuff = nil then
Exit;
pDest := @aFixed[0];
iLen := SizeOf(aFixed) div SizeOf(Char);
case ADataType of
dtObject,
dtRowSetRef,
dtCursorRef,
dtRowRef,
dtArrayRef:
;
dtWideMemo,
dtWideHMemo,
dtXML,
dtWideString:
AddAttribute(APropName, PWideChar(ABuff), ALen, True);
dtMemo,
dtHMemo,
dtAnsiString:
begin
pDest := nil;
iLen := FEncoder.Decode(ABuff, ALen, Pointer(pDest), ecUTF16, ecANSI);
AddAttribute(APropName, pDest, iLen, True);
end;
dtByteString,
dtBlob,
dtHBlob,
dtHBFile:
AddAttribute(APropName, FDBin2Hex(ABuff, ALen), True);
dtBoolean:
AddAttribute(APropName, C_Bools[PWord(ABuff)^ <> 0], False);
dtSByte:
begin
FDInt2Str(ABuff, SizeOf(ShortInt), pDest, iLen, False, 0);
AddAttribute(APropName, pDest, iLen, False);
end;
dtInt16:
begin
FDInt2Str(ABuff, SizeOf(SmallInt), pDest, iLen, False, 0);
AddAttribute(APropName, pDest, iLen, False);
end;
dtInt32:
begin
FDInt2Str(ABuff, SizeOf(Integer), pDest, iLen, False, 0);
AddAttribute(APropName, pDest, iLen, False);
end;
dtInt64:
begin
FDInt2Str(ABuff, SizeOf(Int64), pDest, iLen, False, 0);
AddAttribute(APropName, pDest, iLen, False);
end;
dtByte:
begin
FDInt2Str(ABuff, SizeOf(Byte), pDest, iLen, True, 0);
AddAttribute(APropName, pDest, iLen, False);
end;
dtUInt16:
begin
FDInt2Str(ABuff, SizeOf(Word), pDest, iLen, True, 0);
AddAttribute(APropName, pDest, iLen, False);
end;
dtUInt32,
dtParentRowRef:
begin
FDInt2Str(ABuff, SizeOf(Cardinal), pDest, iLen, True, 0);
AddAttribute(APropName, pDest, iLen, False);
end;
dtUInt64:
begin
FDInt2Str(ABuff, SizeOf(UInt64), pDest, iLen, True, 0);
AddAttribute(APropName, pDest, iLen, False);
end;
dtSingle:
AddAttribute(APropName, FDFloat2Str(PSingle(ABuff)^, '.'), False);
dtDouble:
AddAttribute(APropName, FDFloat2Str(PDouble(ABuff)^, '.'), False);
dtExtended:
AddAttribute(APropName, FDFloat2Str(PExtended(ABuff)^, '.'), False);
dtCurrency:
AddAttribute(APropName, FDCurr2Str(PCurrency(ABuff)^, '.'), False);
dtBCD,
dtFmtBCD:
begin
FDBCD2Str(pDest, iLen, PBcd(ABuff)^, '.');
AddAttribute(APropName, pDest, iLen, False);
end;
dtDateTime:
begin
dt := TimeStampToDateTime(MSecsToTimeStamp(PDateTimeRec(ABuff)^.DateTime));
DecodeDate(dt, y, mo, d);
DecodeTime(dt, h, mi, se, ms);
iLen := WideFormatBuf(pDest^, iLen, Pointer(CDateTimeISO8601Format)^,
Length(CDateTimeISO8601Format), [y, mo, d, h, mi, se], FormatSettings);
AddAttribute(APropName, pDest, iLen, True);
end;
dtDateTimeStamp:
begin
pTS := PSQLTimeStamp(ABuff);
iLen := WideFormatBuf(pDest^, iLen, Pointer(CDateTimeISO8601Format)^,
Length(CDateTimeISO8601Format), [pTS^.Year, pTS^.Month, pTS^.Day, pTS^.Hour,
pTS^.Minute, pTS^.Second], FormatSettings);
AddAttribute(APropName, pDest, iLen, True);
end;
dtTimeIntervalFull,
dtTimeIntervalYM,
dtTimeIntervalDS:
begin
pInt := PFDSQLTimeInterval(ABuff);
if pInt^.Sign < 0 then
sSign := '-'
else
sSign := '';
case pInt^.Kind of
itYear: sVal := Format('%sP%uY', [sSign, pInt^.Years]);
itMonth: sVal := Format('%sP%uM', [sSign, pInt^.Months]);
itDay: sVal := Format('%sP%uD', [sSign, pInt^.Days]);
itHour: sVal := Format('%sT%uH', [sSign, pInt^.Hours]);
itMinute: sVal := Format('%sT%uM', [sSign, pInt^.Minutes]);
itSecond: sVal := Format('%sT%uS%uF', [sSign, pInt^.Seconds, pInt^.Fractions]);
itYear2Month: sVal := Format('%sP%uY%uM', [sSign, pInt^.Years, pInt^.Months]);
itDay2Hour: sVal := Format('%sP%uDT%uH', [sSign, pInt^.Days, pInt^.Hours]);
itDay2Minute: sVal := Format('%sP%uDT%uH%uM', [sSign, pInt^.Days, pInt^.Hours, pInt^.Minutes]);
itDay2Second: sVal := Format('%sP%uDT%uH%uM%uS%uF', [sSign, pInt^.Days, pInt^.Hours, pInt^.Minutes, pInt^.Seconds, pInt^.Fractions]);
itHour2Minute: sVal := Format('%sT%uH%uM', [sSign, pInt^.Hours, pInt^.Minutes]);
itHour2Second: sVal := Format('%sT%uH%uM%uS%uF', [sSign, pInt^.Hours, pInt^.Minutes, pInt^.Seconds, pInt^.Fractions]);
itMinute2Second: sVal := Format('%sT%uM%uS%uF', [sSign, pInt^.Minutes, pInt^.Seconds, pInt^.Fractions]);
end;
AddAttribute(APropName, sVal, True);
end;
dtTime:
begin
rTS := FDTime2SQLTimeStamp(PInteger(ABuff)^);
iLen := WideFormatBuf(pDest^, iLen, Pointer(CTimeFormat)^,
Length(CTimeFormat), [rTS.Hour, rTS.Minute, rTS.Second], FormatSettings);
AddAttribute(APropName, pDest, iLen, True);
end;
dtDate:
begin
rTS := FDDate2SQLTimeStamp(PInteger(ABuff)^);
iLen := WideFormatBuf(pDest^, iLen, Pointer(CDateFormat)^,
Length(CDateFormat), [rTS.Year, rTS.Month, rTS.Day], FormatSettings);
AddAttribute(APropName, pDest, iLen, True);
end;
dtGUID:
AddAttribute(APropName, GUIDToString(PGUID(ABuff)^), True);
end;
end;
{-------------------------------------------------------------------------------}
type
TFDJSONStorageBmk = class(TObject)
private
FPos: Int64;
FToken: TFDJSONToken;
FTokenString: String;
end;
function TFDJSONStorage.GetBookmark: TObject;
begin
Result := TFDJSONStorageBmk.Create;
if FMode = smRead then
TFDJSONStorageBmk(Result).FPos := GetReadPos
else
TFDJSONStorageBmk(Result).FPos := FStream.Position;
TFDJSONStorageBmk(Result).FToken := FToken;
TFDJSONStorageBmk(Result).FTokenString := FTokenString;
end;
{-------------------------------------------------------------------------------}
procedure TFDJSONStorage.SetBookmark(const AValue: TObject);
begin
if FMode = smRead then
SetReadPos(TFDJSONStorageBmk(AValue).FPos)
else
FStream.Position := TFDJSONStorageBmk(AValue).FPos;
FToken := TFDJSONStorageBmk(AValue).FToken;
FTokenString := TFDJSONStorageBmk(AValue).FTokenString;
end;
{-------------------------------------------------------------------------------}
var
oFact: TFDFactory;
{$IFDEF MSWINDOWS}
i: Integer;
{$ENDIF}
initialization
{$IFDEF MSWINDOWS}
SetLength(C_EOL, Length(C_FD_EOL));
for i := 1 to Length(C_FD_EOL) do
C_EOL[i - 1] := Ord(C_FD_EOL[i]);
{$ELSE}
SetLength(C_EOL, 1);
C_EOL[0] := Ord(C_FD_EOL);
{$ENDIF}
oFact := TFDMultyInstanceFactory.Create(TFDJSONStorage, IFDStanStorage,
'JSON;.JSON');
finalization
FDReleaseFactory(oFact);
end.
|
unit Delphi.Mocks.Tests.MethodData;
interface
uses
SysUtils,
DUnitX.TestFramework,
Rtti,
Delphi.Mocks,
Delphi.Mocks.Interfaces;
type
{$M+}
ISimpleInterface = interface
function MissingArg(Value: Integer): Integer;
end;
{$M-}
{$M+}
[TestFixture]
TTestMethodData = class
published
[Test, Ignore]
procedure Expectation_Before_Verifies_To_True_When_Prior_Method_Called_Atleast_Once;
[Test]
procedure AllowRedefineBehaviorDefinitions_IsTrue_RedefinedIsAllowed;
[Test]
procedure AllowRedefineBehaviorDefinitions_IsFalse_ExceptionIsThrown_WhenRedefining;
[Test]
procedure AllowRedefineBehaviorDefinitions_IsFalse_NoExceptionIsThrown_WhenAddingNormal;
[Test]
procedure AllowRedefineBehaviorDefinitions_IsTrue_OldBehaviorIsDeleted;
[Test]
procedure BehaviourMustBeDefined_IsFalse_AndBehaviourIsNotDefined_RaisesNoException;
[Test]
procedure BehaviourMustBeDefined_IsTrue_AndBehaviourIsNotDefined_RaisesException;
end;
{$M-}
implementation
uses
Delphi.Mocks.Helpers,
Delphi.Mocks.MethodData,
classes, System.TypInfo, StrUtils;
{ TTestMethodData }
procedure TTestMethodData.Expectation_Before_Verifies_To_True_When_Prior_Method_Called_Atleast_Once;
begin
Assert.IsTrue(False, 'Not implemented');
end;
procedure TTestMethodData.AllowRedefineBehaviorDefinitions_IsTrue_RedefinedIsAllowed;
var
methodData : IMethodData;
someValue1,
someValue2 : TValue;
begin
someValue1 := TValue.From<Integer>(1);
someValue2 := TValue.From<Integer>(2);
methodData := TMethodData.Create('x', 'x', TSetupMethodDataParameters.Create(FALSE, False, TRUE));
methodData.WillReturnWhen(TArray<TValue>.Create(someValue1), someValue1, nil);
methodData.WillReturnWhen(TArray<TValue>.Create(someValue1), someValue2, nil);
// no exception is raised
Assert.IsTrue(True);
end;
procedure TTestMethodData.AllowRedefineBehaviorDefinitions_IsFalse_ExceptionIsThrown_WhenRedefining;
var
methodData : IMethodData;
someValue1,
someValue2 : TValue;
begin
someValue1 := TValue.From<Integer>(1);
someValue2 := TValue.From<Integer>(2);
methodData := TMethodData.Create('x', 'x', TSetupMethodDataParameters.Create(FALSE, FALSE, FALSE));
methodData.WillReturnWhen(TArray<TValue>.Create(someValue1), someValue1, nil);
Assert.WillRaise(procedure
begin
methodData.WillReturnWhen(TArray<TValue>.Create(someValue1), someValue2, nil);
end, EMockSetupException);
end;
procedure TTestMethodData.AllowRedefineBehaviorDefinitions_IsFalse_NoExceptionIsThrown_WhenAddingNormal;
var
methodData : IMethodData;
someValue1,
someValue2 : TValue;
begin
someValue1 := TValue.From<Integer>(1);
someValue2 := TValue.From<Integer>(2);
methodData := TMethodData.Create('x', 'x', TSetupMethodDataParameters.Create(FALSE, FALSE, FALSE));
methodData.WillReturnWhen(TArray<TValue>.Create(someValue1), someValue1, nil);
methodData.WillReturnWhen(TArray<TValue>.Create(someValue2), someValue2, nil);
Assert.IsTrue(True);
end;
procedure TTestMethodData.AllowRedefineBehaviorDefinitions_IsTrue_OldBehaviorIsDeleted;
var
methodData : IMethodData;
someValue1,
someValue2 : TValue;
outValue : TValue;
begin
someValue1 := TValue.From<Integer>(1);
someValue2 := TValue.From<Integer>(2);
methodData := TMethodData.Create('x', 'x', TSetupMethodDataParameters.Create(TRUE, TRUE, TRUE));
methodData.WillReturnWhen(TArray<TValue>.Create(someValue1), someValue1, nil);
methodData.WillReturnWhen(TArray<TValue>.Create(someValue1), someValue2, nil);
methodData.RecordHit(TArray<TValue>.Create(someValue1), TrttiContext.Create.GetType(TypeInfo(integer)), outValue);
Assert.AreEqual(someValue2.AsInteger, outValue.AsInteger );
end;
procedure TTestMethodData.BehaviourMustBeDefined_IsFalse_AndBehaviourIsNotDefined_RaisesNoException;
var
methodData : IMethodData;
someValue : TValue;
begin
methodData := TMethodData.Create('x', 'x', TSetupMethodDataParameters.Create(FALSE, FALSE, FALSE));
methodData.RecordHit(TArray<TValue>.Create(), nil, someValue);
// no exception should be raised
Assert.IsTrue(True);
end;
procedure TTestMethodData.BehaviourMustBeDefined_IsTrue_AndBehaviourIsNotDefined_RaisesException;
var
methodData : IMethodData;
someValue : TValue;
begin
methodData := TMethodData.Create('x', 'x', TSetupMethodDataParameters.Create(FALSE, TRUE, FALSE));
Assert.WillRaise(procedure
begin
methodData.RecordHit(TArray<TValue>.Create(), TRttiContext.Create.GetType(TypeInfo(Integer)), someValue);
end, EMockException);
end;
initialization
TDUnitX.RegisterTestFixture(TTestMethodData);
end.
|
unit MediaStorage.RecordStorage.Visual.RecordPreview;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufmForm_B,Player.Control,Player.VideoOutput.Base,VideoPane.Monitor,
ExtCtrls,MediaProcessing.Definitions,SyncObjs,MediaStream.Framer,
StdCtrls, ExtendControls, uTimeBar,MediaStorage.RecordStorage;
type
TfmMediaStorageRecordPreview = class(TfmForm_B)
paScreen: TPanel;
paMonitor: TPanel;
paTime: TTimeScalePanel;
Panel1: TPanel;
edProperties: TExtendMemo;
ckTimeBar: TExtendCheckBox;
procedure ckTimeBarClick(Sender: TObject);
private
FPlayerMonitor: TfrmVideoPaneMonitor;
FPlayer: TWindowStreamPlayer;
FReadThread : TThread;
procedure OnFrameReceived(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal);
procedure FillWithRecords(const aRecords: TrsRecordObjectInfoArray);
constructor Create; reintroduce; overload;
public
constructor Create(aRecordStorage: TRecordStorage; const aSourceName: string; const aStart,aEnd: TDateTime); reintroduce; overload;
constructor Create(const aRecords: TrsRecordObjectInfoArray); reintroduce; overload;
destructor Destroy; override;
class procedure Run(aRecordStorage: TRecordStorage; const aSourceName: string; const aStart,aEnd: TDateTime); overload;
class procedure Run(const aRecords: TrsRecordObjectInfoArray); overload;
end;
implementation
uses VclUtils,
Player.VideoOutput.AllTypes,
Player.AudioOutput.AllTypes,
MediaStorage.Transport,
MediaStream.Framer.Mp6,
MediaStream.FramerFactory;
{$R *.dfm}
type
TReadThread = class (TThread)
private
FRecords: TrsRecordObjectInfoArray;
FOwner: TfmMediaStorageRecordPreview;
FPosition: integer;
protected
procedure ProcessFile(aReader: IRecordObjectReader; aFramerClass: TStreamFramerClass; aDuration: integer);
procedure Execute; override;
public
constructor Create(aOwner: TfmMediaStorageRecordPreview; aRecords: TrsRecordObjectInfoArray);
destructor Destroy; override;
end;
{ TReadThread }
constructor TReadThread.Create(aOwner: TfmMediaStorageRecordPreview;aRecords: TrsRecordObjectInfoArray);
begin
FOwner:=aOwner;
FRecords:=aRecords;
inherited Create(false);
end;
destructor TReadThread.Destroy;
begin
inherited;
end;
procedure TReadThread.ProcessFile(aReader: IRecordObjectReader; aFramerClass: TStreamFramerClass; aDuration: integer);
const
aMethodName = 'TReadThread.ProcessFile';
var
aTicks: Cardinal;
aDelay : int64;
aData: pointer;
aDataSize: cardinal;
aInfo: pointer;
aInfoSize: cardinal;
aFormat: TMediaStreamDataHeader;
aFramer: TStreamFramer; //Записывать ли аудио
aStream : TStream;
aFrameDuration: integer;
i: integer;
begin
aStream:=aReader.GetStream;
aFramer:=aFramerClass.Create;
try
aFramer.OpenStream(aStream);
aFrameDuration:=40; //40 - это кол-во мсек на кадр
if (aFramer is TStreamFramerMp6) then
begin
TStreamFramerMp6(aFramer).Reader.ReadIndexTable;
i:=TStreamFramerMp6(aFramer).Reader.IndexTable.GetVideoFrameCount;
if i>0 then
aFrameDuration:=aDuration div i;
end;
while not Terminated do
begin
aTicks := GetTickCount;
//----------- Читаем фрейм
if not aFramer.GetNextFrame(aFormat,aData,aDataSize, aInfo,aInfoSize) then
break;
inc(FPosition,aFrameDuration);
if FOwner<>nil then
FOwner.OnFrameReceived(aFormat,aData,aDataSize,aInfo,aInfoSize);
aTicks := GetTickCount - aTicks;
if aFormat.biMediaType=mtVideo then
begin
aDelay:=int64(aFrameDuration)-int64(aTicks);
if aDelay<0 then
aDelay:=0;
Sleep(aDelay);
end;
end;
finally
aFramer.Free;
end;
end;
procedure TReadThread.Execute;
const
aMethodName = 'TReadThread.Execute';
var
i: Integer;
aReader : IRecordObjectReader;
aFramerClass: TStreamFramerClass;
begin
//SetCurrentThreadName('Source: MediaServer.Stream.Source.RecordStorage.'+ClassName);
FPosition:=0;
for i := 0 to High(FRecords) do
begin
if Terminated then
break;
try
aReader:=FRecords[i].Transport.GetReader;
aFramerClass:=GetFramerClassFromFileName(FRecords[i].Transport.ConnectionString);
FOwner.edProperties.Lines.Add(
Format('Проигрывается файл N%d, %s, %s - %s ',
[i+1,ExtractFileName(FRecords[i].Transport.ConnectionString),DateTimeToStr(FRecords[i].StartDateTime),DateTimeToStr(FRecords[i].EndDateTime)]));
ProcessFile(aReader,
aFramerClass,
Round((FRecords[i].EndDateTime-FRecords[i].StartDateTime)*MSecsPerDay)
);
aReader:=nil; //Удобно для отладки
except
on E:Exception do
begin
Application.ShowException(E);
end;
end;
end;
end;
{ TfmMediaStorageRecordPreview }
procedure TfmMediaStorageRecordPreview.ckTimeBarClick(Sender: TObject);
begin
inherited;
paTime.Visible:=ckTimeBar.Checked;
end;
constructor TfmMediaStorageRecordPreview.Create(aRecordStorage: TRecordStorage; const aSourceName: string; const aStart,aEnd: TDateTime);
var
//aRecordStorage: TRecordStorage;
aRecords: TrsRecordObjectInfoArray;
begin
Create;
Caption:='Просмотр: '+aRecordStorage.GetConnectionString+', '+aSourceName;
edProperties.Lines.Clear;
edProperties.Lines.Add('Свойства соединения:');
TWaitCursor.SetUntilIdle;
//aRecordStorage:=TRecordStorageProvider.CreateStorage(aUDLPath,aTransport);
try
aRecords:=aRecordStorage.GetRecords(
aRecordStorage.GetRecordSourceByName(aSourceName).Id,
aStart,aEnd);
edProperties.Lines.Add(' Строка подключения = '+aRecordStorage.GetConnectionString);
edProperties.Lines.Add(Format(' Период = %s - %s',[DateToStr(aStart),DateToStr(aEnd)]));
edProperties.Lines.Add(Format('Найдено %d записей:',[Length(aRecords)]));
finally
//aRecordStorage.Free;
end;
FillWithRecords(aRecords);
end;
constructor TfmMediaStorageRecordPreview.Create;
begin
inherited Create(Application);
FPlayer:=TWindowStreamPlayer.Create(TPlayerVideoOutput_AllTypes,TPlayerAudioOutput_AllTypes);
FPlayer.Control.Parent:=paScreen;
FPlayer.Control.Align:=alClient;
FPlayer.KeepAspectRatio:=true;
FPlayerMonitor:=TfrmVideoPaneMonitor.Create(self);
FPlayerMonitor.Parent:=paMonitor;
FPlayerMonitor.Align:=alTop;
FPlayerMonitor.Player:=FPlayer;
paMonitor.AutoSize:=true;
end;
constructor TfmMediaStorageRecordPreview.Create(
const aRecords: TrsRecordObjectInfoArray);
begin
Create;
FillWithRecords(aRecords);
end;
destructor TfmMediaStorageRecordPreview.Destroy;
begin
FreeAndNil(FReadThread);
inherited;
end;
procedure TfmMediaStorageRecordPreview.FillWithRecords(const aRecords: TrsRecordObjectInfoArray);
var
aLayer: TTimeScaleLayer;
i: integer;
begin
if Length(aRecords)=0 then
exit;
paTime.StartDateTime:=aRecords[0].StartDateTime;
paTime.EndDateTime:=aRecords[High(aRecords)].EndDateTime;
aLayer:=paTime.Layers.Add;
aLayer.Color:=$8404992;
for i := 0 to High(aRecords) do
begin
edProperties.Lines.Add(Format(' N%d: %s - %s',[i+1,DateTimeToStr(aRecords[i].StartDateTime),DateTimeToStr(aRecords[i].EndDateTime)]));
aLayer.AddRange(aRecords[i].StartDateTime,aRecords[i].EndDateTime);
end;
FReadThread:=TReadThread.Create(self,aRecords);
end;
procedure TfmMediaStorageRecordPreview.OnFrameReceived(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal);
begin
if FPlayerMonitor.ckDisableDisplay.Checked then
begin
exit;
end;
FPlayerMonitor.OnDataSourceData(nil,aFormat,aData,aDataSize,aInfo,aInfoSize,FPlayer.VideoOutput);
FPlayer.ProcessFrame(aFormat,aData,aDataSize,aInfo,aInfoSize);
end;
class procedure TfmMediaStorageRecordPreview.Run(
const aRecords: TrsRecordObjectInfoArray);
begin
TfmMediaStorageRecordPreview.Create(aRecords).Show;
end;
class procedure TfmMediaStorageRecordPreview.Run(aRecordStorage: TRecordStorage; const aSourceName: string; const aStart,aEnd: TDateTime);
begin
TfmMediaStorageRecordPreview.Create(aRecordStorage,aSourceName,aStart,aEnd).Show;
end;
end.
|
{ ---------------------------------------------------------------------------- }
{ BulbTracer for MB3D }
{ Copyright (C) 2016-2017 Andreas Maschke }
{ ---------------------------------------------------------------------------- }
unit MeshReader;
interface
uses
SysUtils, Classes, Contnrs, VectorMath, SyncObjs, Generics.Collections,
VertexList;
type
TAbstractFileReader = class
end;
TLightwaveObjFileReader = class( TAbstractFileReader )
public
procedure LoadFromFile(const Filename: String; Faces: TFacesList);
end;
TWavefrontObjFileReader = class( TAbstractFileReader )
public
procedure LoadFromFile(const Filename: String; Faces: TFacesList);
end;
implementation
uses
Windows, Math, DateUtils, MeshIOUtil;
{ -------------------------- TLightwaveObjFileReader ------------------------- }
procedure TLightwaveObjFileReader.LoadFromFile(const Filename: String; Faces: TFacesList);
var
FileStream: TFileStream;
Byte5: Array [0..4] of Byte;
ChunkId, SubId: String;
ChunkLen: Int32;
ASRec, BSRec: EndianCnvSnglRec;
I, J, VertexCount, Position, EdgeCount: Integer;
V1, V2, V3: Int32;
X, Y, Z: Single;
EOF: Boolean;
function ReadString4: AnsiString;
var
ReadLen: Integer;
begin
ReadLen := FileStream.Read(Byte5[0], 4);
Result := PAnsiChar(@Byte5[0]);
EOF := ReadLen < 4;
end;
procedure SkipBytes(const Length: Integer);
var
I, ReadLen: Integer;
begin
for I := 0 to Length - 1 do begin
ReadLen := FileStream.Read(Byte5[0], 1);
EOF := ReadLen < 1;
if EOF then
break;
end;
end;
function ReadInt32: Int32;
var
Buf: Int32;
PBuf: Pointer;
ReadLen: Integer;
begin
PBuf := @Buf;
ReadLen := FileStream.Read(PBuf^, 4);
EOF := ReadLen < 4;
if not EOF then
Result := SwapEndianInt32( Buf )
else
Result := 0;
end;
function ReadInt16: Int16;
var
Buf: Int16;
PBuf: Pointer;
ReadLen: Integer;
begin
PBuf := @Buf;
ReadLen := FileStream.Read(PBuf^, 2);
EOF := ReadLen < 2;
if not EOF then
Result := SwapEndianInt16( Buf )
else
Result := 0;
end;
function ReadSingle: Single;
var
ReadLen: Integer;
PBuf: Pointer;
begin
PBuf := @BSRec.EndianVal;
ReadLen := FileStream.Read(PBuf^, 4);
EOF := ReadLen < 4;
if not EOF then begin
SwapBytesSingle( @ASRec, @BSRec );
Result := ASRec.EndianVal;
end
else
Result := 0.0;
end;
function ReadVertexId( var Position: Integer ): Int32;
var
P1, P2: Word;
begin
P1 := ReadInt16;
Position := Position + 2;
if P1 < LW_MAXU2 then
Result := P1
else begin
P2 := ReadInt16;
Result := ( P1 shl 16 + P2 ) - Longword($FF000000);
Position := Position + 2;
end;
end;
begin
FileStream := TFileStream.Create(Filename, fmOpenRead);
try
Faces.Clear;
Byte5[4] := 0;
ChunkId := ReadString4;
if ChunkId<>'FORM' then
raise Exception.Create('Missing <FORM>-header');
SkipBytes(4);
ChunkId := ReadString4;
if ChunkId<>'LWO2' then
raise Exception.Create('Missing <LWO2>-header');
while( not EOF ) do begin
ChunkId := ReadString4;
ChunkLen := ReadInt32;
if EOF then
break;
if ChunkId = 'PNTS' then begin
VertexCount := ChunkLen div 12;
for I := 0 to VertexCount - 1 do begin
X := ReadSingle;
if EOF then
break;
Y := ReadSingle;
if EOF then
break;
Z := ReadSingle;
if EOF then
break;
Faces.AddUnvalidatedVertex(X, Y, Z);
end
end
else if ChunkId = 'POLS' then begin
SubId := ReadString4;
if SubId <> 'FACE' then begin
// raise Exception.Create('POLS-type <FACE> expected');
SkipBytes( ChunkLen - 4 );
end
else begin
Position := 4;
while Position < ChunkLen do begin
EdgeCount := ReadInt16;
Position := Position + 2;
if EdgeCount = 3 then begin
V1 := ReadVertexId( Position );
V2 := ReadVertexId( Position );
V3 := ReadVertexId( Position );
if EOF then
break;
Faces.AddFace(V1, V2, V3);
end
else begin
for J:=0 to EdgeCount - 1 do begin
ReadVertexId( Position );
end;
end;
if EOF then
break;
end;
end;
end
else
SkipBytes( ChunkLen );
end;
finally
FileStream.Free;
end;
end;
{ -------------------------- TWavefrontObjFileReader ------------------------- }
// Reads only the portions currently needed: vertices and polygons/faces
procedure TWavefrontObjFileReader.LoadFromFile(const Filename: String; Faces: TFacesList);
var
Line: String;
Lines, TokenLst: TStringList;
FS: TFormatSettings;
function GetVertexFromStr( const VertexStr: String): Integer;
var
P: Integer;
begin
P := Pos( '/', VertexStr );
if P > 1 then
Result := StrToInt( Copy( VertexStr, 1, P - 1 ) ) - 1
else
Result := StrToInt( VertexStr ) - 1;
end;
begin
FS := TFormatSettings.Create('en-US');
Lines := TStringList.Create;
try
Lines.LoadFromFile( Filename );
Faces.Clear;
TokenLst := TStringList.Create;
try
TokenLst.Delimiter := ' ';
TokenLst.StrictDelimiter := True;
for Line in Lines do begin
TokenLst.DelimitedText := Line;
if ( TokenLst.Count in [4, 7] ) and ( TokenLst[ 0 ] = 'v' ) then begin
Faces.AddUnvalidatedVertex( StrToFloat( TokenLst[ 1 ], FS ), StrToFloat( TokenLst[ 2 ], FS ), StrToFloat( TokenLst[ 3 ], FS ) );
end
else if ( TokenLst.Count = 4 ) and ( TokenLst[ 0 ] = 'f' ) then begin
Faces.AddFace( GetVertexFromStr( TokenLst[ 1 ] ), GetVertexFromStr( TokenLst[ 2 ] ), GetVertexFromStr( TokenLst[ 3 ] ) );
end
else if ( TokenLst.Count = 5 ) and ( TokenLst[ 0 ] = 'f' ) then begin
Faces.AddFace( GetVertexFromStr( TokenLst[ 1 ] ), GetVertexFromStr( TokenLst[ 2 ] ), GetVertexFromStr( TokenLst[ 3 ] ) );
Faces.AddFace( GetVertexFromStr( TokenLst[ 1 ] ), GetVertexFromStr( TokenLst[ 3 ] ), GetVertexFromStr( TokenLst[ 4 ] ) );
end;
end;
finally
TokenLst.Free;
end;
finally
Lines.Free;
end;
end;
end.
|
unit Devices.Streamlux700f;
interface
uses
GMGlobals, Devices.ReqCreatorBase, GMConst;
type
TStreamlux700fReqCreator = class(TDevReqCreator)
private
procedure AddChannelRequest(ID_Prm, ID_Src, N_Src: int);
procedure AddRequestString(const s: string);
public
procedure AddRequests(); override;
end;
implementation
uses
GMSqlQuery;
{ TStreamlux700fReqCreator }
procedure TStreamlux700fReqCreator.AddRequestString(const s: string);
begin
AddStringRequestToSendBuf(s + #13, rqtStreamlux700f);
end;
procedure TStreamlux700fReqCreator.AddChannelRequest(ID_Prm, ID_Src, N_Src: int);
begin
FReqDetails.ID_Prm := ID_Prm;
case ID_Src of
SRC_AI:
case N_Src of
1: AddRequestString('DQD');
2: AddRequestString('DQH');
3: AddRequestString('DQS');
4: AddRequestString('DV');
5: AddRequestString('DS');
6: AddRequestString('DC');
7: AddRequestString('DL');
end;
SRC_CNT_MTR:
case N_Src of
1: AddRequestString('DI+');
end;
end;
end;
procedure TStreamlux700fReqCreator.AddRequests;
begin
ReadFromQueryFmt('select * from DeviceSystem where ID_Device = %d order by ID_Src, N_Src', [FReqDetails.ID_Device],
procedure(q: TGMSqlQuery)
begin
AddChannelRequest(
q.FieldByName('ID_Prm').AsInteger,
q.FieldByName('ID_Src').AsInteger,
q.FieldByName('N_Src').AsInteger);
end);
end;
end.
|
(*
Name: isadmin
Copyright: Copyright (C) SIL International.
Documentation:
Description:
Create Date: 20 Jun 2006
Modified Date: 26 Jun 2012
Authors: mcdurdin
Related Files:
Dependencies:
Bugs:
Todo:
Notes:
History: 20 Jun 2006 - mcdurdin - Initial version
03 May 2011 - mcdurdin - I2890 - Record diagnostic data when encountering registry errors
26 Jun 2012 - mcdurdin - I3379 - KM9 - Remove old Winapi references now in Delphi libraries
*)
unit isadmin;
interface
uses baseerror;
type
EIsAdminError = class(EKeymanBaseError);
const
E_IsAdmin_NotInstalledCorrectly = $01;
function IsAdministrator: Boolean;
implementation
uses Winapi.Shlobj, Windows, ErrorControlledRegistry, RegistryKeys, KeymanPaths, SysUtils, utilsystem; //, utilkeyman;
{-------------------------------------------------------------------------------
- IsAdministrator -
------------------------------------------------------------------------------}
{$R-}
var
FIsAdministrator: Boolean = False;
FIsAdministrator_Init: Boolean = False;
function IsAdministrator_Groups: Boolean; forward;
function IsAdministrator_SecurityPriv: Boolean; forward;
function IsAdministrator_AccessPriv: Boolean; forward;
function IsAdministrator: Boolean;
begin
if FIsAdministrator_Init then
begin
Result := FIsAdministrator;
Exit;
end;
if GetVersion and $80000000 = $80000000
then Result := True
else Result := IsAdministrator_AccessPriv;
FIsAdministrator := Result;
FIsAdministrator_Init := True;
end;
function IsAdministrator_AccessPriv: Boolean;
var
s: string;
hFile: THandle;
begin
Result := False;
{ Check registry access permissions - both system\ccs\... and Keyman keys }
with TRegistryErrorControlled.Create do // I2890
try
RootKey := HKEY_LOCAL_MACHINE;
if not OpenKeyReadOnly(SRegKey_KeymanEngine) then
raise EIsAdminError.Create(E_IsAdmin_NotInstalledCorrectly, 'Keyman does not appear to be installed correctly: '+
'the Keyman registry settings are missing. Please reinstall Keyman.');
finally
Free;
end;
s := TKeymanPaths.KeyboardsInstallPath;
with TRegistryErrorControlled.Create do // I2890
try
RootKey := HKEY_LOCAL_MACHINE;
if not OpenKey(SRegKey_KeyboardLayouts, False) then Exit;
CloseKey;
if not OpenKey(SRegKey_KeymanEngine, False) then Exit; //!!!
finally
Free;
end;
{ Get the Keyman keyboard install path }
s := TKeymanPaths.KeyboardsInstallDir;
if not DirectoryExists(s) then
{ Don't want to create any directories, so check for write access to CSIDL_COMMON_APPDATA instead }
s := ExtractFileDir(IncludeTrailingPathDelimiter(GetFolderPath(CSIDL_COMMON_APPDATA)));
{ Check for write access to this path }
if FileExists(PChar(s+'\kmcheck.tmp')) then DeleteFile(PChar(s+'\kmcheck.tmp'));
hFile := CreateFile(PChar(s+'\kmcheck.tmp'), GENERIC_READ or GENERIC_WRITE, 0,
nil, CREATE_ALWAYS, FILE_FLAG_DELETE_ON_CLOSE, 0);
if hFile = INVALID_HANDLE_VALUE then Exit;
CloseHandle(hFile);
Result := True;
end;
function IsAdministrator_SecurityPriv: Boolean;
var
priv: TTokenPrivileges;
luid: TLargeInteger;
hAccessToken: THandle;
dw: DWord;
const
SE_SECURITY_NAME = 'SeSecurityPrivilege';
begin
Result := True;
if (GetVersion and $80000000) = $80000000 then Exit; // Win95/98, not NT
Result := False;
if not OpenThreadToken(GetCurrentThread(), TOKEN_ADJUST_PRIVILEGES, TRUE, hAccessToken) then
begin
if GetLastError <> ERROR_NO_TOKEN then Exit;
if not OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, hAccessToken) then Exit;
end;
try
if LookupPrivilegeValue(nil, SE_SECURITY_NAME, luid) then
begin
priv.PrivilegeCount := 1;
priv.Privileges[0].luid := luid;
priv.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED;
if AdjustTokenPrivileges(hAccessToken, FALSE, priv, 0, nil, dw) then
begin
if GetLastError = ERROR_NOT_ALL_ASSIGNED then Exit;
Result := True;
end;
end;
finally
CloseHandle(hAccessToken);
end;
end;
function IsAdministrator_Groups: Boolean;
const SECURITY_NT_AUTHORITY: SID_IDENTIFIER_AUTHORITY = (Value:(0,0,0,0,0,5));
const SECURITY_BUILTIN_DOMAIN_RID: DWord = $00000020;
const DOMAIN_ALIAS_RID_ADMINS: DWord = $00000220;
var
hAccessToken: THandle;
InfoBuffer: PChar;
ptgGroups: PTokenGroups;
dwInfoBufferSize: DWord;
psidAdministrators: PSID;
siaNtAuthority: SID_IDENTIFIER_AUTHORITY;
x: UINT;
bSuccess: Boolean;
begin
Result := True;
if (GetVersion and $80000000) = $80000000 then Exit; // Win95/98, not NT
Result := False;
InfoBuffer := AllocMem(1024);
try
ptgGroups := PTokenGroups(InfoBuffer);
siaNtAuthority := SECURITY_NT_AUTHORITY;
if not OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, hAccessToken) then
begin
if GetLastError <> ERROR_NO_TOKEN then Exit;
//
// retry against process token if no thread token exists
//
if not OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, hAccessToken) then Exit;
end;
bSuccess := GetTokenInformation(hAccessToken, TokenGroups, InfoBuffer, 1024, dwInfoBufferSize);
if not bSuccess and (dwInfoBufferSize > 1024) then
begin
FreeMem(InfoBuffer);
InfoBuffer := AllocMem(dwInfoBufferSize);
ptgGroups := PTokenGroups(InfoBuffer);
bSuccess := GetTokenInformation(hAccessToken, TokenGroups, InfoBuffer, dwInfoBufferSize, dwInfoBufferSize);
end;
CloseHandle(hAccessToken);
if not bSuccess then
begin
Exit;
end;
if not AllocateAndInitializeSid(siaNtAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, psidAdministrators) then Exit;
// assume that we don't find the admin SID.
bSuccess := FALSE;
for x := 0 to ptgGroups.GroupCount - 1 do
if EqualSid(psidAdministrators, ptgGroups.Groups[x].Sid) then
begin
bSuccess := True;
Break;
end;
FreeSid(psidAdministrators);
Result := bSuccess;
finally
FreeMem(InfoBuffer);
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC MSSQL metadata }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.Phys.MSSQLMeta;
interface
uses
System.Classes,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.Phys, FireDAC.Phys.Meta, FireDAC.Phys.SQLGenerator;
type
TFDPhysMSSQLMetadata = class (TFDPhysConnectionMetadata)
private
FSchemaCaseSensitive,
FCatalogCaseSensitive: Boolean;
FCaseSensParts: TFDPhysNameParts;
FNameDoubleQuote: Boolean;
FMSDriver: Boolean;
FColumnOriginProvided: Boolean;
protected
function GetKind: TFDRDBMSKind; override;
function GetTxSavepoints: Boolean; override;
function GetEventSupported: Boolean; override;
function GetEventKinds: String; override;
function GetParamNameMaxLength: Integer; override;
function GetNameParts: TFDPhysNameParts; override;
function GetNameQuotedCaseSensParts: TFDPhysNameParts; override;
function GetNameCaseSensParts: TFDPhysNameParts; override;
function GetNameDefLowCaseParts: TFDPhysNameParts; override;
function GetNameQuoteChar(AQuote: TFDPhysNameQuoteLevel; ASide: TFDPhysNameQuoteSide): Char; override;
function GetInlineRefresh: Boolean; override;
function GetSelectOptions: TFDPhysSelectOptions; override;
function GetLimitOptions: TFDPhysLimitOptions; override;
function GetIdentityInsertSupported: Boolean; override;
function GetDefValuesSupported: TFDPhysDefaultValues; override;
function GetLockNoWait: Boolean; override;
function GetAsyncAbortSupported: Boolean; override;
function GetAsyncNativeTimeout: Boolean; override;
function GetCommandSeparator: String; override;
function GetLineSeparator: TFDTextEndOfLine; override;
function GetArrayExecMode: TFDPhysArrayExecMode; override;
function GetColumnOriginProvided: Boolean; override;
function InternalEncodeObjName(const AParsedName: TFDPhysParsedName;
const ACommand: IFDPhysCommand): String; override;
function InternalDecodeObjName(const AName: String;
out AParsedName: TFDPhysParsedName; const ACommand: IFDPhysCommand;
ARaise: Boolean): Boolean; override;
function InternalEscapeBoolean(const AStr: String): String; override;
function InternalEscapeDate(const AStr: String): String; override;
function InternalEscapeDateTime(const AStr: String): String; override;
function InternalEscapeFloat(const AStr: String): String; override;
function InternalEscapeFunction(const ASeq: TFDPhysEscapeData): String; override;
function InternalEscapeTime(const AStr: String): String; override;
function InternalGetSQLCommandKind(const ATokens: TStrings): TFDPhysCommandKind; override;
public
constructor Create(const AConnectionObj: TFDPhysConnection;
ACatalogCaseSensitive, ASchemaCaseSensitive, ASchemaCaseInsSearch,
ANameDoubleQuote, AMSDriver: Boolean; AServerVersion, AClientVersion: TFDVersion;
AColumnOriginProvided: Boolean);
end;
TFDPhysMSSQLCommandGenerator = class(TFDPhysCommandGenerator)
protected
function GetInlineRefresh(const AStmt: String;
ARequest: TFDUpdateRequest): String; override;
function GetIdentityInsert(const ATable, AStmt: String;
ARequest: TFDUpdateRequest): String; override;
function GetIdentity(ASessionScope: Boolean): String; override;
function GetPessimisticLock: String; override;
function GetSavepoint(const AName: String): String; override;
function GetRollbackToSavepoint(const AName: String): String; override;
function GetCommitSavepoint(const AName: String): String; override;
function GetCall(const AName: String): String; override;
function GetLimitSelect(const ASQL: String; ASkip, ARows: Integer;
var AOptions: TFDPhysLimitOptions): String; override;
function GetColumnType(AColumn: TFDDatSColumn): String; override;
function GetMerge(AAction: TFDPhysMergeAction): String; override;
end;
implementation
uses
System.SysUtils,
FireDAC.Stan.Consts, FireDAC.Stan.Util;
{-------------------------------------------------------------------------------}
{ TFDPhysMSSQLMetadata }
{-------------------------------------------------------------------------------}
constructor TFDPhysMSSQLMetadata.Create(const AConnectionObj: TFDPhysConnection;
ACatalogCaseSensitive, ASchemaCaseSensitive, ASchemaCaseInsSearch,
ANameDoubleQuote, AMSDriver: Boolean; AServerVersion, AClientVersion: TFDVersion;
AColumnOriginProvided: Boolean);
begin
inherited Create(AConnectionObj, AServerVersion, AClientVersion, False);
FCatalogCaseSensitive := ACatalogCaseSensitive;
FSchemaCaseSensitive := ASchemaCaseSensitive;
FNameDoubleQuote := ANameDoubleQuote;
FMSDriver := AMSDriver;
FCaseSensParts := [];
if FCatalogCaseSensitive then
FCaseSensParts := FCaseSensParts + [npCatalog];
if FSchemaCaseSensitive then
FCaseSensParts := FCaseSensParts + [npSchema, npBaseObject, npObject];
if ASchemaCaseInsSearch then
FCISearch := True;
ConfigQuoteChars;
FColumnOriginProvided := AColumnOriginProvided;
FKeywords.CommaText :=
'ADD,EXTERNAL,PROCEDURE,ALL,FETCH,PUBLIC,ALTER,FILE,RAISERROR,AND,' +
'FILLFACTOR,READ,ANY,FOR,READTEXT,AS,FOREIGN,RECONFIGURE,ASC,' +
'FREETEXT,REFERENCES,AUTHORIZATION,FREETEXTTABLE,REPLICATION,' +
'BACKUP,FROM,RESTORE,BEGIN,FULL,RESTRICT,BETWEEN,FUNCTION,RETURN,' +
'BREAK,GOTO,REVERT,BROWSE,GRANT,REVOKE,BULK,GROUP,RIGHT,BY,HAVING,' +
'ROLLBACK,CASCADE,HOLDLOCK,ROWCOUNT,CASE,IDENTITY,ROWGUIDCOL,CHECK,' +
'IDENTITY_INSERT,RULE,CHECKPOINT,IDENTITYCOL,SAVE,CLOSE,IF,SCHEMA,' +
'CLUSTERED,IN,SECURITYAUDIT,COALESCE,INDEX,SELECT,COLLATE,INNER,' +
'SEMANTICKEYPHRASETABLE,COLUMN,INSERT,SEMANTICSIMILARITYDETAILSTABLE,' +
'COMMIT,INTERSECT,SEMANTICSIMILARITYTABLE,COMPUTE,INTO,SESSION_USER,' +
'CONSTRAINT,IS,SET,CONTAINS,JOIN,SETUSER,CONTAINSTABLE,KEY,SHUTDOWN,' +
'CONTINUE,KILL,SOME,CONVERT,LEFT,STATISTICS,CREATE,LIKE,SYSTEM_USER,' +
'CROSS,LINENO,TABLE,CURRENT,LOAD,TABLESAMPLE,CURRENT_DATE,MERGE,' +
'TEXTSIZE,CURRENT_TIME,NATIONAL,THEN,CURRENT_TIMESTAMP,NOCHECK,' +
'TO,CURRENT_USER,NONCLUSTERED,TOP,CURSOR,NOT,TRAN,DATABASE,NULL,' +
'TRANSACTION,DBCC,NULLIF,TRIGGER,DEALLOCATE,OF,TRUNCATE,DECLARE,' +
'OFF,TRY_CONVERT,DEFAULT,OFFSETS,TSEQUAL,DELETE,ON,UNION,DENY,' +
'OPEN,UNIQUE,DESC,OPENDATASOURCE,UNPIVOT,DISK,OPENQUERY,UPDATE,' +
'DISTINCT,OPENROWSET,UPDATETEXT,DISTRIBUTED,OPENXML,USE,DOUBLE,' +
'OPTION,USER,DROP,OR,VALUES,DUMP,ORDER,VARYING,ELSE,OUTER,VIEW,' +
'END,OVER,WAITFOR,ERRLVL,PERCENT,WHEN,ESCAPE,PIVOT,WHERE,EXCEPT,' +
'PLAN,WHILE,EXEC,PRECISION,WITH,EXECUTE,PRIMARY,WITHIN GROUP,' +
'EXISTS,PRINT,WRITETEXT,EXIT,PROC';
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLMetadata.GetKind: TFDRDBMSKind;
begin
Result := TFDRDBMSKinds.MSSQL;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLMetadata.GetNameQuotedCaseSensParts: TFDPhysNameParts;
begin
Result := FCaseSensParts;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLMetadata.GetNameCaseSensParts: TFDPhysNameParts;
begin
Result := FCaseSensParts;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLMetadata.GetNameDefLowCaseParts: TFDPhysNameParts;
begin
Result := [npSchema, npBaseObject, npObject];
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLMetadata.GetParamNameMaxLength: Integer;
begin
Result := 128;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLMetadata.GetNameParts: TFDPhysNameParts;
begin
Result := [npCatalog, npSchema, npBaseObject, npObject];
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLMetadata.GetNameQuoteChar(AQuote: TFDPhysNameQuoteLevel;
ASide: TFDPhysNameQuoteSide): Char;
begin
Result := #0;
case AQuote of
ncDefault:
if ASide = nsLeft then
Result := '['
else
Result := ']';
ncSecond:
if FNameDoubleQuote then
Result := '"';
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLMetadata.GetTxSavepoints: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLMetadata.GetEventSupported: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLMetadata.GetEventKinds: String;
begin
Result := S_FD_EventKind_MSSQL_Events;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLMetadata.GetInlineRefresh: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLMetadata.GetLimitOptions: TFDPhysLimitOptions;
begin
if GetServerVersion >= svMSSQL2005 then
Result := [loSkip, loRows]
else
Result := inherited GetLimitOptions();
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLMetadata.GetSelectOptions: TFDPhysSelectOptions;
begin
Result := [soWithoutFrom, soInlineView];
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLMetadata.GetIdentityInsertSupported: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLMetadata.GetDefValuesSupported: TFDPhysDefaultValues;
begin
Result := dvDefVals;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLMetadata.GetLockNoWait: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLMetadata.GetAsyncAbortSupported: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLMetadata.GetAsyncNativeTimeout: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLMetadata.GetCommandSeparator: String;
begin
Result := 'GO';
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLMetadata.GetLineSeparator: TFDTextEndOfLine;
begin
Result := elWindows;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLMetadata.GetArrayExecMode: TFDPhysArrayExecMode;
begin
if FMSDriver then
Result := aeCollectAllErrors
else
// FreeTDS has broken Array DML implementation
Result := aeUpToFirstError;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLMetadata.GetColumnOriginProvided: Boolean;
begin
Result := FMSDriver and FColumnOriginProvided;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLMetadata.InternalDecodeObjName(const AName: String;
out AParsedName: TFDPhysParsedName; const ACommand: IFDPhysCommand;
ARaise: Boolean): Boolean;
var
i: Integer;
begin
Result := inherited InternalDecodeObjName(AName, AParsedName, ACommand, ARaise);
if Result then begin
i := Pos(';', AParsedName.FObject);
if i > 0 then begin
AParsedName.OverInd := StrToInt(Trim(Copy(AParsedName.FObject, i + 1, MaxInt)));
AParsedName.FObject := Copy(AParsedName.FObject, 1, i - 1);
end;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLMetadata.InternalEncodeObjName(
const AParsedName: TFDPhysParsedName; const ACommand: IFDPhysCommand): String;
begin
Result := inherited InternalEncodeObjName(AParsedName, ACommand);
if AParsedName.OverInd > 1 then
Result := Result + ';' + IntToStr(AParsedName.OverInd);
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLMetadata.InternalEscapeBoolean(
const AStr: String): String;
begin
if CompareText(AStr, S_FD_True) = 0 then
Result := '1'
else
Result := '0';
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLMetadata.InternalEscapeDate(const AStr: String): String;
begin
Result := 'CONVERT(DATETIME, ' + AnsiQuotedStr(AStr, '''') + ', 20)';
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLMetadata.InternalEscapeDateTime(const AStr: String): String;
begin
Result := 'CONVERT(DATETIME, ' + AnsiQuotedStr(AStr, '''') + ', 20)';
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLMetadata.InternalEscapeTime(const AStr: String): String;
begin
Result := 'CONVERT(DATETIME, ' + AnsiQuotedStr(AStr, '''') + ', 114)';
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLMetadata.InternalEscapeFloat(const AStr: String): String;
begin
Result := AStr;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLMetadata.InternalEscapeFunction(const ASeq: TFDPhysEscapeData): String;
var
sName: String;
A1, A2, A3: String;
rSeq: TFDPhysEscapeData;
i: Integer;
function AddArgs: string;
begin
Result := '(' + AddEscapeSequenceArgs(ASeq) + ')';
end;
begin
sName := ASeq.FName;
if Length(ASeq.FArgs) >= 1 then begin
A1 := ASeq.FArgs[0];
if Length(ASeq.FArgs) >= 2 then begin
A2 := ASeq.FArgs[1];
if Length(ASeq.FArgs) >= 3 then
A3 := ASeq.FArgs[2];
end;
end;
case ASeq.FFunc of
// the same
// char
efASCII,
efCHAR,
efLEFT,
efLTRIM,
efREPLACE,
efRIGHT,
efRTRIM,
efSPACE,
efSUBSTRING,
// numeric
efACOS,
efASIN,
efATAN,
efABS,
efCEILING,
efCOS,
efCOT,
efDEGREES,
efEXP,
efFLOOR,
efLOG,
efLOG10,
efPOWER,
efPI,
efSIGN,
efSIN,
efSQRT,
efTAN: Result := sName + AddArgs;
// character
efBIT_LENGTH: Result := '(DATALENGTH(' + A1 + ') * 8)';
efCHAR_LENGTH: Result := 'LEN' + AddArgs;
efCONCAT: Result := '(' + A1 + ' + ' + A2 + ')';
efINSERT: Result := 'STUFF' + AddArgs;
efLCASE: Result := 'LOWER' + AddArgs;
efLENGTH: Result := 'LEN(RTRIM(' + A1 + '))';
efLOCATE:
begin
Result := 'CHARINDEX(' + A1 + ', ' + A2;
if Length(ASeq.FArgs) = 3 then
Result := Result + ', ' + A3;
Result := Result + ')'
end;
efOCTET_LENGTH:Result := 'DATALENGTH' + AddArgs;
efPOSITION: Result := 'CHARINDEX' + AddArgs;
efREPEAT: Result := 'REPLICATE' + AddArgs;
efUCASE: Result := 'UPPER' + AddArgs;
// numeric
efRANDOM: Result := 'RAND' + AddArgs;
efTRUNCATE: Result := 'CAST(' + A1 + ' AS BIGINT)';
efATAN2: Result := 'ATN2' + AddArgs;
efMOD: Result := '((' + A1 + ') % (' + A2 + '))';
efROUND:
if A2 = '' then
Result := sName + '(' + A1 + ', 0)'
else
Result := sName + AddArgs;
efRADIANS:
Result := sName + '(' + A1 + ' + 0.0)';
// date and time
efCURDATE,
efCURTIME,
efNOW: Result := 'GETDATE()';
efDAYNAME: Result := 'DATENAME(WEEKDAY, ' + A1 + ')';
efDAYOFMONTH: Result := 'DATEPART(DAY, ' + A1 + ')';
efDAYOFWEEK: Result := '((DATEPART(WEEKDAY, ' + A1 + ') + @@DATEFIRST - 1) % 7 + 1)';
efDAYOFYEAR: Result := 'DATEPART(DAYOFYEAR, ' + A1 + ')';
efEXTRACT:
begin
rSeq.FKind := eskFunction;
A1 := UpperCase(FDUnquote(Trim(A1), ''''));
if A1 = 'DAY' then
A1 := 'DAYOFMONTH';
rSeq.FName := A1;
SetLength(rSeq.FArgs, 1);
rSeq.FArgs[0] := ASeq.FArgs[1];
EscapeFuncToID(rSeq);
Result := InternalEscapeFunction(rSeq);
end;
efHOUR: Result := 'DATEPART(HOUR, ' + A1 + ')';
efMINUTE: Result := 'DATEPART(MINUTE, ' + A1 + ')';
efMONTH: Result := 'DATEPART(MONTH, ' + A1 + ')';
efMONTHNAME: Result := 'DATENAME(MONTH, ' + A1 + ')';
efQUARTER: Result := 'DATEPART(QUARTER, ' + A1 + ')';
efSECOND: Result := 'DATEPART(SECOND, ' + A1 + ')';
efTIMESTAMPADD:
begin
A1 := UpperCase(FDUnquote(Trim(A1), ''''));
if A1 = 'FRAC_SECOND' then begin
A1 := 'MILLISECOND';
A2 := '(' + A2 + ' / 1000)';
end;
ASeq.FArgs[0] := A1;
ASeq.FArgs[1] := A2;
Result := 'DATEADD' + AddArgs;
end;
efTIMESTAMPDIFF:
begin
A1 := UpperCase(FDUnquote(Trim(A1), ''''));
if A1 = 'FRAC_SECOND' then
A1 := 'MILLISECOND';
ASeq.FArgs[0] := A1;
Result := 'DATEDIFF' + AddArgs;
if A1 = 'MILLISECOND' then
Result := '(' + Result + ' * 1000.0)';
end;
efWEEK: Result := 'DATEPART(WEEK, ' + A1 + ')';
efYEAR: Result := 'DATEPART(YEAR, ' + A1 + ')';
// system
efCATALOG: Result := 'DB_NAME()';
efSCHEMA:
if GetServerVersion >= svMSSQL2005 then
Result := 'SCHEMA_NAME()'
else
Result := 'CURRENT_USER()';
efIFNULL: Result := 'CASE WHEN ' + A1 + ' IS NULL THEN ' + A2 + ' ELSE ' + A1 + ' END';
efIF: Result := 'CASE WHEN ' + A1 + ' THEN ' + A2 + ' ELSE ' + A3 + ' END';
efDECODE:
begin
Result := 'CASE ' + ASeq.FArgs[0];
i := 1;
while i < Length(ASeq.FArgs) - 1 do begin
Result := Result + ' WHEN ' + ASeq.FArgs[i] + ' THEN ' + ASeq.FArgs[i + 1];
Inc(i, 2);
end;
if i = Length(ASeq.FArgs) - 1 then
Result := Result + ' ELSE ' + ASeq.FArgs[i];
Result := Result + ' END';
end;
// convert
efCONVERT:
Result := 'CONVERT(' + A2 + ', ' + A1 + ')';
else
UnsupportedEscape(ASeq);
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLMetadata.InternalGetSQLCommandKind(
const ATokens: TStrings): TFDPhysCommandKind;
var
sToken: String;
begin
sToken := ATokens[0];
if (sToken = 'EXEC') or (sToken = 'EXECUTE') then
Result := skExecute
else if sToken = 'BEGIN' then
if ATokens.Count = 1 then
Result := skNotResolved
else if (ATokens[1] = 'TRAN') or (ATokens[1] = 'TRANSACTION') then
Result := skStartTransaction
else
Result := inherited InternalGetSQLCommandKind(ATokens)
else if sToken = 'IF' then
// IF @@TRANCOUNT > 0 COMMIT | ROLLBACK
if ATokens.Count = 1 then
Result := skNotResolved
else if ATokens[1] = 'COMMIT' then
Result := skCommit
else if ATokens[1] = 'ROLLBACK' then
Result := skRollback
else
Result := inherited InternalGetSQLCommandKind(ATokens)
else if sToken = 'RECEIVE' then
Result := skSelect
else
Result := inherited InternalGetSQLCommandKind(ATokens);
end;
{-------------------------------------------------------------------------------}
{ TFDPhysMSSQLCommandGenerator }
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLCommandGenerator.GetInlineRefresh(const AStmt: String;
ARequest: TFDUpdateRequest): String;
begin
Result := GenerateSelect(False);
if Result <> '' then
Result := AStmt + ';' + BRK + Result
else
Result := AStmt;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLCommandGenerator.GetIdentityInsert(
const ATable, AStmt: String; ARequest: TFDUpdateRequest): String;
begin
Result := 'SET IDENTITY_INSERT ' + ATable + ' ON;' + BRK + AStmt +
';' + BRK + 'SET IDENTITY_INSERT ' + ATable + ' OFF';
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLCommandGenerator.GetIdentity(ASessionScope: Boolean): String;
begin
if not ASessionScope and
((FConnMeta.ServerVersion = 0) or (FConnMeta.ServerVersion >= svMSSQL2000)) then
Result := 'SCOPE_IDENTITY()'
else
Result := '@@IDENTITY';
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLCommandGenerator.GetPessimisticLock: String;
var
lNeedFrom: Boolean;
begin
if not FOptions.UpdateOptions.LockWait then
Result := 'SET LOCK_TIMEOUT 0;' + BRK;
lNeedFrom := False;
Result := Result + 'SELECT ' + GetSelectList(True, False, lNeedFrom) + BRK +
'FROM ' + GetFrom + ' WITH(ROWLOCK,UPDLOCK)' + BRK +
'WHERE ' + GetWhere(False, True, False);
FCommandKind := skSelectForLock;
ASSERT(lNeedFrom);
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLCommandGenerator.GetSavepoint(const AName: String): String;
begin
Result := 'IF @@TRANCOUNT = 0 BEGIN SET IMPLICIT_TRANSACTIONS OFF BEGIN TRANSACTION END SAVE TRANSACTION ' + AName;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLCommandGenerator.GetRollbackToSavepoint(const AName: String): String;
begin
Result := 'ROLLBACK TRANSACTION ' + AName;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLCommandGenerator.GetCommitSavepoint(const AName: String): String;
begin
Result := '';
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLCommandGenerator.GetCall(const AName: String): String;
begin
Result := 'EXECUTE ' + AName;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLCommandGenerator.GetLimitSelect(const ASQL: String;
ASkip, ARows: Integer; var AOptions: TFDPhysLimitOptions): String;
var
s: string;
function OrderByHasNumbers: Boolean;
var
i: Integer;
begin
Result := False;
for i := 1 to Length(s) do
if FDInSet(s[i], ['0' .. '9']) then begin
Result := True;
Break;
end;
end;
begin
if (GetSQLOrderByPos > 0) and (FConnMeta.ServerVersion >= svMSSQL2012) then begin
s := UpperCase(ASQL);
if not (FDHasKW(s, 'UNION') or FDHasKW(s, 'INTERSECT') or FDHasKW(s, 'EXCEPT')) then
if (ASkip > 0) and (ARows + ASkip <> MAXINT) then
Result := ASQL + BRK + 'OFFSET ' + IntToStr(ASkip) + ' ROWS FETCH FIRST ' + IntToStr(ARows) + ' ROWS ONLY'
else if ASkip > 0 then
Result := ASQL + BRK + 'OFFSET ' + IntToStr(ASkip) + ' ROWS'
else if ARows >= 0 then
Result := ASQL + BRK + 'OFFSET 0 ROWS FETCH FIRST ' + IntToStr(ARows) + ' ROWS ONLY'
else begin
Result := ASQL;
AOptions := [];
end
else
Result := inherited GetLimitSelect(ASQL, ASkip, ARows, AOptions);
end
else if (GetSQLOrderByPos > 0) and (FConnMeta.ServerVersion >= svMSSQL2005) then begin
if (ASkip > 0) and (ARows + ASkip <> MAXINT) or
(ASkip > 0) or (ARows >= 0) then begin
s := Copy(ASQL, GetSQLOrderByPos, MAXINT);
// ORDER BY A.FIELD and ORDER BY N are not supported by this algorithm
if (Pos('.', s) <> 0) or OrderByHasNumbers() then
Result := inherited GetLimitSelect(ASQL, ASkip, ARows, AOptions)
else begin
Result := 'SELECT T.* FROM (' +
'SELECT T.*, ROW_NUMBER() OVER (' + s + ') AS ' +
C_FD_SysColumnPrefix + 'rn FROM (' + Copy(ASQL, 1, GetSQLOrderByPos - 1) + ') T) T ' +
'WHERE ';
if (ASkip > 0) and (ARows + ASkip <> MAXINT) then
Result := Result + 'T.' + C_FD_SysColumnPrefix + 'rn <= ' + IntToStr(ASkip + ARows) +
' AND T.' + C_FD_SysColumnPrefix + 'rn > ' + IntToStr(ASkip)
else if ASkip > 0 then
Result := Result + 'T.' + C_FD_SysColumnPrefix + 'rn > ' + IntToStr(ASkip)
else if ARows >= 0 then
Result := Result + 'T.' + C_FD_SysColumnPrefix + 'rn <= ' + IntToStr(ARows);
end;
end
else begin
Result := ASQL;
AOptions := [];
end;
end
else
Result := inherited GetLimitSelect(ASQL, ASkip, ARows, AOptions);
end;
{-------------------------------------------------------------------------------}
// http://msdn.microsoft.com/en-us/library/ms187752(v=sql.120).aspx
function TFDPhysMSSQLCommandGenerator.GetColumnType(AColumn: TFDDatSColumn): String;
begin
if caExpr in AColumn.ActualAttributes then begin
Result := ' AS ' + AColumn.Expression;
Exit;
end;
case AColumn.DataType of
dtBoolean:
Result := 'BIT';
dtSByte,
dtInt16:
Result := 'SMALLINT';
dtInt32,
dtUInt16:
Result := 'INT';
dtInt64,
dtUInt32,
dtUInt64:
Result := 'BIGINT';
dtByte:
Result := 'TINYINT';
dtSingle:
Result := 'REAL';
dtDouble,
dtExtended:
Result := 'FLOAT';
dtCurrency:
Result := 'MONEY';
dtBCD,
dtFmtBCD:
Result := 'DECIMAL' + GetColumnDim(-1, AColumn.Precision, AColumn.Scale, -1,
FOptions.FormatOptions.MaxBcdPrecision, 0);
dtDateTime,
dtDateTimeStamp:
if FConnMeta.ServerVersion < svMSSQL2008 then
Result := 'DATETIME'
else
Result := 'DATETIME2';
dtTime:
if FConnMeta.ServerVersion < svMSSQL2008 then
Result := 'DATETIME'
else
Result := 'TIME';
dtDate:
if FConnMeta.ServerVersion < svMSSQL2008 then
Result := 'DATETIME'
else
Result := 'DATE';
dtAnsiString:
begin
if caFixedLen in AColumn.ActualAttributes then
Result := 'CHAR'
else
Result := 'VARCHAR';
Result := Result + GetColumnDim(AColumn.Size, -1, -1, -1, -1, -1);
end;
dtWideString:
begin
if caFixedLen in AColumn.ActualAttributes then
Result := 'NCHAR'
else
Result := 'NVARCHAR';
Result := Result + GetColumnDim(AColumn.Size, -1, -1, -1, -1, -1);
end;
dtByteString:
begin
if caFixedLen in AColumn.ActualAttributes then
Result := 'BINARY'
else
Result := 'VARBINARY';
Result := Result + GetColumnDim(AColumn.Size, -1, -1, -1, -1, -1);
end;
dtBlob,
dtHBlob:
if FConnMeta.ServerVersion < svMSSQL2005 then
Result := 'IMAGE'
else
Result := 'VARBINARY(MAX)';
dtMemo,
dtHMemo:
if FConnMeta.ServerVersion < svMSSQL2005 then
Result := 'TEXT'
else
Result := 'VARCHAR(MAX)';
dtWideMemo,
dtWideHMemo:
if FConnMeta.ServerVersion < svMSSQL2005 then
Result := 'NTEXT'
else
Result := 'NVARCHAR(MAX)';
dtXML:
if FConnMeta.ServerVersion < svMSSQL2005 then
Result := 'NTEXT'
else begin
Result := 'XML';
if AColumn.SourceDirectory <> '' then
Result := Result + '(' + AColumn.SourceDirectory + ')';
end;
dtHBFile:
if FConnMeta.ServerVersion < svMSSQL2005 then
Result := 'IMAGE'
else begin
Result := 'VARBINARY(MAX) FILESTREAM';
end;
dtGUID:
Result := 'UNIQUEIDENTIFIER';
dtUnknown,
dtTimeIntervalFull,
dtTimeIntervalYM,
dtTimeIntervalDS,
dtRowSetRef,
dtCursorRef,
dtRowRef,
dtArrayRef,
dtParentRowRef,
dtObject:
Result := '';
end;
if (Result <> '') and (caAutoInc in AColumn.ActualAttributes) then
Result := Result + ' IDENTITY(1,1)';
end;
{-------------------------------------------------------------------------------}
function TFDPhysMSSQLCommandGenerator.GetMerge(AAction: TFDPhysMergeAction): String;
begin
Result := '';
case AAction of
maInsertUpdate:
Result := GenerateUpdate() + ';' + BRK + 'IF @@ROWCOUNT = 0' + BRK +
'BEGIN' + BRK + GenerateInsert() + ';' + BRK + 'END';
maInsertIgnore:
Result := 'IF NOT EXISTS (SELECT 1 FROM ' + GetFrom() + ' WHERE ' +
GetWhere(False, True, False) + ')' + BRK +
'BEGIN' + BRK + GenerateInsert() + ';' + BRK + 'END';
end;
end;
{-------------------------------------------------------------------------------}
initialization
FDPhysManager().RegisterRDBMSKind(TFDRDBMSKinds.MSSQL, S_FD_MSSQL_RDBMS);
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.