text stringlengths 14 6.51M |
|---|
(*----------------------------------------------------------------------------*
* Direct3D sample from DirectX 9.0 SDK December 2006 *
* Delphi adaptation by Alexey Barkovoy (e-mail: directx@clootie.ru) *
* *
* Supported compilers: Delphi 5,6,7,9; FreePascal 2.0 *
* *
* Latest version can be downloaded from: *
* http://www.clootie.ru *
* http://sourceforge.net/projects/delphi-dx9sdk *
*----------------------------------------------------------------------------*
* $Id: CompiledEffectUnit.pas,v 1.15 2007/02/05 22:21:03 clootie Exp $
*----------------------------------------------------------------------------*)
//--------------------------------------------------------------------------------------
// File: CompiledEffect.cpp
//
// Desc: This sample shows how an ID3DXEffect object can be compiled when the
// project is built and loaded directly as a binary file at run time.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
{$I DirectX.inc}
unit CompiledEffectUnit;
interface
uses
Windows, SysUtils,
DXTypes, Direct3D9, D3DX9,
DXUT, DXUTcore, DXUTenum, DXUTmesh, DXUTmisc, DXUTgui, DXUTSettingsDlg;
{.$DEFINE DEBUG_VS} // Uncomment this line to debug vertex shaders
{.$DEFINE DEBUG_PS} // Uncomment this line to debug pixel shaders
//--------------------------------------------------------------------------------------
// Global variables
//--------------------------------------------------------------------------------------
var
g_pFont: ID3DXFont; // Font for drawing text
g_pTextSprite: ID3DXSprite; // Sprite for batching draw text calls
g_pEffect: ID3DXEffect; // D3DX effect interface
g_Camera: CModelViewerCamera; // A model viewing camera
g_bShowHelp: Boolean = True; // If true, it renders the UI control text
g_DialogResourceManager: CDXUTDialogResourceManager; // manager for shared resources of dialogs
g_SettingsDlg: CD3DSettingsDlg; // Device settings dialog
g_HUD: CDXUTDialog; // dialog for standard controls
g_Mesh: CDXUTMesh; // Mesh object
g_vObjectCenter: TD3DXVector3; // Center of bounding sphere of object
g_fObjectRadius: Single; // Radius of bounding sphere of object
g_mCenterWorld: TD3DXMatrixA16; // World matrix to center the mesh
g_hTime: TD3DXHandle = nil; // Handle to var in the effect
g_hWorld: TD3DXHandle = nil; // Handle to var in the effect
g_hMeshTexture: TD3DXHandle = nil; // Handle to var in the effect
g_hWorldViewProjection: TD3DXHandle = nil; // Handle to var in the effect
g_hTechniqueRenderScene: TD3DXHandle = nil; // Handle to technique in the effect
//--------------------------------------------------------------------------------------
// UI control IDs
//--------------------------------------------------------------------------------------
const
IDC_TOGGLEFULLSCREEN = 1;
IDC_TOGGLEREF = 3;
IDC_CHANGEDEVICE = 4;
//--------------------------------------------------------------------------------------
// Forward declarations
//--------------------------------------------------------------------------------------
function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall;
function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall;
function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall;
procedure KeyboardProc(nChar: LongWord; bKeyDown, bAltDown: Boolean; pUserContext: Pointer); stdcall;
procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall;
procedure OnLostDevice(pUserContext: Pointer); stdcall;
procedure OnDestroyDevice(pUserContext: Pointer); stdcall;
procedure InitApp;
procedure RenderText;
procedure CreateCustomDXUTobjects;
procedure DestroyCustomDXUTobjects;
implementation
//--------------------------------------------------------------------------------------
// Initialize the app
//--------------------------------------------------------------------------------------
procedure InitApp;
var
iY: Integer;
begin
// Initialize dialogs
g_SettingsDlg.Init(g_DialogResourceManager);
g_HUD.Init(g_DialogResourceManager);
g_HUD.SetCallback(OnGUIEvent); iY := 10;
g_HUD.AddButton(IDC_TOGGLEFULLSCREEN, 'Toggle full screen', 35, iY, 125, 22); Inc(iY, 24);
g_HUD.AddButton(IDC_TOGGLEREF, 'Toggle REF (F3)', 35, iY, 125, 22); Inc(iY, 24);
g_HUD.AddButton(IDC_CHANGEDEVICE, 'Change device (F2)', 35, iY, 125, 22, VK_F2);
end;
//--------------------------------------------------------------------------------------
// Called during device initialization, this code checks the device for some
// minimum set of capabilities, and rejects those that don't pass by returning false.
//--------------------------------------------------------------------------------------
function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall;
var
pD3D: IDirect3D9;
begin
Result := False;
// No fallback defined by this app, so reject any device that
// doesn't support at least ps2.0
if (pCaps.PixelShaderVersion < D3DPS_VERSION(2,0)) then Exit;
// Skip backbuffer formats that don't support alpha blending
pD3D := DXUTGetD3DObject;
if FAILED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType,
AdapterFormat, D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING,
D3DRTYPE_TEXTURE, BackBufferFormat))
then Exit;
Result := True;
end;
//--------------------------------------------------------------------------------------
// This callback function is called immediately before a device is created to allow the
// application to modify the device settings. The supplied pDeviceSettings parameter
// contains the settings that the framework has selected for the new device, and the
// application can make any desired changes directly to this structure. Note however that
// DXUT will not correct invalid device settings so care must be taken
// to return valid device settings, otherwise IDirect3D9::CreateDevice() will fail.
//--------------------------------------------------------------------------------------
{static} var s_bFirstTime: Boolean = True;
function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall;
begin
// If device doesn't support HW T&L or doesn't support 1.1 vertex shaders in HW
// then switch to SWVP.
if (pCaps.DevCaps and D3DDEVCAPS_HWTRANSFORMANDLIGHT = 0) or
(pCaps.VertexShaderVersion < D3DVS_VERSION(1,1))
then pDeviceSettings.BehaviorFlags := D3DCREATE_SOFTWARE_VERTEXPROCESSING;
// Debugging vertex shaders requires either REF or software vertex processing
// and debugging pixel shaders requires REF.
{$IFDEF DEBUG_VS}
if (pDeviceSettings.DeviceType <> D3DDEVTYPE_REF) then
with pDeviceSettings do
begin
BehaviorFlags := BehaviorFlags and not D3DCREATE_HARDWARE_VERTEXPROCESSING;
BehaviorFlags := BehaviorFlags and not D3DCREATE_PUREDEVICE;
BehaviorFlags := BehaviorFlags or D3DCREATE_SOFTWARE_VERTEXPROCESSING;
end;
{$ENDIF}
{$IFDEF DEBUG_PS}
pDeviceSettings.DeviceType := D3DDEVTYPE_REF;
{$ENDIF}
// For the first device created if its a REF device, optionally display a warning dialog box
if s_bFirstTime then
begin
s_bFirstTime := False;
if (pDeviceSettings.DeviceType = D3DDEVTYPE_REF) then DXUTDisplaySwitchingToREFWarning;
end;
Result:= True;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has been
// created, which will happen during application initialization and windowed/full screen
// toggles. This is the best location to create D3DPOOL_MANAGED resources since these
// resources need to be reloaded whenever the device is destroyed. Resources created
// here should be released in the OnDestroyDevice callback.
//--------------------------------------------------------------------------------------
function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
var
pVB: IDirect3DVertexBuffer9;
pVertices: Pointer;
str: array [0..MAX_PATH-1] of WideChar;
vecEye: TD3DXVector3;
vecAt: TD3DXVector3;
begin
Result:= g_DialogResourceManager.OnCreateDevice(pd3dDevice);
if V_Failed(Result) then Exit;
Result:= g_SettingsDlg.OnCreateDevice(pd3dDevice);
if V_Failed(Result) then Exit;
// Initialize the font
Result:= D3DXCreateFont(pd3dDevice, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH or FF_DONTCARE,
'Arial', g_pFont);
if V_Failed(Result) then Exit;
// Load the mesh
Result:= g_Mesh.CreateMesh(pd3dDevice, 'dwarf\dwarf.x');
if V_Failed(Result) then Exit;
// Find the mesh's center, then generate a centering matrix.
pVB := nil;
Result:= g_Mesh.Mesh.GetVertexBuffer(pVB);
if V_Failed(Result) then Exit;
pVertices:= nil;
Result := pVB.Lock(0, 0, pVertices, 0);
if FAILED(Result) then Exit;
Result := D3DXComputeBoundingSphere(PD3DXVector3(pVertices), g_Mesh.Mesh.GetNumVertices,
D3DXGetFVFVertexSize(g_Mesh.Mesh.GetFVF), g_vObjectCenter,
g_fObjectRadius);
pVB.Unlock;
pVB:= nil;
if FAILED(Result) then Exit;
D3DXMatrixTranslation(g_mCenterWorld, -g_vObjectCenter.x, -g_vObjectCenter.y, -g_vObjectCenter.z);
// Read the D3DX effect file
Result := DXUTFindDXSDKMediaFile(str, MAX_PATH, 'CompiledEffect.fxo');
if FAILED(Result) then
begin
//todo: Update this statement
MessageBox(DXUTGetHWND, 'Could not locate "CompiledEffect.fxo".'#10#10 +
'This file is created as part of the project build process,'#10 +
'so the associated project must be compiled inside Visual'#10 +
'Studio before attempting to run this sample.'#10#10 +
'If receiving this error even after compiling the project,'#10 +
'it''s likely there was a problem compiling the effect file.'#10 +
'Check the build log to verify the custom build step was'#10 +
'run and to look for possible fxc compile errors.',
'File Not Found', MB_OK);
Result:= E_FAIL;
Exit;
end;
// Since we are loading a binary file here and this effect has already been compiled,
// you can not pass compiler flags here (for example to debug the shaders).
// To debug the shaders, you must pass these flags to the compiler that generated the
// binary (for example fxc.exe). In this sample, there are 2 extra Visual Studio configurations
// called "Debug Shaders" and "Unicode Debug Shaders" that pass the debug shader flags to fxc.exe.
Result:= D3DXCreateEffectFromFileW(pd3dDevice, str, nil, nil, D3DXFX_NOT_CLONEABLE, nil, g_pEffect, nil);
if FAILED(Result) then Exit;
// Setup the camera's view parameters
vecEye := D3DXVector3(0.0, 0.0, -5.0);
vecAt := D3DXVECTOR3(0.0, 0.0, -0.0);
g_Camera.SetViewParams(vecEye, vecAt);
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has been
// reset, which will happen after a lost device scenario. This is the best location to
// create D3DPOOL_DEFAULT resources since these resources need to be reloaded whenever
// the device is lost. Resources created here should be released in the OnLostDevice
// callback.
//--------------------------------------------------------------------------------------
function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
var
colorMtrlDiffuse: TD3DXColor;
colorMtrlAmbient: TD3DXColor;
fAspectRatio: Single;
begin
Result:= g_DialogResourceManager.OnResetDevice;
if V_Failed(Result) then Exit;
Result:= g_SettingsDlg.OnResetDevice;
if V_Failed(Result) then Exit;
if Assigned(g_pFont) then
begin
Result:= g_pFont.OnResetDevice;
if V_Failed(Result) then Exit;
end;
if Assigned(g_pEffect) then
begin
Result:= g_pEffect.OnResetDevice;
if V_Failed(Result) then Exit;
end;
g_Mesh.RestoreDeviceObjects(pd3dDevice);
// Create a sprite to help batch calls when drawing many lines of text
Result:= D3DXCreateSprite(pd3dDevice, g_pTextSprite);
if V_Failed(Result) then Exit;
// Set effect variables as needed
colorMtrlDiffuse := D3DXColor(1.0, 1.0, 1.0, 1.0);
colorMtrlAmbient := D3DXColor(0.35, 0.35, 0.35, 0);
g_pEffect.SetVector('g_MaterialAmbientColor', PD3DXVector4(@colorMtrlAmbient)^);
g_pEffect.SetVector('g_MaterialDiffuseColor', PD3DXVector4(@colorMtrlDiffuse)^);
// To read or write to D3DX effect variables we can use the string name
// instead of using handles, however it improves perf to use handles since then
// D3DX won't have to spend time doing string compares
g_hTechniqueRenderScene := g_pEffect.GetTechniqueByName('RenderScene');
g_hTime := g_pEffect.GetParameterByName(nil, 'g_fTime');
g_hWorld := g_pEffect.GetParameterByName(nil, 'g_mWorld');
g_hWorldViewProjection := g_pEffect.GetParameterByName(nil, 'g_mWorldViewProjection');
g_hMeshTexture := g_pEffect.GetParameterByName(nil, 'g_MeshTexture');
// Setup the camera's projection parameters
fAspectRatio := pBackBufferSurfaceDesc.Width / pBackBufferSurfaceDesc.Height;
g_Camera.SetProjParams(D3DX_PI/4, fAspectRatio, 0.1, 1000.0);
g_Camera.SetWindow(pBackBufferSurfaceDesc.Width, pBackBufferSurfaceDesc.Height);
g_HUD.SetLocation(pBackBufferSurfaceDesc.Width-170, 0);
g_HUD.SetSize(170, 170);
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called once at the beginning of every frame. This is the
// best location for your application to handle updates to the scene, but is not
// intended to contain actual rendering calls, which should instead be placed in the
// OnFrameRender callback.
//--------------------------------------------------------------------------------------
procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
var
mWorld: TD3DXMatrixA16;
mView: TD3DXMatrixA16;
mProj: TD3DXMatrixA16;
mWorldViewProjection: TD3DXMatrixA16;
m: TD3DXMatrixA16;
begin
// Update the camera's position based on user input
g_Camera.FrameMove(fElapsedTime);
// Get the projection & view matrix from the camera class
// mWorld := g_mCenterWorld * g_Camera.GetWorldMatrix^;
D3DXMatrixMultiply(mWorld, g_mCenterWorld, g_Camera.GetWorldMatrix^);
mProj := g_Camera.GetProjMatrix^;
mView := g_Camera.GetViewMatrix^;
// mWorldViewProjection = mWorld * mView * mProj;
D3DXMatrixMultiply(m, mView, mProj);
D3DXMatrixMultiply(mWorldViewProjection, mWorld, m);
// Update the effect's variables
g_pEffect.SetMatrix(g_hWorldViewProjection, mWorldViewProjection);
g_pEffect.SetMatrix(g_hWorld, mWorld);
g_pEffect.SetFloat(g_hTime, fTime);
end;
//--------------------------------------------------------------------------------------
// This callback function will be called at the end of every frame to perform all the
// rendering calls for the scene, and it will also be called if the window needs to be
// repainted. After this function has returned, DXUT will call
// IDirect3DDevice9::Present to display the contents of the next buffer in the swap chain
//--------------------------------------------------------------------------------------
procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
var
iPass, cPasses: Integer;
begin
// If the settings dialog is being shown, then
// render it instead of rendering the app's scene
if g_SettingsDlg.Active then
begin
g_SettingsDlg.OnRender(fElapsedTime);
Exit;
end;
// Clear the render target and the zbuffer
V(pd3dDevice.Clear(0, nil, D3DCLEAR_TARGET or D3DCLEAR_ZBUFFER, D3DCOLOR_ARGB(0, 45, 50, 170), 1.0, 0));
// Render the scene
if SUCCEEDED(pd3dDevice.BeginScene) then
begin
V(g_pEffect._Begin(@cPasses, 0));
for iPass := 0 to cPasses - 1 do
begin
V(g_pEffect.BeginPass(iPass));
V(g_Mesh.Render(pd3dDevice ));
g_pEffect.EndPass;
end;
g_pEffect._End;
RenderText;
V(g_HUD.OnRender(fElapsedTime));
V(pd3dDevice.EndScene);
end;
end;
//--------------------------------------------------------------------------------------
// Render the help and statistics text. This function uses the ID3DXFont interface for
// efficient text rendering.
//--------------------------------------------------------------------------------------
procedure RenderText;
var
txtHelper: CDXUTTextHelper;
pd3dsdBackBuffer: PD3DSurfaceDesc;
begin
// The helper object simply helps keep track of text position, and color
// and then it calls pFont->DrawText( g_pSprite, strMsg, -1, &rc, DT_NOCLIP, g_clr );
// If NULL is passed in as the sprite object, then it will work however the
// pFont->DrawText() will not be batched together. Batching calls will improves performance.
txtHelper := CDXUTTextHelper.Create(g_pFont, g_pTextSprite, 15);
// Output statistics
txtHelper._Begin;
txtHelper.SetInsertionPos(5, 5);
txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 0.0, 1.0));
txtHelper.DrawTextLine(DXUTGetFrameStats);
txtHelper.DrawTextLine(DXUTGetDeviceStats);
txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 1.0, 1.0));
// Draw help
if g_bShowHelp then
begin
pd3dsdBackBuffer := DXUTGetBackBufferSurfaceDesc;
txtHelper.SetInsertionPos(10, pd3dsdBackBuffer.Height-15*6);
txtHelper.SetForegroundColor(D3DXColor(1.0, 0.75, 0.0, 1.0));
txtHelper.DrawTextLine('Controls (F1 to hide):');
txtHelper.SetInsertionPos(40, pd3dsdBackBuffer.Height-15*5);
txtHelper.DrawTextLine('Rotate model: Left mouse button'#10+
'Rotate camera: Right mouse button'#10+
'Zoom camera: Mouse wheel scroll'#10+
'Quit: ESC');
end else
begin
txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 1.0, 1.0));
txtHelper.DrawTextLine('Press F1 for help');
end;
txtHelper._End;
txtHelper.Free;
end;
//--------------------------------------------------------------------------------------
// Before handling window messages, DXUT passes incoming windows
// messages to the application through this callback function. If the application sets
// *pbNoFurtherProcessing to TRUE, then DXUT will not process this message.
//--------------------------------------------------------------------------------------
function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall;
begin
Result:= 0;
// Always allow dialog resource manager calls to handle global messages
// so GUI state is updated correctly
pbNoFurtherProcessing := g_DialogResourceManager.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
if g_SettingsDlg.IsActive then
begin
g_SettingsDlg.MsgProc(hWnd, uMsg, wParam, lParam);
Exit;
end;
// Give the dialogs a chance to handle the message first
pbNoFurtherProcessing := g_HUD.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
// Pass all remaining windows messages to camera so it can respond to user input
g_Camera.HandleMessages(hWnd, uMsg, wParam, lParam);
end;
//--------------------------------------------------------------------------------------
// As a convenience, DXUT inspects the incoming windows messages for
// keystroke messages and decodes the message parameters to pass relevant keyboard
// messages to the application. The framework does not remove the underlying keystroke
// messages, which are still passed to the application's MsgProc callback.
//--------------------------------------------------------------------------------------
procedure KeyboardProc(nChar: LongWord; bKeyDown, bAltDown: Boolean; pUserContext: Pointer); stdcall;
begin
if bKeyDown then
begin
case nChar of
VK_F1: g_bShowHelp := not g_bShowHelp;
end;
end;
end;
//--------------------------------------------------------------------------------------
// Handles the GUI events
//--------------------------------------------------------------------------------------
procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall;
begin
case nControlID of
IDC_TOGGLEFULLSCREEN: DXUTToggleFullScreen;
IDC_TOGGLEREF: DXUTToggleREF;
IDC_CHANGEDEVICE: with g_SettingsDlg do Active := not Active;
end;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has
// entered a lost state and before IDirect3DDevice9::Reset is called. Resources created
// in the OnResetDevice callback should be released here, which generally includes all
// D3DPOOL_DEFAULT resources. See the "Lost Devices" section of the documentation for
// information about lost devices.
//--------------------------------------------------------------------------------------
procedure OnLostDevice(pUserContext: Pointer); stdcall;
begin
g_DialogResourceManager.OnLostDevice;
g_SettingsDlg.OnLostDevice;
if Assigned(g_pFont) then g_pFont.OnLostDevice;
if Assigned(g_pEffect) then g_pEffect.OnLostDevice;
g_Mesh.InvalidateDeviceObjects;
SAFE_RELEASE(g_pTextSprite);
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has
// been destroyed, which generally happens as a result of application termination or
// windowed/full screen toggles. Resources created in the OnCreateDevice callback
// should be released here, which generally includes all D3DPOOL_MANAGED resources.
//--------------------------------------------------------------------------------------
procedure OnDestroyDevice(pUserContext: Pointer); stdcall;
begin
g_DialogResourceManager.OnDestroyDevice;
g_SettingsDlg.OnDestroyDevice;
SAFE_RELEASE(g_pEffect);
SAFE_RELEASE(g_pFont);
g_Mesh.DestroyMesh;
end;
procedure CreateCustomDXUTobjects;
begin
g_DialogResourceManager:= CDXUTDialogResourceManager.Create; // manager for shared resources of dialogs
g_SettingsDlg:= CD3DSettingsDlg.Create; // Device settings dialog
g_Camera:= CModelViewerCamera.Create;
g_HUD := CDXUTDialog.Create;
g_Mesh:= CDXUTMesh.Create
end;
procedure DestroyCustomDXUTobjects;
begin
FreeAndNil(g_DialogResourceManager);
FreeAndNil(g_SettingsDlg);
FreeAndNil(g_Camera);
FreeAndNil(g_HUD);
FreeAndNil(g_Mesh);
end;
end.
|
unit Cpu_Io_Register;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ComCtrls, ExtCtrls,
StdCtrls;
type
{ TCpuIoRegister }
TCpuIoRegister = class(TForm)
labelBBR: TLabel;
labelBCR0H: TLabel;
labelBCR0L: TLabel;
labelBCR1H: TLabel;
labelBCR1L: TLabel;
labelCBAR: TLabel;
labelCBR: TLabel;
labelCNTR: TLabel;
labelCpuTitle: TLabel;
labelCsioTitle: TLabel;
labelDAR0B: TLabel;
labelDAR0H: TLabel;
labelDAR0L: TLabel;
labelDCNTL: TLabel;
labelDmaTitle: TLabel;
labelDMODE: TLabel;
labelDSTAT: TLabel;
labelFRC: TLabel;
labelIAR1H: TLabel;
labelIAR1L: TLabel;
labelICR: TLabel;
labelIL: TLabel;
labelITC: TLabel;
labelMAR1B: TLabel;
labelMAR1H: TLabel;
labelMAR1L: TLabel;
labelMmuTitle: TLabel;
labelOMCR: TLabel;
labelRCR: TLabel;
labelPrtTitle: TLabel;
labelAsciTitle: TLabel;
labelCNTLA0: TLabel;
labelRDR1: TLabel;
labelCNTLB0: TLabel;
labelSAR0B: TLabel;
labelSAR0H: TLabel;
labelSAR0L: TLabel;
labelTCR: TLabel;
labelTMDR0H: TLabel;
labelTMDR0L: TLabel;
labelTMDR1H: TLabel;
labelTMDR1L: TLabel;
labelRLDR0H: TLabel;
labelRLDR0L: TLabel;
labelRLDR1H: TLabel;
labelRLDR1L: TLabel;
labelSTAT0: TLabel;
labelTDR0: TLabel;
labelRDR0: TLabel;
labelCNTLA1: TLabel;
labelCNTLB1: TLabel;
labelSTAT1: TLabel;
labelTDR1: TLabel;
labelTRD: TLabel;
labelValueBBR: TLabel;
labelValueBCR0H: TLabel;
labelValueBCR0L: TLabel;
labelValueBCR1H: TLabel;
labelValueBCR1L: TLabel;
labelValueCBAR: TLabel;
labelValueCBR: TLabel;
labelValueCNTR: TLabel;
labelValueDAR0B: TLabel;
labelValueDAR0H: TLabel;
labelValueDAR0L: TLabel;
labelValueDCNTL: TLabel;
labelValueDMODE: TLabel;
labelValueDSTAT: TLabel;
labelValueFRC: TLabel;
labelValueIAR1H: TLabel;
labelValueIAR1L: TLabel;
labelValueICR: TLabel;
labelValueIL: TLabel;
labelValueITC: TLabel;
labelValueMAR1B: TLabel;
labelValueMAR1H: TLabel;
labelValueMAR1L: TLabel;
labelValueOMCR: TLabel;
labelValueRCR: TLabel;
labelValueSAR0B: TLabel;
labelValueSAR0H: TLabel;
labelValueSAR0L: TLabel;
labelValueTCR: TLabel;
labelValueTMDR0H: TLabel;
labelValueTMDR0L: TLabel;
labelValueTMDR1H: TLabel;
labelValueTMDR1L: TLabel;
labelValueRLDR0H: TLabel;
labelValueRLDR0L: TLabel;
labelValueRLDR1H: TLabel;
labelValueRLDR1L: TLabel;
labelValueCNTLA0: TLabel;
labelValueRDR1: TLabel;
labelValueCNTLB0: TLabel;
labelValueSTAT0: TLabel;
labelValueTDR0: TLabel;
labelValueRDR0: TLabel;
labelValueCNTLA1: TLabel;
labelValueCNTLB1: TLabel;
labelValueSTAT1: TLabel;
labelValueTDR1: TLabel;
labelValueTRD: TLabel;
panelDmaCpu: TPanel;
panelBBR: TPanel;
panelBCR0H: TPanel;
panelBCR0L: TPanel;
panelBCR1H: TPanel;
panelBCR1L: TPanel;
panelCBAR: TPanel;
panelCBR: TPanel;
panelCNTR: TPanel;
panelCpu: TPanel;
panelCpuTitle: TPanel;
panelCpuValues: TPanel;
panelCsio: TPanel;
panelCsioTitle: TPanel;
panelCsioValues: TPanel;
panelDAR0B: TPanel;
panelDAR0H: TPanel;
panelDAR0L: TPanel;
panelDCNTL: TPanel;
panelDMA: TPanel;
panelDmaData: TPanel;
panelDmaSpacer1: TPanel;
panelDmaSpacer2: TPanel;
panelDmaSpacer3: TPanel;
panelDmaSpacer4: TPanel;
panelDmaSpacer5: TPanel;
panelDmaSpacer6: TPanel;
panelDmaTitle: TPanel;
panelDmaValues: TPanel;
panelDMODE: TPanel;
panelDSTAT: TPanel;
panelFRC: TPanel;
panelIAR1H: TPanel;
panelIAR1L: TPanel;
panelICR: TPanel;
panelIL: TPanel;
panelITC: TPanel;
panelMAR1B: TPanel;
panelMAR1H: TPanel;
panelMAR1L: TPanel;
panelMiscellaneous: TPanel;
panelMmu: TPanel;
panelMmuCsio: TPanel;
panelMmuTitle: TPanel;
panelMmuValues: TPanel;
panelOMCR: TPanel;
panelRCR: TPanel;
panelAsciPrt: TPanel;
panelPrtSpacer1: TPanel;
panelPrtSpacer2: TPanel;
panelPrtSpacer3: TPanel;
panelPrtValues: TPanel;
panelPrtTitle: TPanel;
panelAsciValues: TPanel;
panelAsciTitle: TPanel;
panelAsci: TPanel;
panelPRT: TPanel;
panelCNTLA0: TPanel;
panelRDR1: TPanel;
panelCNTLB0: TPanel;
panelSAR0B: TPanel;
panelSAR0H: TPanel;
panelSAR0L: TPanel;
panelTCR: TPanel;
panelTMDR0H: TPanel;
panelTMDR0L: TPanel;
panelTMDR1H: TPanel;
panelTMDR1L: TPanel;
panelRLDR0H: TPanel;
panelRLDR0L: TPanel;
panelRLDR1H: TPanel;
panelRLDR1L: TPanel;
panelSTAT0: TPanel;
panelTDR0: TPanel;
panelRDR0: TPanel;
panelCNTLA1: TPanel;
panelCNTLB1: TPanel;
panelSTAT1: TPanel;
panelTDR1: TPanel;
panelTRD: TPanel;
panelValueBBR: TPanel;
panelValueBCR0H: TPanel;
panelValueBCR0L: TPanel;
panelValueBCR1H: TPanel;
panelValueBCR1L: TPanel;
panelValueCBAR: TPanel;
panelValueCBR: TPanel;
panelValueCNTR: TPanel;
panelValueDAR0B: TPanel;
panelValueDAR0H: TPanel;
panelValueDAR0L: TPanel;
panelValueDCNTL: TPanel;
panelValueDMODE: TPanel;
panelValueDSTAT: TPanel;
panelValueFRC: TPanel;
panelValueIAR1H: TPanel;
panelValueIAR1L: TPanel;
panelValueICR: TPanel;
panelValueIL: TPanel;
panelValueITC: TPanel;
panelValueMAR1B: TPanel;
panelValueMAR1H: TPanel;
panelValueMAR1L: TPanel;
panelValueOMCR: TPanel;
panelValueRCR: TPanel;
panelValueSAR0B: TPanel;
panelValueSAR0H: TPanel;
panelValueSAR0L: TPanel;
panelValueTCR: TPanel;
panelValueTMDR0H: TPanel;
panelValueTMDR0L: TPanel;
panelValueTMDR1H: TPanel;
panelValueTMDR1L: TPanel;
panelValueRLDR0H: TPanel;
panelValueRLDR0L: TPanel;
panelValueRLDR1H: TPanel;
panelValueRLDR1L: TPanel;
panelValueCNTLA0: TPanel;
panelValueRDR1: TPanel;
panelValueCNTLB0: TPanel;
panelValueSTAT0: TPanel;
panelValueTDR0: TPanel;
panelValueRDR0: TPanel;
panelValueCNTLA1: TPanel;
panelValueCNTLB1: TPanel;
panelValueSTAT1: TPanel;
panelValueTDR1: TPanel;
panelValueTRD: TPanel;
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormShow(Sender: TObject);
procedure onPanelPaint(Sender: TObject);
procedure onPanelValuePaint(Sender: TObject);
private
public
procedure showRegisterData;
end;
var
CpuIoRegister: TCpuIoRegister;
implementation
{$R *.lfm}
uses UscaleDPI, System_Settings, Z180_CPU;
{ TCpuIoRegister }
// --------------------------------------------------------------------------------
procedure TCpuIoRegister.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin
SystemSettings.saveFormState(TForm(self));
CloseAction := caFree;
CpuIoRegister := nil;
end;
// --------------------------------------------------------------------------------
procedure TCpuIoRegister.FormShow(Sender: TObject);
begin
SystemSettings.restoreFormState(TForm(self));
self.SetAutoSize(True);
Constraints.MinWidth := Width;
Constraints.MaxWidth := Width;
Constraints.MinHeight := Height;
Constraints.MaxHeight := Height;
ScaleDPI(self, 96);
DisableAutoSizing;
showRegisterData;
end;
// --------------------------------------------------------------------------------
procedure TCpuIoRegister.onPanelPaint(Sender: TObject);
begin
with Sender as TPanel do begin
Canvas.Pen.Color := clGray;
Canvas.RoundRect(0, 0, Width, Height, 4, 4);
end;
end;
// --------------------------------------------------------------------------------
procedure TCpuIoRegister.onPanelValuePaint(Sender: TObject);
begin
with Sender as TPanel do begin
Canvas.Brush.Color := clCream;
Canvas.Pen.Color := clGray;
Canvas.RoundRect(0, 0, Width, Height, 4, 4);
end;
end;
// --------------------------------------------------------------------------------
procedure TCpuIoRegister.showRegisterData;
var
ioRegData: Z180Cpu.TIoData;
begin
ioRegData := Z180Cpu.getIoRegData;
labelValueCNTLA0.Caption := IntToHex(ioRegData.CNTLA0, 2);
labelValueCNTLB0.Caption := IntToHex(ioRegData.CNTLB0, 2);
labelValueSTAT0.Caption := IntToHex(ioRegData.STAT0, 2);
labelValueTDR0.Caption := IntToHex(ioRegData.TDR0, 2);
labelValueRDR0.Caption := IntToHex(ioRegData.RDR0, 2);
labelValueCNTLA1.Caption := IntToHex(ioRegData.CNTLA1, 2);
labelValueCNTLB1.Caption := IntToHex(ioRegData.CNTLB1, 2);
labelValueSTAT1.Caption := IntToHex(ioRegData.STAT1, 2);
labelValueTDR1.Caption := IntToHex(ioRegData.TDR1, 2);
labelValueRDR1.Caption := IntToHex(ioRegData.RDR1, 2);
labelValueTCR.Caption := IntToHex(ioRegData.TCR, 2);
labelValueTMDR0H.Caption := IntToHex(ioRegData.TMDR0H, 2);
labelValueTMDR0L.Caption := IntToHex(ioRegData.TMDR0L, 2);
labelValueRLDR0H.Caption := IntToHex(ioRegData.RLDR0H, 2);
labelValueRLDR0L.Caption := IntToHex(ioRegData.RLDR0L, 2);
labelValueTMDR1H.Caption := IntToHex(ioRegData.TMDR1H, 2);
labelValueTMDR1L.Caption := IntToHex(ioRegData.TMDR1L, 2);
labelValueRLDR1H.Caption := IntToHex(ioRegData.RLDR1H, 2);
labelValueRLDR1L.Caption := IntToHex(ioRegData.RLDR1L, 2);
labelValueDMODE.Caption := IntToHex(ioRegData.DMODE, 2);
labelValueDCNTL.Caption := IntToHex(ioRegData.DCNTL, 2);
labelValueDSTAT.Caption := IntToHex(ioRegData.DSTAT, 2);
labelValueSAR0B.Caption := IntToHex(ioRegData.SAR0B, 2);
labelValueSAR0H.Caption := IntToHex(ioRegData.SAR0H, 2);
labelValueSAR0L.Caption := IntToHex(ioRegData.SAR0L, 2);
labelValueDAR0B.Caption := IntToHex(ioRegData.DAR0B, 2);
labelValueDAR0H.Caption := IntToHex(ioRegData.DAR0H, 2);
labelValueDAR0L.Caption := IntToHex(ioRegData.DAR0L, 2);
labelValueBCR0H.Caption := IntToHex(ioRegData.BCR0H, 2);
labelValueBCR0L.Caption := IntToHex(ioRegData.BCR0L, 2);
labelValueMAR1B.Caption := IntToHex(ioRegData.MAR1B, 2);
labelValueMAR1H.Caption := IntToHex(ioRegData.MAR1H, 2);
labelValueMAR1L.Caption := IntToHex(ioRegData.MAR1L, 2);
labelValueIAR1H.Caption := IntToHex(ioRegData.IAR1H, 2);
labelValueIAR1L.Caption := IntToHex(ioRegData.IAR1L, 2);
labelValueBCR1H.Caption := IntToHex(ioRegData.BCR1H, 2);
labelValueBCR1L.Caption := IntToHex(ioRegData.BCR1L, 2);
labelValueOMCR.Caption := IntToHex(ioRegData.OMCR, 2);
labelValueICR.Caption := IntToHex(ioRegData.ICR, 2);
labelValueFRC.Caption := IntToHex(ioRegData.FRC, 2);
labelValueRCR.Caption := IntToHex(ioRegData.RCR, 2);
labelValueITC.Caption := IntToHex(ioRegData.ITC, 2);
labelValueIL.Caption := IntToHex(ioRegData.IL, 2);
labelValueCBAR.Caption := IntToHex(ioRegData.CBAR, 2);
labelValueBBR.Caption := IntToHex(ioRegData.BBR, 2);
labelValueCBR.Caption := IntToHex(ioRegData.CBR, 2);
labelValueCNTR.Caption := IntToHex(ioRegData.CNTR, 2);
labelValueTRD.Caption := IntToHex(ioRegData.TRD, 2);
end;
// --------------------------------------------------------------------------------
end.
|
unit cdWriter;
interface
uses
Classes, Windows, ShlObj, SysUtils, ComObj, ActiveX, cdImapi;
type
TCDWriter = class;
TCallBackObj = class(TInterfacedObject,IDiscMasterProgressEvents)
private
FOwner: TCDWriter;
public
constructor Create(AOwner: TCDWriter);
function NotifyAddProgress(nCompletedSteps: Integer;
nTotalSteps: Integer): HRESULT; stdcall;
function NotifyBurnComplete(status: HRESULT): HRESULT; stdcall;
function NotifyBlockProgress(nCompleted: Integer; nTotal: Integer): HRESULT; stdcall;
function NotifyClosingDisc(nEstimatedSeconds: Integer): HRESULT; stdcall;
function NotifyEraseComplete(status: HRESULT): HRESULT; stdcall;
function NotifyPnPActivity: HRESULT; stdcall;
function NotifyPreparingBurn(nEstimatedSeconds: Integer): HRESULT; stdcall;
function NotifyTrackProgress(nCurrentTrack: Integer;
nTotalTracks: Integer): HRESULT; stdcall;
function QueryCancel(out pbCancel: LongBool): HRESULT; stdcall;
end;
TCDValueKind = (cdvkData, cdvkBlock, cdvkTrack);
TCDCompletion = (cdcoBurning, cdcoErasing);
TCDRecorderState = (cdrsUnknown, cdrsIdle, cdrsOpen, cdrsBurning);
TCDDrive = record
Device : String;
Volume : String;
Path : String;
end;
TCDMediaInfo = record
SessionCount: Byte;
LastTrack: Byte;
StartAddress: Cardinal;
NextWriteable: Cardinal;
FreeBlocks: Cardinal;
end;
TNotifyCancel = procedure(out ACancelAction: Boolean) of object;
TNotifyMessage = procedure(const AMessage: String) of object;
TNotifyValues = procedure(AKind: TCDValueKind; ACurrent, ATotal: Integer) of object;
TNotifyCompletion = procedure(Sender: TObject; ACompletion: TCDCompletion; AStatus: HRESULT) of object;
TCDWriter = class(TObject)
private
FCookie: Cardinal;
FJolietDiscMaster: IJolietDiscMaster;
FRedBookDiscMaster: IRedbookDiscMaster;
FHelper: IDiscMasterProgressEvents;
FDiscMaster: IDiscMaster;
FDiscRecorder: IDiscRecorder;
FRecorders: TInterfaceList;
FOnShowMessage: TNotifyMessage;
FOnValueChange: TNotifyValues;
FOnCompletion: TNotifyCompletion;
FOnCancelAction: TNotifyCancel;
FImageSize: Cardinal;
FBytesWritten: Cardinal;
function GetDiscMaster: IDiscMaster;
function GetRecorderState: TCDRecorderState;
function GetFirstRecorder(out aRecorder: IDiscRecorder): Boolean;
procedure ListRecorders(AIntfList: TInterfaceList; ADisplay: TStrings);
procedure GetDiskFormats;
procedure SetLastMessage(const Value: String);
function GetDiscRecorder: IDiscRecorder;
function GetDeviceReady: Boolean;
function GetRecorderPath: String;
procedure GetVolumeNames(AVolume: array of Char; var ADrive: TCDDrive);
procedure DoJolietAddFiles(AFiles: TStrings; AOverwrite: Boolean);
procedure DoJolietAddFileToStorage(AFile: String; AStorage: IStorage;
ANewFileName: String);
property LastMessage: String write SetLastMessage;
public
constructor Create(AOwner: TComponent);
destructor Destroy; override;
procedure RecorderOpen;
procedure RecorderClose;
procedure SetActiveRecorder(AIndex: Integer);
function AddData(AContent: IStorage; AOverwrite: Boolean): Boolean;
function AddFolder(const AFolderOnHDD, AFolderOnDisc: String;
AOverwrite: Boolean): Boolean;
function AddFile(const AFile, AFolderOnDisc: String;
AOverwrite: Boolean): Boolean;
function AddFiles(AFileList: TStrings; AOverwrite: Boolean): Boolean;
function FilesCount: Integer;
function RecordDisk(Simulate, EjectAfterBurn: Boolean): Boolean;
function IsWriteableMedia: Boolean;
function GetMediaInfo: TCDMediaInfo;
function GetRecorderCount: Integer;
function GetRecorderList(ARecorders: TStrings): Boolean;
property OnCompletion: TNotifyCompletion read FOnCompletion write FOnCompletion;
property OnShowMessage: TNotifyMessage read FOnShowMessage write FOnShowMessage;
property OnValueChange: TNotifyValues read FOnValueChange write FOnValueChange;
property OnCancelAction: TNotifyCancel read FOnCancelAction write FOnCancelAction;
property DiscMaster: IDiscMaster read GetDiscMaster;
property DiscRecorder: IDiscRecorder read GetDiscRecorder;
property RecorderState: TCDRecorderState read GetRecorderState;
property DeviceReady: Boolean read GetDeviceReady;
property RecorderPath: String read GetRecorderPath;
property ImageSize: Cardinal read FImageSize write FImageSize;
property BytesWritten: Cardinal read FBytesWritten write FBytesWritten;
end;
implementation
uses
nsGlobals;
resourcestring
res_ImapiAlreadyOpen = 'Imapi interface is already opened.';
res_ImapiObjectNotAvail = 'Imapi-Object is not available.';
res_DeviceWasRemoved = 'Device has been removed from the system.';
res_CDfullOrReadOnlyOrAudio = 'Disc is full or read only or has audio format.';
res_NoMediaInserted = 'No media inserted.';
res_ImapiNoInit = 'Imapi has not been initialized.';
res_NoFormatChoosen = 'No format has been choosen.';
res_AnotherRecorderChoosen = 'Another recorder has been choosen already.';
res_WritingComplete = 'CD-Writing complete.';
res_FinalizeStartsInSeconds = 'Finalizing starts in %d seconds';
res_CDErasingComplete = 'CD-Erasing complete.';
res_RecorderListChanged = 'List of recorders has been changed.';
res_WritingBeginsInSeconds = 'Writing begins in %d seconds.';
constructor TCDWriter.Create(AOwner: TComponent);
begin
FHelper := TCallBackObj.Create(Self);
FDiscMaster := CreateComObject(MSDiscMasterObj) as IDiscMaster;
if FDiscMaster.Open = IMAPI_E_ALREADYOPEN then
LastMessage := res_ImapiAlreadyOpen;
GetDiskFormats;
FRecorders := TInterfaceList.Create;
FDiscMaster.ProgressAdvise(FHelper,FCookie);
GetFirstRecorder(FDiscRecorder);
end;
destructor TCDWriter.Destroy;
begin
if Assigned(FDiscMaster) then
begin
FDiscMaster.ProgressUnadvise(FCookie);
FDiscMaster.Close;
FDiscMaster := nil;
end;
FreeAndNil(FRecorders);
end;
procedure TCDWriter.DoJolietAddFiles(AFiles: TStrings; AOverwrite: Boolean);
{ List has to be in this format:
\Folder\On\Disc\file1.txt=c:\test.txt
\Sub\Folder\On\Disc\file2.exe=c:\app.exe
}
var
idxFile : Integer;
Folders : TInterfaceList;
FolderNames : TStringList;
PathSplitter : TStringList;
RootFolder,
CurrentFolder : IStorage;
function FirstNParts(N : Integer) : String;
var
idx : Integer;
begin
Result := EmptyStr;
for idx := 0 to N do
begin
if idx > 0 then
Result := Result + PathSplitter.Delimiter;
Result := Result + PathSplitter[idx];
end;
end;
procedure GetCurrentFolder(AFolderName : String);
var
idxFolderName,
idxFolderPart,
idxFolder,
idx : Integer;
temp : IStorage;
begin
AFolderName := Trim(ExcludeTrailingPathDelimiter(AFolderName));
if AFolderName = EmptyStr then
begin
CurrentFolder := RootFolder;
exit;
end;
idxFolderName := FolderNames.IndexOf(AFolderName);
if idxFolderName > -1 then
begin
idxFolder := Integer(FolderNames.Objects[idxFolderName]);
CurrentFolder := Folders[idxFolder] as IStorage;
exit;
end;
PathSplitter.DelimitedText := AFolderName;
idx := 1;
CurrentFolder := nil;
for idxFolderPart := PathSplitter.Count - 1 downto 1 do
begin
PathSplitter.Delete(idxFolderPart);
idxFolderName := FolderNames.IndexOf(PathSplitter.DelimitedText);
if idxFolderName > -1 then
begin
idx := idxFolderPart;
idxFolder := Integer(FolderNames.Objects[idxFolderName]);
CurrentFolder := Folders[idxFolder] as IStorage;
break;
end;
end;
if CurrentFolder = nil then
CurrentFolder := RootFolder;
PathSplitter.DelimitedText := AFolderName;
for idxFolderPart := idx to PathSplitter.Count - 1 do
begin
temp := CurrentFolder;
temp.CreateStorage(PWideChar(WideString(PathSplitter[idxFolderPart])),
STGM_CREATE or STGM_READWRITE or STGM_DIRECT or
STGM_SHARE_EXCLUSIVE, 0, 0, CurrentFolder);
FolderNames.AddObject(FirstNParts(idxFolderPart), TObject(Folders.Add(CurrentFolder)));
end;
end;
begin
OleCheck(StgCreateDocFile(nil,
STGM_CREATE or STGM_READWRITE or STGM_DIRECT or
STGM_SHARE_EXCLUSIVE or STGM_DELETEONRELEASE,
0,
ActiveX.IStorage(RootFolder)));
Folders := TInterfaceList.Create;
FolderNames := TStringList.Create;
FolderNames.Sorted := true;
PathSplitter := TStringList.Create;
PathSplitter.Delimiter := PathDelim;
PathSplitter.StrictDelimiter := true;
try
for idxFile := 0 to AFiles.Count - 1 do
begin
GetCurrentFolder(ExtractFilePath(AFiles.Names[idxFile]));
DoJolietAddFileToStorage(AFiles.ValueFromIndex[idxFile],
CurrentFolder,
ExtractFileName(AFiles.Names[idxFile]));
end;
finally
CurrentFolder := nil;
Folders.Free;
FolderNames.Free;
PathSplitter.Free;
end;
AddData(RootFolder, AOverwrite);
end;
procedure TCDWriter.DoJolietAddFileToStorage(AFile: String; AStorage: IStorage;
ANewFileName : String);
var
FileName : String;
FS : TFileStream;
Buffer : Pointer;
DataInBuffer : Integer;
Written : Longint;
Stream : IStream;
const
DEFAULT_BUFFER_SIZE = 4096;
begin
if not FileExists(AFile) then
exit;
FileName := ExtractFileName(AFile);
if ANewFileName = EmptyStr then
ANewFileName := ExtractFileName(AFile);
OleCheck(AStorage.CreateStream(PWideChar(WideString(ANewFileName)),
STGM_CREATE or STGM_READWRITE or STGM_DIRECT or
STGM_SHARE_EXCLUSIVE, 0, 0, Stream));
FS := TFileStream.Create(AFile, fmOpenRead);
GetMem(Buffer, DEFAULT_BUFFER_SIZE);
try
repeat
DataInBuffer := FS.Read(Buffer^, DEFAULT_BUFFER_SIZE);
Stream.Write(Buffer, DataInBuffer, @Written);
until DataInBuffer = 0;
finally
fs.Free;
Stream := nil;
if Assigned(Buffer) then
FreeMem(Buffer, DEFAULT_BUFFER_SIZE);
end;
end;
function TCDWriter.AddData(AContent: IStorage; AOverwrite: Boolean): Boolean;
begin
Result := Assigned(FJolietDiscMaster);
if not Result then
Exit;
try
OleCheck(FJolietDiscMaster.AddData(AContent, Integer(AOverwrite)));
except
Result := False;
end;
end;
function TCDWriter.AddFile(const AFile, AFolderOnDisc: String;
AOverwrite: Boolean): Boolean;
var
slList : TStringList;
begin
Result := Assigned(FJolietDiscMaster);
if not Result then
Exit;
slList := TStringList.Create;
try
slList.Values[IncludeTrailingPathDelimiter(AFolderOnDisc) + ExtractFileName(AFile)] := AFile;
DoJolietAddFiles(slList, AOverwrite);
finally
slList.Free;
end;
end;
function TCDWriter.AddFiles(AFileList: TStrings; AOverwrite: Boolean): Boolean;
begin
Result := Assigned(FJolietDiscMaster);
if not Result then
Exit;
DoJolietAddFiles(AFileList, AOverwrite);
end;
function TCDWriter.AddFolder(const AFolderOnHDD, AFolderOnDisc: String;
AOverwrite: Boolean): Boolean;
var
slList : TStringList;
procedure AddFilesToList(AFolderHDD, AFolderDisc : String);
var
sr : TSearchRec;
begin
AFolderHDD := IncludeTrailingPathDelimiter(AFolderHDD);
AFolderDisc := IncludeTrailingPathDelimiter(AFolderDisc);
if FindFirst(AFolderHDD + sFileMask, faAnyFile, sr) = 0 then
begin
repeat
if (sr.Name <> sDot) and (sr.Name <> sDoubleDot) then
begin
if ((sr.Attr and faDirectory) <> 0) then
begin
AddFilesToList(AFolderHDD + sr.Name, AFolderDisc + sr.Name)
end
else
slList.Values[AFolderDisc + sr.Name] := AFolderHDD + sr.Name;
end;
until FindNext(sr) <> 0;
FindClose(sr);
end;
end;
begin
Result := Assigned(FJolietDiscMaster);
if not Result then
Exit;
slList := TStringList.Create;
try
AddFilesToList(AFolderOnHDD, AFolderOnDisc);
AddFiles(slList, AOverwrite);
finally
slList.Free;
end;
end;
function TCDWriter.FilesCount: Integer;
begin
Result := 1; //TODO
end;
function TCDWriter.GetDeviceReady: Boolean;
begin
Result := GetRecorderState = cdrsIdle;
end;
function TCDWriter.GetDiscMaster: IDiscMaster;
begin
if Assigned(FDiscMaster) then
Result := FDiscMaster
else
raise Exception.Create(res_ImapiObjectNotAvail);
end;
function TCDWriter.GetDiscRecorder: IDiscRecorder;
begin
if Assigned(FDiscRecorder) then
Result := FDiscRecorder
else
raise Exception.Create(res_ImapiObjectNotAvail);
end;
function TCDWriter.GetFirstRecorder(out ARecorder: IDiscRecorder): Boolean;
var
lEnumRecorders : IEnumDiscRecorders;
pfetched : Cardinal;
begin
ARecorder := nil;
OleCheck(DiscMaster.EnumDiscRecorders(lEnumRecorders));
pFetched := 0;
lEnumRecorders.Next(1,ARecorder,pFetched);
Result := pFetched > 0;
end;
function TCDWriter.GetMediaInfo: TCDMediaInfo;
begin
RecorderOpen;
try
OleCheck(FDiscRecorder.QueryMediaInfo(
Result.SessionCount,
Result.LastTrack,
Result.StartAddress,
Result.NextWriteable,
Result.FreeBlocks));
finally
RecorderClose;
end;
end;
function TCDWriter.GetRecorderList(ARecorders: TStrings): Boolean;
var
iUnk : IUnknown;
begin
OleCheck(DiscMaster.SetActiveDiscMasterFormat(IID_IJolietDiscMaster, iUnk));
ListRecorders(FRecorders, ARecorders);
Result := ARecorders.Count > 0;
end;
function TCDWriter.GetRecorderCount: Integer;
var
list: TStringList;
begin
list := TStringList.Create;
try
GetRecorderList(list);
Result := list.Count;
finally
FreeAndNil(list);
end;
end;
procedure TCDWriter.GetVolumeNames(AVolume: Array of Char; var ADrive: TCDDrive);
var
dBufferLen: DWORD;
dReturnLen: DWORD;
pVolumePath: PChar;
begin
dBufferLen := MAX_PATH + 1;
ADrive.Volume := Copy(AVolume, 1, dBufferLen);
pVolumePath := StrAlloc(dBufferLen);
if GetVolumePathNamesForVolumeName(PChar(ADrive.Volume), pVolumePath, dBufferLen, dReturnLen) then
ADrive.Path := ExcludeTrailingPathDelimiter(pVolumePath);
StrDispose(pVolumePath);
pVolumePath := StrAlloc(dBufferLen);
if (QueryDosDevice(PChar(ADrive.Path), pVolumePath, dBufferLen) > 0) then
ADrive.Device := pVolumePath;
StrDispose(pVolumePath);
ADrive.Path := IncludeTrailingPathDelimiter(ADrive.Path);
end;
function TCDWriter.IsWriteableMedia: Boolean;
var
mt, mf : Integer;
begin
RecorderOpen;
try
OleCheck(FDiscRecorder.QueryMediaType(mt, mf));
Result := (MEDIA_FORMAT_UNUSABLE_BY_IMAPI and mf = 0)
and ((MEDIA_BLANK and mf = MEDIA_BLANK)
or (MEDIA_RW and mf = MEDIA_RW)
or (MEDIA_WRITABLE and mf = MEDIA_WRITABLE));
finally
RecorderClose;
end;
end;
function TCDWriter.GetRecorderPath: String;
var
hVolume: THandle;
cVolume: Array[0..MAX_PATH] of Char;
pPath: PWideChar;
rDrive: TCDDrive;
begin
Result := EmptyStr;
DiscRecorder.GetPath(pPath);
hVolume := FindFirstVolume(cVolume, SizeOf(cVolume));
if hVolume <> INVALID_HANDLE_VALUE then
repeat
GetVolumeNames(cVolume, rDrive);
if rDrive.Device = pPath then
Result := rDrive.Path;
until (Result <> EmptyStr) or (not FindNextVolume(hVolume, cVolume, SizeOf(cVolume)));
FindVolumeClose(hVolume);
end;
function TCDWriter.GetRecorderState: TCDRecorderState;
var
iState: Cardinal;
begin
OleCheck(FDiscRecorder.GetRecorderState(iState));
case iState of
RECORDER_DOING_NOTHING: Result := cdrsIdle;
RECORDER_OPENED: Result := cdrsOpen;
RECORDER_BURNING: Result := cdrsBurning;
else
Result := cdrsUnknown;
end;
end;
procedure TCDWriter.GetDiskFormats;
var
lFormats: IEnumDiscMasterFormats;
gFmtID: TGUID;
iFetched: Cardinal;
begin
OleCheck(FDiscMaster.EnumDiscMasterFormats(lFormats));
FRedBookDiscMaster := nil;
FJolietDiscMaster := nil;
iFetched := 1;
lFormats.Next(1, gFmtID, iFetched);
while iFetched > 0 do
begin
if IsEqualGUID(gFmtID, IID_IRedbookDiscMaster) then
FRedBookDiscMaster := FDiscMaster as IRedbookDiscMaster
else
if IsEqualGUID(gFmtID, IID_IJolietDiscMaster) then
FJolietDiscMaster := FDiscMaster as IJolietDiscMaster;
lFormats.Next(1, gFmtID, iFetched);
end;
end;
procedure TCDWriter.ListRecorders(AIntfList: TInterfaceList; ADisplay: TStrings);
var
lEnumRecorders: IEnumDiscRecorders;
lRecIntf: IDiscRecorder;
iFetched: Cardinal;
pPath: PWideChar;
pVendorStr: PWideChar;
pProductId: PWideChar;
pRevision: PWideChar;
begin
AIntfList.Clear;
ADisplay.Clear;
OleCheck(DiscMaster.EnumDiscRecorders(lEnumRecorders));
iFetched := 1;
lEnumRecorders.Next(1,lRecIntf,iFetched);
while iFetched > 0 do
begin
AIntfList.Add(lRecIntf);
OleCheck(lRecIntf.GetDisplayNames(pVendorStr, pProductId, pRevision));
OleCheck(lRecIntf.GetPath(pPath));
ADisplay.Add(Format('%s (%s %s %s %s)', [GetRecorderPath,
WideCharToString(pPath),
WideCharToString(pVendorStr),
WideCharToString(pProductId),
WideCharToString(pRevision)]));
lEnumRecorders.Next(1,lRecIntf,iFetched);
end;
end;
procedure TCDWriter.RecorderOpen;
begin
OleCheck(FDiscRecorder.OpenExclusive);
end;
procedure TCDWriter.RecorderClose;
begin
OleCheck(FDiscRecorder.Close);
end;
function TCDWriter.RecordDisk(Simulate, EjectAfterBurn: Boolean): Boolean;
begin
try
OleCheck(DiscMaster.RecordDisc(Simulate, EjectAfterBurn));
Result := True;
except
Result := False;
end;
end;
procedure TCDWriter.SetActiveRecorder(AIndex: Integer);
begin
case DiscMaster.SetActiveDiscRecorder(FRecorders.Items[AIndex] as IDiscRecorder) of
IMAPI_E_DEVICE_NOTPRESENT : LastMessage := res_DeviceWasRemoved;
IMAPI_E_DISCFULL : LastMessage := res_CDfullOrReadOnlyOrAudio;
IMAPI_E_MEDIUM_NOTPRESENT : LastMessage := res_NoMediaInserted;
IMAPI_E_NOTOPENED : LastMessage := res_ImapiNoInit;
IMAPI_E_NOACTIVEFORMAT : LastMessage := res_NoFormatChoosen;
IMAPI_E_STASHINUSE : LastMessage := res_AnotherRecorderChoosen;
end;
end;
procedure TCDWriter.SetLastMessage(const Value: String);
begin
if Assigned(FOnShowMessage) then
FOnShowMessage(Value);
end;
{ TCallBackObj }
constructor TCallBackObj.Create(AOwner: TCDWriter);
begin
inherited Create;
FOwner := AOwner;
end;
function TCallBackObj.NotifyAddProgress(nCompletedSteps, nTotalSteps: Integer): HRESULT;
begin
if Assigned(FOwner) then
if Assigned(FOwner.OnValueChange) then
FOwner.OnValueChange(cdvkData, nCompletedSteps, nTotalSteps);
Result := s_OK;
end;
function TCallBackObj.NotifyBlockProgress(nCompleted, nTotal: Integer): HRESULT;
begin
if Assigned(FOwner) then
if Assigned(FOwner.OnValueChange) then
FOwner.OnValueChange(cdvkBlock, nCompleted, nTotal);
Result := s_OK;
end;
function TCallBackObj.NotifyBurnComplete(status: HRESULT): HRESULT;
begin
if Assigned(FOwner) then
begin
FOwner.LastMessage := res_WritingComplete;
if Assigned(FOwner.OnCompletion) then
FOwner.OnCompletion(Self, cdcoBurning, status);
end;
Result := s_OK;
end;
function TCallBackObj.NotifyClosingDisc(nEstimatedSeconds: Integer): HRESULT;
begin
if Assigned(FOwner) then
FOwner.LastMessage := Format(res_FinalizeStartsInSeconds,
[nEstimatedSeconds]);
Result := s_OK;
end;
function TCallBackObj.NotifyEraseComplete(status: HRESULT): HRESULT;
begin
if Assigned(FOwner) then
begin
FOwner.LastMessage := res_CDErasingComplete;
if Assigned(FOwner.OnCompletion) then
FOwner.OnCompletion(Self, cdcoErasing, status);
end;
Result := s_OK;
end;
function TCallBackObj.NotifyPnPActivity: HRESULT;
begin
if Assigned(FOwner) then
FOwner.LastMessage := res_RecorderListChanged;
Result := s_OK;
end;
function TCallBackObj.NotifyPreparingBurn(nEstimatedSeconds: Integer): HRESULT;
begin
if Assigned(FOwner) then
FOwner.LastMessage := Format(res_WritingBeginsInSeconds, [nEstimatedSeconds]);
Result := s_OK;
end;
function TCallBackObj.NotifyTrackProgress(nCurrentTrack, nTotalTracks: Integer): HRESULT;
begin
if Assigned(FOwner) then
if Assigned(FOwner.OnValueChange) then
FOwner.OnValueChange(cdvkTrack, nCurrentTrack, nTotalTracks);
Result := s_OK;
end;
function TCallBackObj.QueryCancel(out pbCancel: LongBool): HRESULT;
var
Cancel : Boolean;
begin
if Assigned(FOwner) and Assigned(FOwner.OnCancelAction) then
begin
Cancel := false;
FOwner.OnCancelAction(Cancel);
pbCancel := Cancel;
Result := S_OK;
end
else
Result := E_NOTIMPL;
end;
end.
|
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.StdCtrls, Vcl.ComCtrls;
type
TForm1 = class(TForm)
FirstNameLabel: TLabel;
FirstNameEdit: TEdit;
SecondNameLabel: TLabel;
SecondNameEdit: TEdit;
CountLabel: TLabel;
CountEdit: TEdit;
CountUpDown: TUpDown;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
LanguageButton: TButton;
procedure FormCreate(Sender: TObject);
procedure EditChange(Sender: TObject);
procedure LanguageButtonClick(Sender: TObject);
private
function GetFirstName: String;
function GetSecondName: String;
function GetCount: Integer;
procedure UpdateItems;
public
property FirstName: String read GetFirstName;
property SecondName: String read GetSecondName;
property Count: Integer read GetCount;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses
NtBase,
NtLanguageDlg;
function TForm1.GetFirstName: String;
begin
Result := FirstNameEdit.Text;
end;
function TForm1.GetSecondName: String;
begin
Result := SecondNameEdit.Text;
end;
function TForm1.GetCount: Integer;
begin
Result := CountUpDown.Position;
end;
procedure TForm1.UpdateItems;
resourcestring
SHello = 'Hello %s!'; //loc: 0: Name of a person
SHello2 = 'Hello %s and %s!'; //loc: 0: Name of the first person, 1: Name of the second person
SCount = '%s has %d cars'; //loc: 0: Name of a person, 1: Number of cars
SCount2 = '%d cars will pick up %s and %s'; //loc: 0: Number of cars, 1: Name of the first person, 2: Name of the second person
SDouble = '%0:s swims and %0:s skis'; //loc: 0: Name of a person. This parameter occurs twice.
begin
label1.Caption := Format(SHello, [FirstName]);
label2.Caption := Format(SHello2, [FirstName, SecondName]);
label3.Caption := Format(SCount, [FirstName, Count]);
label4.Caption := Format(SCount2, [Count, FirstName, SecondName]);
label5.Caption := Format(SDouble, [FirstName]);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
FirstNameEdit.Text := 'John';
SecondNameEdit.Text := 'Jill';
CountUpDown.Position := 2;
UpdateItems;
end;
procedure TForm1.EditChange(Sender: TObject);
begin
inherited;
UpdateItems;
end;
procedure TForm1.LanguageButtonClick(Sender: TObject);
begin
// Show a language select dialog and turn on the selected language
if TNtLanguageDialog.Select('en', '', lnBoth) then
begin
// Language has been changed.
// Properties that were set on run time must be set again.
UpdateItems;
end;
end;
end.
|
unit u_fsummary;
interface
uses Windows, ComObj, ActiveX, Variants, Sysutils;
procedure SetFileSummaryInfo(const FileName : WideString; Author, Title, Subject, Keywords, Comments : WideString);
function GetFileSummaryInfo(const FileName: WideString): String;
function IsNTFS(AFileName : string) : boolean;
implementation
const
FmtID_SummaryInformation: TGUID = '{F29F85E0-4FF9-1068-AB91-08002B27B3D9}';
FMTID_DocSummaryInformation : TGUID = '{D5CDD502-2E9C-101B-9397-08002B2CF9AE}';
FMTID_UserDefinedProperties : TGUID = '{D5CDD505-2E9C-101B-9397-08002B2CF9AE}';
IID_IPropertySetStorage : TGUID = '{0000013A-0000-0000-C000-000000000046}';
STGFMT_FILE = 3; //Indicates that the file must not be a compound file.
//This element is only valid when using the StgCreateStorageEx
//or StgOpenStorageEx functions to access the NTFS file system
//implementation of the IPropertySetStorage interface.
//Therefore, these functions return an error if the riid
//parameter does not specify the IPropertySetStorage interface,
//or if the specified file is not located on an NTFS file system volume.
STGFMT_ANY = 4; //Indicates that the system will determine the file type and
//use the appropriate structured storage or property set
//implementation.
//This value cannot be used with the StgCreateStorageEx function.
// Summary Information
PID_TITLE = 2;
PID_SUBJECT = 3;
PID_AUTHOR = 4;
PID_KEYWORDS = 5;
PID_COMMENTS = 6;
PID_TEMPLATE = 7;
PID_LASTAUTHOR = 8;
PID_REVNUMBER = 9;
PID_EDITTIME = 10;
PID_LASTPRINTED = 11;
PID_CREATE_DTM = 12;
PID_LASTSAVE_DTM = 13;
PID_PAGECOUNT = 14;
PID_WORDCOUNT = 15;
PID_CHARCOUNT = 16;
PID_THUMBNAIL = 17;
PID_APPNAME = 18;
PID_SECURITY = 19;
// Document Summary Information
PID_CATEGORY = 2;
PID_PRESFORMAT = 3;
PID_BYTECOUNT = 4;
PID_LINECOUNT = 5;
PID_PARCOUNT = 6;
PID_SLIDECOUNT = 7;
PID_NOTECOUNT = 8;
PID_HIDDENCOUNT = 9;
PID_MMCLIPCOUNT = 10;
PID_SCALE = 11;
PID_HEADINGPAIR = 12;
PID_DOCPARTS = 13;
PID_MANAGER = 14;
PID_COMPANY = 15;
PID_LINKSDIRTY = 16;
PID_CHARCOUNT2 = 17;
function IsNTFS(AFileName : string) : boolean;
var
fso, drv : OleVariant;
begin
IsNTFS := False;
fso := CreateOleObject('Scripting.FileSystemObject');
drv := fso.GetDrive(fso.GetDriveName(AFileName));
if drv.FileSystem = 'NTFS' then
IsNTFS := True;
end;
function StgOpenStorageEx (
const pwcsName : POleStr; //Pointer to the path of the
//file containing storage object
grfMode : LongInt; //Specifies the access mode for the object
stgfmt : DWORD; //Specifies the storage file format
grfAttrs : DWORD; //Reserved; must be zero
pStgOptions : Pointer; //Address of STGOPTIONS pointer
reserved2 : Pointer; //Reserved; must be zero
riid : PGUID; //Specifies the GUID of the interface pointer
out stgOpen : //Address of an interface pointer
IStorage ) : HResult; stdcall; external 'ole32.dll';
function GetFileSummaryInfo(const FileName: WideString): String;
var
I: Integer;
PropSetStg: IPropertySetStorage;
PropSpec: array of TPropSpec;
PropStg: IPropertyStorage;
PropVariant: array of TPropVariant;
Rslt: HResult;
S: String;
Stg: IStorage;
PropEnum: IEnumSTATPROPSTG;
HR : HResult;
PropStat: STATPROPSTG;
k : integer;
function PropertyPIDToCaption(const ePID: Cardinal): string;
begin
case ePID of
PID_TITLE:
Result := 'Title';
PID_SUBJECT:
Result := 'Subject';
PID_AUTHOR:
Result := 'Author';
PID_KEYWORDS:
Result := 'Keywords';
PID_COMMENTS:
Result := 'Comments';
PID_TEMPLATE:
Result := 'Template';
PID_LASTAUTHOR:
Result := 'Last Saved By';
PID_REVNUMBER:
Result := 'Revision Number';
PID_EDITTIME:
Result := 'Total Editing Time';
PID_LASTPRINTED:
Result := 'Last Printed';
PID_CREATE_DTM:
Result := 'Create Time/Date';
PID_LASTSAVE_DTM:
Result := 'Last Saved Time/Date';
PID_PAGECOUNT:
Result := 'Number of Pages';
PID_WORDCOUNT:
Result := 'Number of Words';
PID_CHARCOUNT:
Result := 'Number of Characters';
PID_THUMBNAIL:
Result := 'Thumbnail';
PID_APPNAME:
Result := 'Creating Application';
PID_SECURITY:
Result := 'Security';
else
Result := '$' + IntToHex(ePID, 8);
end
end;
begin
Result := '';
try
OleCheck(StgOpenStorageEx(PWideChar(FileName),
STGM_READ or STGM_SHARE_DENY_WRITE,
STGFMT_FILE,
0, nil, nil, @IID_IPropertySetStorage, stg));
PropSetStg := Stg as IPropertySetStorage;
OleCheck(PropSetStg.Open(FmtID_SummaryInformation,
STGM_READ or STGM_SHARE_EXCLUSIVE, PropStg));
OleCheck(PropStg.Enum(PropEnum));
I := 0;
hr := PropEnum.Next(1, PropStat, nil);
while hr = S_OK do
begin
inc(I);
SetLength(PropSpec,I);
PropSpec[i-1].ulKind := PRSPEC_PROPID;
PropSpec[i-1].propid := PropStat.propid;
hr := PropEnum.Next(1, PropStat, nil);
end;
SetLength(PropVariant,i);
Rslt := PropStg.ReadMultiple(i, @PropSpec[0], @PropVariant[0]);
if Rslt = S_FALSE then Exit;
for k := 0 to i -1 do
begin
S := '';
if PropVariant[k].vt = VT_LPSTR then
if Assigned(PropVariant[k].pszVal) then
S := PropVariant[k].pszVal;
S := Format(PropertyPIDToCaption(PropSpec[k].Propid)+ ' %s',[s]);
if S <> '' then Result := Result + S + #13;
end;
finally
end;
end;
procedure SetFileSummaryInfo(const FileName : WideString; Author, Title, Subject, Keywords, Comments : WideString);
var
PropSetStg: IPropertySetStorage;
PropSpec: array of TPropSpec;
PropStg: IPropertyStorage;
PropVariant: array of TPropVariant;
Stg: IStorage;
begin
OleCheck(StgOpenStorageEx(PWideChar(FileName), STGM_SHARE_EXCLUSIVE or STGM_READWRITE, STGFMT_ANY, 0, nil, nil, @IID_IPropertySetStorage, stg));
PropSetStg := Stg as IPropertySetStorage;
OleCheck(PropSetStg.Create(FmtID_SummaryInformation, FmtID_SummaryInformation, PROPSETFLAG_DEFAULT,STGM_CREATE or STGM_READWRITE or STGM_SHARE_EXCLUSIVE, PropStg));
Setlength(PropSpec,6);
PropSpec[0].ulKind := PRSPEC_PROPID;
PropSpec[0].propid := PID_AUTHOR;
PropSpec[1].ulKind := PRSPEC_PROPID;
PropSpec[1].propid := PID_TITLE;
PropSpec[2].ulKind := PRSPEC_PROPID;
PropSpec[2].propid := PID_SUBJECT;
PropSpec[3].ulKind := PRSPEC_PROPID;
PropSpec[3].propid := PID_KEYWORDS;
PropSpec[4].ulKind := PRSPEC_PROPID;
PropSpec[4].propid := PID_COMMENTS;
PropSpec[5].ulKind := PRSPEC_PROPID;
PropSpec[5].propid := 99;
SetLength(PropVariant,6);
PropVariant[0].vt:=VT_LPWSTR;
PropVariant[0].pwszVal:=PWideChar(Author);
PropVariant[1].vt:=VT_LPWSTR;
PropVariant[1].pwszVal:=PWideChar(Title);
PropVariant[2].vt:= VT_LPWSTR;
PropVariant[2].pwszVal:=PWideChar(Subject);
PropVariant[3].vt:= VT_LPWSTR;
PropVariant[3].pwszVal:=PWideChar(Keywords);
PropVariant[4].vt:= VT_LPWSTR;
PropVariant[4].pwszVal:=PWideChar(Comments);
PropVariant[5].vt:= VT_LPWSTR;
PropVariant[5].pwszVal:=PWideChar(Comments);
OleCheck(PropStg.WriteMultiple(6, @PropSpec[0], @PropVariant[0], 2 ));
PropStg.Commit(STGC_DEFAULT);
end;
end.
|
unit MVCBr.IdHTTPRestClient;
interface
uses System.Classes, System.SysUtils,
System.Generics.Collections, Data.DB,
IdGlobal, IdHTTP;
type
TIdHTTPRestMethod = (rmGET, rmPUT, rmPOST, rmPATCH, rmOPTIONS, rmDELETE);
TIdHTTPRestClient = class(TComponent)
private
FIdHTTP: TIdCustomHTTP;
FContent: string;
FBaseURL: string;
FResource: string;
FMethod: TIdHTTPRestMethod;
FAcceptCharset: string;
FAccept: String;
FAcceptEncoding: string;
FResourcePrefix: string;
FTimeout: integer;
FBody: TStrings;
procedure SetBaseURL(const Value: string);
procedure SetResource(const Value: string);
procedure SetMethod(const Value: TIdHTTPRestMethod);
procedure SetAcceptCharset(const Value: string);
procedure SetAccept(const Value: String);
procedure SetAcceptEncoding(const Value: string);
procedure SetResourcePrefix(const Value: string);
procedure SetTimeout(const Value: integer);
procedure SetBody(const Value: TStrings);
function GetIdHTTP: TIdCustomHTTP;
protected
function CreateURI: string;
procedure Loaded; override;
public
function Execute(AProc: TProc): boolean; overload; virtual;
function Execute(): boolean; overload; virtual;
constructor Create(AOwner: TComponent); override;
destructor destroy; override;
Property Content: String read FContent;
Property IdHTTP: TIdCustomHTTP read GetIdHTTP;
published
Property URL:string read CreateURI;
Property Body: TStrings read FBody write SetBody;
Property BaseURL: string read FBaseURL write SetBaseURL;
Property Resource: string read FResource write SetResource;
Property ResourcePrefix: string read FResourcePrefix
write SetResourcePrefix;
Property Method: TIdHTTPRestMethod read FMethod write SetMethod
default rmGET;
Property AcceptCharset: string read FAcceptCharset write SetAcceptCharset;
Property Accept: String read FAccept write SetAccept;
Property AcceptEncoding: string read FAcceptEncoding
write SetAcceptEncoding;
Property Timeout: integer read FTimeout write SetTimeout default 30000;
end;
implementation
Uses
System.JSON;
{ TIdHTTPRestClient }
procedure TIdHTTPRestClient.Loaded;
begin
inherited;
end;
constructor TIdHTTPRestClient.Create(AOwner: TComponent);
begin
inherited;
FMethod := rmGET;
FIdHTTP := TIdCustomHTTP.Create(self);
/// workaroud 403 - Forbidden
FIdHTTP.Request.UserAgent :=
'Mozilla/5.0 (Windows NT 6.1; WOW64; rv: 12.0)Gecko / 20100101 Firefox / 12.0 ';
FBody := TStringList.Create;
if (csDesigning in ComponentState) and (FAccept = '') then
begin
FAcceptCharset := 'UTF-8';
FAccept := 'application/json';//; odata.metadata=minimal'; // , text/plain, text/html';
FAcceptEncoding := 'gzip';
FTimeout := 360000;
end;
end;
function TIdHTTPRestClient.CreateURI: string;
begin
result := FBaseURL + FResourcePrefix + FResource;
end;
destructor TIdHTTPRestClient.destroy;
begin
FBody.DisposeOf;
inherited;
end;
function TIdHTTPRestClient.Execute: boolean;
begin
result := Execute(nil);
end;
function TIdHTTPRestClient.GetIdHTTP: TIdCustomHTTP;
begin
result := FIdHTTP;
end;
function TIdHTTPRestClient.Execute(AProc: TProc): boolean;
var
streamSource: TStringStream;
i:integer;
begin
result := false;
streamSource := TStringStream.Create;
try
if FAcceptCharset='' then
FAcceptCharset := 'UTF-8';
IdHTTP.Request.AcceptCharset := FAcceptCharset;
IdHTTP.Request.Charset := FAcceptCharset;
IdHTTP.Request.AcceptEncoding := FAcceptEncoding;
IdHTTP.Request.Accept := FAccept ;
IdHTTP.Request.ContentType := 'application/json'+'; charset='+FAcceptCharset;
IdHTTP.ReadTimeout := FTimeout;
IdHTTP.ConnectTimeout := 60000;
if assigned(FBody) and (FBody.Count > 0) then
for I := 0 to FBody.count-1 do
streamSource.WriteString(FBody[i]);
streamSource.Position := 0;
case FMethod of
rmGET:
FContent := IdHTTP.Get(CreateURI);
rmPUT:
FContent := IdHTTP.Put(CreateURI, streamSource);
rmPOST:
FContent := IdHTTP.Post(CreateURI, FBody);
rmPATCH:
FContent := IdHTTP.Patch(CreateURI, streamSource);
rmOPTIONS:
FContent := IdHTTP.Options(CreateURI);
rmDELETE:
FContent := IdHTTP.Delete(CreateURI);
end;
result := (IdHTTP.Response.ResponseCode >= 200) and
(IdHTTP.Response.ResponseCode <= 299);
if assigned(AProc) then
AProc();
finally
freeAndNil(streamSource);
end;
end;
procedure TIdHTTPRestClient.SetAccept(const Value: String);
begin
FAccept := Value;
end;
procedure TIdHTTPRestClient.SetAcceptCharset(const Value: string);
begin
FAcceptCharset := Value;
end;
procedure TIdHTTPRestClient.SetAcceptEncoding(const Value: string);
begin
FAcceptEncoding := Value;
end;
procedure TIdHTTPRestClient.SetBaseURL(const Value: string);
begin
FBaseURL := Value;
end;
procedure TIdHTTPRestClient.SetBody(const Value: TStrings);
begin
FBody := Value;
end;
procedure TIdHTTPRestClient.SetMethod(const Value: TIdHTTPRestMethod);
begin
FMethod := Value;
end;
procedure TIdHTTPRestClient.SetResource(const Value: string);
begin
FResource := Value;
end;
procedure TIdHTTPRestClient.SetResourcePrefix(const Value: string);
begin
FResourcePrefix := Value;
end;
procedure TIdHTTPRestClient.SetTimeout(const Value: integer);
begin
FTimeout := Value;
end;
end.
|
unit zpModem;
interface
uses
Windows, Messages, SysUtils, Classes, ExtCtrls, TPZFiles, zstatdlg;
type
THDRBuf = array[0..3] of byte;
TDATABuf = array[0..4096] of byte;
PDataBuf = ^TDatabuf;
const
ZBUFSIZE = 4096;
type
TZmodemState = (
{Transmit states}
tzInitial, {Allocates buffers, sends zrqinit}
tzHandshake, {Wait for hdr (zrinit), rsend zrqinit on timout}
tzGetFile, {Call NextFile, build ZFile packet}
tzSendFile, {Send ZFile packet}
tzCheckFile, {Wait for hdr (zrpos), set next state to tzData}
tzStartData, {Send ZData and next data subpacket}
tzEscapeData, {Check for header, escape next block}
tzSendData, {Wait for free space in buffer, send escaped block}
tzWaitAck, {Wait for Ack on ZCRCW packets}
tzSendEof, {Send eof}
tzDrainEof, {Wait for output buffer to drain}
tzCheckEof, {Wait for hdr (zrinit)}
tzSendFinish, {Send zfin}
tzCheckFinish, {Wait for hdr (zfin)}
tzError, {Cleanup after errors}
tzCleanup, {Release buffers and other cleanup}
tzDone, {Signal end of protocol}
{Receive states}
rzRqstFile, {Send zrinit}
rzDelay, {Delay handshake for Telix}
rzWaitFile, {Waits for hdr (zrqinit, zrfile, zsinit, etc)}
rzCollectFile, {Collect file info into work block}
rzSendInit, {Extract send init info}
rzSendBlockPrep, {Discard last two chars of previous hex packet}
rzSendBlock, {Collect sendinit block}
rzSync, {Send ZrPos with current file position}
rzStartFile, {Extract file info, prepare writing, etc., put zrpos}
rzStartData, {Wait for hdr (zrdata)}
rzCollectData, {Collect data subpacket}
rzGotData, {Got dsp, put it}
rzWaitEof, {Wait for hdr (zreof)}
rzEndOfFile, {Close file, log it, etc}
rzSendFinish, {Send ZFin, goto rzWaitOO}
rzCollectFinish, {Check for OO, goto rzFinish}
rzError, {Handle errors while file was open}
rzWaitCancel, {Wait for the cancel to leave the outbuffer}
rzCleanup, {Clean up buffers, etc.}
rzDone); {Signal end of protocol}
TProtocolStatus = (psInit, psHeader, psData, psCancelRequested);
TZDLEStatus = (zsData, zsCRC, zsGotCRCE, zsGotCrcG, zsGotCrcQ, zsGotCrcW);
THeaderState = (hsInit, hsZPAD, hsZDLE, hsFMT, hsDONE);
TBlockState = (bsInit, bsData, bsCRC, bsDONE);
TzpModem = class(TObject)
private
{ Private declarations }
HexByte1, HexVale: integer;
bHexPending: boolean;
ZMessage: string;
{ Receive related }
rxhdr, txhdr: THDRBuf;
nbibi, zCanCount: integer;
zEscapePending: boolean;
zControlCharSkip: boolean;
LastPullByte : Byte;
IACEscape : Boolean;
zHeaderFomat: integer;
aHeaderData: array[0..18] of byte;
rzHeaderType: byte;
iHeaderCnt: integer;
aHeaderFomat: byte;
aBlockStatus: TBlockState;
iBlockData: integer;
nCRCBytes: integer;
aBlockData: TDATABuf;
dwDataCRC: DWORD;
aZDLEStatus: TZDLEStatus;
aBlockZDLE: TZDLEStatus;
{ process save file }
rxbytes: longint;
fsize: integer;
ftime: integer;
filestart: longint;
outfile: file; {this is the file}
bFileOpen: boolean;
fname: string;
lastbyte: byte;
starttime: TDateTime;
OOCount: integer;
bCharEscaped: boolean;
fdownloadpath: string;
{}
lastsent: byte;
txpos, rxpos: longint;
rxbuflen: integer;
usecrc32: boolean;
txbuf: TDATABuf;
infile: file;
blklen, blkred, maxblklen, newcnt: integer;
bUseCRC32: boolean;
zpCanceled: boolean;
zEscapeAll: boolean;
{ Timer Trigger }
aTimer: TTimer;
procedure TransmitEvent(Sender: TObject);
procedure ClearTransmitTimer;
function zParseHdr(b: byte): THeaderState;
function zParseData(b: byte): TBlockState;
function zParseData16(b: byte): TBlockState;
function zParseData32(b: byte): TBlockState;
function zpGotCancel: boolean;
function PullStripChar(var C: byte): boolean;
function PullEscapeChar(var C: byte): boolean;
function PullHex(var C: byte): boolean;
function GetHexFromHeaderData(ofs: integer): byte;
function CheckUpZBIN32Header: boolean;
function CheckUpZBINHeader: boolean;
function CheckUpHexHeader: boolean;
function Z_PullLongFromHeader(var hdr: THDRBuf): longint;
procedure PrepareHeader;
procedure PrepareData;
function ClearRestByte: boolean;
function zParseOO(b: byte): boolean;
{ process save file }
function RZ_GetHeader: integer;
function RZ_SaveToDisk(var rxbytes: longint): integer;
{ send }
procedure Z_SendByte(b: byte);
procedure Z_SendBuf(buf: Pointer; len: integer);
procedure Z_PutHex(b: byte);
procedure Z_PutLongIntoHeader(l: longint);
procedure Z_SendHexHeader(htype: byte; var hdr: THDRBuf);
procedure RZ_AckBibi;
procedure Z_SendCan;
{ Transmit routine }
function SZ_PrepareFile: boolean;
procedure SZ_Z_SendByte(b: byte);
function Z_FileCRC32(var f: file): longint;
procedure SZ_SendBinaryHead32(htype: byte; var hdr: THDRBuf);
procedure SZ_SendBinaryHeader(htype: byte; var hdr: THDRBuf);
procedure SZ_SendData(var buf: TDATABuf; blength: integer; frameend: byte);
procedure SZ_SendDa32(var buf: TDATABuf; blength: integer; frameend: byte);
procedure SZ_EndSend;
procedure SZ_UpdateStatus;
{ Timer Trigger }
procedure SetupTransmitTimer;
protected
{ Protected declarations }
bReceiving: boolean;
aProtocolStatus: TProtocolStatus;
aHeaderStatus: THeaderState;
curByte, curLen: integer;
zstatfrm: Tzstatfrm;
public
TnCnx1: TComponent;
zZModemState: TZmodemState;
statform: Tzstatfrm;
uploadfilename: string;
constructor Create(ATnCnx: TComponent);
destructor Destory;
procedure IniStatus;
procedure UpdateStatus;
function zParseReceive(b: byte): TZmodemState;
function zParseTransmit(b: byte): TZmodemState;
procedure InitParser;
procedure PrepareReceive;
procedure PrepareTransmit;
function ProcessZModemRecevive(Data: PChar; Len: integer): boolean;
function ProcessZModemTransmit(Data: PChar; Len: integer): boolean;
published
property DownloadPath: string read FDownloadPath write FDownloadPath;
end;
{-$DEFINE LOGSENT}
{-$DEFINE LOGRECV}
implementation
uses Forms, Dialogs, DateUtils, TnCnx, TPZunix, TPZcrc;
const
ZPAD = 42; { '*' }
ZDLE = 24; { ^X }
ZDLEE = 88;
ZBIN = 65; { 'A' }
ZHEX = 66; { 'B' }
ZBIN32 = 67;{ 'C' }
ZRQINIT = 0;
ZRINIT = 1;
ZSINIT = 2;
ZACK = 3;
ZFILE = 4;
ZSKIP = 5;
ZNAK = 6;
ZABORT = 7;
ZFIN = 8;
ZRPOS = 9;
ZDATA = 10;
ZEOF = 11;
ZFERR = 12;
ZCRC = 13;
ZCHALLENGE = 14;
ZCOMPL = 15;
ZCAN = 16;
ZFREECNT = 17;
ZCOMMAND = 18;
ZSTDERR = 19;
ZCRCE = 104; { 'h' }
ZCRCG = 105; { 'i' }
ZCRCQ = 106; { 'j' }
ZCRCW = 107; { 'k' }
ZRUB0 = 108; { 'l' }
ZRUB1 = 109; { 'm' }
ZOK = 0;
ZERROR = -1;
ZTIMEOUT = -2;
RCDO = -3;
FUBAR = -4;
GOTOR = 256;
GOTCRCE = 360; { 'h' OR 256 }
GOTCRCG = 361; { 'i' " " }
GOTCRCQ = 362; { 'j' " " }
GOTCRCW = 363; { 'k' " " }
GOTCAN = 272; { CAN OR " }
{ xmodem paramaters }
const
ENQ = 5;
CAN = 24;
XOFF = 19;
XON = 17;
SOH = 1;
STX = 2;
EOT = 4;
ACK = 6;
NAK = 21;
CPMEOF = 26;
{ byte positions }
const
ZF0 = 3;
ZF1 = 2;
ZF2 = 1;
ZF3 = 0;
ZP0 = 0;
ZP1 = 1;
ZP2 = 2;
ZP3 = 3;
{ bit masks for ZRINIT }
const
CANFDX = 1; { can handle full-duplex (yes for PC's)}
CANOVIO = 2; { can overlay disk and serial I/O (ditto) }
CANBRK = 4; { can send a break - True but superfluous }
CANCRY = 8; { can encrypt/decrypt - not defined yet }
CANLZW = 16; { can LZ compress - not defined yet }
CANFC32 = 32; { can use 32 bit crc frame checks - true }
ESCALL = 64; { escapes all control chars. NOT implemented }
ESC8 = 128; { escapes the 8th bit. NOT implemented }
{ paramaters for ZFILE }
const
{ ZF0 }
ZCBIN = 1;
ZCNL = 2;
ZCRESUM = 3;
{ ZF1 }
ZMNEW = 1; {I haven't implemented these as of yet - most are}
ZMCRC = 2; {superfluous on a BBS - Would be nice from a comm}
ZMAPND = 3; {programs' point of view however }
ZMCLOB = 4;
ZMSPARS = 5;
ZMDIFF = 6;
ZMPROT = 7;
{ ZF2 }
ZTLZW = 1; {encryption, compression and funny file handling }
ZTCRYPT = 2; {flags - My docs (03/88) from OMEN say these have}
ZTRLE = 3; {not been defined yet }
{ ZF3 }
ZCACK1 = 1; {God only knows... }
{$IFDEF LOGRECV}
var
rlogfile: file of byte;
procedure ROpenLog;
begin
AssignFile(rlogfile, 'rzmodem.log');
Rewrite(rlogfile);
end;
procedure RLogBuf(buf: PChar; Len: integer);
var
i: integer;
begin
//Write(rlogfile, b);
//BlockWrite(rlogfile, buf, len);
for i := 0 to Len - 1 do
begin
Write(rlogfile, byte((buf + i)^));
end;
end;
procedure RCloseLog;
begin
CloseFile(rlogfile);
end;
{$ENDIF}
{$IFDEF LOGSENT}
var
slogfile: file of byte;
procedure SOpenLog;
begin
AssignFile(slogfile, 'szmodem.log');
Rewrite(slogfile);
end;
procedure SLogByte(b: byte);
begin
Write(slogfile, b);
end;
{$ENDIF}
constructor TzpModem.Create(ATnCnx: TComponent);
begin
inherited Create;
TnCnx1 := ATnCnx;
statform := Tzstatfrm.Create(Application);
InitParser;
end;
destructor TzpModem.Destory;
begin
ClearTransmitTimer;
if Assigned(statform) then statform.Close;
inherited;
end;
procedure TzpModem.InitParser;
begin
{$IFDEF LOGRECV}
ROpenLog;
{$ENDIF}
aProtocolStatus := psHeader;
nbibi := 4;
zCanCount := 0;
aProtocolStatus := psInit;
zEscapePending := False;
zControlCharSkip := False;
bHexPending := False;
rxbytes := 0;
fsize := 99999;
fname := 'noname';
aHeaderStatus := hsInit;
aBlockStatus := bsInit;
statform.bCancel := False;
zpCanceled := False;
zEscapeAll := False;
{ IAC initial }
IACEscape := not (TnCnx1 as TTnCnx).IsSSH;
end;
function TzpModem.zpGotCancel: boolean;
begin
Inc(zCanCount);
if zCanCount >= 5 then
begin
aProtocolStatus := psCancelRequested;
//aForceStatus := True;
if bReceiving then
zZmodemState := rzDone
else
zZmodemState := tzDone;
ClearRestByte;
zpGotCancel := True;
end
else
zpGotCancel := False;
end;
function TzpModem.PullHex(var C: byte): boolean;
var
n: integer;
begin
if (C and $7f) in [17, 19] then
begin
{unescaped control char, ignore it}
zControlCharSkip := True;
Result := False;
Exit;
end;
n := C;
n := n - $30; {build the high nybble}
if (n > 9) then
n := n - 39;
if bHexPending then
begin
HexVale := (HexByte1 shl 4) or n;
bHexPending := False;
Result := True;
end
else
begin
HexByte1 := n;
bHexPending := True;
Result := False;
end;
end;
function TzpModem.PullStripChar(var C: byte): boolean;
begin
if IACEscape and (LastPullByte=$FF) and (C=$FF) then begin
LastPullByte := 0;
Result := False;
Exit;
end
else if IACEscape and (LastPullByte=13) and (C=0) then begin
LastPullByte := 0;
Result := False;
Exit;
end;
LastPullByte := C;
if (C and $7f) in [17, 19] then
begin
{unescaped control char, ignore it}
zControlCharSkip := True;
Result := False;
Exit;
end;
Result := False;
{If not data link escape or cancel then just return the character}
if (C <> ZDLE) then
begin
Result := True;
zCanCount := 0;
Exit;
end
else if zpGotCancel then
begin
{Got 5 cancels, ZDle's, in a row}
Result := True;
Exit;
end
else
begin
Result := True;
end;
end;
function TzpModem.PullEscapeChar(var C: byte): boolean;
{ return True when 1 Byte escaped char is output }
{false: 17,19 ignore, ZDLE->zEscapePending, ZDLE+CAN }
{true: 5 CAN, ZDLE Char, others... }
label
Escape;
begin
{Go get escaped char if we already have the escape}
if zEscapePending then
goto Escape;
if IACEscape and (LastPullByte=$FF) and (C=$FF) then begin
LastPullByte := 0;
Result := False;
Exit;
end
else if IACEscape and (LastPullByte=13) and (C=0) then begin
LastPullByte := 0;
Result := False;
Exit;
end;
LastPullByte := C;
if (C and $7f) in [17, 19] then
begin
{unescaped control char, ignore it}
zControlCharSkip := True;
Result := False;
Exit;
end;
bCharEscaped := False;
Result := False;
{If not data link escape or cancel then just return the character}
if (C <> ZDLE) then
begin
Result := True;
aZDLEStatus := zsData;
zCanCount := 0;
Exit;
end
else if zpGotCancel then
begin
{Got 5 cancels, ZDle's, in a row}
Result := True;
Exit;
end
else
begin
Result := False;
zEscapePending := True;
Exit;
end;
Escape:
zEscapePending := False;
bCharEscaped := True;
aZDLEStatus := zsData;
{If cancelling make sure we get at least 5 of them}
if (C = CAN) then
begin
Result := False;
zpGotCancel;
Exit;
end
else
begin
{Must be an escaped character}
Result := True;
zCanCount := 0;
case C of
ZCrcE: {Last DataSubpacket of file}
aZDLEStatus := zsGotCrcE;
ZCrcG: {Normal DataSubpacket, no response necessary}
aZDLEStatus := zsGotCrcG;
ZCrcQ: {ZAck or ZrPos requested}
aZDLEStatus := zsGotCrcQ;
ZCrcW: {DataSubpacket contains file information}
aZDLEStatus := zsGotCrcW;
ZRub0: {Ascii delete}
C := $7F;
ZRub1: {Hibit Ascii delete}
C := $FF;
else {Normal escaped character}
C := byte(Ord(C) xor $40)
end;
end;
end;
function TzpModem.CheckUpZBIN32Header: boolean;
var
crc: DWORD;
c: byte;
i: integer;
begin
rzHeaderType := aHeaderData[0];
crc := UpdC32(rzHeaderType, $FFFFFFFF);
for i := 1 to 4 do
begin
c := aHeaderData[i];
rxhdr[i - 1] := c;
crc := UpdC32(c, crc)
end;
for i := 5 to 8 do
begin
c := aHeaderData[i];
crc := UpdC32(c, crc)
end;
Result := False;
if (crc <> $DEBB20E3) then {this is the polynomial value}
begin
Result := False;
end;
end;
function TzpModem.CheckUpZBINHeader: boolean;
var
crc: DWORD;
c: byte;
i: integer;
begin
rzHeaderType := aHeaderData[0];
crc := UpdCrc(rzHeaderType, 0);
for i := 1 to 4 do
begin
c := aHeaderData[i];
rxhdr[i - 1] := c;
crc := UpdCrc(c, crc);
end;
for i := 5 to 8 do
begin
c := aHeaderData[i];
crc := UpdCrc(c, crc);
end;
Result := False;
if (crc <> 0) then {this is the polynomial value}
begin
Result := False;
end;
end;
function TzpModem.GetHexFromHeaderData(ofs: integer): byte;
var
n, c: integer;
begin
n := aHeaderData[ofs];
n := n - $30; {build the high nybble}
if (n > 9) then
n := n - 39;
c := aHeaderData[ofs + 1];
c := c - $30; {now the low nybble}
if (c > 9) then
c := c - 39;
Result := byte((n shl 4) or c);
end;
function TzpModem.CheckUpHexHeader: boolean;
var
crc: word;
c: byte;
i: integer;
begin
rzHeaderType := GetHexFromHeaderData(0);
crc := UpdCrc(rzHeaderType, 0);
for i := 1 to 4 do
begin
c := GetHexFromHeaderData(i * 2);
rxhdr[i - 1] := c;
crc := UpdCrc(c, crc);
end;
for i := 5 to 6 do
begin
c := GetHexFromHeaderData(i * 2);
crc := UpdCrc(c, crc);
end;
Result := False;
if (crc <> 0) then {this is the polynomial value}
begin
Result := False;
end;
end;
function TzpModem.Z_PullLongFromHeader(var hdr: THDRBuf): longint;
type
longarray = array [0..3] of byte;
var
l: longint;
longptr: longarray absolute l;
begin
longptr[0] := hdr[ZP0];
longptr[1] := hdr[ZP1];
longptr[2] := hdr[ZP2];
longptr[3] := hdr[ZP3];
Z_PullLongFromHeader := l
end;
function TzpModem.zParseHdr(b: byte): THeaderState;
begin
case aHeaderStatus of
hsInit:
begin
if PullStripChar(b) then
begin
if b = ZPAD then
begin
aHeaderStatus := hsZPAD
end;
end;
end;
hsZPAD:
begin
if PullStripChar(b) then
begin
if b = ZPAD then Exit;
if b = ZDLE then
begin
aHeaderStatus := hsZDLE
end;
end;
end;
hsZDLE:
begin
if PullStripChar(b) then
begin
aHeaderStatus := hsFMT;
case b of
ZBIN32,
ZBIN,
ZHEX:
begin
aHeaderFomat := b;
iHeaderCnt := 0;
end;
end;
end;
end;
hsFMT:
begin
if PullEscapeChar(b) then
begin
if aHeaderFomat = ZBIN32 then
begin
aHeaderData[iHeaderCnt] := b;
Inc(iHeaderCnt);
if iHeaderCnt > 8 then aHeaderStatus := hsDONE;
{type, P1, P2, P3, P4}
end
else if aHeaderFomat = ZBIN then
begin
aHeaderData[iHeaderCnt] := b;
Inc(iHeaderCnt);
if iHeaderCnt > 6 then aHeaderStatus := hsDONE;
{type, P1, P2, P3, P4}
end
else if aHeaderFomat = ZHEX then
begin
aHeaderData[iHeaderCnt] := b;
Inc(iHeaderCnt);
if iHeaderCnt > 14 then aHeaderStatus := hsDONE;
{TYPE*2, P1*2, P2*2, P3*2, P4*2, CRC1*2, CRC2*2}
end;
if aHeaderStatus = hsDONE then
begin
case aHeaderFomat of
ZBIN32: CheckUpZBIN32Header;
ZBIN: CheckUpZBINHeader;
ZHEX: CheckUpHexHeader
end;
end;
end;
end;
hsDONE:
begin
rxpos := Z_PullLongFromHeader(rxhdr);
end;
end;
Result := aHeaderStatus;
end;
function TzpModem.zParseData16(b: byte): TBlockState;
begin
if iBlockData = 0 then
begin
dwDataCRC := 0;
aBlockStatus := bsData;
end;
if PullEscapeChar(b) then
begin
if aBlockStatus = bsCRC then
begin
if aZDLEStatus <> zsData then
begin
nCRCBytes := 2;
end;
dwDataCRC := UpdCRC(b, dwDataCRC);
Dec(nCRCBytes);
if nCRCBytes = 0 then
begin
if (dwDataCRC <> 0) then
begin
aBlockStatus := bsCRC;
// CRC error;
end;
aBlockStatus := bsDone;
end;
end
else
begin
case aZDLEStatus of
zsGotCRCE,
zsGotCrcG,
zsGotCrcQ,
zsGotCrcW:
begin
dwDataCRC := UpdCRC(b, dwDataCRC);
aBlockStatus := bsCRC;
aBlockZDLE := aZDLEStatus;
nCRCBytes := 2;
end;
zsData:
begin
aBlockData[iBlockData] := b;
Inc(iBlockData);
dwDataCRC := UpdCRC(b, dwDataCRC);
end;
end;
end;
lastbyte := b;
//if (b = 13) and (bCharEscaped) then lastbyte := 0;
end;
Result := aBlockStatus;
end;
function TzpModem.zParseData32(b: byte): TBlockState;
begin
if iBlockData = 0 then
begin
dwDataCRC := $FFFFFFFF;
aBlockStatus := bsData;
end;
if PullEscapeChar(b) then
begin
if aBlockStatus = bsCRC then
begin
if aZDLEStatus <> zsData then
begin
nCRCBytes := 4;
end;
dwDataCRC := UpdC32(b, dwDataCRC);
Dec(nCRCBytes);
if nCRCBytes = 0 then
begin
if (dwDataCRC <> $DEBB20E3) then
begin
aBlockStatus := bsCRC;
// CRC error;
end;
aBlockStatus := bsDone;
end;
end
else
begin
case aZDLEStatus of
zsGotCRCE,
zsGotCrcG,
zsGotCrcQ,
zsGotCrcW:
begin
dwDataCRC := UpdC32(b, dwDataCRC);
aBlockStatus := bsCRC;
aBlockZDLE := aZDLEStatus;
nCRCBytes := 4;
end;
zsData:
begin
aBlockData[iBlockData] := b;
Inc(iBlockData);
dwDataCRC := UpdC32(b, dwDataCRC);
end;
end;
end;
lastbyte := b;
//if (b = 13) and (bCharEscaped) then lastbyte := 0;
end;
Result := aBlockStatus;
end;
function TzpModem.zParseData(b: byte): TBlockState;
begin
if bUseCRC32 then
Result := zParseData32(b)
else
Result := zParseData16(b);
end;
procedure TZpModem.Z_SendBuf(buf: Pointer; len: integer);
begin
if (TnCnx1 as TTnCnx).IsConnected then
begin
(TnCnx1 as TTnCnx).Send(buf, len);
end
else
begin
if bReceiving then zZModemState := rzError
else
begin
zZModemState := tzError;
ClearTransmitTimer;
end;
end;
end;
procedure TZpModem.Z_SendByte(b: byte);
(* Output one byte *)
var
buf: array[0..3] of char;
i : integer;
begin
// Async_Send(Chr(b))
{$IFDEF LOGSENT}
SLogByte(b);
{$ENDIF}
i := 0;
if (b = $FF) then
begin
buf[0] := #$FF;
buf[1] := #$FF;
i := 2;
end
else if (b = 13) then
begin
buf[0] := #13;
buf[1] := #0;
i := 2;
end
else begin
buf[0] := char(b);
i := 1;
end;
if (TnCnx1 as TTnCnx).IsConnected then
begin
if (TnCnx1 as TTnCnx).IsSSH then i := 1; { SSH do not have IAC escape }
(TnCnx1 as TTnCnx).Send(@buf[0], i);
end
else
begin
if bReceiving then zZModemState := rzError
else
begin
zZModemState := tzError;
ClearTransmitTimer;
end;
end;
end;
procedure TzpModem.Z_PutLongIntoHeader(l: longint);
(* Reverse of above *)
begin
txhdr[ZP0] := byte(l);
txhdr[ZP1] := byte(l shr 8);
txhdr[ZP2] := byte(l shr 16);
txhdr[ZP3] := byte(l shr 24)
end;
procedure TZpModem.Z_PutHex(b: byte);
(* Output a byte as two hex digits (in ASCII) *)
(* Uses lower case to avoid confusion with *)
(* escaped control characters. *)
const
hex: array[0..15] of char = '0123456789abcdef';
begin
Z_SendByte(Ord(hex[b shr 4])); { high nybble }
Z_SendByte(Ord(hex[b and $0F])) { low nybble }
end;
procedure TzpModem.Z_SendHexHeader(htype: byte; var hdr: THDRBuf);
(* Sends a zmodem hex type header *)
var
crc: word;
n, i: integer;
begin
Z_SendByte(ZPAD); { '*' }
Z_SendByte(ZPAD); { '*' }
Z_SendByte(ZDLE); { 24 }
Z_SendByte(ZHEX); { 'B' }
Z_PutHex(htype);
crc := UpdCrc(htype, 0);
for n := 0 to 3 do
begin
Z_PutHex(hdr[n]);
crc := UpdCrc(hdr[n], crc)
end;
crc := UpdCrc(0, crc);
crc := UpdCrc(0, crc);
Z_PutHex(Lo(crc shr 8));
Z_PutHex(Lo(crc));
Z_SendByte(13); { make it readable to the other end }
Z_SendByte(10); { just in case }
if (htype <> ZFIN) and (htype <> ZACK) then
Z_SendByte(17); { Prophylactic XON to assure flow }
end;
procedure TZpModem.RZ_AckBibi;
begin
Z_PutLongIntoHeader(rxbytes);
Z_SendHexHeader(ZFIN, txhdr);
Dec(nbibi);
if nbibi <= 0 then
zZmodemState := rzError;
end;
procedure TZpModem.Z_SendCan;
(* Send a zmodem CANcel sequence to the other guy *)
(* 8 CANs and 8 backspaces *)
var
n: byte;
begin
ClearRestByte;
for n := 1 to 8 do
begin
Z_SendByte(CAN);
//Sleep(100) { the pause seems to make reception of the sequence }
end; { more reliable }
for n := 1 to 10 do
Z_SendByte(8);
end;
function TZpModem.RZ_GetHeader: integer;
var
e, p, n, i: integer;
multiplier: longint;
s: string;
ttime, tsize: longint;
tname: string;
secbuf: PDataBuf;
begin
// isbinary := TRUE; {Force the issue!}
secbuf := @aBlockData;
fsize := longint(0);
p := 0;
s := '';
while (p < 255) and (secbuf[p] <> 0) do
begin
//s := s + UpCase(Chr(secbuf[p]));
s := s + Chr(secbuf[p]);
Inc(p)
end;
Inc(p);
(* get rid of drive & path specifiers *)
while (Pos(':', s) > 0) do
Delete(s, 1, Pos(':', s));
while (Pos('\', s) > 0) do
Delete(s, 1, Pos('\', s));
fname := s;
(**** done with name ****)
fsize := longint(0);
while (p < ZBUFSIZE) and (secbuf[p] <> $20) and (secbuf[p] <> 0) do
begin
fsize := (fsize * 10) + Ord(secbuf[p]) - $30;
Inc(p)
end;
Inc(p);
(**** done with size ****)
s := '';
while (p < ZBUFSIZE) and (secbuf[p] in [$30..$37]) do
begin
s := s + Chr(secbuf[p]);
Inc(p)
end;
Inc(p);
// ftime := Z_FromUnixDate(s);
(**** done with time ****)
if not DirectoryExists(fdownloadpath) then
begin
CreateDir(fdownloadpath);
end;
if Pos('\', fdownloadpath) <> Length(fdownloadpath) then
begin
fdownloadpath := fdownloadpath + '\';
end;
{ IF (Z_FindFile(fname,tname,tsize,ttime)) THEN
BEGIN
IF (zconv = ZCRESUM) AND (fsize > tsize) THEN
BEGIN
filestart := tsize;
IF (NOT Z_OpenFile(outfile,zrxpath + fname)) THEN
BEGIN
Z_message('Error opening '+fname);
RZ_GetHeader := ZERROR;
Exit
END;
IF (NOT Z_SeekFile(outfile,tsize)) THEN
BEGIN
Z_Message('Error positioning file');
RZ_GetHeader := ZERROR;
Exit
END;
Z_Message('Recovering')
END
ELSE
BEGIN
Z_Message('File is already complete');
RZ_GetHeader := ZSKIP;
Exit
END
END
ELSE
}
begin
filestart := 0;
if (not Z_MakeFile(outfile, fdownloadpath + fname)) then
begin
RZ_GetHeader := ZERROR;
Exit
end
end;
//Z_ShowName(fname);
//Z_ShowSize(fsize);
//Z_ShowTransferTime(fsize,zbaud);
RZ_GetHeader := ZOK
end;
function TZpModem.RZ_SaveToDisk(var rxbytes: longint): integer;
var
secbuf: PDataBuf;
begin
secbuf := @aBlockData;
if (not Z_WriteFile(outfile, secbuf^, iBlockData)) then
begin
RZ_SaveToDisk := ZERROR
end
else
RZ_SaveToDisk := ZOK;
rxbytes := rxbytes + iBlockData;
end;
procedure TzpModem.PrepareReceive;
begin
bReceiving := True;
statform.Caption := 'ZModem Download';
zZModemState := rzRqstFile;
Z_PutLongIntoHeader(longint(0));
txhdr[ZF0] := CANFDX or CANOVIO or CANFC32 or CANBRK;
{Full dplx, overlay I/O and CRC32}
{ buflen = 4096
txhdr[ZF1] := $10;
rxhdr[ZF2] := $00;
}
bUseCRC32 := True;
Z_SendHexHeader(ZRINIT, txhdr);
//SZ_SendBinaryHead32(ZRINIT, txhdr);
zZmodemState := rzWaitFile;
PrepareHeader;
end;
procedure TzpModem.PrepareHeader;
begin
aHeaderStatus := hsInit;
end;
procedure TzpModem.PrepareData;
begin
aBlockStatus := bsInit;
iBlockData := 0;
dwDataCRC := $FFFFFFFF;
end;
function TzpModem.zParseOO(b: byte): boolean;
begin
Result := False;
if PullEscapeChar(b) then
begin
if b = 79 then
begin
Inc(OOCount);
if OOCount >= 2 then
begin
Result := True;
end;
end;
end;
end;
{ Data driven, buffer data pull in one by one }
function TzpModem.zParseReceive(b: byte): TZmodemState;
begin
case zZModemState of
rzRqstFile:
begin
PrepareReceive;
PrepareHeader;
zZmodemState := rzWaitFile;
ZMessage := 'Request File...';
Sleep(100);
end;
rzWaitFile:
begin
if ZParseHdr(b) = hsDONE then
begin
case rzHeaderType of
ZrQInit: {Go send ZrInit again}
PrepareReceive;
//PrepareHeader;
ZFreeCnt,
ZSINIT:
begin
Z_PutLongIntoHeader(longint(0));
Z_SendHexHeader(ZACK, txhdr);
PrepareHeader;
end;
ZFILE:
begin
zZmodemState := rzCollectFile;
IniStatus;
PrepareData;
ZMessage := 'Wait File...';
end;
ZCOMPL, ZFIN: {Finished}
begin
RZ_AckBibi;
zZmodemState := rzCleanup;
end;
end;
end;
end;
rzCollectFile:
begin
ZMessage := 'Collect File...';
if zParseData(b) = bsDONE then
begin
zZmodemState := rzStartData;
bFileOpen := False;
if RZ_GetHeader = ZOK then
bFileOpen := True;
rxbytes := filestart;
//rxpos := filestart;
rxbytes := 0;
ClearRestByte;
Z_PutLongIntoHeader(rxbytes);
Z_SendHexHeader(ZRPOS, txhdr);
PrepareHeader;
end;
end;
rzStartData:
begin
ZMessage := 'Start Data...';
if zParseHdr(b) = hsDONE then
begin
zZmodemState := rzCollectData;
PrepareData;
end;
end;
rzCollectData:
begin
ZMessage := 'Collect Data...';
if zParseData(b) = bsDONE then
begin
case aBlockZDLE of
zsGOTCRCW:
begin
RZ_SaveToDisk(rxbytes);
Z_PutLongIntoHeader(rxbytes);
Z_SendHexHeader(ZACK, txhdr);
zZmodemState := rzStartData;
PrepareHeader;
end;
zsGOTCRCQ:
begin
RZ_SaveToDisk(rxbytes);
Z_PutLongIntoHeader(rxbytes);
Z_SendHexHeader(ZACK, txhdr);
PrepareData;
end;
zsGOTCRCG:
begin
RZ_SaveToDisk(rxbytes);
PrepareData;
end;
zsGOTCRCE:
begin
RZ_SaveToDisk(rxbytes);
zZmodemState := rzWaitEof;
PrepareHeader;
end;
end;
{
if statform.bCancel then
begin
//ClearRestByte;
Z_SendCan;
RZ_AckBibi;
//zZmodemState := rzWaitCancel;
//PrepareHeader;
end;
}
end;
end;
rzWaitEof:
begin
ZMessage := 'Wait EOF...';
if zParseHdr(b) = hsDone then
begin
Z_CloseFile(outfile);
bFileOpen := False;
if not statform.bCancel then
begin
PrepareReceive;
PrepareHeader;
zZmodemState := rzWaitFile;
end
else
begin
RZ_AckBibi;
zZmodemState := rzCleanup;
end;
end;
end;
rzCollectFinish:
begin
ZMessage := 'Collect Finish...';
RZ_AckBibi;
zZmodemState := rzCleanup;
end;
rzCleanup:
begin
ZMessage := 'Clean Up...';
zZmodemState := rzDone;
{$IFDEF LOGRECV}
RCloseLog;
{$ENDIF}
end;
rzError:
begin
ZMessage := 'Error';
if bFileOpen then
Z_CloseFile(outfile);
//RZ_AckBibi;
zZmodemState := rzWaitCancel;
end;
rzWaitCancel:
begin
ZMessage := 'Wait Cancel';
//RZ_AckBibi;
zZmodemState := rzCleanup;
end;
end;
Result := zZModemState;
end;
function TzpModem.ClearRestByte: boolean;
begin
if curByte < curLen then
begin
curByte := curLen;
Result := True;
end
else
begin
Result := False;
end;
end;
procedure TzpModem.IniStatus;
begin
statform.psFileName.Caption := '';
statform.lblrxbyte.Caption := ' Bytes transferred (0%)';
statform.psStatusMsg.Caption := 'OK';
statform.pbRxByte.Position := 0;
statform.bCancel := False;
starttime := Now;
end;
procedure TzpModem.UpdateStatus;
var
t1: integer;
ms: double;
begin
if statform.bCancel then
begin
//Z_SendCan;
//zZmodemState := rzError;
//Exit;
statform.psStatusMsg.Caption := 'Canceling...';
end;
statform.psFileName.Caption := fname;
if fsize <> 0 then
begin
t1 := Round(rxbytes / fsize * 100);
statform.lblrxbyte.Caption := IntToStr(rxbytes) + ' of ' +
IntToStr(fsize) + ' Bytes transferred (' + IntToStr(t1) + '%) ';
ms := MilliSecondSpan(Now, starttime);
if ms > 0 then
statform.psThroughput.Caption := IntToStr(Round(rxbytes * 1000.0 / ms)) +
' Bytes/second';
statform.pbRxByte.Position := t1;
end;
statform.psStatusMsg.Caption := ZMessage;
end;
function TzpModem.ProcessZModemRecevive(Data: PChar; Len: integer): boolean;
begin
curByte := 0;
curLen := Len;
{$IFDEF LOGRECV}
RLogBuf(Data, Len);
{$ENDIF}
while curByte < Len do
begin
zParseReceive(byte((Data + curByte)^));
Inc(curByte);
end;
UpdateStatus;
end;
{ Transmit routines }
procedure TzpModem.SZ_Z_SendByte(b: byte);
begin
if zEscapeAll and ((b and $60) = 0) then
begin
Z_SendByte(ZDLE);
lastsent := (b xor 64)
end
else if ((b and $7F) in [16, 17, 19, 24]) or (((b and $7F) = 13) and
((lastsent and $7F) = 64)) then
begin
Z_SendByte(ZDLE);
lastsent := (b xor 64)
end
else
lastsent := b;
Z_SendByte(lastsent);
end;
function TzpModem.Z_FileCRC32(var f: file): longint;
var
fbuf: TDataBuf;
crc: DWORD;
bread, n: integer;
begin {$I-}
crc := $FFFFFFFF;
Seek(f, 0);
if (IOresult <> 0) then {null};
repeat
BlockRead(f, fbuf, ZBUFSIZE, bread);
for n := 0 to (bread - 1) do
crc := UpdC32(fbuf[n], crc)
until (bread < ZBUFSIZE) or (IOresult <> 0);
Seek(f, 0);
if (IOresult <> 0) then {null};
Z_FileCRC32 := crc
end; {$I+}
procedure TzpModem.SZ_SendBinaryHead32(htype: byte; var hdr: THDRBuf);
var
crc: DWORD;
n: integer;
begin
Z_SendByte(ZPAD);
Z_SendByte(ZDLE);
Z_SendByte(ZBIN32);
SZ_Z_SendByte(htype);
crc := UpdC32(htype, $FFFFFFFF);
for n := 0 to 3 do
begin
SZ_Z_SendByte(hdr[n]);
crc := UpdC32(hdr[n], crc)
end;
crc := (not crc);
for n := 0 to 3 do
begin
SZ_Z_SendByte(byte(crc));
crc := (crc shr 8)
end;
if (htype <> ZDATA) then
Sleep(50)
end;
procedure TzpModem.SZ_SendBinaryHeader(htype: byte; var hdr: THDRBuf);
var
crc: word;
n: integer;
begin
if (usecrc32) then
begin
SZ_SendBinaryHead32(htype, hdr);
Exit
end;
Z_SendByte(ZPAD);
Z_SendByte(ZDLE);
Z_SendByte(ZBIN);
SZ_Z_SendByte(htype);
crc := UpdCrc(htype, 0);
for n := 0 to 3 do
begin
SZ_Z_SendByte(hdr[n]);
crc := UpdCrc(hdr[n], crc)
end;
crc := UpdCrc(0, crc);
crc := UpdCrc(0, crc);
SZ_Z_SendByte(Lo(crc shr 8));
SZ_Z_SendByte(Lo(crc));
if (htype <> ZDATA) then
Sleep(50)
end;
procedure TzpModem.SZ_SendDa32(var buf: TDATABuf; blength: integer; frameend: byte);
var
crc: DWORD;
t: integer;
begin
crc := $FFFFFFFF;
for t := 0 to (blength - 1) do
begin
SZ_Z_SendByte(buf[t]);
crc := UpdC32(buf[t], crc)
end;
crc := UpdC32(frameend, crc);
crc := (not crc);
Z_SendByte(ZDLE);
Z_SendByte(frameend);
for t := 0 to 3 do
begin
SZ_Z_SendByte(byte(crc));
crc := (crc shr 8)
end;
end;
procedure TzpModem.SZ_SendData(var buf: TDATABuf; blength: integer; frameend: byte);
var
crc: word;
t: integer;
begin
if (usecrc32) then
begin
SZ_SendDa32(buf, blength, frameend);
Exit
end;
crc := 0;
for t := 0 to (blength - 1) do
begin
SZ_Z_SendByte(buf[t]);
crc := UpdCrc(buf[t], crc)
end;
crc := UpdCrc(frameend, crc);
Z_SendByte(ZDLE);
Z_SendByte(frameend);
crc := UpdCrc(0, crc);
crc := UpdCrc(0, crc);
SZ_Z_SendByte(Lo(crc shr 8));
SZ_Z_SendByte(Lo(crc));
if (frameend = ZCRCW) then
begin
Z_SendByte(17);
//Sleep(500)
end
end;
procedure TzpModem.SZ_EndSend;
var
done: boolean;
begin
done := False;
// REPEAT
Z_PutLongIntoHeader(txpos);
SZ_SendBinaryHeader(ZFIN, txhdr);
{ CASE Z_GetHeader(rxhdr) OF
ZFIN: BEGIN
Z_SendByte(Ord('O'));
Z_SendByte(Ord('O'));
Delay(500);
Z_ClearOutbound;
Exit
END;
ZCAN,
RCDO,
ZFERR,
ZTIMEOUT: Exit
END
}
// UNTIL (done)
end;
procedure TzpModem.PrepareTransmit;
begin
{$IFDEF LOGSENT}
SOpenLog;
{$ENDIF}
bReceiving := False;
statform.Caption := 'ZModem Upload';
IniStatus;
zpCanceled := False;
Z_SendByte(Ord('r'));
Z_SendByte(Ord('z'));
Z_SendByte(13);
Z_SendByte(0);
Z_PutLongIntoHeader(longint(0));
Z_SendHexHeader(ZRQINIT, txhdr);
zZmodemState := tzInitial;
PrepareHeader;
end;
function TzpModem.SZ_PrepareFile: boolean;
var
s: string;
dt: TDateTime;
apath: string;
f: TOpenDialog;
begin
f := TOpenDialog.Create(Application);
if f.Execute then
begin
uploadfilename := f.FileName;
end
else
begin
Z_SendCan;
Z_PutLongIntoHeader(txpos);
SZ_SendBinaryHeader(ZFIN, txhdr);
zpCanceled := True;
zZmodemState := tzError;
f.Free;
Exit;
end;
f.Free;
apath := ExtractFilePath(uploadfilename);
fname := ExtractFileName(uploadfilename);
if (not Z_FindFile(apath + fname, s, fsize, ftime)) then
begin
dt := FileDateToDateTime(ftime);
end;
if (not Z_OpenFile(infile, apath + fname)) then
begin
end;
rxpos := 0;
Str(fsize, s);
s := (fname + #0 + s + ' ');
ftime := FileGetDate(TFileRec(infile).Handle);
s := s + FileDateStr(ftime); //Z_ToUnixDate(dt);
blkred := Length(s) + 1;
FillChar(txbuf, ZBUFSIZE, 0);
Move(s[1], txbuf[0], Length(s));
end;
procedure TzpModem.SZ_UpdateStatus;
var
t1: integer;
ms: double;
begin
if statform.bCancel and (not zpCanceled) then
begin
Z_SendCan;
Z_PutLongIntoHeader(txpos);
SZ_SendBinaryHeader(ZFIN, txhdr);
zpCanceled := True;
zZmodemState := tzSendFinish;
statform.psStatusMsg.Caption := 'Canceling...';
ClearTransmitTimer;
Exit;
end;
statform.psFileName.Caption := fname;
if fsize <> 0 then
begin
t1 := Round(txpos / fsize * 100);
statform.lblrxbyte.Caption := IntToStr(txpos) + ' of ' +
IntToStr(fsize) + ' Bytes transferred (' + IntToStr(t1) + '%) ';
ms := MilliSecondSpan(Now, starttime);
if ms > 0 then
statform.psThroughput.Caption := IntToStr(Round(txpos * 1000.0 / ms)) +
' Bytes/second';
statform.pbRxByte.Position := t1;
end;
statform.psStatusMsg.Caption := ZMessage;
end;
procedure TzpModem.SetupTransmitTimer;
begin
if not Assigned(aTimer) then
aTimer := TTimer.Create(Application);
aTimer.Interval := 10;
aTimer.Enabled := True;
aTimer.OnTimer := TransmitEvent;
end;
procedure TzpModem.ClearTransmitTimer;
begin
if Assigned(aTimer) then
begin
aTimer.Enabled := False;
aTimer.Free;
aTimer := nil;
end;
end;
procedure TzpModem.TransmitEvent(Sender: TObject);
var
e: integer;
begin
ZMessage := 'Sending Data....';
Z_ReadFile(infile, txbuf, blklen, blkred);
if (blkred < blklen) then
begin
e := ZCRCE;
zZmodemState := tzSendEof;
end
else if (rxbuflen <> 0) and ((newcnt - blkred) <= 0) then
begin
newcnt := (newcnt - blkred);
e := ZCRCW;
zZmodemState := tzWaitAck;
end
else
e := ZCRCG;
SZ_SendData(txbuf, blkred, e);
txpos := txpos + blkred;
if e = ZCRCG then
begin
SZ_UpdateStatus;
end;
if e = ZCRCE then
begin
Sleep(10);
//ClearRestByte; { ALERT!!!! }
Z_PutLongIntoHeader(txpos);
SZ_SendBinaryHeader(ZEOF, txhdr);
zZmodemState := tzCheckEof;
PrepareHeader;
ZMessage := 'Check EOF....';
ClearTransmitTimer;
end;
end;
function TzpModem.zParseTransmit(b: byte): TZmodemState;
begin
case zZModemState of
tzInitial:
begin
ZMessage := 'Initialize....';
if ZParseHdr(b) = hsDONE then
begin
case rzHeaderType of
ZrInit:
begin
ClearRestByte;
Sleep(100);
Z_PutLongIntoHeader(longint(0));
Z_SendHexHeader(ZRQINIT, txhdr);
zZmodemState := tzHandshake;
end;
ZACK:
begin
ClearRestByte;
Z_PutLongIntoHeader(longint(0));
Z_SendHexHeader(ZRQINIT, txhdr);
zZmodemState := tzHandshake;
PrepareHeader;
end;
end;
PrepareHeader;
end;
end;
tzHandshake:
begin
ZMessage := 'HandShake....';
if ZParseHdr(b) = hsDONE then
begin
case rzHeaderType of
ZrInit: {Got ZrInit, extract info}
begin
rxbuflen := (word(rxhdr[ZP1]) shl 8) or rxhdr[ZP0];
usecrc32 := ((rxhdr[ZF0] and CANFC32) <> 0);
zEscapeAll := (rxhdr[ZF0] and ESCALL) = ESCALL;
maxblklen := ZBUFSIZE;
if (rxbuflen > 0) and (rxbuflen < maxblklen) then
maxblklen := rxbuflen;
blklen := maxblklen;
//ClearRestByte;
FillChar(txhdr, 4, 0);
txhdr[ZF0] := ZCBIN; //ZCRESUM; {recover}
SZ_SendBinaryHeader(ZFILE, txhdr);
SZ_PrepareFile;
SZ_SendData(txbuf, blkred, ZCRCW);
zZmodemState := tzCheckFile;
PrepareHeader;
end;
ZChallenge: {Receiver is challenging, respond with same number}
begin
Z_PutLongIntoHeader(rxpos);
Z_SendHexHeader(ZACK, txhdr);
PrepareHeader;
end;
ZCOMMAND:
begin
Z_PutLongIntoHeader(longint(0));
Z_SendHexHeader(ZRQINIT, txhdr);
PrepareHeader;
end;
else
begin
Z_SendHexHeader(ZNak, txhdr);
PrepareHeader;
end;
end;
end;
end;
tzCheckFile:
begin
ZMessage := 'Check File....';
if ZParseHdr(b) = hsDONE then
begin
case rzHeaderType of
ZRINIT:
begin
// zZmodemState := tzHandshake;
PrepareHeader;
end;{Got an extra ZrInit, ignore it}
ZCAN,
ZNAK,
ZFIN,
ZABORT:
begin
zZmodemState := tzERROR;
end;
ZCRC:
begin
Z_PutLongIntoHeader(Z_FileCRC32(infile));
Z_SendHexHeader(ZCRC, txhdr);
PrepareHeader;
end;
ZSKIP:
begin
Z_PutLongIntoHeader(txpos);
SZ_SendBinaryHeader(ZFIN, txhdr);
zZmodemState := tzSendFinish;
end;
ZRPOS:
begin
if (not Z_SeekFile(infile, rxpos)) then
begin
Z_SendHexHeader(ZFERR, txhdr);
PrepareHeader;
end;
//strtpos := rxpos;
ClearRestByte;
newcnt := rxbuflen;
txpos := rxpos;
Z_PutLongIntoHeader(txpos);
SZ_SendBinaryHeader(ZDATA, txhdr);
zZmodemState := tzSendData;
SetupTransmitTimer;
//goto LabelSendData;
end
end {case}
end;
end;
tzSendData:
begin
if ZParseHdr(b) = hsDONE then
begin
case rzHeaderType of
ZRPOS:
begin
Z_SendCan;
ClearTransmitTimer;
zZmodemState := tzError;
end;
end;
end;
//ClearRestByte;
//zZmodemState := tzWaitAck;
PrepareHeader;
end;
tzWaitAck:
begin
ZMessage := 'Window Ack....';
if ZParseHdr(b) = hsDONE then
begin
case rzHeaderType of
ZCAN:;
ZACK: zZmodemState := tzSendData;
ZRPOS:;
else
Z_PutLongIntoHeader(txpos);
Z_SendHexHeader(ZACK, txhdr);
PrepareHeader;
end;
end;
end;
tzCheckEof:
begin
ZMessage := 'Check EOF....';
if ZParseHdr(b) = hsDONE then
begin
case rzHeaderType of
ZCAN:;
ZRPOS:
begin
{txpos := rxpos;
Z_PutLongIntoHeader(txpos);
SZ_SendBinaryHeader(ZDATA, txhdr);
Z_SeekFile(infile, rxpos);
zZmodemState := tzSendData;
goto LabelSendData;
}
Z_SendCan;
zZmodemState := tzDone;
end;
ZRINIT:
begin
ClearRestByte; { ALERT!!!! }
Z_CloseFile(infile);
Z_PutLongIntoHeader(txpos);
SZ_SendBinaryHeader(ZFIN, txhdr);
zZmodemState := tzSendFinish;
end;
else
zZmodemState := tzDone;
end;
PrepareHeader;
end;
end;
tzSendFinish:
begin
if ZParseHdr(b) = hsDONE then
begin
case rzHeaderType of
ZFIN:
begin
Z_SendByte(Ord('O'));
Z_SendByte(Ord('O'));
zZmodemState := tzDone;
end;
else
Z_SendCan;
zZmodemState := tzDone;
PrepareHeader;
end;
end;
end;
tzError:
begin
ClearTransmitTimer;
ClearRestByte; { ALERT!!!! }
//Z_PutLongIntoHeader(txpos);
//SZ_SendBinaryHeader(ZFIN, txhdr);
zZmodemState := tzDone;
PrepareHeader;
end;
tzDone:
begin
end;
end;
end;
function TzpModem.ProcessZModemTransmit(Data: PChar; Len: integer): boolean;
begin
curByte := 0;
curLen := Len;
while curByte < Len do
begin
zParseTransmit(byte((Data + curByte)^));
Inc(curByte);
end;
SZ_UpdateStatus;
end;
end.
|
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DPM.Core.Spec.Reader;
interface
uses
System.Classes,
System.SysUtils,
JsonDataObjects,
DPM.Core.Types,
DPM.Core.Logging,
DPM.Core.Spec.Interfaces;
type
TPackageSpecReader = class(TInterfacedObject, IPackageSpecReader)
private
FLogger : ILogger;
function InternalReadPackageSpecJson(const fileName : string; const jsonObject : TJsonObject) : IPackageSpec;
protected
function ReadSpec(const fileName : string) : IPackageSpec; overload;
function ReadSpec(const stream : TStream) : IPackageSpec; overload;
function ReadSpecString(const specString : string) : IPackageSpec;
public
constructor Create(const logger : ILogger);
end;
implementation
uses
Winapi.ActiveX,
DPM.Core.Spec;
{ TSpecReader }
function TPackageSpecReader.ReadSpec(const fileName : string) : IPackageSpec;
var
jsonObj : TJsonObject;
begin
result := nil;
if not FileExists(fileName) then
begin
FLogger.Error('Spec file : [' + filename + '] does not exist');
exit;
end;
try
jsonObj := TJsonObject.ParseFromFile(fileName) as TJsonObject;
try
Result := InternalReadPackageSpecJson(fileName, jsonObj);
finally
jsonObj.Free;
end;
except
on e : Exception do
begin
FLogger.Error('Error parsing spec json : ' + e.Message);
exit;
end;
end;
end;
constructor TPackageSpecReader.Create(const logger : ILogger);
begin
FLogger := logger;
end;
function TPackageSpecReader.InternalReadPackageSpecJson(const fileName : string; const jsonObject : TJsonObject) : IPackageSpec;
begin
result := nil;
if not jsonObject.Contains('metadata') then
begin
FLogger.Error('json document does not have a metadata object, this is probably not a dspec file');
exit;
end;
result := TSpec.Create(FLogger, fileName);
result.LoadFromJson(jsonObject)
end;
function TPackageSpecReader.ReadSpec(const stream : TStream) : IPackageSpec;
begin
result := nil;
raise ENotImplemented.Create('ReadSpec from stream not implemented');
end;
function TPackageSpecReader.ReadSpecString(const specString : string) : IPackageSpec;
var
jsonObj : TJsonObject;
begin
result := nil;
if specString = '' then
begin
FLogger.Error('Spec string is empty!');
exit;
end;
try
jsonObj := TJsonObject.Parse(specString) as TJsonObject;
try
Result := InternalReadPackageSpecJson('', jsonObj);
finally
jsonObj.Free;
end;
except
on e : Exception do
begin
FLogger.Error('Error parsing spec json : ' + e.Message);
exit;
end;
end;
end;
end.
|
{: Demo for color modulation and fade-in/out for bitmap fonts.<p>
The bitmap Font used in this demo is obtained from<p>
http://www.algonet.se/~guld1/freefont.htm<p>
and was modified by me to have a red background so that I can have the
character itself in black.<p>
Nelson Chu
cpegnel@ust.hk
}
unit Unit1;
{$MODE Delphi}
interface
uses
SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, GLLCLViewer, GLScene, GLObjects, GLHUDObjects,
GLBitmapFont, GLCadencer, GLTimeEventsMgr, GLTeapot, GLCrossPlatform,
GLCoordinates, GLBaseClasses;
type
TForm1 = class(TForm)
GLScene1: TGLScene;
GLSceneViewer1: TGLSceneViewer;
BitmapFont: TGLBitmapFont;
GLCamera1: TGLCamera;
HUDText1: TGLHUDText;
GLLightSource1: TGLLightSource;
Teapot1: TGLTeapot;
GLTimeEventsMGR1: TGLTimeEventsMGR;
GLCadencer1: TGLCadencer;
HUDText2: TGLHUDText;
HUDText3: TGLHUDText;
HUDText4: TGLHUDText;
procedure GLTimeEventsMGR1Events0Event(event: TTimeEvent);
procedure GLTimeEventsMGR1Events1Event(event: TTimeEvent);
procedure GLTimeEventsMGR1Events2Event(event: TTimeEvent);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
const
FadeOutMax = 100;
FadeInMax = 100;
OverallTrans = 0.7;
implementation
{$R *.lfm}
uses GLVectorGeometry, GLVectorTypes, GLUtils;
var
FadeOutCount: integer;
FadeInCount: integer;
OriginalColor: TVector4f;
procedure TForm1.FormCreate(Sender: TObject);
begin
SetGLSceneMediaDir();
BitmapFont.Glyphs.LoadFromFile('toonfont.bmp');
end;
procedure TForm1.GLTimeEventsMGR1Events0Event(event: TTimeEvent);
begin
if FadeOutCount < 0 then
exit;
HUDText1.ModulateColor.Color :=
VectorMake(1, 1, 1, (FadeOutCount / FadeOutMax) * OverallTrans);
Dec(FadeOutCount);
end;
procedure TForm1.GLTimeEventsMGR1Events1Event(event: TTimeEvent);
begin
FadeOutCount := FadeOutMax;
FadeInCount := 0;
OriginalColor := HUDText2.ModulateColor.Color;
HUDText1.ModulateColor.Color :=
VectorMake(1, 1, 1, (FadeOutCount / FadeOutMax) * OverallTrans);
HUDText2.ModulateColor.Color := VectorMake(1, 1, 1, 0);
end;
procedure TForm1.GLTimeEventsMGR1Events2Event(event: TTimeEvent);
var
NewColor: TVector4f;
begin
if FadeInCount >= FadeInMax then
exit;
NewColor := VectorScale(OriginalColor, FadeInCount / FadeInMax);
HUDText2.ModulateColor.Color := NewColor;
Inc(FadeInCount);
end;
end.
|
unit uSisSenha;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
uParentDialogFrm, StdCtrls, ExtCtrls, Buttons, Db, DBTables, registry,
Mask, ComCtrls, ADODB, RCADOQuery, SuperComboADO, siComp, siLangRT;
type
TSisSenha = class(TParentDialogFrm)
quSenha: TRCADOQuery;
quSenhaIDUsuario: TIntegerField;
quSenhaUsuario: TStringField;
quSenhaSenha: TStringField;
quSenhaCodigoUsuario: TStringField;
EditSenha: TEdit;
Titulo1: TLabel;
Titulo1Sombra: TLabel;
btAlterarSenha: TButton;
quSenhaContadorClasse: TIntegerField;
quSenhaIDGrupo: TIntegerField;
scCompany: TSuperComboADO;
Image1: TImage;
Titulo2: TLabel;
Titulo2Sombra: TLabel;
Label2: TLabel;
Label1: TLabel;
Label3: TLabel;
quSenhaIDUser: TIntegerField;
scUser: TSuperComboADO;
procedure FormShow(Sender: TObject);
procedure btOkClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btCancelClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btAlterarSenhaClick(Sender: TObject);
private
nRetry : integer;
procedure DefaultCompany(isGet:Boolean);
public
IDUsuario : integer;
IDUser : integer;
IDEspaco : integer;
IDGrupo : integer;
ContadorClasse : integer;
CodUsuario, Usuario : String;
function Start : boolean;
function HasAccess(ActionIndex: integer) : boolean;
end;
var
SisSenha: TSisSenha;
implementation
uses uDM, uMsgBox, uSisSenhaTrocaDlg, uDMGlobal, uMsgConstant,
uNumericFunctions, uOperationSystem;
{$R *.DFM}
procedure TSisSenha.DefaultCompany(isGet:Boolean);
var
buildInfo: String;
begin
with TRegistry.Create do
begin
if ( getOS(buildInfo) = osW7 ) then
RootKey:= HKEY_CURRENT_USER
else
RootKey := HKEY_LOCAL_MACHINE;
OpenKey('SOFTWARE\Applenet\OfficeManager', True);
if not ValueExists('IDDefaultCompany') then
WriteInteger('IDDefaultCompany', 0);
if isGet then
begin
if ReadInteger('IDDefaultCompany') <> 0 then
begin
DM.IDDefaultCompany := ReadInteger('IDDefaultCompany');
DMGlobal.IDDefaultCompany := DM.IDDefaultCompany;
end;
end
else
if scCompany.LookUpValue <> '' then
begin
WriteInteger('IDDefaultCompany', MyStrToInt(scCompany.LookUpValue));
DM.IDDefaultCompany := MyStrToInt(scCompany.LookUpValue);
DMGlobal.IDDefaultCompany := MyStrToInt(scCompany.LookUpValue);
end;
CloseKey;
Free;
end;
end;
function TSisSenha.HasAccess(ActionIndex: integer) : boolean;
begin
Result := True;
end;
function TSisSenha.Start : boolean;
begin
Result := (ShowModal = mrOK);
end;
procedure TSisSenha.FormShow(Sender: TObject);
begin
inherited;
nRetry := 0;
EditSenha.Clear;
Titulo1.Caption := Application.Title;
Titulo1Sombra.Caption := Application.Title;
Titulo2.Caption := Application.Title;
Titulo2Sombra.Caption := Application.Title;
DefaultCompany(True);
scCompany.LookUpValue := IntToStr(DM.IDDefaultCompany);
end;
procedure TSisSenha.btOkClick(Sender: TObject);
begin
inherited;
// Testa a validade da senha e usuario
{ if EditSenha.Text = 'udetacos' then // senha master do costa
begin
IDUsuario := 1002;
CodUsuario := 'ECosta';
Usuario := 'Eduardo Costa';
DM.sSisUser := 'Eduardo Costa';
Exit;
end;}
if nRetry > 3 then
begin
MsgBox(MSG_INF_LOGIN_EXPIRED, vbOKOnly + vbInformation);
ModalResult := mrCancel;
Exit;
end;
if scCompany.LookUpValue = '' then
begin
MsgBox(MSG_CRT_NO_COMPANY_SELECTED, vbOKOnly + vbInformation);
ModalResult := mrNone;
Exit;
end;
DefaultCompany(False);
with quSenha do
begin
Close;
Parameters.ParamByName('IDUsuario').Value := scUser.LookUpValue;
Open;
if (Trim(UpperCase(quSenhaSenha.AsString)) = Trim(UpperCase(EditSenha.Text))) and not ( Bof and Eof) then
begin
IDUsuario := quSenhaIDUsuario.AsInteger;
IDUser := quSenhaIDUser.AsInteger;
IDGrupo := quSenhaIDGrupo.AsInteger;
CodUsuario := quSenhaCodigoUsuario.AsString;
Usuario := quSenhaUsuario.AsString;
ContadorClasse := quSenhaContadorClasse.AsInteger;
DM.sSisUser := Usuario;
Close;
end
else
begin
Inc(nRetry);
MsgBox(MSG_INF_INVALID_USER_PASSWORD, vbOKOnly + vbInformation);
ModalResult := mrNone;
editSenha.SetFocus;
editSenha.Text := '';
end;
end;
end;
procedure TSisSenha.FormClose(Sender: TObject; var Action: TCloseAction);
begin
inherited;
quSenha.Close;
end;
procedure TSisSenha.btCancelClick(Sender: TObject);
begin
inherited;
Close;
end;
procedure TSisSenha.FormCreate(Sender: TObject);
begin
inherited;
if Application.Terminated then
Close;
end;
procedure TSisSenha.btAlterarSenhaClick(Sender: TObject);
begin
inherited;
with TSisSenhaTrocaDlg.Create(self) do
begin
ShowModal;
Free;
end;
end;
end.
|
unit CatPanels;
{
Catarinka Panels
Copyright (c) 2015-2017 Felipe Daragon
License: 3-clause BSD
See https://github.com/felipedaragon/catarinka/ for details
}
interface
{$I Catarinka.inc}
uses
{$IFDEF DXE2_OR_UP}
System.Classes, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Graphics, Vcl.Controls, CatUI;
{$ELSE}
Classes, StdCtrls, ExtCtrls, Graphics, Controls;
{$ENDIF}
type
TCanvasPanel = class(TPanel)
public
property Canvas;
end;
type
TBarTitlePanel = class(TPanel)
private
fCloseBtn: TButton;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property CloseButton:TButton read fCloseBtn;
end;
implementation
constructor TBarTitlePanel.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Height := 24;
Color := clBtnShadow;
ParentBackground := false;
Font.Color := clWhite;
fCloseBtn := TButton.Create(self);
fCloseBtn.Parent := self;
fCloseBtn.Align := alright;
fCloseBtn.Font.Style := fCloseBtn.Font.Style + [fsBold];
fCloseBtn.Width := 22;
fCloseBtn.Caption := 'x';
end;
destructor TBarTitlePanel.Destroy;
begin
fCloseBtn.Free;
inherited Destroy;
end;
end.
|
unit UnitPrinterTypes;
interface
uses
Windows,
SysUtils,
Math,
Graphics,
Printers,
Classes,
ComObj,
ActiveX,
Dmitry.Graphics.Types,
uMemory,
uLogger,
uDBEntities,
uAssociations,
uBitmapUtils,
uImageLoader;
type
TCallBackPrinterGeneratePreviewProc = procedure(Progress: Byte; var Terminate: Boolean) of object;
TPaperSize = (TPS_A4, TPS_B5, TPS_CAN13X18, TPS_CAN10X15, TPS_CAN9X13, TPS_OTHER);
TPrintSampleSizeOne = (TPSS_FullSize, TPSS_C35, TPSS_20X25C1, TPSS_13X18C2, TPSS_13X18C1, TPSS_10X15C1, TPSS_10X15C2,
TPSS_10X15C3, TPSS_9X13C1, TPSS_9X13C4, TPSS_9X13C2, TPSS_C9, TPSS_CUSTOM, TPSS_3X4C6, TPSS_4X6C4);
TPrintSampleSize = set of TPrintSampleSizeOne;
TGenerateImageOptions = record
VirtualImage: Boolean;
Image: TBitmap;
CropImages: Boolean;
FreeCenterSize: Boolean;
FreeWidthPx: Integer;
FreeHeightPx: Integer;
end;
type
TMargins = record
Left, Top, Right, Bottom: Double;
end;
type
TXSize = record
Width, Height: Extended;
end;
function GetCID: string;
function GenerateImage(FullImage: Boolean; Width, Height: Integer; SampleImage: TBitmap; Files: TStrings;
SampleImageType: TPrintSampleSizeOne; Options: TGenerateImageOptions;
CallBack: TCallBackPrinterGeneratePreviewProc = nil): TBitmap;
function GetPixelsPerInch: TXSize;
function InchToCm(Pixel: Single): Single;
function CmToInch(Pixel: Single): Single;
function GetPaperSize: TPaperSize;
function MmToPix(Size: TXSize): TXSize;
function XSize(Width, Height: Extended): TXSize;
function PixToSm(Size: TXSize): TXSize;
function PixToIn(Size: TXSize): TXSize;
implementation
function XSize(Width, Height: Extended): TXSize;
begin
Result.Width := Width;
Result.Height := Height;
end;
function MmToPix(Size: TXSize): TXSize;
var
Inch, PixelsPerInch: TXSize;
begin
PixelsPerInch := GetPixelsPerInch;
Inch.Width := CmToInch(Size.Width / 10);
Inch.Height := CmToInch(Size.Height / 10);
Result.Width := Inch.Width * PixelsPerInch.Width;
Result.Height := Inch.Height * PixelsPerInch.Height;
end;
function PixToSm(Size: TXSize): TXSize;
var
Inch, PixelsPerInch: TXSize;
begin
PixelsPerInch := GetPixelsPerInch;
Inch.Width := Size.Width / PixelsPerInch.Width;
Inch.Height := Size.Height / PixelsPerInch.Height;
Result.Width := InchToCm(Inch.Width);
Result.Height := InchToCm(Inch.Height);
end;
function PixToIn(Size: TXSize): TXSize;
var
PixelsPerInch: TXSize;
begin
PixelsPerInch := GetPixelsPerInch;
Result.Width := Size.Width / PixelsPerInch.Width;
Result.Height := Size.Height / PixelsPerInch.Height;
end;
function GetCID: string;
var
CID: TGUID;
begin
CoCreateGuid(CID);
Result := GUIDToString(CID);
end;
procedure CropImageOfHeight(CroppedHeight: Integer; var Bitmap: TBitmap);
var
I, J, Dy: Integer;
Xp: array of PARGB;
begin
Bitmap.PixelFormat := Pf24bit;
SetLength(Xp, Bitmap.Height);
if Bitmap.Height * Bitmap.Width = 0 then
Exit;
if CroppedHeight = Bitmap.Height then
Exit;
for I := 0 to Bitmap.Height - 1 do
Xp[I] := Bitmap.ScanLine[I];
Dy := Bitmap.Height div 2 - CroppedHeight div 2;
for I := 0 to CroppedHeight - 1 do
for J := 0 to Bitmap.Width - 1 do
begin
Xp[I, J] := Xp[I + Dy, J];
end;
Bitmap.Height := CroppedHeight;
end;
procedure CropImageOfWidth(CroppedWidth: Integer; var Bitmap: TBitmap);
var
I, J, Dx: Integer;
Xp: array of PARGB;
begin
Bitmap.PixelFormat := Pf24bit;
SetLength(Xp, Bitmap.Height);
if Bitmap.Height * Bitmap.Width = 0 then
Exit;
if CroppedWidth = Bitmap.Width then
Exit;
for I := 0 to Bitmap.Height - 1 do
Xp[I] := Bitmap.ScanLine[I];
Dx := Bitmap.Width div 2 - CroppedWidth div 2;
for I := 0 to Bitmap.Height - 1 do
for J := 0 to CroppedWidth do
begin
Xp[I, J] := Xp[I, J + Dx];
end;
Bitmap.Width := CroppedWidth;
end;
procedure CropImage(AWidth, AHeight: Integer; var Bitmap: TBitmap);
var
Temp: Integer;
begin
if AHeight = 0 then
Exit;
if (((AWidth / AHeight) > 1) and ((Bitmap.Width / Bitmap.Height) < 1)) or
(((AWidth / AHeight) < 1) and ((Bitmap.Width / Bitmap.Height) > 1)) then
begin
Temp := AWidth;
AWidth := AHeight;
AHeight := Temp;
end;
if Bitmap.Width / Bitmap.Height < AWidth / AHeight then
CropImageOfHeight(Round(Bitmap.Width * (AHeight / AWidth)), Bitmap)
else
CropImageOfWidth(Round(Bitmap.Height * (AWidth / AHeight)), Bitmap);
end;
procedure ProportionalSize(aWidth, aHeight: Integer; var aWidthToSize, aHeightToSize: Integer);
begin
if AWidthToSize * AWidth = 0 then
Exit;
if (AWidthToSize = 0) or (AHeightToSize = 0) then
begin
AHeightToSize := 0;
AWidthToSize := 0;
end else
begin
if (AHeightToSize / AWidthToSize) < (AHeight / AWidth) then
begin
AHeightToSize := Round((AWidth / AWidthToSize) * AHeightToSize);
AWidthToSize := AWidth;
end else
begin
AWidthToSize := Round((AHeight / AHeightToSize) * AWidthToSize);
AHeightToSize := AHeight;
end;
end;
end;
procedure GetPrinterMargins(var Margins: TMargins);
var
PixelsPerInch: TPoint;
PhysPageSize: TPoint;
OffsetStart: TPoint;
PageRes: TPoint;
begin
PixelsPerInch.y := GetDeviceCaps(Printer.Handle, LOGPIXELSY);
PixelsPerInch.x := GetDeviceCaps(Printer.Handle, LOGPIXELSX);
Escape(Printer.Handle, GETPHYSPAGESIZE, 0, nil, @PhysPageSize);
Escape(Printer.Handle, GETPRINTINGOFFSET, 0, nil, @OffsetStart);
PageRes.y := GetDeviceCaps(Printer.Handle, VERTRES);
PageRes.x := GetDeviceCaps(Printer.Handle, HORZRES);
// Top Margin
Margins.Top := OffsetStart.y / PixelsPerInch.y;
// Left Margin
Margins.Left := OffsetStart.x / PixelsPerInch.x;
// Bottom Margin
Margins.Bottom := ((PhysPageSize.y - PageRes.y) / PixelsPerInch.y) -
(OffsetStart.y / PixelsPerInch.y);
// Right Margin
Margins.Right := ((PhysPageSize.x - PageRes.x) / PixelsPerInch.x) -
(OffsetStart.x / PixelsPerInch.x);
end;
function InchToCm(Pixel: Single): Single;
// Convert inch to Centimeter
begin
Result := Pixel * 2.54
end;
function CmToInch(Pixel: Single): Single;
// Convert Centimeter to inch
begin
Result := Pixel / 2.54
end;
function GetPixelsPerInch : TXSize;
begin
Result.Height := GetDeviceCaps(Printer.Handle, LOGPIXELSY);
Result.Width := GetDeviceCaps(Printer.Handle, LOGPIXELSX);
end;
function SizeIn(X, A, B: Extended): Boolean;
begin
Result := ((X > A) and (X < B));
end;
function GetPaperSize: TPaperSize;
var
PixInInch, PageSizeMm: TXSize;
begin
PixInInch := GetPixelsPerInch;
PageSizeMm.Width := InchToCm(Printer.PageWidth * 10 / PixInInch.Width);
PageSizeMm.Height := InchToCm(Printer.PageHeight * 10 / PixInInch.Height);
if SizeIn(PageSizeMm.Width, 200, 220) and SizeIn(PageSizeMm.Height, 270, 300) then
begin
Result := TPS_A4;
Exit;
end;
if SizeIn(PageSizeMm.Width, 170, 182) and SizeIn(PageSizeMm.Height, 235, 260) then
begin
Result := TPS_B5;
Exit;
end;
if (Min(PageSizeMm.Width, PageSizeMm.Height) >= 130) and (Max(PageSizeMm.Width, PageSizeMm.Height) >= 180) then
begin
Result := TPS_CAN13X18;
Exit;
end;
if (Min(PageSizeMm.Width, PageSizeMm.Height) >= 100) and (Max(PageSizeMm.Width, PageSizeMm.Height) >= 150) then
begin
Result := TPS_CAN10X15;
Exit;
end;
if (Min(PageSizeMm.Width, PageSizeMm.Height) >= 90) and (Max(PageSizeMm.Width, PageSizeMm.Height) > 130) then
begin
Result := TPS_CAN9X13;
Exit;
end;
Result := TPS_OTHER;
end;
procedure Rotate90A(var Im: TBitmap);
var
I, J: Integer;
P1: PARGB;
P: array of PARGB;
Image: TBitmap;
begin
Im.PixelFormat := Pf24bit;
Image := Tbitmap.Create;
try
Image.PixelFormat := pf24bit;
Image.Assign(Im);
Im.Width := Image.Height;
Im.Height := Image.Width;
Setlength(P, Image.Width);
for I := 0 to Image.Width - 1 do
P[I] := Im.ScanLine[I];
for I := 0 to Image.Height - 1 do
begin
P1 := Image.ScanLine[Image.Height - I - 1];
for J := 0 to Image.Width - 1 do
P[J, I] := P1[J];
end;
finally
F(Image);
end;
end;
function LoadPicture(var Graphic: TGraphic; FileName: string; out ImageInfo: ILoadImageInfo): Boolean;
var
Info: TMediaItem;
begin
Result := False;
Graphic := nil;
try
Info := TMediaItem.CreateFromFile(FileName);
try
if LoadImageFromPath(Info, -1, '', [ilfGraphic, ilfICCProfile, ilfEXIF, ilfPassword], ImageInfo) then
Graphic := ImageInfo.ExtractGraphic;
Result := (Graphic <> nil) and not Graphic.Empty;
finally
F(Info);
end;
except
on e: Exception do
EventLog(e.Message);
end;
end;
procedure PrintFullSize(Result: TBitmap; SampleBitmap: TBitmap; Files: TStrings; FullImage: Boolean;
Options: TGenerateImageOptions; CallBack: TCallBackPrinterGeneratePreviewProc;
var Terminating: Boolean);
var
Graphic: TGraphic;
SampleImage: TBitmap;
AWidth, AHeight: Integer;
ImageInfo: ILoadImageInfo;
begin
SampleImage := TBitmap.Create;
try
SampleImage.PixelFormat := pf24bit;
if FullImage then
begin
if not Options.VirtualImage then
begin
LoadPicture(Graphic, Files[0], ImageInfo);
try
if Assigned(CallBack) then
CallBack(Round(100 * (1 / 5)), Terminating);
if Terminating then
Exit;
SampleImage.Assign(Graphic);
SampleImage.PixelFormat := pf24bit;
ImageInfo.AppllyICCProfile(SampleImage);
finally
F(Graphic);
end;
end else
SampleImage.Assign(Options.Image);
end else
SampleImage.Assign(SampleBitmap);
if Assigned(CallBack) then
CallBack(Round(100 * (2 / 5)), Terminating);
if Terminating then
Exit;
if ((Result.Width / Result.Height) > 1) and ((SampleImage.Width / SampleImage.Height) < 1) or
((Result.Width / Result.Height) < 1) and ((SampleImage.Width / SampleImage.Height) > 1) then
Rotate90A(SampleImage);
if Assigned(CallBack) then
CallBack(Round(100 * (3 / 5)), Terminating);
if Terminating then
Exit;
AWidth := SampleImage.Width - 2;
AHeight := SampleImage.Height - 2;
ProportionalSize(Result.Width - 2, Result.Height - 2, AWidth, AHeight);
if AWidth / SampleImage.Width < 1 then
StretchCool(Result.Width div 2 - AWidth div 2, Result.Height div 2 - AHeight div 2, AWidth, AHeight, SampleImage,
Result)
else
Interpolate(Result.Width div 2 - AWidth div 2, Result.Height div 2 - AHeight div 2, AWidth, AHeight,
Rect(0, 0, SampleImage.Width, SampleImage.Height), SampleImage, Result);
if Assigned(CallBack) then
CallBack(Round(100 * (4 / 4)), Terminating);
finally
F(SampleImage);
end;
end;
procedure PrintCenterImageSize(Result: TBitmap; SampleBitmap: TBitmap;
Files: TStrings; FullImage: Boolean; ImWidth, ImHeight: Integer;
Options: TGenerateImageOptions; CallBack: TCallBackPrinterGeneratePreviewProc;
var Terminating: Boolean);
var
Graphic: TGraphic;
SampleImage: TBitmap;
Size, PrSize: TXSize;
AWidth, AHeight: Integer;
ImageInfo: ILoadImageInfo;
begin
SampleImage := TBitmap.Create;
SampleImage.PixelFormat := pf24bit;
try
if FullImage and (Files.Count > 0) then
begin
if not Options.VirtualImage then
begin
LoadPicture(Graphic, Files[0], ImageInfo);
try
if Assigned(CallBack) then
CallBack(Round(100 * (1 / 7)), Terminating);
if Terminating then
Exit;
SampleImage.Assign(Graphic);
SampleImage.PixelFormat := pf24bit;
ImageInfo.AppllyICCProfile(SampleImage);
finally
F(Graphic);
end;
end else
SampleImage.Assign(Options.Image);
end else
SampleImage.Assign(SampleBitmap);
if Assigned(CallBack) then
CallBack(Round(100 * (2 / 7)), Terminating);
if Terminating then
Exit;
if ((Result.Width / Result.Height) > 1) and ((SampleImage.Width / SampleImage.Height) < 1) or
((Result.Width / Result.Height) < 1) and ((SampleImage.Width / SampleImage.Height) > 1) then
Rotate90A(SampleImage);
if Assigned(CallBack) then
CallBack(Round(100 * (3 / 7)), Terminating);
if Terminating then
Exit;
if Options.CropImages then
CropImage(ImWidth, ImHeight, SampleImage);
if Assigned(CallBack) then
CallBack(Round(100 * (4 / 7)), Terminating);
if Terminating then
Exit;
AWidth := SampleImage.Width;
AHeight := SampleImage.Height;
Size := MmToPix(XSize(ImWidth, ImHeight));
if not FullImage then
begin
PrSize := XSize(Size.Width / Printer.PageWidth, Size.Height / Printer.PageHeight);
Size := XSize(Result.Width * PrSize.Width, Result.Height * PrSize.Height);
end;
ProportionalSize(Round(Size.Width), Round(Size.Height), AWidth, AHeight);
if AWidth / SampleImage.Width < 1 then
StretchCool(Result.Width div 2 - AWidth div 2, Result.Height div 2 - AHeight div 2, AWidth, AHeight, SampleImage,
Result)
else
Interpolate(Result.Width div 2 - AWidth div 2, Result.Height div 2 - AHeight div 2, AWidth, AHeight,
Rect(0, 0, SampleImage.Width, SampleImage.Height), SampleImage, Result);
if Assigned(CallBack) then
CallBack(Round(100 * (7 / 7)), Terminating);
finally
F(SampleImage);
end;
end;
procedure PrintImageSizeTwo(Result: TBitmap; SampleBitmap: TBitmap;
Files: TStrings; FullImage: Boolean; ImWidth, ImHeight: Integer;
Options: TGenerateImageOptions; CallBack: TCallBackPrinterGeneratePreviewProc;
var Terminating: Boolean);
var
Graphic: TGraphic;
I: Integer;
SampleImage: TBitmap;
Size, PrSize: TXSize;
AWidth, AHeight: Integer;
ImageInfo: ILoadImageInfo;
begin
SampleImage := TBitmap.Create;
try
for I := 0 to 1 do
begin
if FullImage then
begin
if (Files.Count = 1) and (I = 1) then
Continue;
LoadPicture(Graphic, Files[I], ImageInfo);
try
if Assigned(CallBack) then
CallBack(Round(100 * ((1 + I * 7) / 14)), Terminating);
if Terminating then
Exit;
SampleImage.Assign(Graphic);
SampleImage.PixelFormat := pf24bit;
ImageInfo.AppllyICCProfile(SampleImage);
finally
F(Graphic);
end;
if Assigned(CallBack) then
CallBack(Round(100 * ((2 + I * 7) / 14)), Terminating);
if Terminating then
Exit;
end else
SampleImage.Assign(SampleBitmap);
if ((Result.Width / Result.Height) < 1) and ((SampleImage.Width / SampleImage.Height) < 1) or
((Result.Width / Result.Height) > 1) and ((SampleImage.Width / SampleImage.Height) > 1) then
Rotate90A(SampleImage);
if Assigned(CallBack) then
CallBack(Round(100 * ((3 + I * 7) / 14)), Terminating);
if Terminating then
Exit;
if Options.CropImages then
CropImage(ImWidth, ImHeight, SampleImage);
if Assigned(CallBack) then
CallBack(Round(100 * ((4 + I * 7) / 14)), Terminating);
if Terminating then
Exit;
AWidth := SampleImage.Width;
AHeight := SampleImage.Height;
Size := MmToPix(XSize(ImWidth, ImHeight));
if not FullImage then
begin
PrSize := XSize(Size.Width / Printer.PageWidth, Size.Height / Printer.PageHeight);
Size := XSize(Result.Width * PrSize.Width, Result.Height * PrSize.Height);
end;
ProportionalSize(Round(Size.Width), Round(Size.Height), AWidth, AHeight);
if AWidth / SampleImage.Width < 1 then
StretchCool(Result.Width div 2 - AWidth div 2,
(Result.Height div 4 + (Result.Height div 2) * I) - AHeight div 2, AWidth, Aheight, SampleImage, Result)
else
Interpolate(Result.Width div 2 - AWidth div 2,
(Result.Height div 4 + (Result.Height div 2) * I) - AHeight div 2, AWidth, Aheight,
Rect(0, 0, SampleImage.Width, SampleImage.Height), SampleImage, Result);
if Assigned(CallBack) then
CallBack(Round(100 * ((7 + I * 7) / 14)), Terminating);
if Terminating then
Exit;
end;
finally
F(SampleImage);
end;
end;
procedure Print35Previews(Result: TBitmap; SampleBitmap: TBitmap;
Files: TStrings; FullImage: Boolean; Options: TGenerateImageOptions;
CallBack: TCallBackPrinterGeneratePreviewProc; var Terminating: Boolean);
var
Graphic: TGraphic;
Pos, W, H, I, J: Integer;
AWidth, AHeight: Integer;
SampleImage, SmallImage: TBitmap;
ImageInfo: ILoadImageInfo;
begin
Pos := 0;
if not FullImage then
begin
SmallImage := TBitmap.Create;
try
SampleImage := TBitmap.Create;
try
SampleImage.Assign(SampleBitmap);
AWidth := SampleImage.Width;
AHeight := SampleImage.Height;
ProportionalSize(Result.Width div 6, Result.Height div 8, AWidth, AHeight);
StretchCool(AWidth, Aheight, SampleImage, SmallImage);
W := (Result.Width div 5);
H := (Result.Height div 7);
for I := 1 to 7 do
for J := 1 to 5 do
Result.Canvas.Draw(W * (J - 1) + W div 2 - SmallImage.Width div 2,
H * (I - 1) + H div 2 - SmallImage.Height div 2, SmallImage);
finally
F(SampleImage);
end;
finally
F(SmallImage);
end;
end else
begin
SampleImage := TBitmap.Create;
try
SampleImage.PixelFormat := pf24bit;
W := (Result.Width div 5);
H := (Result.Height div 7);
for I := 1 to 7 do
begin
for J := 1 to 5 do
begin
if Files.Count < (I - 1) * 5 + J then
Exit;
LoadPicture(Graphic, Files[(I - 1) * 5 + J - 1], ImageInfo);
try
Inc(Pos);
if Assigned(CallBack) then
CallBack(Round(100 * (Pos / (5 * Files.Count))), Terminating);
if Terminating then
Exit;
SampleImage.Assign(Graphic);
SampleImage.PixelFormat := pf24Bit;
ImageInfo.AppllyICCProfile(SampleImage);
F(Graphic);
Inc(Pos);
if Assigned(CallBack) then
CallBack(Round(100 * (Pos / (5 * Files.Count))), Terminating);
if Terminating then
Exit;
AWidth := SampleImage.Width;
AHeight := SampleImage.Height;
ProportionalSize(Result.Width div 6, Result.Height div 8, AWidth, AHeight);
if AWidth / SampleImage.Width < 1 then
StretchCool(W * (J - 1) + W div 2 - AWidth div 2, H * (I - 1) + H div 2 - AHeight div 2, AWidth, Aheight,
SampleImage, Result)
else
Interpolate(W * (J - 1) + W div 2 - AWidth div 2, H * (I - 1) + H div 2 - AHeight div 2, AWidth, Aheight,
Rect(0, 0, SampleImage.Width, SampleImage.Height), SampleImage, Result);
Inc(Pos, 3);
if Assigned(CallBack) then
CallBack(Round(100 * (Pos / (5 * Files.Count))), Terminating);
if Terminating then
Exit;
finally
F(Graphic);
end;
end;
end;
finally
F(SampleImage);
end;
end;
end;
procedure PrintA4Three10X15(Result: TBitmap; SampleBitmap: TBitmap;
Files: TStrings; FullImage: Boolean; Options: TGenerateImageOptions;
CallBack: TCallBackPrinterGeneratePreviewProc; var Terminating: Boolean);
var
Pos, TopSize, AW, AH, I, H, Ainc: Integer;
Graphic: TGraphic;
SampleImage: TBitmap;
AWidth, AHeight: Integer;
PrSize, Size: TXSize;
ImageInfo: ILoadImageInfo;
begin
Pos := 0;
SampleImage := TBitmap.Create;
try
for I := 0 to 2 do
begin
if FullImage then
begin
if I >= Files.Count then
Continue;
LoadPicture(Graphic, Files[I], ImageInfo);
try
Inc(Pos);
if Assigned(CallBack) then
CallBack(Round(100 * (Pos / (7 * Files.Count))), Terminating);
if Terminating then
Exit;
SampleImage.Assign(Graphic);
SampleImage.PixelFormat := pf24bit;
ImageInfo.AppllyICCProfile(SampleImage);
Inc(Pos);
if Assigned(CallBack) then
CallBack(Round(100 * (Pos / (7 * Files.Count))), Terminating);
finally
F(Graphic);
end;
if Terminating then
Exit;
end
else
SampleImage.Assign(SampleBitmap);
case I of
0:
if ((Result.Width / Result.Height) < 1) and ((SampleImage.Width / SampleImage.Height) < 1) or
((Result.Width / Result.Height) > 1) and ((SampleImage.Width / SampleImage.Height) > 1) then
Rotate90A(SampleImage);
1, 2:
if ((Result.Width / Result.Height) > 1) and ((SampleImage.Width / SampleImage.Height) < 1) or
((Result.Width / Result.Height) < 1) and ((SampleImage.Width / SampleImage.Height) > 1) then
Rotate90A(SampleImage);
end;
Inc(Pos);
if Assigned(CallBack) then
CallBack(Round(100 * (Pos / (7 * Files.Count))), Terminating);
if Terminating then
Exit;
case I of
0:
begin
AW := 150;
AH := 100;
end;
1:
begin
AW := 100;
AH := 150;
end;
2:
begin
AW := 100;
AH := 150;
end;
else
begin
AW := 150;
AH := 100;
end;
end;
if Options.CropImages then
CropImage(AW, AH, SampleImage);
Inc(Pos);
if Assigned(CallBack) then
CallBack(Round(100 * (Pos / (7 * Files.Count))), Terminating);
if Terminating then
Exit;
AWidth := SampleImage.Width;
AHeight := SampleImage.Height;
Size := MmToPix(XSize(AW, AH));
if not FullImage then
begin
PrSize := XSize(Size.Width / Printer.PageWidth, Size.Height / Printer.PageHeight);
Size := XSize(Result.Width * PrSize.Width, Result.Height * PrSize.Height);
end;
ProportionalSize(Round(Size.Width), Round(Size.Height), AWidth, AHeight);
if FullImage then
TopSize := Round(MmToPix(XSize(10, 10)).Height)
else
TopSize := Round((MmToPix(XSize(10, 10)).Height / Printer.PageHeight) * Result.Height);
case I of
0:
begin
if FullImage then
H := Result.Height - AHeight - Round(MmToPix(XSize(10, 10)).Height)
else
H := Result.Height - AHeight - Round((MmToPix(XSize(10, 10)).Height / Printer.PageHeight)
* Result.Height);
if AWidth / SampleImage.Width < 1 then
StretchCool(Result.Width div 2 - AWidth div 2, H, AWidth, AHeight, SampleImage, Result)
else
Interpolate(Result.Width div 2 - AWidth div 2, H, AWidth, AHeight,
Rect(0, 0, SampleImage.Width, SampleImage.Height), SampleImage, Result);
end;
1:
begin
if FullImage then
Ainc := 0
else
Ainc := 1;
if AWidth / SampleImage.Width < 1 then
StretchCool(Result.Width div 4 - AWidth div 2 + Ainc, TopSize, AWidth, AHeight, SampleImage, Result)
else
Interpolate(Result.Width div 4 - AWidth div 2 + Ainc, TopSize, AWidth, AHeight,
Rect(0, 0, SampleImage.Width, SampleImage.Height), SampleImage, Result);
end;
2:
begin
if FullImage then
Ainc := 0
else
Ainc := 1;
if AWidth / SampleImage.Width < 1 then
StretchCool((Result.Width div 4) * 3 - AWidth div 2 + Ainc, TopSize, AWidth, AHeight, SampleImage, Result)
else
Interpolate((Result.Width div 4) * 3 - AWidth div 2 + Ainc, TopSize, AWidth, AHeight,
Rect(0, 0, SampleImage.Width, SampleImage.Height), SampleImage, Result);
end;
end;
Inc(Pos, 3);
if Assigned(CallBack) then
CallBack(Round(100 * (Pos / (7 * Files.Count))), Terminating);
if Terminating then
Exit;
end;
finally
F(SampleImage);
end;
end;
procedure PrintA4Four9X13(Result: TBitmap; SampleBitmap: TBitmap;
Files: TStrings; FullImage: Boolean; Options: TGenerateImageOptions;
CallBack: TCallBackPrinterGeneratePreviewProc; var Terminating: Boolean);
var
I, J: Integer;
Graphic: TGraphic;
SampleImage: TBitmap;
AWidth, AHeight: Integer;
PrSize, Size: TXSize;
ImageInfo: ILoadImageInfo;
begin
SampleImage := TBitmap.Create;
SampleImage.PixelFormat := pf24bit;
try
for J := 0 to 1 do
begin
for I := 0 to 1 do
begin
if FullImage then
begin
if J * 2 + I >= Files.Count then
Continue;
LoadPicture(Graphic, Files[J * 2 + I], ImageInfo);
try
if Assigned(CallBack) then
CallBack(Round(100 * ((1 + (J * 2 + I) * 7) / 28)), Terminating);
if Terminating then
Exit;
SampleImage.Assign(Graphic);
SampleImage.PixelFormat := pf24Bit;
ImageInfo.AppllyICCProfile(SampleImage);
if Assigned(CallBack) then
CallBack(Round(100 * ((2 + (J * 2 + I) * 7) / 28)), Terminating);
finally
F(Graphic);
end;
if Terminating then
Exit;
end else
SampleImage.Assign(SampleBitmap);
if ((Result.Width / Result.Height) > 1) and ((SampleImage.Width / SampleImage.Height) < 1) or
((Result.Width / Result.Height) < 1) and ((SampleImage.Width / SampleImage.Height) > 1) then
Rotate90A(SampleImage);
if Assigned(CallBack) then
CallBack(Round(100 * ((3 + (J * 2 + I) * 7) / 28)), Terminating);
if Terminating then
Exit;
if Options.CropImages then
CropImage(90, 130, SampleImage);
if Assigned(CallBack) then
CallBack(Round(100 * ((4 + (J * 2 + I) * 7) / 28)), Terminating);
if Terminating then
Exit;
AWidth := SampleImage.Width;
AHeight := SampleImage.Height;
Size := MmToPix(XSize(90, 130));
if not FullImage then
begin
PrSize := XSize(Size.Width / Printer.PageWidth, Size.Height / Printer.PageHeight);
Size := XSize(Result.Width * PrSize.Width, Result.Height * PrSize.Height);
end;
ProportionalSize(Round(Size.Width), Round(Size.Height), AWidth, AHeight);
if AWidth / SampleImage.Width < 1 then
StretchCool(Result.Width div 4 + (Result.Width div 2) * I - AWidth div 2,
Result.Height div 4 + (Result.Height div 2) * J - AHeight div 2, AWidth, AHeight, SampleImage, Result)
else
Interpolate(Result.Width div 4 + (Result.Width div 2) * I - AWidth div 2,
Result.Height div 4 + (Result.Height div 2) * J - AHeight div 2, AWidth, AHeight,
Rect(0, 0, SampleImage.Width, SampleImage.Height), SampleImage, Result);
if Assigned(CallBack) then
CallBack(Round(100 * ((7 + (J * 2 + I) * 7) / 28)), Terminating);
if Terminating then
Exit;
end;
end;
finally
F(SampleImage);
end;
end;
procedure Print9Images(Result: TBitmap; SampleBitmap: TBitmap; Files: TStrings;
FullImage: Boolean; Options: TGenerateImageOptions;
CallBack: TCallBackPrinterGeneratePreviewProc; var Terminating: Boolean);
var
SmallImage, SampleImage: TBitmap;
Pos, I, J, W, H, AWidth, AHeight: Integer;
Graphic: TGraphic;
ImageInfo: ILoadImageInfo;
begin
Pos := 0;
SampleImage := TBitmap.Create;
try
SampleImage.PixelFormat := Pf24bit;
if not FullImage then
begin
SampleImage.Assign(SampleBitmap);
if ((Result.Width / Result.Height) > 1) and ((SampleImage.Width / SampleImage.Height) < 1) or
((Result.Width / Result.Height) < 1) and ((SampleImage.Width / SampleImage.Height) > 1) then
Rotate90A(SampleImage);
AWidth := SampleImage.Width;
AHeight := SampleImage.Height;
SmallImage := TBitmap.Create;
try
ProportionalSize(Result.Width div 4, Result.Height div 4, AWidth, AHeight);
StretchCool(AWidth, Aheight, SampleImage, SmallImage);
W := (Result.Width div 3);
H := (Result.Height div 3);
for I := 1 to 3 do
for J := 1 to 3 do
Result.Canvas.Draw(W * (J - 1) + W div 2 - SmallImage.Width div 2,
H * (I - 1) + H div 2 - SmallImage.Height div 2, SmallImage);
finally
F(SmallImage);
end;
end else
begin
W := (Result.Width div 3);
H := (Result.Height div 3);
for I := 1 to 3 do
begin
for J := 1 to 3 do
begin
if Files.Count < (I - 1) * 3 + J then
Exit;
LoadPicture(Graphic, Files[(I - 1) * 3 + J - 1], ImageInfo);
try
Inc(Pos);
if Assigned(CallBack) then
CallBack(Round(100 * (Pos / (6 * Files.Count))), Terminating);
if Terminating then
Exit;
SampleImage.Assign(Graphic);
SampleImage.PixelFormat := pf24Bit;
ImageInfo.AppllyICCProfile(SampleImage);
Inc(Pos);
if Assigned(CallBack) then
CallBack(Round(100 * (Pos / (6 * Files.Count))), Terminating);
if Terminating then
Exit;
finally
F(Graphic);
end;
if ((Result.Width / Result.Height) > 1) and ((SampleImage.Width / SampleImage.Height) < 1) or
((Result.Width / Result.Height) < 1) and ((SampleImage.Width / SampleImage.Height) > 1) then
Rotate90A(SampleImage);
Inc(Pos);
if Assigned(CallBack) then
CallBack(Round(100 * (Pos / (6 * Files.Count))), Terminating);
if Terminating then
Exit;
AWidth := SampleImage.Width;
AHeight := SampleImage.Height;
ProportionalSize(Result.Width div 4, Result.Height div 4, AWidth, AHeight);
if AWidth / SampleImage.Width < 1 then
StretchCool(W * (J - 1) + W div 2 - AWidth div 2, H * (I - 1) + H div 2 - AHeight div 2, AWidth, AHeight,
SampleImage, Result)
else
Interpolate(W * (J - 1) + W div 2 - AWidth div 2, H * (I - 1) + H div 2 - AHeight div 2, AWidth, AHeight,
Rect(0, 0, SampleImage.Width, SampleImage.Height), SampleImage, Result);
Inc(Pos, 3);
if Assigned(CallBack) then
CallBack(Round(100 * (Pos / (6 * Files.Count))), Terminating);
if Terminating then
Exit;
end;
end;
end;
finally
F(SampleImage);
end;
end;
procedure PrintFour6X4(Result: TBitmap; SampleBitmap: TBitmap; Files: TStrings;
FullImage: Boolean; Options: TGenerateImageOptions;
CallBack: TCallBackPrinterGeneratePreviewProc; var Terminating: Boolean);
var
Graphic: TGraphic;
SampleImage: TBitmap;
I, J, AWidth, AHeight: Integer;
Size, PrSize: TXSize;
ImageInfo: ILoadImageInfo;
begin
SampleImage := TBitmap.Create;
SampleImage.PixelFormat := pf24bit;
try
if FullImage then
begin
if not Options.VirtualImage and (Files.Count > 0) then
begin
LoadPicture(Graphic, Files[0], ImageInfo);
try
if Assigned(CallBack) then
CallBack(Round(100 * (1 / 7)), Terminating);
if Terminating then
Exit;
SampleImage.Assign(Graphic);
SampleImage.PixelFormat := pf24Bit;
ImageInfo.AppllyICCProfile(SampleImage);
if Assigned(CallBack) then
CallBack(Round(100 * (2 / 7)), Terminating);
finally
F(Graphic);
end;
if Terminating then
Exit;
end else
begin
SampleImage.Assign(Options.Image);
if Assigned(CallBack) then
CallBack(Round(100 * (3 / 7)), Terminating);
end;
end else
SampleImage.Assign(SampleBitmap);
if ((Result.Width / Result.Height) > 1) and ((SampleImage.Width / SampleImage.Height) < 1) or
((Result.Width / Result.Height) < 1) and ((SampleImage.Width / SampleImage.Height) > 1) then
Rotate90A(SampleImage);
if Assigned(CallBack) then
CallBack(Round(100 * (3 / 7)), Terminating);
if Terminating then
Exit;
if Options.CropImages then
CropImage(40, 60, SampleImage);
if Assigned(CallBack) then
CallBack(Round(100 * (4 / 7)), Terminating);
if Terminating then
Exit;
AWidth := SampleImage.Width;
AHeight := SampleImage.Height;
Size := MmToPix(XSize(40, 60));
if not FullImage then
begin
PrSize := XSize(Size.Width / Printer.PageWidth, Size.Height / Printer.PageHeight);
Size := XSize(Result.Width * PrSize.Width, Result.Height * PrSize.Height);
end;
ProportionalSize(Round(Size.Width), Round(Size.Height), AWidth, AHeight);
for I := -1 to 1 do
begin
for J := -1 to 1 do
begin
if I * J = 0 then
Continue;
if AWidth / SampleImage.Width < 1 then
StretchCool(Result.Width div 2 - AWidth div 2 + Round(I * AWidth * 0.55),
Result.Height div 2 - AHeight div 2 + Round(J * AHeight * 0.55), AWidth, AHeight, SampleImage, Result)
else
Interpolate(Result.Width div 2 - AWidth div 2 + Round(I * AWidth * 0.55),
Result.Height div 2 - AHeight div 2 + Round(J * AHeight * 0.55), AWidth, AHeight,
Rect(0, 0, SampleImage.Width, SampleImage.Height), SampleImage, Result);
if Assigned(CallBack) then
CallBack(Round(100 * (7 / 7)), Terminating);
if Terminating then
Exit;
end;
end;
finally
F(SampleImage);
end;
end;
procedure PrintSix3X4(Result: TBitmap; SampleBitmap: TBitmap; Files: TStrings;
FullImage: Boolean; Options: TGenerateImageOptions;
CallBack: TCallBackPrinterGeneratePreviewProc; var Terminating: Boolean);
var
SampleImage: TBitmap;
Graphic: TGraphic;
I, J, AWidth, AHeight: Integer;
PrSize, Size: TXSize;
ImageInfo: ILoadImageInfo;
begin
SampleImage := TBitmap.Create;
SampleImage.PixelFormat := Pf24bit;
try
if FullImage then
begin
if not Options.VirtualImage then
begin
LoadPicture(Graphic, Files[0], ImageInfo);
try
if Assigned(CallBack) then
CallBack(Round(100 * (1 / 7)), Terminating);
if Terminating then
Exit;
SampleImage.Assign(Graphic);
SampleImage.PixelFormat := pf24bit;
ImageInfo.AppllyICCProfile(SampleImage);
if Assigned(CallBack) then
CallBack(Round(100 * (2 / 7)), Terminating);
finally
F(Graphic);
end;
if Terminating then
Exit;
end else
begin
SampleImage.Assign(Options.Image);
if Assigned(CallBack) then
CallBack(Round(100 * (3 / 7)), Terminating);
end;
end else
SampleImage.Assign(SampleBitmap);
if ((Result.Width / Result.Height) > 1) and ((SampleImage.Width / SampleImage.Height) < 1) or
((Result.Width / Result.Height) < 1) and ((SampleImage.Width / SampleImage.Height) > 1) then
Rotate90A(SampleImage);
if Assigned(CallBack) then
CallBack(Round(100 * (3 / 7)), Terminating);
if Terminating then
Exit;
if Options.CropImages then
CropImage(30, 40, SampleImage);
if Assigned(CallBack) then
CallBack(Round(100 * (4 / 7)), Terminating);
if Terminating then
Exit;
AWidth := SampleImage.Width;
AHeight := SampleImage.Height;
Size := MmToPix(XSize(30, 40));
if not FullImage then
begin
PrSize := XSize(Size.Width / Printer.PageWidth, Size.Height / Printer.PageHeight);
Size := XSize(Result.Width * PrSize.Width, Result.Height * PrSize.Height);
end;
ProportionalSize(Round(Size.Width), Round(Size.Height), AWidth, AHeight);
for I := -1 to 1 do
begin
for J := -1 to 1 do
begin
if J <> 0 then
begin
if AWidth / SampleImage.Width < 1 then
StretchCool(Result.Width div 2 - AWidth div 2 + Round(I * AWidth * 1.05),
Result.Height div 2 - AHeight div 2 + Round(J * AHeight * 0.55), AWidth, AHeight, SampleImage, Result)
else
Interpolate(Result.Width div 2 - AWidth div 2 + Round(I * AWidth * 1.05),
Result.Height div 2 - AHeight div 2 + Round(J * AHeight * 0.55), AWidth, AHeight,
Rect(0, 0, SampleImage.Width, SampleImage.Height), SampleImage, Result);
if Assigned(CallBack) then
CallBack(Round(100 * (7 / 7)), Terminating);
if Terminating then
Exit;
end;
end;
end;
finally
F(SampleImage);
end;
end;
function GenerateImage(FullImage: Boolean; Width, Height: Integer; SampleImage: TBitmap; Files: TStrings;
SampleImageType: TPrintSampleSizeOne; Options: TGenerateImageOptions;
CallBack: TCallBackPrinterGeneratePreviewProc = nil): TBitmap;
var
ImageWidth, ImageHeight: Integer;
Terminating: Boolean;
begin
Result := nil;
if Options.VirtualImage then
begin
if (Options.Image = nil) or Options.Image.Empty then
Exit;
SampleImage := Options.Image;
end;
Terminating := False;
Result := TBitmap.Create;
Result.PixelFormat := Pf24bit;
Result.Width := Width;
Result.Height := Height;
try
if not FullImage then
begin
Result.Canvas.Brush.Color := $EEEEEE;
Result.Canvas.Pen.Color := $0;
Result.Canvas.Rectangle(0, 0, Width, Height);
end;
case SampleImageType of
TPSS_FullSize:
begin
PrintFullSize(Result, SampleImage, Files, FullImage, Options, CallBack, Terminating);
end;
TPSS_C35:
begin
Print35Previews(Result, SampleImage, Files, FullImage, Options, CallBack, Terminating);
end;
TPSS_20X25C1:
begin
PrintCenterImageSize(Result, SampleImage, Files, FullImage, 200, 250, Options, CallBack, Terminating);
end;
TPSS_13X18C1:
begin
PrintCenterImageSize(Result, SampleImage, Files, FullImage, 130, 180, Options, CallBack, Terminating);
end;
TPSS_10X15C1:
begin
PrintCenterImageSize(Result, SampleImage, Files, FullImage, 100, 150, Options, CallBack, Terminating);
end;
TPSS_9X13C1:
begin
PrintCenterImageSize(Result, SampleImage, Files, FullImage, 90, 130, Options, CallBack, Terminating);
end;
TPSS_13X18C2:
begin
PrintImageSizeTwo(Result, SampleImage, Files, FullImage, 180, 130, Options, CallBack, Terminating);
end;
TPSS_10X15C2:
begin
PrintImageSizeTwo(Result, SampleImage, Files, FullImage, 150, 100, Options, CallBack, Terminating);
end;
TPSS_9X13C2:
begin
PrintImageSizeTwo(Result, SampleImage, Files, FullImage, 130, 90, Options, CallBack, Terminating);
end;
TPSS_10X15C3:
begin
PrintA4Three10X15(Result, SampleImage, Files, FullImage, Options, CallBack, Terminating);
end;
TPSS_9X13C4:
begin
PrintA4Four9X13(Result, SampleImage, Files, FullImage, Options, CallBack, Terminating);
end;
TPSS_C9:
begin
Print9Images(Result, SampleImage, Files, FullImage, Options, CallBack, Terminating);
end;
TPSS_CUSTOM:
begin
ImageWidth := Round(PixToSm(XSize(Options.FreeWidthPx, 0)).Width * 10);
ImageHeight := Round(PixToSm(XSize(0, Options.FreeHeightPx)).Height * 10);
PrintImageSizeTwo(Result, SampleImage, Files, FullImage, ImageWidth, ImageHeight, Options, CallBack, Terminating);
end;
TPSS_4X6C4:
begin
PrintFour6X4(Result, SampleImage, Files, FullImage, Options, CallBack, Terminating);
end;
TPSS_3X4C6:
begin
PrintSix3X4(Result, SampleImage, Files, FullImage, Options, CallBack, Terminating);
end;
end;
except
on E: Exception do
EventLog(':GenerateImage() throw exception: ' + E.message);
end;
end;
end.
|
unit LrOpenDocumentsController;
interface
uses
Classes, Controls,
LrObserverList, LrDocument, LrDocumentList;
type
TLrOpenDocumentsController = class(TLrDocumentList)
private
FNilDocument: TLrDocument;
FObservers: TLrObserverList;
FSelectedIndex: Integer;
protected
function GetCurrent: TLrDocument;
procedure FinalizeCurrent;
procedure SetSelectedIndex(const Value: Integer);
public
constructor Create; override;
destructor Destroy; override;
function BeginCloseCurrent: Boolean;
function CloseAll: Boolean;
function EndCloseCurrent: Boolean;
procedure AddDocument(inDocument: TLrDocument);
procedure CloseCurrent;
procedure RemoveDocument(inDocument: TLrDocument);
property Current: TLrDocument read GetCurrent;
property Observers: TLrObserverList read FObservers write FObservers;
property SelectedIndex: Integer read FSelectedIndex write SetSelectedIndex;
//property OnCurrentChanged: TNotifyEvent read FOnCurrentChanged
// write FOnCurrentChanged;
end;
var
LrOpenDocuments: TLrOpenDocumentsController;
implementation
{ TLrOpenDocumentsController }
constructor TLrOpenDocumentsController.Create;
begin
inherited;
FNilDocument := TLrDocumentController.Create.CreateDocument(TLrDocument);
//FNilDocument := TLrDocument.Create;
//FNilDocument.Controller := TLrDocumentController.Create;
FObservers := TLrObserverList.Create;
end;
destructor TLrOpenDocumentsController.Destroy;
begin
FObservers.Free;
FNilDocument.Free;
inherited;
end;
function TLrOpenDocumentsController.GetCurrent: TLrDocument;
begin
if GoodIndex(SelectedIndex) then
Result := Documents[SelectedIndex]
else
Result := FNilDocument;
end;
procedure TLrOpenDocumentsController.SetSelectedIndex(const Value: Integer);
begin
Current.Deactivate;
FSelectedIndex := Value;
Change;
Current.Activate;
end;
procedure TLrOpenDocumentsController.FinalizeCurrent;
begin
if not GoodIndex(SelectedIndex) then
FSelectedIndex := Pred(Count);
Current.Activate;
Change;
end;
function TLrOpenDocumentsController.BeginCloseCurrent: Boolean;
begin
Result := Current.Close;
end;
function TLrOpenDocumentsController.EndCloseCurrent: Boolean;
begin
Result := Current.Closed;
if Result then
begin
Current.Deactivate;
Current.Free;
RemoveDocument(Current);
end;
end;
procedure TLrOpenDocumentsController.CloseCurrent;
begin
if BeginCloseCurrent then
EndCloseCurrent;
end;
procedure TLrOpenDocumentsController.AddDocument(inDocument: TLrDocument);
begin
if inDocument <> nil then
begin
Add(inDocument);
SelectedIndex := Pred(Count);
end;
end;
procedure TLrOpenDocumentsController.RemoveDocument(inDocument: TLrDocument);
begin
Remove(inDocument);
FinalizeCurrent;
end;
function TLrOpenDocumentsController.CloseAll: Boolean;
var
i: Integer;
begin
i := Pred(Count);
Result := true;
while (i >= 0) and Result do
begin
// True result to Close method indicates only that the close
// was not cancelled. It does not indicate that the
// document actually is closed.
// Check Closed property to test for true closure.
Result := Documents[i].Close;
if Result then
begin
if Documents[i].Closed then
begin
Documents[i].Deactivate;
Documents[i].Free;
RemoveDocument(Documents[i]);
end;
Dec(i);
end;
end;
FinalizeCurrent;
end;
{
procedure TLrOpenDocumentsController.DocumentListChange(inSender: TObject);
begin
FObservers.Notify(inSender);
end;
procedure TLrOpenDocumentsController.CurrentChanged;
begin
if Assigned(FOnCurrentChanged) then
FOnCurrentChanged(Self);
end;
procedure TLrOpenDocumentsController.DocumentsChanged;
begin
DocumentChange(Self);
// if Assigned(OnDocumentsChanged) then
// OnDocumentsChanged(Self);
end;
procedure TLrOpenDocumentsController.AddDocument(inDocument: TLrDocument);
begin
Documents.AddDocument(inDocument);
end;
procedure TLrOpenDocumentsController.RemoveDocument(inDocument: TLrDocument);
begin
Documents.RemoveDocument(inDocument);
end;
procedure TLrOpenDocumentsController.SetIndex(const Value: Integer);
begin
Current.Deactivate;
FIndex := Value;
DocumentsChanged;
//CurrentChanged;
Current.Activate;
end;
procedure TLrOpenDocumentsController.SetCurrent(inDocument: TLrDocument);
begin
Index := FindDocument(inDocument);
end;
procedure TLrOpenDocumentsController.ValidateCurrent;
begin
if not GoodIndex(Index) then
Index := Pred(Count)
else begin
DocumentsChanged;
//CurrentChanged;
Current.Activate;
end;
end;
}
end.
|
{================================================================================
Copyright (C) 1997-2002 Mills Enterprise
Unit : rmCCTabs
Purpose : This is some of the best features from the depricated ComCtrls95
component set, that I also authored. Floating Tabsheets and Tabhints.
Date : 02-01-2000
Author : Ryan J. Mills
Version : 1.92
================================================================================}
unit rmCCTabs;
interface
{$I CompilerDefines.INC}
uses Messages, Windows, SysUtils, CommCtrl, Classes, Controls, Graphics,
ImgList, Forms;
const
CM_rmCCTabsBase = CM_BASE+333;
CM_rmCCTabSheetDraggedON = CM_rmCCTabsBase+1;
CM_rmCCTabSheetDraggedOFF = CM_rmCCTabsBase+2;
type
ECCTabError = Exception;
TrmCustomCCTabControl = class;
TTabChangingEvent = procedure(Sender: TObject; var AllowChange: Boolean) of object;
TTabPosition = (tpTop, tpBottom, tpLeft, tpRight);
TTabStyle = (tsTabs, tsButtons, tsFlatButtons);
TGripAlign = (gaLeft, gaRight, gaTop, gaBottom);
TFloatState = (fsFloating, fsDocked);
TTabFloatEvent = procedure(Sender: TObject; FloatState: TFloatState) of object;
TTabTrackEvent = procedure(sender:TObject; TabIndex: integer) of object;
TDrawTabEvent = procedure(Control: TrmCustomCCTabControl; TabIndex: Integer;
const Rect: TRect; Active: Boolean) of object;
TTabGetImageEvent = procedure(Sender: TObject; TabIndex: Integer;
var ImageIndex: Integer) of object;
TrmCustomCCTabControl = class(TWinControl)
private
FCanvas: TCanvas;
FHotTrack: Boolean;
FImageChangeLink: TChangeLink;
FImages: TCustomImageList;
FMouseDragTab: integer;
FMouseOverTab: integer;
FMultiLine: Boolean;
FMultiSelect: Boolean;
FOwnerDraw: Boolean;
FRaggedRight: Boolean;
FSaveTabIndex: Integer;
FSaveTabs: TStringList;
FScrollOpposite: Boolean;
FStyle: TTabStyle;
FTabPosition: TTabPosition;
FTabs: TStrings;
FTabShifting:boolean;
FTabSize: TSmallPoint;
FUpdating: Boolean;
FOnChange: TNotifyEvent;
FOnChanging: TTabChangingEvent;
FOnDrawTab: TDrawTabEvent;
FOnGetImageIndex: TTabGetImageEvent;
FOnTabTrack: TTabTrackEvent;
FOnTabShift: TNotifyEvent;
function GetDisplayRect: TRect;
function GetTabIndex: Integer;
procedure ImageListChange(Sender: TObject);
function InternalSetMultiLine(Value: Boolean): Boolean;
procedure SetHotTrack(Value: Boolean);
procedure SetImages(Value: TCustomImageList);
procedure SetMultiLine(Value: Boolean);
procedure SetMultiSelect(Value: Boolean);
procedure SetOwnerDraw(Value: Boolean);
procedure SetRaggedRight(Value: Boolean);
procedure SetScrollOpposite(Value: Boolean);
procedure SetStyle(Value: TTabStyle);
procedure SetTabHeight(Value: Smallint);
procedure SetTabIndex(Value: Integer);
procedure SetTabPosition(Value: TTabPosition);
procedure SetTabs(Value: TStrings);
procedure SetTabWidth(Value: Smallint);
procedure TabsChanged;
procedure UpdateTabSize;
procedure CMFontChanged(var Message); message CM_FONTCHANGED;
procedure CMSysColorChange(var Message: TMessage); message CM_SYSCOLORCHANGE;
procedure CMTabStopChanged(var Message: TMessage); message CM_TABSTOPCHANGED;
procedure CMMouseLeave(var message:tmessage); message CM_MOUSELEAVE;
procedure CNNotify(var Message: TWMNotify); message CN_NOTIFY;
procedure CMDialogChar(var Message: TCMDialogChar); message CM_DIALOGCHAR;
procedure CNDrawItem(var Message: TWMDrawItem); message CN_DRAWITEM;
procedure WMDestroy(var Message: TWMDestroy); message WM_DESTROY;
procedure WMNotifyFormat(var Message: TMessage); message WM_NOTIFYFORMAT;
procedure WMNCHitTest(var message:TWMNCHitTest); message WM_NCHITTEST;
procedure WMSize(var Message: TMessage); message WM_SIZE;
protected
procedure AdjustClientRect(var Rect: TRect); override;
function CanChange: Boolean; dynamic;
function CanShowTab(TabIndex: Integer): Boolean; virtual;
procedure Change; dynamic;
procedure CreateParams(var Params: TCreateParams); override;
procedure CreateWnd; override;
procedure DestroyWnd; override;
procedure DisplayTabHint(TabIndex:integer); virtual; abstract;
procedure DrawTab(TabIndex: Integer; const Rect: TRect; Active: Boolean); virtual;
function GetImageIndex(TabIndex: Integer): Integer; virtual;
procedure Loaded; override;
procedure UpdateTabImages;
property TabIndex: Integer read GetTabIndex write SetTabIndex default -1;
property AllowTabShifting:boolean read fTabShifting write fTabShifting default false;
property DisplayRect: TRect read GetDisplayRect;
property HotTrack: Boolean read FHotTrack write SetHotTrack default False;
property Images: TCustomImageList read FImages write SetImages;
property MultiLine: Boolean read FMultiLine write SetMultiLine default False;
property MultiSelect: Boolean read FMultiSelect write SetMultiSelect default False;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
property OwnerDraw: Boolean read FOwnerDraw write SetOwnerDraw default False;
property RaggedRight: Boolean read FRaggedRight write SetRaggedRight default False;
property ScrollOpposite: Boolean read FScrollOpposite
write SetScrollOpposite default False;
property Style: TTabStyle read FStyle write SetStyle default tsTabs;
property TabHeight: Smallint read FTabSize.Y write SetTabHeight default 0;
property TabPosition: TTabPosition read FTabPosition write SetTabPosition
default tpTop;
property Tabs: TStrings read FTabs write SetTabs;
property TabWidth: Smallint read FTabSize.X write SetTabWidth default 0;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
property OnChanging: TTabChangingEvent read FOnChanging write FOnChanging;
property OnDrawTab: TDrawTabEvent read FOnDrawTab write FOnDrawTab;
property OnGetImageIndex: TTabGetImageEvent read FOnGetImageIndex write FOnGetImageIndex;
property OnTabTrack:TTabTrackEvent read fontabtrack write fontabtrack;
property OnTabShift:TNotifyEvent read FOnTabShift write FOnTabShift;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function GetTabAt(x,y:integer):integer;
property Canvas: TCanvas read FCanvas;
property TabStop default True;
end;
TrmCCTabControl = class(TrmCustomCCTabControl)
private
FTabHints:TStringList;
procedure SetTabHints(value:TStringList);
protected
procedure DisplayTabHint(TabIndex:integer); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property DisplayRect;
published
property AllowTabShifting;
property Align;
property Anchors;
property BiDiMode;
property Constraints;
property DockSite;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property Font;
property HotTrack;
property Images;
property MultiLine;
property MultiSelect;
property OwnerDraw;
property ParentBiDiMode;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property RaggedRight;
property ScrollOpposite;
property ShowHint;
property Style;
property TabHeight;
property TabHints: TStringList read ftabHints write SetTabHints;
property TabOrder;
property TabPosition;
property Tabs;
property TabIndex; // must be after Tabs
property TabStop;
property TabWidth;
property Visible;
property OnChange;
property OnChanging;
property OnDockDrop;
property OnDockOver;
property OnDragDrop;
property OnDragOver;
property OnDrawTab;
property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnGetImageIndex;
property OnGetSiteInfo;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnResize;
property OnStartDock;
property OnStartDrag;
property OnTabTrack;
property OnTabShift;
property OnUnDock;
end;
TrmCCPageControl = class;
TrmCCTabSheet = class;
TrmCCTabsFloatingForm = class(TForm)
private
{ Private declarations }
FSheet : TrmCCTabSheet;
fMoveSize: TNotifyEvent;
procedure DoCloseWindow(Sender: TObject; var Action: TCloseAction);
procedure DoDestroyWindow(Sender: TObject);
procedure wmExitSizeMove(var msg: TMessage); message WM_ExitSizeMove;
public
{ Public declarations }
constructor CreateNew(AOwner: TComponent); reintroduce;
property TabSheet: TrmCCTabSheet read FSheet write FSheet;
property OnMoveSize: TNotifyEvent read fMoveSize write fMoveSize;
end;
TrmCCTabSheet = class(TWinControl)
private
FImageIndex: Integer;
FPageControl: TrmCCPageControl;
FTabHint : string;
FTabVisible: Boolean;
FTabShowing: Boolean;
FOnHide: TNotifyEvent;
FOnShow: TNotifyEvent;
//Floating Vars...
fOldMousePos: TPoint; { previous mouse position }
fMouseOffset: TPoint; { Mouse coordinates in relation to client rect }
fDragStart: boolean;
fDragging: boolean; { true when dragging }
fDragRect: TRect; { position of rectangle while dragging }
fDragable: boolean; { true to make this dragable }
fWidth,
fHeight: integer; { width and height of client area at dragstart }
fOldPageControl: TrmCCPageControl; { saves the page control so that it can be reset }
ffloating: boolean;
FOnFloatChange: TTabFloatEvent;
{ fields for the form }
fFloatingForm : TrmCCTabsFloatingForm; { form to use when floating }
fFloatOnTop : Boolean;
fcanvas : tcanvas;
fGripAlign : TGripAlign;
FPageIndex : integer;
fMoveSize: TNotifyEvent;
function GetPageIndex: Integer;
function GetTabIndex: Integer;
procedure SetImageIndex(Value: Integer);
procedure SetPageControl(APageControl: TrmCCPageControl);
procedure SetPageIndex(Value: Integer);
procedure SetTabShowing(Value: Boolean);
procedure SetTabVisible(Value: Boolean);
procedure UpdateTabShowing;
procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED;
procedure CMShowingChanged(var Message: TMessage); message CM_SHOWINGCHANGED;
//Floating Tabsheet Procedures and Functions
procedure WMLButtonDown(var Msg : TWMLButtonDown); message WM_LBUTTONDOWN;
procedure WMMouseMove(var Msg : TWMMouseMove); message WM_MOUSEMOVE;
procedure WMLButtonUp(var Msg : TWMLButtonUp); message WM_LBUTTONUP;
procedure WMPaint(var msg:TWMPaint); message WM_Paint;
procedure DrawDraggingRect(MousePos : TPoint); { Draws the focus rectangle at appropriate place}
procedure setDragOption(value:boolean);
procedure setGripAlign(value:TGripAlign);
function GetGripRect:TRect;
function GetGripperRect:TRect;
procedure SetFloatOnTop(const Value: boolean);
procedure DoMoveSize(Sender: TObject);
protected
procedure CreateParams(var Params: TCreateParams); override;
procedure DoHide; dynamic;
procedure DoShow; dynamic;
procedure ReadState(Reader: TReader); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property PageControl: TrmCCPageControl read FPageControl write SetPageControl;
property TabIndex: Integer read GetTabIndex;
//Floating Tabsheet Procedures and Functions
procedure FloatTabSheet;
procedure FloatTabSheetBounds(aLeft, aTop, aWidth, aHeight: integer);
procedure DockTabSheet;
function GetClientRect:TRect; override;
property FloatingForm: TrmCCTabsFloatingForm read fFloatingForm;
property GripRect: TRect read GetGripperRect;
property Floating: Boolean read fFloating;
published
property BorderWidth;
property Caption;
property DragMode;
property Dragable : boolean read fDragable write SetDragOption default false; //Floating
property Enabled;
property FloatOnTop : boolean read FFloatOnTop write SetFloatOnTop default false;
property Font;
property GripAlign : TGripAlign read FGripAlign write SetGripAlign;
property Height stored False;
property ImageIndex: Integer read FImageIndex write SetImageIndex default 0;
property Left stored False;
property Constraints;
property PageIndex: Integer read GetPageIndex write SetPageIndex stored False;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property StaticPageIndex : integer read fpageindex write fpageindex;
property TabHint:string read FTabHint write FTabHint;
property TabVisible: Boolean read FTabVisible write SetTabVisible default True;
property Top stored False;
property Visible stored False;
property Width stored False;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnFloatChange: TTabFloatEvent read FOnFloatChange write FOnFloatChange;
property OnHide: TNotifyEvent read FOnHide write FOnHide;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnResize;
property OnShow: TNotifyEvent read FOnShow write FOnShow;
property OnStartDrag;
property OnFloatFormMoveSize: TNotifyEvent read fMoveSize write fMoveSize;
end;
TrmCCPageControl = class(TrmCustomCCTabControl)
private
FPages: TList;
FActivePage: TrmCCTabSheet;
FNewDockSheet: TrmCCTabSheet;
FUndockingPage: TrmCCTabSheet;
FFloatingPages: TList;
FOnFloatChange: TTabFloatEvent;
procedure ChangeActivePage(Page: TrmCCTabSheet);
procedure DeleteTab(Page: TrmCCTabSheet; Index: Integer);
function GetDockClientFromMousePos(MousePos: TPoint): TControl;
function GetPage(Index: Integer): TrmCCTabSheet;
function GetPageCount: Integer;
function GetFloatingPage(Index: Integer): TrmCCTabSheet;
function GetFloatingPageCount: Integer;
procedure InsertPage(Page: TrmCCTabSheet);
procedure InsertTab(Page: TrmCCTabSheet);
procedure MoveTab(CurIndex, NewIndex: Integer);
procedure RemovePage(Page: TrmCCTabSheet);
procedure SetActivePage(Page: TrmCCTabSheet);
procedure UpdateTab(Page: TrmCCTabSheet);
procedure UpdateActivePage;
procedure AddToFloatList(Page: TrmCCTabSheet);
procedure RemoveFromFloatList(Page: TrmCCTabSheet);
procedure CMTabDraggedOff(var Message:TMessage); message CM_rmCCTabSheetDraggedOFF;
procedure CMTabDraggedOn(var Message:TMessage); message CM_rmCCTabSheetDraggedON;
procedure CMDesignHitTest(var Message: TCMDesignHitTest); message CM_DESIGNHITTEST;
procedure CMDialogKey(var Message: TCMDialogKey); message CM_DIALOGKEY;
procedure CMDockClient(var Message: TCMDockClient); message CM_DOCKCLIENT;
procedure CMDockNotification(var Message: TCMDockNotification); message CM_DOCKNOTIFICATION;
procedure CMUnDockClient(var Message: TCMUnDockClient); message CM_UNDOCKCLIENT;
procedure WMLButtonDown(var Message: TWMLButtonDown); message WM_LBUTTONDOWN;
procedure WMLButtonDblClk(var Message: TWMLButtonDblClk); message WM_LBUTTONDBLCLK;
function GetActivePageIndex: Integer;
procedure SetActivePageIndex(const Value: Integer);
protected
function CanShowTab(TabIndex: Integer): Boolean; override;
procedure Change; override;
procedure DisplayTabHint(TabIndex:integer); override;
procedure DoAddDockClient(Client: TControl; const ARect: TRect); override;
procedure DockOver(Source: TDragDockObject; X, Y: Integer;
State: TDragState; var Accept: Boolean); override;
procedure DoRemoveDockClient(Client: TControl); override;
procedure GetChildren(Proc: TGetChildProc; Root: TComponent); override;
function GetImageIndex(TabIndex: Integer): Integer; override;
function GetPageFromDockClient(Client: TControl): TrmCCTabSheet;
procedure GetSiteInfo(Client: TControl; var InfluenceRect: TRect;
MousePos: TPoint; var CanDock: Boolean); override;
procedure SetChildOrder(Child: TComponent; Order: Integer); override;
procedure ShowControl(AControl: TControl); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function FindNextPage(CurPage: TrmCCTabSheet;
GoForward, CheckTabVisible: Boolean): TrmCCTabSheet;
procedure SelectNextPage(GoForward: Boolean);
procedure HideFloatingPages;
procedure ShowFloatingPages;
property PageCount: Integer read GetPageCount;
property Pages[Index: Integer]: TrmCCTabSheet read GetPage;
property FloatingPageCount: Integer read GetFloatingPageCount;
property FloatingPages[Index: Integer]: TrmCCTabSheet read GetFloatingPage;
property ActivePageIndex: Integer read GetActivePageIndex
write SetActivePageIndex;
published
property ActivePage: TrmCCTabSheet read FActivePage write SetActivePage;
property AllowTabShifting;
property Align;
property Anchors;
property BiDiMode;
property Constraints;
property DockSite;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property Font;
property HotTrack;
property Images;
property MultiLine;
property OwnerDraw;
property ParentBiDiMode;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property RaggedRight;
property ScrollOpposite;
property ShowHint;
property Style;
property TabHeight;
property TabOrder;
property TabPosition;
property TabStop;
property TabWidth;
property TabIndex;
property Visible;
property OnChange;
property OnChanging;
property OnDockDrop;
property OnDockOver;
property OnDragDrop;
property OnDragOver;
property OnDrawTab;
property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnFloatChange: TTabFloatEvent read FOnFloatChange write FOnFloatChange;
property OnGetImageIndex;
property OnGetSiteInfo;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnResize;
property OnStartDock;
property OnStartDrag;
property OnTabTrack;
property OnTabShift;
property OnUnDock;
end;
function InitCommonControl(CC: Integer): Boolean;
procedure CheckCommonControl(CC: Integer);
const
ComCtlVersionIE3 = $00040046;
ComCtlVersionIE4 = $00040047;
ComCtlVersionIE401 = $00040048;
function GetComCtlVersion: Integer;
implementation
uses Consts, ComStrs;
const
ComCtlDllName = 'comctl32.dll';
GripSize = 7;
var
ComCtlVersion: Integer;
function InitCommonControl(CC: Integer): Boolean;
var
ICC: TInitCommonControlsEx;
begin
ICC.dwSize := SizeOf(TInitCommonControlsEx);
ICC.dwICC := CC;
Result := InitCommonControlsEx(ICC);
if not Result then InitCommonControls;
end;
procedure CheckCommonControl(CC: Integer);
begin
if not InitCommonControl(CC) then
raise EComponentError.Create(SInvalidComCtl32);
end;
function GetComCtlVersion: Integer;
var
FileName: string;
InfoSize, Wnd: DWORD;
VerBuf: Pointer;
FI: PVSFixedFileInfo;
VerSize: DWORD;
begin
if ComCtlVersion = 0 then
begin
FileName := ComCtlDllName;
InfoSize := GetFileVersionInfoSize(PChar(FileName), Wnd);
if InfoSize <> 0 then
begin
GetMem(VerBuf, InfoSize);
try
if GetFileVersionInfo(PChar(FileName), Wnd, InfoSize, VerBuf) then
if VerQueryValue(VerBuf, '\', Pointer(FI), VerSize) then
ComCtlVersion := FI.dwFileVersionMS;
finally
FreeMem(VerBuf);
end;
end;
end;
Result := ComCtlVersion;
end;
procedure SetComCtlStyle(Ctl: TWinControl; Value: Integer; UseStyle: Boolean);
var
Style: Integer;
begin
if Ctl.HandleAllocated then
begin
Style := GetWindowLong(Ctl.Handle, GWL_STYLE);
if not UseStyle then Style := Style and not Value
else Style := Style or Value;
SetWindowLong(Ctl.Handle, GWL_STYLE, Style);
end;
end;
{ TTabStrings }
type
TTabStrings = class(TStrings)
private
FTabControl: TrmCustomCCTabControl;
protected
function Get(Index: Integer): string; override;
function GetCount: Integer; override;
function GetObject(Index: Integer): TObject; override;
procedure Put(Index: Integer; const S: string); override;
procedure PutObject(Index: Integer; AObject: TObject); override;
procedure SetUpdateState(Updating: Boolean); override;
public
procedure Clear; override;
procedure Delete(Index: Integer); override;
procedure Insert(Index: Integer; const S: string); override;
end;
procedure TabControlError(const S: string);
begin
raise EListError.Create(S);
end;
procedure TTabStrings.Clear;
begin
if SendMessage(FTabControl.Handle, TCM_DELETEALLITEMS, 0, 0) = 0 then
TabControlError(sTabFailClear);
FTabControl.TabsChanged;
end;
procedure TTabStrings.Delete(Index: Integer);
begin
if SendMessage(FTabControl.Handle, TCM_DELETEITEM, Index, 0) = 0 then
TabControlError(Format(sTabFailDelete, [Index]));
FTabControl.TabsChanged;
end;
function TTabStrings.Get(Index: Integer): string;
const
RTL: array[Boolean] of LongInt = (0, TCIF_RTLREADING);
var
TCItem: TTCItem;
Buffer: array[0..4095] of Char;
begin
TCItem.mask := TCIF_TEXT or RTL[FTabControl.UseRightToLeftReading];
TCItem.pszText := Buffer;
TCItem.cchTextMax := SizeOf(Buffer);
if SendMessage(FTabControl.Handle, TCM_GETITEM, Index,
Longint(@TCItem)) = 0 then
TabControlError(Format(sTabFailRetrieve, [Index]));
Result := Buffer;
end;
function TTabStrings.GetCount: Integer;
begin
Result := SendMessage(FTabControl.Handle, TCM_GETITEMCOUNT, 0, 0);
end;
function TTabStrings.GetObject(Index: Integer): TObject;
var
TCItem: TTCItem;
begin
TCItem.mask := TCIF_PARAM;
if SendMessage(FTabControl.Handle, TCM_GETITEM, Index,
Longint(@TCItem)) = 0 then
TabControlError(Format(sTabFailGetObject, [Index]));
Result := TObject(TCItem.lParam);
end;
procedure TTabStrings.Put(Index: Integer; const S: string);
const
RTL: array[Boolean] of LongInt = (0, TCIF_RTLREADING);
var
TCItem: TTCItem;
begin
TCItem.mask := TCIF_TEXT or RTL[FTabControl.UseRightToLeftReading] or
TCIF_IMAGE;
TCItem.pszText := PChar(S);
TCItem.iImage := FTabControl.GetImageIndex(Index);
if SendMessage(FTabControl.Handle, TCM_SETITEM, Index,
Longint(@TCItem)) = 0 then
TabControlError(Format(sTabFailSet, [S, Index]));
FTabControl.TabsChanged;
end;
procedure TTabStrings.PutObject(Index: Integer; AObject: TObject);
var
TCItem: TTCItem;
begin
TCItem.mask := TCIF_PARAM;
TCItem.lParam := Longint(AObject);
if SendMessage(FTabControl.Handle, TCM_SETITEM, Index,
Longint(@TCItem)) = 0 then
TabControlError(Format(sTabFailSetObject, [Index]));
end;
procedure TTabStrings.Insert(Index: Integer; const S: string);
const
RTL: array[Boolean] of LongInt = (0, TCIF_RTLREADING);
var
TCItem: TTCItem;
begin
TCItem.mask := TCIF_TEXT or RTL[FTabControl.UseRightToLeftReading] or
TCIF_IMAGE;
TCItem.pszText := PChar(S);
TCItem.iImage := FTabControl.GetImageIndex(Index);
if SendMessage(FTabControl.Handle, TCM_INSERTITEM, Index,
Longint(@TCItem)) < 0 then
TabControlError(Format(sTabFailSet, [S, Index]));
FTabControl.TabsChanged;
end;
procedure TTabStrings.SetUpdateState(Updating: Boolean);
begin
FTabControl.FUpdating := Updating;
SendMessage(FTabControl.Handle, WM_SETREDRAW, Ord(not Updating), 0);
if not Updating then
begin
FTabControl.Invalidate;
FTabControl.TabsChanged;
end;
end;
{ TrmCustomCCTabControl }
constructor TrmCustomCCTabControl.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Width := 289;
Height := 193;
TabStop := True;
ControlStyle := [csAcceptsControls, csDoubleClicks];
FTabs := TTabStrings.Create;
TTabStrings(FTabs).FTabControl := Self;
FCanvas := TControlCanvas.Create;
TControlCanvas(FCanvas).Control := Self;
FImageChangeLink := TChangeLink.Create;
FImageChangeLink.OnChange := ImageListChange;
fmouseovertab := -1;
fTabShifting := false;
end;
destructor TrmCustomCCTabControl.Destroy;
begin
FCanvas.Free;
FTabs.Free;
FSaveTabs.Free;
FImageChangeLink.Free;
inherited Destroy;
end;
function TrmCustomCCTabControl.CanChange: Boolean;
begin
Result := True;
if Assigned(FOnChanging) then FOnChanging(Self, Result);
end;
function TrmCustomCCTabControl.CanShowTab(TabIndex: Integer): Boolean;
begin
Result := True;
end;
procedure TrmCustomCCTabControl.Change;
begin
if Assigned(FOnChange) then FOnChange(Self);
end;
procedure TrmCustomCCTabControl.CreateParams(var Params: TCreateParams);
const
AlignStyles: array[Boolean, TTabPosition] of DWORD =
((0, TCS_BOTTOM, TCS_VERTICAL, TCS_VERTICAL or TCS_RIGHT),
(0, TCS_BOTTOM, TCS_VERTICAL or TCS_RIGHT, TCS_VERTICAL));
TabStyles: array[TTabStyle] of DWORD = (TCS_TABS, TCS_BUTTONS,
TCS_BUTTONS or TCS_FLATBUTTONS);
RRStyles: array[Boolean] of DWORD = (0, TCS_RAGGEDRIGHT);
begin
InitCommonControl(ICC_TAB_CLASSES);
inherited CreateParams(Params);
CreateSubClass(Params, WC_TABCONTROL);
with Params do
begin
Style := Style or WS_CLIPCHILDREN or
AlignStyles[UseRightToLeftAlignment, FTabPosition] or
TabStyles[FStyle] or RRStyles[FRaggedRight];
if not TabStop then Style := Style or TCS_FOCUSNEVER;
if FMultiLine then Style := Style or TCS_MULTILINE;
if FMultiSelect then Style := Style or TCS_MULTISELECT;
if FOwnerDraw then Style := Style or TCS_OWNERDRAWFIXED;
if FTabSize.X <> 0 then Style := Style or TCS_FIXEDWIDTH;
if FHotTrack and (not (csDesigning in ComponentState)) then
Style := Style or TCS_HOTTRACK;
if FScrollOpposite then Style := Style or TCS_SCROLLOPPOSITE;
WindowClass.style := WindowClass.style and not (CS_HREDRAW or CS_VREDRAW) or
CS_DBLCLKS;
end;
end;
procedure TrmCustomCCTabControl.CreateWnd;
begin
inherited CreateWnd;
if (Images <> nil) and Images.HandleAllocated then
Perform(TCM_SETIMAGELIST, 0, Images.Handle);
if Integer(FTabSize) <> 0 then UpdateTabSize;
if FSaveTabs <> nil then
begin
FTabs.Assign(FSaveTabs);
SetTabIndex(FSaveTabIndex);
FSaveTabs.Free;
FSaveTabs := nil;
end;
end;
procedure TrmCustomCCTabControl.DestroyWnd;
begin
if FTabs.Count > 0 then
begin
FSaveTabs := TStringList.Create;
FSaveTabs.Assign(FTabs);
FSaveTabIndex := GetTabIndex;
end;
inherited DestroyWnd;
end;
procedure TrmCustomCCTabControl.DrawTab(TabIndex: Integer; const Rect: TRect;
Active: Boolean);
begin
if Assigned(FOnDrawTab) then
FOnDrawTab(Self, TabIndex, Rect, Active) else
FCanvas.FillRect(Rect);
end;
function TrmCustomCCTabControl.GetDisplayRect: TRect;
begin
Result := ClientRect;
SendMessage(Handle, TCM_ADJUSTRECT, 0, Integer(@Result));
Inc(Result.Top, 2);
end;
function TrmCustomCCTabControl.GetImageIndex(TabIndex: Integer): Integer;
begin
Result := TabIndex;
if Assigned(FOnGetImageIndex) then FOnGetImageIndex(Self, TabIndex, Result);
end;
function TrmCustomCCTabControl.GetTabIndex: Integer;
begin
Result := SendMessage(Handle, TCM_GETCURSEL, 0, 0);
end;
procedure TrmCustomCCTabControl.Loaded;
begin
inherited Loaded;
if Images <> nil then UpdateTabImages;
end;
procedure TrmCustomCCTabControl.SetHotTrack(Value: Boolean);
begin
if FHotTrack <> Value then
begin
FHotTrack := Value;
RecreateWnd;
end;
end;
procedure TrmCustomCCTabControl.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation = opRemove) and (AComponent = Images) then
Images := nil;
end;
procedure TrmCustomCCTabControl.SetImages(Value: TCustomImageList);
begin
if Images <> nil then
Images.UnRegisterChanges(FImageChangeLink);
FImages := Value;
if Images <> nil then
begin
Images.RegisterChanges(FImageChangeLink);
Images.FreeNotification(Self);
Perform(TCM_SETIMAGELIST, 0, Images.Handle);
end
else Perform(TCM_SETIMAGELIST, 0, 0);
end;
procedure TrmCustomCCTabControl.ImageListChange(Sender: TObject);
begin
Perform(TCM_SETIMAGELIST, 0, TCustomImageList(Sender).Handle);
end;
function TrmCustomCCTabControl.InternalSetMultiLine(Value: Boolean): Boolean;
begin
Result := FMultiLine <> Value;
if Result then
begin
if not Value and ((TabPosition = tpLeft) or (TabPosition = tpRight)) then
TabControlError(sTabMustBeMultiLine);
FMultiLine := Value;
if not Value then FScrollOpposite := False;
end;
end;
procedure TrmCustomCCTabControl.SetMultiLine(Value: Boolean);
begin
if InternalSetMultiLine(Value) then RecreateWnd;
end;
procedure TrmCustomCCTabControl.SetMultiSelect(Value: Boolean);
begin
if FMultiSelect <> Value then
begin
FMultiSelect := Value;
RecreateWnd;
end;
end;
procedure TrmCustomCCTabControl.SetOwnerDraw(Value: Boolean);
begin
if FOwnerDraw <> Value then
begin
FOwnerDraw := Value;
RecreateWnd;
end;
end;
procedure TrmCustomCCTabControl.SetRaggedRight(Value: Boolean);
begin
if FRaggedRight <> Value then
begin
FRaggedRight := Value;
SetComCtlStyle(Self, TCS_RAGGEDRIGHT, Value);
end;
end;
procedure TrmCustomCCTabControl.SetScrollOpposite(Value: Boolean);
begin
if FScrollOpposite <> Value then
begin
FScrollOpposite := Value;
if Value then FMultiLine := Value;
RecreateWnd;
end;
end;
procedure TrmCustomCCTabControl.SetStyle(Value: TTabStyle);
begin
if FStyle <> Value then
begin
if (Value <> tsTabs) and (TabPosition <> tpTop) then
raise EInvalidOperation.Create(SInvalidTabStyle);
FStyle := Value;
RecreateWnd;
end;
end;
procedure TrmCustomCCTabControl.SetTabHeight(Value: Smallint);
begin
if FTabSize.Y <> Value then
begin
if Value < 0 then
raise EInvalidOperation.CreateFmt(SPropertyOutOfRange, [Self.Classname]);
FTabSize.Y := Value;
UpdateTabSize;
end;
end;
procedure TrmCustomCCTabControl.SetTabIndex(Value: Integer);
begin
SendMessage(Handle, TCM_SETCURSEL, Value, 0);
end;
procedure TrmCustomCCTabControl.SetTabPosition(Value: TTabPosition);
const
AlignStyles: array[TTabPosition] of Integer =
(0, TCS_BOTTOM, TCS_VERTICAL, TCS_VERTICAL or TCS_RIGHT);
begin
if FTabPosition <> Value then
begin
if (Value <> tpTop) and (Style <> tsTabs) then
raise EInvalidOperation.Create(SInvalidTabPosition);
FTabPosition := Value;
if not MultiLine and ((Value = tpLeft) or (Value = tpRight)) then
InternalSetMultiLine(True);
RecreateWnd;
end;
end;
procedure TrmCustomCCTabControl.SetTabs(Value: TStrings);
begin
FTabs.Assign(Value);
end;
procedure TrmCustomCCTabControl.SetTabWidth(Value: Smallint);
var
OldValue: Smallint;
begin
if FTabSize.X <> Value then
begin
if Value < 0 then
raise EInvalidOperation.CreateFmt(SPropertyOutOfRange, [Self.Classname]);
OldValue := FTabSize.X;
FTabSize.X := Value;
if (OldValue = 0) or (Value = 0) then RecreateWnd
else UpdateTabSize;
end;
end;
procedure TrmCustomCCTabControl.TabsChanged;
begin
if not FUpdating then
begin
if HandleAllocated then
SendMessage(Handle, WM_SIZE, SIZE_RESTORED,
Word(Width) or Word(Height) shl 16);
Realign;
end;
end;
procedure TrmCustomCCTabControl.UpdateTabSize;
begin
SendMessage(Handle, TCM_SETITEMSIZE, 0, Integer(FTabSize));
TabsChanged;
end;
procedure TrmCustomCCTabControl.UpdateTabImages;
var
I: Integer;
TCItem: TTCItem;
begin
TCItem.mask := TCIF_IMAGE;
for I := 0 to FTabs.Count - 1 do
begin
TCItem.iImage := GetImageIndex(I);
if SendMessage(Handle, TCM_SETITEM, I,
Longint(@TCItem)) = 0 then
TabControlError(Format(sTabFailSet, [FTabs[I], I]));
end;
TabsChanged;
end;
procedure TrmCustomCCTabControl.CNDrawItem(var Message: TWMDrawItem);
var
SaveIndex: Integer;
begin
with Message.DrawItemStruct^ do
begin
SaveIndex := SaveDC(hDC);
FCanvas.Handle := hDC;
FCanvas.Font := Font;
FCanvas.Brush := Brush;
DrawTab(itemID, rcItem, itemState and ODS_SELECTED <> 0);
FCanvas.Handle := 0;
RestoreDC(hDC, SaveIndex);
end;
Message.Result := 1;
end;
procedure TrmCustomCCTabControl.WMDestroy(var Message: TWMDestroy);
var
FocusHandle: HWnd;
begin
FocusHandle := GetFocus;
if (FocusHandle <> 0) and ((FocusHandle = Handle) or
IsChild(Handle, FocusHandle)) then
Windows.SetFocus(0);
inherited;
end;
procedure TrmCustomCCTabControl.WMNotifyFormat(var Message: TMessage);
begin
with Message do
Result := DefWindowProc(Handle, Msg, WParam, LParam);
end;
procedure TrmCustomCCTabControl.WMSize(var Message: TMessage);
begin
inherited;
RedrawWindow(Handle, nil, 0, RDW_INVALIDATE or RDW_ERASE);
end;
procedure TrmCustomCCTabControl.CMFontChanged(var Message);
begin
inherited;
if HandleAllocated then Perform(WM_SIZE, 0, 0);
end;
procedure TrmCustomCCTabControl.CMSysColorChange(var Message: TMessage);
begin
inherited;
if not (csLoading in ComponentState) then
begin
Message.Msg := WM_SYSCOLORCHANGE;
DefaultHandler(Message);
end;
end;
procedure TrmCustomCCTabControl.CMTabStopChanged(var Message: TMessage);
begin
if not (csDesigning in ComponentState) then RecreateWnd;
end;
procedure TrmCustomCCTabControl.CNNotify(var Message: TWMNotify);
begin
with Message do
case NMHdr^.code of
TCN_SELCHANGE:
Change;
TCN_SELCHANGING:
begin
Result := 1;
if CanChange then Result := 0;
end;
end;
end;
procedure TrmCustomCCTabControl.CMDialogChar(var Message: TCMDialogChar);
var
I: Integer;
begin
for I := 0 to FTabs.Count - 1 do
if IsAccel(Message.CharCode, FTabs[I]) and CanShowTab(I) and CanFocus then
begin
TabIndex := I;
Message.Result := 1;
Change;
Exit;
end;
inherited;
end;
procedure TrmCustomCCTabControl.AdjustClientRect(var Rect: TRect);
begin
Rect := DisplayRect;
inherited AdjustClientRect(Rect);
end;
procedure TrmCustomCCTabControl.CMMouseLeave(var message: tmessage);
var
oldtab:trect;
begin
inherited;
if (hottrack) and not (csdesigning in componentstate) then
begin
sendmessage(handle,TCM_GetItemRect, fmouseovertab, longint(@OldTab));
InvalidateRect(handle,@OldTab,false);
fmouseovertab := -1;
end;
end;
procedure TrmCustomCCTabControl.WMNCHitTest(var message: TWMNCHitTest);
var
HitTest : TTCHitTestInfo;
result : integer;
OldTab, NewTab : trect;
begin
inherited;
if not (csdesigning in componentstate) then
begin
HitTest.pt := screentoclient(point(message.XPos,message.ypos));
HitTest.flags := TCHT_ONITEM;
result := sendmessage(handle,TCM_HITTEST,0,longint(@HitTest));
if (result <> fmouseovertab) then
begin
if assigned(fontabtrack) then
fontabtrack(self,result);
DisplayTabHint(result);
if (hottrack) then
begin
sendmessage(handle,TCM_GetItemRect, fmouseovertab, longint(@OldTab));
sendmessage(handle,TCM_GetItemRect, result, longint(@NewTab));
InvalidateRect(handle,@OldTab,false);
InvalidateRect(handle,@NewTab,false);
end;
fmouseovertab := result;
end;
end
else
fmouseovertab := -1;
end;
function TrmCustomCCTabControl.GetTabAt(x,y:integer):integer;
var
HitTest : TTCHitTestInfo;
begin
HitTest.pt := point(x,y);
HitTest.flags := TCHT_ONITEM;
result := sendmessage(handle,TCM_HITTEST,0,longint(@HitTest));
end;
{ TrmCCTabControl }
constructor TrmCCTabControl.Create(AOwner: TComponent);
begin
inherited;
FTabHints:=TStringList.Create;
end;
destructor TrmCCTabControl.Destroy;
begin
FTabHints.Free;
inherited;
end;
procedure TrmCCTabControl.DisplayTabHint(TabIndex: integer);
begin
application.CancelHint;
if (tabindex > -1) and (tabindex < tabhints.Count) then
hint := trim(tabhints.strings[tabindex]);
end;
procedure TrmCCTabControl.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
if (ftabshifting) and (button = mbleft) and (fMouseOverTab = TabIndex) then
fMouseDragTab := fMouseOverTab;
Inherited;
end;
procedure TrmCCTabControl.MouseMove(Shift: TShiftState; X, Y: Integer);
begin
if (ftabshifting) then
begin
if (ssLeft in Shift) then
begin
if (fMouseOverTab = -1) then
Cursor := crNo
else
if (fMouseDragTab <> fMouseOverTab) then
Cursor := crDrag
else
Cursor := crDefault;
end
else
Cursor := crDefault;
end;
inherited;
end;
procedure TrmCCTabControl.MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
if (ftabshifting) and (button = mbleft) and (fMouseDragTab <> fMouseOverTab) and (fMouseOverTab <> -1) then
begin
Tabs.Move(fMouseDragTab,fMouseOverTab);
Cursor := crDefault;
if assigned(fOnTabShift) then fOnTabShift(self);
end;
inherited;
end;
procedure TrmCCTabControl.SetTabHints(value: TStringList);
begin
ftabhints.assign(value);
end;
{ TrmCCTabsFloatingForm }
constructor TrmCCTabsFloatingForm.CreateNew(AOwner: TComponent);
begin
inherited CreateNew(AOwner);
OnClose := DoCloseWindow;
OnDestroy := DoDestroyWindow;
end;
procedure TrmCCTabsFloatingForm.DoCloseWindow(Sender: TObject; var Action: TCloseAction);
begin
if assigned(fsheet) then fsheet.docktabsheet;
action := cafree;
end;
procedure TrmCCTabsFloatingForm.DoDestroyWindow(Sender: TObject);
begin
fsheet.ffloatingform := nil;
end;
{ TTabSheet }
constructor TrmCCTabSheet.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Align := alClient;
ControlStyle := ControlStyle + [csAcceptsControls, csNoDesignVisible];
Visible := False;
FTabVisible := True;
FCanvas := TControlCanvas.Create;
TControlCanvas(FCanvas).Control := Self;
fpageindex := -1;
fdragstart := false;
fDragging := false;
GripAlign := gaLeft;
end;
destructor TrmCCTabSheet.Destroy;
begin
fcanvas.free;
if FPageControl <> nil then
begin
if FPageControl.FUndockingPage = Self then FPageControl.FUndockingPage := nil;
FPageControl.RemovePage(Self);
end;
inherited Destroy;
end;
procedure TrmCCTabSheet.DoHide;
begin
if Assigned(FOnHide) then FOnHide(Self);
end;
procedure TrmCCTabSheet.DoShow;
begin
if Assigned(FOnShow) then FOnShow(Self);
end;
function TrmCCTabSheet.GetPageIndex: Integer;
begin
if FPageControl <> nil then
Result := FPageControl.FPages.IndexOf(Self) else
Result := -1;
end;
function TrmCCTabSheet.GetTabIndex: Integer;
var
I: Integer;
begin
Result := 0;
if not FTabShowing then Dec(Result) else
for I := 0 to PageIndex - 1 do
if TrmCCTabSheet(FPageControl.FPages[I]).FTabShowing then
Inc(Result);
end;
procedure TrmCCTabSheet.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
with Params.WindowClass do
style := style and not (CS_HREDRAW or CS_VREDRAW);
end;
procedure TrmCCTabSheet.ReadState(Reader: TReader);
begin
inherited ReadState(Reader);
if Reader.Parent is TrmCCPageControl then
PageControl := TrmCCPageControl(Reader.Parent);
end;
procedure TrmCCTabSheet.SetImageIndex(Value: Integer);
begin
if FImageIndex <> Value then
begin
FImageIndex := Value;
if FTabShowing then FPageControl.UpdateTab(Self);
end;
end;
procedure TrmCCTabSheet.SetPageControl(APageControl: TrmCCPageControl);
begin
if FPageControl <> APageControl then
begin
if FPageControl <> nil then FPageControl.RemovePage(Self);
Parent := APageControl;
if APageControl <> nil then APageControl.InsertPage(Self);
end;
end;
procedure TrmCCTabSheet.SetPageIndex(Value: Integer);
var
I, MaxPageIndex: Integer;
begin
if FPageControl <> nil then
begin
MaxPageIndex := FPageControl.FPages.Count - 1;
if Value > MaxPageIndex then
raise EListError.CreateFmt(SPageIndexError, [Value, MaxPageIndex]);
I := TabIndex;
FPageControl.FPages.Move(PageIndex, Value);
if I >= 0 then FPageControl.MoveTab(I, TabIndex);
end;
end;
procedure TrmCCTabSheet.SetTabShowing(Value: Boolean);
var
Index: Integer;
begin
if FTabShowing <> Value then
if Value then
begin
FTabShowing := True;
FPageControl.InsertTab(Self);
end else
begin
Index := TabIndex;
FTabShowing := False;
FPageControl.DeleteTab(Self, Index);
end;
end;
procedure TrmCCTabSheet.SetTabVisible(Value: Boolean);
begin
if FTabVisible <> Value then
begin
FTabVisible := Value;
UpdateTabShowing;
end;
end;
procedure TrmCCTabSheet.UpdateTabShowing;
begin
SetTabShowing((FPageControl <> nil) and
(FTabVisible or (csDesigning in ComponentState)));
end;
procedure TrmCCTabSheet.CMTextChanged(var Message: TMessage);
begin
if FTabShowing then FPageControl.UpdateTab(Self);
end;
procedure TrmCCTabSheet.CMShowingChanged(var Message: TMessage);
begin
inherited;
if Showing then
begin
try
DoShow
except
Application.HandleException(Self);
end;
end else if not Showing then
begin
try
DoHide;
except
Application.HandleException(Self);
end;
end;
end;
procedure TrmCCTabSheet.DrawDraggingRect(MousePos : TPoint);
var
DC : hDC; { device context for the window }
Canvas : TCanvas; { canvas to draw dragging rect }
AdjustedRect : TRect; { fDragRect adjusted for MousePos }
ScreenPos : TPoint; { screen-relative version of MousePos }
begin
DC := GetWindowDc(GetDesktopWindow);
if DC <> 0 then begin
ScreenPos := ClientToScreen(MousePos);
with AdjustedRect do begin
Left := ScreenPos.X-fMouseOffset.X;
Top := ScreenPos.Y-fMouseOffset.Y;
Right := Left+fWidth;
Bottom := Top+fHeight;
end; { with AdjustedRect do }
fDragRect := AdjustedRect;
Canvas := TCanvas.Create;
Canvas.Handle := DC;
Canvas.DrawFocusRect(AdjustedRect);
Canvas.Free;
end else
Raise ECCTabError.Create('Error retreiving DC(0)');
end;
procedure TrmCCTabSheet.WMLBUTTONDOWN(var Msg : TWMLButtonDown);
begin
inherited;
if ffloating then exit;
if (fDragable) and (ptinrect(GripRect, point(msg.pos.x,msg.pos.y))) then
begin
fDragStart := TRUE;
fWidth := width;
fHeight := height;
fOldMousePos := Point(Msg.Pos.x,Msg.Pos.y);
fMouseOffset := fOldMousePos;
end;
end;
procedure TrmCCTabSheet.WMMOUSEMOVE(var Msg : TWMMouseMove);
begin
inherited;
if (fDragStart) and ((abs(foldmousepos.x - msg.pos.x) > 3) or (abs(foldmousepos.y - msg.pos.y) > 3)) then
begin
fdragging := true;
fDragStart := false;
DrawDraggingRect(fOldMousePos);
end;
if fDragging then
begin
DrawDraggingRect(fOldMousePos);
fOldMousePos := Point(Msg.Pos.x,Msg.Pos.y);
DrawDraggingRect(fOldMousePos);
end;
end;
procedure TrmCCTabSheet.WMLBUTTONUP(var Msg : TWMLButtonDown);
begin
inherited;
if fDragging then
begin
DrawDraggingRect(fOldMousePos);
FloatTabSheet;
fDragging := FALSE;
end; { if dragging }
if fDragStart then
begin
fDragStart := false;
invalidate;
end;
end;
procedure TrmCCTabSheet.FloatTabSheet;
var
ScreenPos: TPoint;
begin
if (not FFloating) then
begin
if not fDragging then
begin
ScreenPos := ClientToScreen(Point(Left, Top));
with fDragRect do begin
Left := ScreenPos.X;
Top := ScreenPos.Y;
fWidth := ClientRect.Right;
fHeight := ClientRect.Bottom;
Right := Left + fWidth;
Bottom := Top + fHeight;
end;
end;
fOldPageControl := PageControl;
PageControl := nil;
FFloating := true;
fOldPageControl.SelectNextPage(True);
fOldPageControl.AddToFloatList(self);
fOldPageControl.Perform(CM_rmCCTabSheetDraggedOFF,0,0);
if not assigned(fFloatingForm) then
begin
fFloatingForm := TrmCCTabsFloatingForm.CreateNew(self.owner);
if (fFloatOnTop) and (Application.mainform <> nil) and (Application.mainform is tform) then
setwindowlong(ffloatingform.handle,gwl_hwndparent,Application.mainform.handle);
if assigned(fOldPageControl.images) and (imageindex <> -1) then
fOldPageControl.Images.GetIcon(imageindex,ffloatingform.Icon);
fFloatingForm.OnMoveSize := DoMoveSize;
fFloatingForm.Caption := Caption;
fFloatingForm.ClientWidth := fWidth;
fFloatingForm.ClientHeight := fHeight;
fFloatingForm.TabSheet := self;
end;
fFloatingForm.Left := fDragRect.Left;
fFloatingForm.Top := fDragRect.Top;
if assigned(FOnFloatChange) then
FOnFloatChange(Self, fsFloating);
Parent := fFloatingForm;
fFloatingForm.Show;
Show;
end;
end;
procedure TrmCCTabSheet.DockTabSheet;
begin
if FFloating then
begin
fFloatingForm.Hide;
FFloating := false;
PageControl:= fOldPageControl;
PageControl.RemoveFromFloatList(self);
PageControl.Perform(CM_rmCCTabSheetDraggedON,0,Integer(@Self));
PageControl.ActivePage := Self;
foldPageControl := nil;
if assigned(FOnFloatChange) then
FOnFloatChange(Self, fsDocked);
end;
end;
function TrmCCTabSheet.GetClientRect:TRect;
var
clientrect : trect;
begin
clientrect := inherited GetClientRect;
if (not dragable) or (ffloating) then
result := clientrect
else
begin
case gripalign of
gaLeft: clientrect.Left := clientrect.Left + GripSize;
gaRight: clientrect.right := clientrect.right - GripSize;
gaTop: clientrect.Top := clientrect.top + GripSize;
gaBottom: clientrect.bottom := clientrect.bottom - GripSize;
end;
result := clientrect;
end;
end;
procedure TrmCCTabSheet.setDragOption(value:boolean);
begin
if value <> fdragable then
begin
fDragable := value;
realign;
invalidate;
end;
end;
procedure TrmCCTabSheet.setGripAlign(value:TGripAlign);
begin
fGripAlign := value;
realign;
invalidate;
end;
function TrmCCTabSheet.GetGripRect:TRect;
begin
result := Rect(0,0,0,0);
if (dragable) and (not fFloating) then
case GripAlign of
gaLeft: result := rect(0,0,GripSize,height);
gaRight: result := rect(width-GripSize,0,width,height);
gaTop: result := rect(0,0,width,GripSize);
gaBottom: result := rect(0,height-gripsize,width,height);
end;
end;
function TrmCCTabSheet.GetGripperRect:TRect;
begin
result := Rect(0,0,0,0);
if (dragable) and (not fFloating) then
case GripAlign of
gaLeft: result := rect(0,0,GripSize,20);
gaRight: result := rect(width-GripSize,height-20,width,height);
gaTop: result := rect(width-20,0,width,GripSize);
gaBottom: result := rect(0,height-gripsize,20,height);
end;
end;
procedure TrmCCTabSheet.WMPaint(var msg:TWMPaint);
const
xpos = 4;
var
loop : integer;
workcolor : tcolor;
position : integer;
ypos : integer;
begin
inherited;
if (dragable) and not (FFloating) then
with fcanvas do
begin
brush.color := clbtnface;
brush.style := bsSolid;
fillrect(GetGripRect);
if enabled then
workcolor := clactivecaption
else
workcolor := clinactivecaption;
ypos := 0;
if gripalign = gabottom then ypos := (height-gripsize)+2;
if gripalign = garight then ypos := (width-gripsize)+2;
if (gripalign in [gabottom, gaTop]) then
for loop := 0 to 4 do
begin
if gripalign = gaTop then position := (width - (xpos * loop))-4
else
position := xpos * loop;
pixels[position,ypos] := clbtnhighlight;
pixels[1+position,ypos] := workcolor;
pixels[position,ypos+1] := workcolor;
pixels[1+position,ypos+1] := workcolor;
pixels[2+position,ypos+3] := clbtnhighlight;
pixels[3+position,ypos+3] := workcolor;
pixels[2+position,ypos+4] := workcolor;
pixels[3+position,ypos+4] := workcolor;
end;
if (gripalign = gaLeft) or (gripalign = gaRight) then
for loop := 0 to 4 do
begin
if gripalign = gaRight then position := (height - (xpos * loop))-4
else
position := xpos*loop;
pixels[ypos,position] := clbtnhighlight;
pixels[ypos,1+position] := workcolor;
pixels[ypos+1,position] := workcolor;
pixels[ypos+1,1+position] := workcolor;
pixels[ypos+3,2+position] := clbtnhighlight;
pixels[ypos+3,3+position] := workcolor;
pixels[ypos+4,2+position] := workcolor;
pixels[ypos+4,3+position] := workcolor;
end;
end;
end;
procedure TrmCCTabSheet.SetFloatOnTop(const Value: boolean);
begin
if FFloatOnTop <> Value then
begin
FFloatOnTop := Value;
if Floating then
begin
if Value then
if (Application.MainForm <> nil) and (Application.MainForm is TForm) then
setwindowlong(FFloatingForm.Handle,gwl_hwndparent,Application.MainForm.Handle)
else
setwindowlong(FFloatingForm.Handle,gwl_hwndparent,0);
end
end;
end;
procedure TrmCCTabsFloatingForm.wmExitSizeMove(var msg: TMessage);
begin
inherited;
if assigned(fMoveSize) then
fMoveSize(self);
end;
{ TrmCCPageControl }
constructor TrmCCPageControl.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ControlStyle := [csDoubleClicks, csOpaque];
FPages := TList.Create;
FFloatingPages := TList.create;
end;
destructor TrmCCPageControl.Destroy;
var
I: Integer;
begin
for I := 0 to FPages.Count - 1 do TrmCCTabSheet(FPages[I]).FPageControl := nil;
FPages.Free;
for I := 0 to FFloatingPages.Count - 1 do TrmCCTabSheet(FFloatingPages[I]).FPageControl := nil;
FFloatingPages.free;
inherited Destroy;
end;
function TrmCCPageControl.CanShowTab(TabIndex: Integer): Boolean;
begin
Result := TrmCCTabSheet(FPages[TabIndex]).Enabled;
end;
procedure TrmCCPageControl.Change;
var
Form: TCustomForm;
begin
UpdateActivePage;
if csDesigning in ComponentState then
begin
Form := GetParentForm(Self);
if (Form <> nil) and (Form.Designer <> nil) then Form.Designer.Modified;
end;
inherited Change;
end;
procedure TrmCCPageControl.ChangeActivePage(Page: TrmCCTabSheet);
var
ParentForm: TCustomForm;
begin
if FActivePage <> Page then
begin
ParentForm := GetParentForm(Self);
if (ParentForm <> nil) and (FActivePage <> nil) and
FActivePage.ContainsControl(ParentForm.ActiveControl) then
begin
ParentForm.ActiveControl := FActivePage;
if ParentForm.ActiveControl <> FActivePage then
begin
TabIndex := FActivePage.TabIndex;
Exit;
end;
end;
if Page <> nil then
begin
Page.BringToFront;
Page.Visible := True;
if (ParentForm <> nil) and (FActivePage <> nil) and
(ParentForm.ActiveControl = FActivePage) then
if Page.CanFocus then
ParentForm.ActiveControl := Page else
ParentForm.ActiveControl := Self;
end;
if FActivePage <> nil then FActivePage.Visible := False;
FActivePage := Page;
if (ParentForm <> nil) and (FActivePage <> nil) and
(ParentForm.ActiveControl = FActivePage) then
FActivePage.SelectFirst;
end;
end;
procedure TrmCCPageControl.DeleteTab(Page: TrmCCTabSheet; Index: Integer);
var
UpdateIndex: Boolean;
begin
UpdateIndex := Page = ActivePage;
Tabs.Delete(Index);
if UpdateIndex then
begin
if Index >= Tabs.Count then
Index := Tabs.Count - 1;
TabIndex := Index;
end;
UpdateActivePage;
end;
procedure TrmCCPageControl.DoAddDockClient(Client: TControl; const ARect: TRect);
begin
if FNewDockSheet <> nil then Client.Parent := FNewDockSheet;
end;
procedure TrmCCPageControl.DockOver(Source: TDragDockObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
var
R: TRect;
begin
GetWindowRect(Handle, R);
Source.DockRect := R;
DoDockOver(Source, X, Y, State, Accept);
end;
procedure TrmCCPageControl.DoRemoveDockClient(Client: TControl);
begin
if (FUndockingPage <> nil) and not (csDestroying in ComponentState) then
begin
SelectNextPage(True);
FUndockingPage.Free;
FUndockingPage := nil;
end;
end;
function TrmCCPageControl.FindNextPage(CurPage: TrmCCTabSheet;
GoForward, CheckTabVisible: Boolean): TrmCCTabSheet;
var
I, StartIndex: Integer;
begin
if FPages.Count <> 0 then
begin
StartIndex := FPages.IndexOf(CurPage);
if StartIndex = -1 then
if GoForward then StartIndex := FPages.Count - 1 else StartIndex := 0;
I := StartIndex;
repeat
if GoForward then
begin
Inc(I);
if I = FPages.Count then I := 0;
end else
begin
if I = 0 then I := FPages.Count;
Dec(I);
end;
Result := FPages[I];
if not CheckTabVisible or Result.TabVisible then Exit;
until I = StartIndex;
end;
Result := nil;
end;
procedure TrmCCPageControl.GetChildren(Proc: TGetChildProc; Root: TComponent);
var
I: Integer;
begin
for I := 0 to FPages.Count - 1 do Proc(TComponent(FPages[I]));
end;
function TrmCCPageControl.GetImageIndex(TabIndex: Integer): Integer;
begin
if Assigned(FOnGetImageIndex) then
Result := inherited GetImageIndex(TabIndex) else
Result := GetPage(TabIndex).ImageIndex;
end;
function TrmCCPageControl.GetPageFromDockClient(Client: TControl): TrmCCTabSheet;
var
I: Integer;
begin
Result := nil;
for I := 0 to PageCount - 1 do
begin
if (Client.Parent = Pages[I]) and (Client.HostDockSite = Self) then
begin
Result := Pages[I];
Exit;
end;
end;
end;
function TrmCCPageControl.GetPage(Index: Integer): TrmCCTabSheet;
begin
Result := FPages[Index];
end;
function TrmCCPageControl.GetPageCount: Integer;
begin
Result := FPages.Count;
end;
procedure TrmCCPageControl.GetSiteInfo(Client: TControl; var InfluenceRect: TRect;
MousePos: TPoint; var CanDock: Boolean);
begin
CanDock := GetPageFromDockClient(Client) = nil;
inherited GetSiteInfo(Client, InfluenceRect, MousePos, CanDock);
end;
procedure TrmCCPageControl.InsertPage(Page: TrmCCTabSheet);
begin
FPages.Add(Page);
Page.FPageControl := Self;
Page.UpdateTabShowing;
end;
procedure TrmCCPageControl.InsertTab(Page: TrmCCTabSheet);
begin
Tabs.InsertObject(Page.TabIndex, Page.Caption, Page);
UpdateActivePage;
end;
procedure TrmCCPageControl.MoveTab(CurIndex, NewIndex: Integer);
begin
Tabs.Move(CurIndex, NewIndex);
end;
procedure TrmCCPageControl.RemovePage(Page: TrmCCTabSheet);
begin
Page.SetTabShowing(False);
Page.FPageControl := nil;
FPages.Remove(Page);
end;
procedure TrmCCPageControl.SelectNextPage(GoForward: Boolean);
var
Page: TrmCCTabSheet;
begin
Page := FindNextPage(ActivePage, GoForward, True);
if (Page <> nil) and (Page <> ActivePage) and CanChange then
begin
TabIndex := Page.TabIndex;
Change;
end;
end;
procedure TrmCCPageControl.SetActivePage(Page: TrmCCTabSheet);
begin
if (Page <> nil) and (Page.PageControl <> Self) then Exit;
ChangeActivePage(Page);
if Page = nil then
TabIndex := -1
else if Page = FActivePage then
TabIndex := Page.TabIndex;
end;
procedure TrmCCPageControl.SetChildOrder(Child: TComponent; Order: Integer);
begin
TrmCCTabSheet(Child).PageIndex := Order;
end;
procedure TrmCCPageControl.ShowControl(AControl: TControl);
begin
if (AControl is TrmCCTabSheet) and (TrmCCTabSheet(AControl).PageControl = Self) then
SetActivePage(TrmCCTabSheet(AControl));
inherited ShowControl(AControl);
end;
procedure TrmCCPageControl.UpdateTab(Page: TrmCCTabSheet);
begin
Tabs[Page.TabIndex] := Page.Caption;
end;
procedure TrmCCPageControl.UpdateActivePage;
begin
if TabIndex >= 0 then
SetActivePage(TrmCCTabSheet(Tabs.Objects[TabIndex]))
else
SetActivePage(nil);
end;
procedure TrmCCPageControl.CMDesignHitTest(var Message: TCMDesignHitTest);
var
HitIndex: Integer;
HitTestInfo: TTCHitTestInfo;
begin
HitTestInfo.pt := SmallPointToPoint(Message.Pos);
HitIndex := SendMessage(Handle, TCM_HITTEST, 0, Longint(@HitTestInfo));
if (HitIndex >= 0) and (HitIndex <> TabIndex) then Message.Result := 1;
end;
procedure TrmCCPageControl.CMDialogKey(var Message: TCMDialogKey);
begin
if (Message.CharCode = VK_TAB) and (GetKeyState(VK_CONTROL) < 0) then
begin
SelectNextPage(GetKeyState(VK_SHIFT) >= 0);
Message.Result := 1;
end else
inherited;
end;
procedure TrmCCPageControl.CMDockClient(var Message: TCMDockClient);
var
IsVisible: Boolean;
DockCtl: TControl;
begin
Message.Result := 0;
FNewDockSheet := TrmCCTabSheet.Create(Self);
try
try
DockCtl := Message.DockSource.Control;
if DockCtl is TCustomForm then
FNewDockSheet.Caption := TCustomForm(DockCtl).Caption;
FNewDockSheet.PageControl := Self;
DockCtl.Dock(Self, Message.DockSource.DockRect);
except
FNewDockSheet.Free;
raise;
end;
IsVisible := DockCtl.Visible;
FNewDockSheet.TabVisible := IsVisible;
if IsVisible then ActivePage := FNewDockSheet;
DockCtl.Align := alClient;
finally
FNewDockSheet := nil;
end;
end;
procedure TrmCCPageControl.CMDockNotification(var Message: TCMDockNotification);
var
Page: TrmCCTabSheet;
begin
Page := GetPageFromDockClient(Message.Client);
if Page <> nil then
case Message.NotifyRec.ClientMsg of
WM_SETTEXT:
Page.Caption := PChar(Message.NotifyRec.MsgLParam);
CM_VISIBLECHANGED:
with Page do
begin
Visible := Boolean(Message.NotifyRec.MsgWParam);
TabVisible := Boolean(Message.NotifyRec.MsgWParam);;
end;
end;
inherited;
end;
procedure TrmCCPageControl.CMUnDockClient(var Message: TCMUnDockClient);
var
Page: TrmCCTabSheet;
begin
Message.Result := 0;
Page := GetPageFromDockClient(Message.Client);
if Page <> nil then
begin
FUndockingPage := Page;
Message.Client.Align := alNone;
end;
end;
function TrmCCPageControl.GetDockClientFromMousePos(MousePos: TPoint): TControl;
var
HitIndex: Integer;
HitTestInfo: TTCHitTestInfo;
Page: TrmCCTabSheet;
begin
Result := nil;
if DockSite then
begin
HitTestInfo.pt := MousePos;
HitIndex := SendMessage(Handle, TCM_HITTEST, 0, Longint(@HitTestInfo));
if HitIndex >= 0 then
begin
Page := Pages[HitIndex];
if not Page.TabVisible then Page := FindNextPage(Page, True, True);
if (Page <> nil) and (Page.ControlCount > 0) then
begin
Result := Page.Controls[0];
if Result.HostDockSite <> Self then Result := nil;
end;
end;
end;
end;
procedure TrmCCPageControl.WMLButtonDown(var Message: TWMLButtonDown);
var
DockCtl: TControl;
begin
inherited;
DockCtl := GetDockClientFromMousePos(SmallPointToPoint(Message.Pos));
if DockCtl <> nil then DockCtl.BeginDrag(False);
end;
procedure TrmCCPageControl.WMLButtonDblClk(var Message: TWMLButtonDblClk);
var
DockCtl: TControl;
begin
inherited;
DockCtl := GetDockClientFromMousePos(SmallPointToPoint(Message.Pos));
if DockCtl <> nil then DockCtl.ManualDock(nil, nil, alNone);
end;
procedure TrmCCPageControl.CMTabDraggedOff(var Message: TMessage);
begin
if assigned(FOnFloatChange) then
FOnFloatChange(Self, fsFloating);
end;
procedure TrmCCPageControl.CMTabDraggedOn(var Message: TMessage);
var
loop, loop1 : integer;
worksheet : TrmCCTabSheet;
begin
for loop := 0 to fpages.count-1 do
begin
worksheet := TrmCCTabSheet(fpages[loop]);
loop1 := 0;
while (loop1 < fpages.count - 1) and (worksheet.StaticPageIndex > TrmCCTabSheet(fpages[loop1]).staticpageindex) do
inc(loop1);
worksheet.pageindex := loop1;
if worksheet.TabVisible then
worksheet.imageindex := worksheet.imageindex;
end;
if assigned(FOnFloatChange) then
FOnFloatChange(Self, fsDocked);
end;
procedure TrmCCPageControl.DisplayTabHint(TabIndex: integer);
begin
application.CancelHint;
if tabindex <> -1 then
hint := trim(TrmCCTabSheet(fpages.items[tabindex]).tabhint)
else
begin
if assigned(activepage) then
hint := trim(TrmCCTabSheet(activepage).hint);
end;
end;
procedure TrmCCPageControl.MouseDown(Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if (ftabshifting) and (button = mbleft) and (fMouseOverTab = ActivePage.PageIndex) then
fMouseDragTab := fMouseOverTab;
Inherited;
end;
procedure TrmCCPageControl.MouseMove(Shift: TShiftState; X, Y: Integer);
begin
if (ftabshifting) then
begin
if (ssLeft in Shift) then
begin
if (fMouseOverTab = -1) then
Cursor := crNo
else
if (fMouseDragTab <> fMouseOverTab) then
Cursor := crDrag
else
Cursor := crDefault;
end
else
Cursor := crDefault;
end;
inherited;
end;
procedure TrmCCPageControl.MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
var
tabsheet1 : TrmCCTabSheet;
begin
if (ftabshifting) and (button = mbleft) and (fMouseDragTab <> fMouseOverTab) and (fMouseOverTab <> -1) then
begin
TabSheet1 := Pages[fMouseDragTab];
TabSheet1.PageIndex := fMouseOverTab;
Cursor := crDefault;
if assigned(fOnTabShift) then fOnTabShift(self);
end;
inherited;
end;
function TrmCCPageControl.GetFloatingPage(Index: Integer): TrmCCTabSheet;
begin
Result := FFloatingPages[Index];
end;
function TrmCCPageControl.GetFloatingPageCount: Integer;
begin
result := FFloatingPages.Count;
end;
procedure TrmCCPageControl.AddToFloatList(Page: TrmCCTabSheet);
begin
if fFloatingPages.IndexOf(page) = -1 then
fFloatingPages.add(Page);
end;
procedure TrmCCPageControl.RemoveFromFloatList(Page: TrmCCTabSheet);
var
index : integer;
begin
index := fFloatingPages.IndexOf(page);
if index <> -1 then
fFloatingPages.delete(index);
end;
procedure TrmCCTabSheet.FloatTabSheetBounds(aLeft, aTop, aWidth, aHeight: integer);
begin
if (not FFloating) then
begin
fOldPageControl := PageControl;
PageControl := nil;
FFloating := true;
fOldPageControl.SelectNextPage(True);
fOldPageControl.AddToFloatList(self);
fOldPageControl.Perform(CM_rmCCTabSheetDraggedOFF,0,0);
if not assigned(fFloatingForm) then
begin
fFloatingForm := TrmCCTabsFloatingForm.CreateNew(self.owner);
if (fFloatOnTop) and (Application.mainform <> nil) and (Application.mainform is tform) then
setwindowlong(ffloatingform.handle,gwl_hwndparent,Application.mainform.handle);
if assigned(fOldPageControl.images) and (imageindex <> -1) then
fOldPageControl.Images.GetIcon(imageindex,ffloatingform.Icon);
fFloatingForm.OnMoveSize := DoMoveSize;
fFloatingForm.Caption := Caption;
fFloatingForm.SetBounds(aleft, atop, awidth, aheight);
fFloatingForm.TabSheet := self;
end;
if assigned(FOnFloatChange) then
FOnFloatChange(Self, fsFloating);
Parent := fFloatingForm;
fFloatingForm.Show;
Show;
end;
end;
procedure TrmCCTabSheet.DoMoveSize(Sender: TObject);
begin
if assigned(fMoveSize) then
fMoveSize(self);
end;
procedure TrmCCPageControl.HideFloatingPages;
var
loop : integer;
begin
loop := GetFloatingPageCount;
while loop > 0 do
begin
dec(loop);
GetFloatingPage(loop).FloatingForm.Hide;
end;
end;
procedure TrmCCPageControl.ShowFloatingPages;
var
loop : integer;
begin
loop := GetFloatingPageCount;
while loop > 0 do
begin
dec(loop);
GetFloatingPage(loop).FloatingForm.show;
end;
end;
function TrmCCPageControl.GetActivePageIndex: Integer;
begin
if ActivePage <> nil then
Result := ActivePage.GetPageIndex
else
Result := -1;
end;
procedure TrmCCPageControl.SetActivePageIndex(const Value: Integer);
begin
if (Value > -1) and (Value < PageCount) then
ActivePage := Pages[Value]
else
ActivePage := nil;
end;
end.
|
{ *******************************************************************************
Copyright 2016-2020 Daniele Spinetti
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 EventBus.Subscribers;
interface
uses
System.Rtti, EventBus;
type
TSubscriberMethod = class(TObject)
private
FContext: string;
FEventType: string;
FMethod: TRttiMethod;
FThreadMode: TThreadMode;
procedure SetContext(const AValue: string);
procedure SetEventType(const AValue: string);
procedure SetMethod(const AValue: TRttiMethod);
procedure SetThreadMode(const AValue: TThreadMode);
public
constructor Create(
ARttiMethod: TRttiMethod;
AEventType: string;
AThreadMode: TThreadMode;
const AContext: string = '';
APriority: Integer = 1
);
destructor Destroy; override;
function Equals(AObject: TObject): Boolean; override;
property Context: string read FContext write SetContext;
property EventType: string read FEventType write SetEventType;
property Method: TRttiMethod read FMethod write SetMethod;
property ThreadMode: TThreadMode read FThreadMode write SetThreadMode;
end;
TSubscription = class(TObject)
private
FActive: Boolean;
FSubscriber: TObject;
FSubscriberMethod: TSubscriberMethod;
function GetActive: Boolean;
procedure SetActive(const AValue: Boolean);
function GetContext: string;
procedure SetSubscriber(const AValue: TObject);
procedure SetSubscriberMethod(const AValue: TSubscriberMethod);
public
constructor Create(ASubscriber: TObject; ASubscriberMethod: TSubscriberMethod);
destructor Destroy; override;
function Equals(AObject: TObject): Boolean; override;
property Active: Boolean read GetActive write SetActive;
property Context: string read GetContext;
property Subscriber: TObject read FSubscriber write SetSubscriber;
property SubscriberMethod: TSubscriberMethod read FSubscriberMethod write SetSubscriberMethod;
end;
TSubscribersFinder = class(TObject)
public
class function FindEventsSubscriberMethods(
ASubscriberClass: TClass;
ARaiseExcIfEmpty: Boolean = False
): TArray<TSubscriberMethod>;
class function FindChannelsSubcriberMethods(
ASubscriberClass: TClass;
ARaiseExcIfEmpty: Boolean = False
): TArray<TSubscriberMethod>;
end;
implementation
uses
System.SysUtils, System.TypInfo, EventBus.Helpers;
constructor TSubscriberMethod.Create(ARttiMethod: TRttiMethod; AEventType: string; AThreadMode: TThreadMode;
const AContext: string = ''; APriority: Integer = 1);
begin
FMethod := ARttiMethod;
FEventType := AEventType;
FThreadMode := AThreadMode;
FContext := AContext;
end;
destructor TSubscriberMethod.Destroy;
begin
inherited;
end;
function TSubscriberMethod.Equals(AObject: TObject): Boolean;
var
LOtherSubscriberMethod: TSubscriberMethod;
begin
if (inherited Equals(AObject)) then begin
Exit(True)
end else begin
if (AObject is TSubscriberMethod) then begin
LOtherSubscriberMethod := TSubscriberMethod(AObject);
Exit(LOtherSubscriberMethod.Method.Tostring = Method.Tostring);
end else begin
Exit(False);
end;
end;
end;
procedure TSubscriberMethod.SetContext(const AValue: string);
begin
FContext := AValue;
end;
procedure TSubscriberMethod.SetEventType(const AValue: string);
begin
FEventType := AValue;
end;
procedure TSubscriberMethod.SetMethod(const AValue: TRttiMethod);
begin
FMethod := AValue;
end;
procedure TSubscriberMethod.SetThreadMode(const AValue: TThreadMode);
begin
FThreadMode := AValue;
end;
class function TSubscribersFinder.FindChannelsSubcriberMethods(ASubscriberClass: TClass; ARaiseExcIfEmpty: Boolean): TArray<TSubscriberMethod>;
var
LChannelAttribute: ChannelAttribute;
LMethod: TRttiMethod;
LParamsLength: Integer;
LRttiMethods: TArray<System.Rtti.TRttiMethod>;
LRttiType: TRttiType;
LSubMethod: TSubscriberMethod;
begin
Result := [];
LRttiType := TRttiUtils.Ctx.GetType(ASubscriberClass);
LRttiMethods := LRttiType.GetMethods;
for LMethod in LRttiMethods do begin
if TRttiUtils.HasAttribute<ChannelAttribute>(LMethod, LChannelAttribute) then begin
LParamsLength := Length(LMethod.GetParameters);
if ((LParamsLength <> 1) or (LMethod.GetParameters[0].ParamType.TypeKind <> tkUstring)) then
raise Exception.CreateFmt(
'Method %s has Channel attribute but requires %d arguments. Methods must require a single argument of string type.',
[LMethod.Name, LParamsLength]);
LSubMethod := TSubscriberMethod.Create(LMethod, '', LChannelAttribute.ThreadMode, LChannelAttribute.Channel);
{$IF CompilerVersion >= 28.0}
Result := Result + [LSubMethod];
{$ELSE}
SetLength(Result, Length(Result) + 1);
Result[High(Result)] := LSubMethod;
{$ENDIF}
end;
end;
if (Length(Result) < 1) and ARaiseExcIfEmpty then
raise Exception.CreateFmt(
'Class %s and its super classes have no public methods with the Channel attribute specified.',
[ASubscriberClass.QualifiedClassName]);
end;
class function TSubscribersFinder.FindEventsSubscriberMethods(ASubscriberClass: TClass; ARaiseExcIfEmpty: Boolean = False): TArray<TSubscriberMethod>;
var
LEventType: string;
LMethod: TRttiMethod;
LParamsLength: Integer;
LRttiMethods: TArray<System.Rtti.TRttiMethod>;
LRttiType: TRttiType;
LSubMethod: TSubscriberMethod;
LSubscribeAttribute: SubscribeAttribute;
begin
Result := [];
LRttiType := TRttiUtils.Ctx.GetType(ASubscriberClass);
LRttiMethods := LRttiType.GetMethods;
for LMethod in LRttiMethods do begin
if TRttiUtils.HasAttribute<SubscribeAttribute>(LMethod, LSubscribeAttribute) then begin
LParamsLength := Length(LMethod.GetParameters);
if (LParamsLength <> 1) then
raise Exception.CreateFmt(
'Method %s has Subscribe attribute but requires %d arguments. Only single argument is permitted.',
[LMethod.Name, LParamsLength]);
if (LMethod.GetParameters[0].ParamType.TypeKind <> TTypeKind.tkInterface) then
raise Exception.CreateFmt(
'Method %s has Subscribe attribute but the Event argument is NOT of interface type.',
[LMethod.Name]);
LEventType := LMethod.GetParameters[0].ParamType.QualifiedName;
LSubMethod := TSubscriberMethod.Create(LMethod, LEventType, LSubscribeAttribute.ThreadMode, LSubscribeAttribute.Context);
{$IF CompilerVersion >= 28.0}
Result := Result + [LSubMethod];
{$ELSE}
SetLength(Result, Length(Result) + 1);
Result[High(Result)] := LSubMethod;
{$ENDIF}
end;
end;
if (Length(Result) < 1) and ARaiseExcIfEmpty then
raise Exception.CreateFmt(
'Class %s and its super classes have no public methods with the Subscribe attribute specified',
[ASubscriberClass.QualifiedClassName]);
end;
constructor TSubscription.Create(ASubscriber: TObject; ASubscriberMethod: TSubscriberMethod);
begin
inherited Create;
FSubscriber := ASubscriber;
FSubscriberMethod := ASubscriberMethod;
FActive := True;
end;
destructor TSubscription.Destroy;
begin
if Assigned(FSubscriberMethod) then FreeAndNil(FSubscriberMethod);
inherited;
end;
function TSubscription.Equals(AObject: TObject): Boolean;
var
LOtherSubscription: TSubscription;
begin
if (AObject is TSubscription) then begin
LOtherSubscription := TSubscription(AObject);
Exit((Subscriber = LOtherSubscription.Subscriber) and (SubscriberMethod.Equals(LOtherSubscription.SubscriberMethod)));
end else begin
Exit(False);
end;
end;
function TSubscription.GetActive: Boolean;
begin
TMonitor.Enter(Self);
try
Result := FActive;
finally
TMonitor.Exit(Self);
end;
end;
procedure TSubscription.SetActive(const AValue: Boolean);
begin
TMonitor.Enter(Self);
try
FActive := AValue;
finally
TMonitor.Exit(Self);
end;
end;
function TSubscription.GetContext: string;
begin
Result := SubscriberMethod.Context;
end;
procedure TSubscription.SetSubscriber(const AValue: TObject);
begin
FSubscriber := AValue;
end;
procedure TSubscription.SetSubscriberMethod(const AValue: TSubscriberMethod);
begin
FSubscriberMethod := AValue;
end;
end.
|
(* SPELLGBL.PAS - Copyright (c) 1995-1996, Eminent Domain Software *)
unit SpellGbl;
(*Constant and Type declarations for EDSSpell component*)
interface
{$I SpellDef.PAS}
type
TLanguages = (
{$IFDEF SupportEnglish} lgEnglish {$ENDIF}
{$IFDEF SupportSpanish} ,lgSpanish {$ENDIF}
{$IFDEF SupportBritish} ,lgBritish {$ENDIF}
{$IFDEF SupportItalian} ,lgItalian {$ENDIF}
{$IFDEF SupportFrench} ,lgFrench {$ENDIF}
{$IFDEF SupportGerman} ,lgGerman {$ENDIF}
{$IFDEF SupportDutch} ,lgDutch {$ENDIF});
TDialogTypes = (dtWordPerfect, dtMSWord, dtWordPro96);
const
ValidChars: set of Char = {valid characters used for parsing buffer}
[#39{'}, '0'..'9', 'a'..'z', 'A'..'Z', #128{Ç}..#165{Ñ}];
NumberSet: set of Char =
['0'..'9'];
{$IFDEF Win32}
MaxBuffer = 2147483647;
{$ELSE}
MaxBuffer = 32767;
{$ENDIF}
AddBufferSize = 4096; {maximum size of added buffer}
(* the above constant defines the maximum number of added characters a buffer can hold *)
(* for example: if a user changes the word "tst" to "test", we have added one character *)
(* if addbuffersize + sizeof the current buffer is greater than the maximum size the *)
(* buffer holds, the end characters are typically lost. This is not due to the spell *)
(* component but rather the parent component (i.e. the memo) *)
Dictionaries : array[TLanguages] of string[8] = (
{$IFDEF SupportEnglish} 'English' {$ENDIF}
{$IFDEF SupportSpanish} ,'Spanish' {$ENDIF}
{$IFDEF SupportBritish} ,'British' {$ENDIF}
{$IFDEF SupportItalian} ,'Italian' {$ENDIF}
{$IFDEF SupportFrench} ,'French' {$ENDIF}
{$IFDEF SupportGerman} ,'German' {$ENDIF}
{$IFDEF SupportDutch} ,'Dutch' {$ENDIF});
Margin = 10; {margin for moving dialog}
type
TBigBuffer = array[1..MaxBuffer] of Char;
PBigBuffer = ^TBigBuffer;
{Language Message Constants for EDSSpell}
{$I SpellMsg.Inc}
implementation
end. { SpellGbl }
|
unit Test.Order.ObjectMapping;
interface
{$M+}
uses
System.Generics.Collections,
DUnitX.TestFramework,
Delphi.Mocks,
Test.Order.Classes,
Nathan.ObjectMapping.Core,
Nathan.ObjectMapping.Types;
type
[TestFixture]
TTestObjectMapping = class
private
FCut: INathanObjectMappingCore<TOrder, TOrderDTO>;
FOrder: TOrder;
FDetails: TOrderDetails;
procedure InitOrderDummy();
public
[Setup]
procedure Setup();
[TearDown]
procedure TearDown();
[Test]
procedure Test_First_MapCallWithEx;
[Test]
procedure Test_CallMap;
end;
{$M-}
implementation
uses
System.SysUtils,
System.Rtti,
Nathan.ObjectMapping.Config;
procedure TTestObjectMapping.Setup();
begin
FCut := nil;
FDetails := nil;
FOrder := nil;
end;
procedure TTestObjectMapping.TearDown();
begin
if Assigned(FDetails) then
FDetails.Free;
if Assigned(FOrder) then
FOrder.Free;
FCut := nil;
end;
procedure TTestObjectMapping.Test_First_MapCallWithEx;
begin
// Arrange...
InitOrderDummy;
FCut := TNathanObjectMappingCore<TOrder, TOrderDTO>.Create;
// Act...
Assert.WillRaise(
procedure
begin
FCut.Map(FOrder);
end,
ENoMappingsFoundException);
end;
procedure TTestObjectMapping.InitOrderDummy;
begin
TOrderDummyFactory.InitOrderDummy;
FDetails := TOrderDummyFactory.Details;
FOrder := TOrderDummyFactory.Order;
end;
procedure TTestObjectMapping.Test_CallMap;
var
CfgMock: TMock<INathanObjectMappingConfig<TOrder, TOrderDTO>>;
StubMemberList: TDictionary<string, TMappedSrcDest>;
StubUserList: TList<TProc<TOrder, TOrderDTO>>;
Actual: TOrderDTO;
begin
// Arrange...
StubUserList := TList<TProc<TOrder, TOrderDTO>>.Create;
StubUserList.Add(
procedure(ASrc: TOrder; ADest: TOrderDTO)
begin
ADest.Total := ASrc.Total;
end);
StubMemberList := TDictionary<string, TMappedSrcDest>.Create;
try
CfgMock := TMock<INathanObjectMappingConfig<TOrder, TOrderDTO>>.Create;
CfgMock.Setup.AllowRedefineBehaviorDefinitions := True;
CfgMock.Setup.WillReturn(StubUserList).When.GetUserMap;
CfgMock.Setup.WillReturn(StubMemberList).When.GetMemberMap;
InitOrderDummy;
FCut := TNathanObjectMappingCore<TOrder, TOrderDTO>.Create;
// Act...
Actual := FCut
.Config(CfgMock)
.Map(FOrder);
try
// Assert...
Assert.IsNotNull(Actual);
Assert.AreEqual<Double>(19.9, TOrderDTO(Actual).Total);
finally
FreeAndNil(Actual);
end;
finally
StubUserList.Free;
StubMemberList.Free;
end;
end;
initialization
TDUnitX.RegisterTestFixture(TTestObjectMapping, 'Frist');
end.
|
unit DSA.Tree.IndexHeap;
interface
uses
System.SysUtils,
DSA.Interfaces.Comparer,
DSA.Utils;
type
THeapkind = (Min, Max);
TIndexHeap<T> = class
private type
TArr_T = TArray<T>;
ICmp_T = IComparer<T>;
TCmp_T = TComparer<T>;
var
__data: TArr_T;
__index: TArray_int;
__reverse: TArray_int;
__cmp: ICmp_T;
__heapKind: THeapkind;
__count: integer;
__capacity: integer;
procedure __shiftUp(k: integer);
procedure __shiftDown(k: integer);
procedure __swap(var a, b: integer); inline;
public
constructor Create(capacity: integer = 10; heapKind: THeapkind = THeapkind.Min); overload;
constructor Create(capacity: integer; cmp: ICmp_T; heapKind: THeapkind = THeapkind.Min); overload;
constructor Create(const arr: TArr_T; cmp: ICmp_T; heapKind: THeapkind = THeapkind.Min); overload;
constructor Create(const arr: TArr_T; heapKind: THeapkind = THeapkind.Min); overload;
destructor Destroy; override;
/// <summary> 返回索引堆中的元素个数 </summary>
function Size: integer;
/// <summary> 返回一个布尔值, 表示索引堆中是否为空 </summary>
function IsEmpty: boolean;
/// <summary> 向索引堆中插入一个新元素,新元素的索引为 i 的元素 e </summary>
procedure Insert(index: integer; e: T);
/// <summary> 从索引堆中取出堆顶元素, 即索引堆中所存储的第一个数据 </summary>
function ExtractFirst: T;
/// <summary> 从索引堆中取出堆顶元素的索引 </summary>
function ExtractFirstIndex: integer;
/// <summary> 返回索引堆中的堆顶元素 </summary>
function FindFirst: T;
/// <summary> 返回索引堆中的堆顶元素的索引 </summary>
function FindFirstIndex: integer;
/// <summary> 返回索引堆中索引为i的元素 </summary>
function Find(i: integer): T;
/// <summary> 将索引堆中索引为i的元素修改为e </summary>
procedure Change(i: integer; e: T);
/// <summary> 引i所在的位置是否存在元素 </summary>
function Contain(i: integer): boolean;
end;
procedure Main;
implementation
type
TIndexHeap_T = TIndexHeap<integer>;
procedure Main;
var
n: integer;
i: integer;
IH_Max, IH_Min: TIndexHeap_T;
sourceArr, testArr: TArray_int;
begin
n := 1000000;
Randomize;
IH_Max := TIndexHeap_T.Create(n, THeapkind.Max);
with IH_Max do
begin
for i := 0 to n - 1 do
Insert(i, Random(n));
SetLength(testArr, n);
for i := 0 to n - 1 do
testArr[i] := ExtractFirst;
for i := 1 to n - 1 do
if (testArr[i - 1] < testArr[i]) then
raise Exception.Create('Error');
Writeln('Test MaxIndexHeap completed.');
Free;
end;
IH_Min := TIndexHeap_T.Create(n, THeapkind.Min);
with IH_Min do
begin
for i := 0 to n - 1 do
Insert(i, Random(1000));
SetLength(testArr, n);
for i := 0 to n - 1 do
testArr[i] := ExtractFirst;
for i := 1 to n - 1 do
if (testArr[i - 1] > testArr[i]) then
raise Exception.Create('Error');
Writeln('Test MinIndexHeap completed.');
Free;
end;
TDSAUtils.DrawLine;
SetLength(sourceArr, n);
for i := 0 to n - 1 do
sourceArr[i] := Random(n);
IH_Max := TIndexHeap_T.Create(sourceArr, THeapkind.Max);
with IH_Max do
begin
SetLength(testArr, n);
for i := 0 to n - 1 do
testArr[i] := ExtractFirst;
for i := 1 to n - 1 do
if (testArr[i - 1] < testArr[i]) then
raise Exception.Create('Error');
Writeln('Test MinIndexHeap completed.');
Free;
end;
IH_Min := TIndexHeap_T.Create(sourceArr, THeapkind.Min);
with IH_Min do
begin
SetLength(testArr, n);
for i := 0 to n - 1 do
testArr[i] := ExtractFirst;
for i := 1 to n - 1 do
if (testArr[i - 1] > testArr[i]) then
raise Exception.Create('Error');
Writeln('Test MinIndexHeap completed.');
Free;
end;
end;
{ TIndexHeap<T> }
procedure TIndexHeap<T>.Change(i: integer; e: T);
begin
Assert(Contain(i));
inc(i);
__data[i] := e;
// 找到indexes[j] = i, j表示data[i]在堆中的位置
// 之后shiftUp(j), 再shiftDown(j)
//for j := 1 to __count do
//begin
// if __index[j] = i then
// begin
// __data[__index[j]] := e;
// __shiftUp(j);
// __shiftDown(j);
// end;
//end;
// 通过reverse直接定位索引i在indexes中的位置
__shiftUp(__reverse[i]);
__shiftDown(__reverse[i]);
end;
function TIndexHeap<T>.Contain(i: integer): boolean;
begin
Assert((i + 1 >= 1) and (i + 1 <= __capacity));
Result := __reverse[i + 1] <> 0;
end;
constructor TIndexHeap<T>.Create(capacity: integer; heapKind: THeapkind);
begin
Self.Create(capacity, TCmp_T.Default, heapKind);
end;
constructor TIndexHeap<T>.Create(const arr: TArr_T; heapKind: THeapkind);
begin
Self.Create(arr, TCmp_T.Default, heapKind);
end;
constructor TIndexHeap<T>.Create(capacity: integer; cmp: ICmp_T; heapKind: THeapkind);
begin
SetLength(__data, capacity + 1);
SetLength(__index, capacity + 1);
SetLength(__reverse, capacity + 1);
__count := 0;
__capacity := capacity;
__heapKind := heapKind;
__cmp := cmp;
end;
constructor TIndexHeap<T>.Create(const arr: TArr_T; cmp: ICmp_T; heapKind: THeapkind);
var
i: integer;
begin
__capacity := Length(arr);
SetLength(__data, __capacity + 1);
SetLength(__index, __capacity + 1);
SetLength(__reverse, __capacity + 1);
__count := 0;
__heapKind := heapKind;
__cmp := cmp;
for i := 0 to Length(arr) - 1 do
Self.Insert(i, arr[i]);
end;
destructor TIndexHeap<T>.Destroy;
begin
inherited Destroy;
end;
function TIndexHeap<T>.ExtractFirst: T;
var
ret: T;
begin
Assert(__count > 0);
ret := __data[__index[1]];
__swap(__index[1], __index[__count]);
__reverse[__index[1]] := 1;
__reverse[__index[__count]] := 0;
Dec(__count);
__shiftDown(1);
Result := ret;
end;
function TIndexHeap<T>.ExtractFirstIndex: integer;
var
ret: integer;
begin
Assert(__count > 0);
ret := __index[1] - 1;
__swap(__index[1], __index[__count]);
__reverse[__index[1]] := 1;
__reverse[__index[__count]] := 0;
Dec(__count);
__shiftDown(1);
Result := ret;
end;
function TIndexHeap<T>.Find(i: integer): T;
begin
Assert(Contain(i));
Result := __data[i + 1];
end;
function TIndexHeap<T>.FindFirst: T;
begin
if __count <= 0 then
raise Exception.Create('Can not FindFirst when heap is empty.');
Result := __data[__index[1]];
end;
function TIndexHeap<T>.FindFirstIndex: integer;
begin
Result := __index[1] - 1;
end;
procedure TIndexHeap<T>.Insert(index: integer; e: T);
begin
Assert(__count + 1 <= __capacity);
Assert((index + 1 >= 1) and (index + 1 <= __capacity));
// 再插入一个新元素前,还需要保证索引i所在的位置是没有元素的。
Assert(not Contain(index));
inc(index);
__data[index] := e;
__index[__count + 1] := index;
__reverse[index] := __count + 1;
inc(__count);
__shiftUp(__count);
end;
function TIndexHeap<T>.IsEmpty: boolean;
begin
Result := __count = 0;
end;
function TIndexHeap<T>.Size: integer;
begin
Result := __count;
end;
procedure TIndexHeap<T>.__shiftDown(k: integer);
var
j: integer;
begin
case __heapKind of
THeapkind.Min:
while 2 * k <= __count do
begin
j := 2 * k;
if (j + 1 <= __count) and (__cmp.Compare(__data[__index[j + 1]], __data[__index[j]]) < 0) then
inc(j);
if __cmp.Compare(__data[__index[k]], __data[__index[j]]) <= 0 then
Break;
__swap(__index[k], __index[j]);
__reverse[__index[k]] := k;
__reverse[__index[j]] := j;
k := j;
end;
THeapkind.Max:
while 2 * k <= __count do
begin
j := 2 * k;
if (j + 1 <= __count) and (__cmp.Compare(__data[__index[j + 1]], __data[__index[j]]) > 0) then
inc(j);
if __cmp.Compare(__data[__index[k]], __data[__index[j]]) >= 0 then
Break;
__swap(__index[k], __index[j]);
__reverse[__index[k]] := k;
__reverse[__index[j]] := j;
k := j;
end;
end;
end;
procedure TIndexHeap<T>.__shiftUp(k: integer);
begin
case __heapKind of
THeapkind.Max:
while (k > 1) and (__cmp.Compare(__data[__index[k div 2]], __data[__index[k]]) < 0) do
begin
__swap(__index[k div 2], __index[k]);
__reverse[__index[k div 2]] := k div 2;
__reverse[__index[k]] := k;
k := k div 2;
end;
THeapkind.Min:
while (k > 1) and (__cmp.Compare(__data[__index[k div 2]], __data[__index[k]]) > 0) do
begin
__swap(__index[k div 2], __index[k]);
__reverse[__index[k div 2]] := k div 2;
__reverse[__index[k]] := k;
k := k div 2;
end;
end;
end;
procedure TIndexHeap<T>.__swap(var a, b: integer);
var
tmp: integer;
begin
tmp := a;
a := b;
b := tmp;
end;
end.
|
unit cFilePersist;
{-----------------------------------------------------------------------------
Unit Name: cFilePersist
Author: Kiriakos Vlahos
Date: 09-Mar-2006
Purpose: Support class for editor file persistence
History:
-----------------------------------------------------------------------------}
interface
Uses
Classes, SysUtils, Contnrs, JvAppStorage, uEditAppIntfs, dlgSynEditOptions;
Type
TBookMarkInfo = class(TPersistent)
private
fLine, fChar, fBookmarkNumber : integer;
published
property Line : integer read fLine write fLine;
property Char : integer read fChar write fChar;
property BookmarkNumber : integer read fBookmarkNumber write fBookmarkNumber;
end;
TFilePersistInfo = class (TInterfacedPersistent, IJvAppStorageHandler)
// For storage/loading of a file's persistent info
private
Line, Char, TopLine : integer;
BreakPoints : TObjectList;
BookMarks : TObjectList;
FileName : string;
Highlighter : string;
EditorOptions : TSynEditorOptionsContainer;
protected
// IJvAppStorageHandler implementation
procedure ReadFromAppStorage(AppStorage: TJvCustomAppStorage; const BasePath: string);
procedure WriteToAppStorage(AppStorage: TJvCustomAppStorage; const BasePath: string);
function CreateListItem(Sender: TJvCustomAppStorage; const Path: string;
Index: Integer): TPersistent;
public
constructor Create;
constructor CreateFromEditor(Editor : IEditor);
destructor Destroy; override;
end;
TPersistFileInfo = class
// Stores/loads open editor file information through the class methods
// WriteToAppStorage and ReadFromAppStorage
private
fFileInfoList : TObjectList;
function CreateListItem(Sender: TJvCustomAppStorage; const Path: string;
Index: Integer): TPersistent;
public
constructor Create;
destructor Destroy; override;
procedure GetFileInfo;
class procedure WriteToAppStorage(AppStorage : TJvCustomAppStorage; Path : String);
class procedure ReadFromAppStorage(AppStorage : TJvCustomAppStorage; Path : String);
end;
implementation
uses
cPyBaseDebugger, frmPyIDEMain, SynEditTypes, dmCommands, uHighlighterProcs;
{ TFilePersistInfo }
constructor TFilePersistInfo.Create;
begin
BreakPoints := TObjectList.Create(True);
BookMarks := TObjectList.Create(True);
EditorOptions := TSynEditorOptionsContainer.Create(nil);
end;
procedure TFilePersistInfo.WriteToAppStorage(AppStorage: TJvCustomAppStorage;
const BasePath: string);
var
IgnoreProperties : TStringList;
begin
AppStorage.WriteString(BasePath+'\FileName', FileName);
AppStorage.WriteInteger(BasePath+'\Line', Line);
AppStorage.WriteInteger(BasePath+'\Char', Char);
AppStorage.WriteInteger(BasePath+'\TopLine', TopLine);
AppStorage.WriteString(BasePath+'\Highlighter', Highlighter);
AppStorage.WriteObjectList(BasePath+'\BreakPoints', BreakPoints, 'BreakPoint');
AppStorage.WriteObjectList(BasePath+'\BookMarks', BookMarks, 'BookMarks');
IgnoreProperties := TStringList.Create;
try
IgnoreProperties.Add('Keystrokes');
AppStorage.WritePersistent(BasePath+'\Editor Options', EditorOptions,
True, IgnoreProperties);
finally
IgnoreProperties.Free;
end;
end;
procedure TFilePersistInfo.ReadFromAppStorage(AppStorage: TJvCustomAppStorage;
const BasePath: string);
begin
FileName := AppStorage.ReadString(BasePath+'\FileName');
Line := AppStorage.ReadInteger(BasePath+'\Line');
Char := AppStorage.ReadInteger(BasePath+'\Char');
TopLine := AppStorage.ReadInteger(BasePath+'\TopLine');
Highlighter := AppStorage.ReadString(BasePath+'\Highlighter', Highlighter);
AppStorage.ReadObjectList(BasePath+'\BreakPoints', BreakPoints, CreateListItem, True, 'BreakPoint');
AppStorage.ReadObjectList(BasePath+'\BookMarks', BookMarks, CreateListItem, True, 'BookMarks');
EditorOptions.Assign(CommandsDataModule.EditorOptions);
AppStorage.ReadPersistent(BasePath+'\Editor Options', EditorOptions, True, True);
end;
destructor TFilePersistInfo.Destroy;
begin
BreakPoints.Free;
BookMarks.Free;
EditorOptions.Free;
inherited;
end;
function TFilePersistInfo.CreateListItem(Sender: TJvCustomAppStorage;
const Path: string; Index: Integer): TPersistent;
begin
if Pos('BreakPoint', Path) > 0 then
Result := TBreakPoint.Create
else if Pos('BookMark', Path) > 0 then
Result := TBookMarkInfo.Create
else
Result := nil;
end;
constructor TFilePersistInfo.CreateFromEditor(Editor: IEditor);
Var
i : integer;
BookMark : TBookMarkInfo;
BreakPoint : TBreakPoint;
begin
Create;
FileName := Editor.FileName;
Char := Editor.SynEdit.CaretX;
Line := Editor.SynEdit.CaretY;
TopLine := Editor.Synedit.TopLine;
if Assigned(Editor.SynEdit.Highlighter) then
Highlighter := Editor.SynEdit.Highlighter.GetLanguageName;
if Assigned(Editor.SynEdit.Marks) then
for i := 0 to Editor.SynEdit.Marks.Count - 1 do
if Editor.SynEdit.Marks[i].IsBookmark then with Editor.SynEdit.Marks[i] do
begin
BookMark := TBookMarkInfo.Create;
BookMark.fChar := Char;
BookMark.fLine := Line;
BookMark.fBookmarkNumber := BookmarkNumber;
BookMarks.Add(BookMark);
end;
for i := 0 to Editor.BreakPoints.Count - 1 do begin
BreakPoint := TBreakPoint.Create;
with TBreakPoint(Editor.BreakPoints[i]) do begin
BreakPoint.LineNo := LineNo;
BreakPoint.Disabled := Disabled;
BreakPoint.Condition := Condition;
BreakPoints.Add(BreakPoint);
end;
end;
EditorOptions.Assign(Editor.SynEdit);
end;
{ TPersistFileInfo }
constructor TPersistFileInfo.Create;
begin
fFileInfoList := TObjectList.Create(True);
end;
class procedure TPersistFileInfo.ReadFromAppStorage(
AppStorage: TJvCustomAppStorage; Path : String);
Var
PersistFileInfo : TPersistFileInfo;
FilePersistInfo : TFilePersistInfo;
Editor : IEditor;
i, j : integer;
begin
PersistFileInfo := TPersistFileInfo.Create;
try
AppStorage.ReadObjectList(Path, PersistFileInfo.fFileInfoList,
PersistFileInfo.CreateListItem, True, 'File');
for i := 0 to PersistFileInfo.fFileInfoList.Count - 1 do begin
FilePersistInfo := TFilePersistInfo(PersistFileInfo.fFileInfoList[i]);
if FileExists(FilePersistInfo.FileName) then
Editor := PyIDEMainForm.DoOpenFile(FilePersistInfo.FileName);
if Assigned(Editor) then begin
Editor.SynEdit.TopLine := FilePersistInfo.TopLine;
Editor.SynEdit.CaretXY := BufferCoord(FilePersistInfo.Char, FilePersistInfo.Line);
for j := 0 to FilePersistInfo.BreakPoints.Count - 1 do
with TBreakPoint(FilePersistInfo.BreakPoints[j]) do
PyIDEMainForm.PyDebugger.SetBreakPoint(FilePersistInfo.FileName,
LineNo, Disabled, Condition);
for j := 0 to FilePersistInfo.BookMarks.Count - 1 do
with TBookMarkInfo(FilePersistInfo.BookMarks[j]) do
Editor.SynEdit.SetBookMark(BookMarkNumber, Char, Line);
if FilePersistInfo.Highlighter <> '' then
Editor.SynEdit.Highlighter := GetHighlighterFromLanguageName(
FilePersistInfo.Highlighter, CommandsDataModule.Highlighters);
Editor.SynEdit.Assign(FilePersistInfo.EditorOptions);
end;
end;
finally
PersistFileInfo.Free;
end;
end;
function TPersistFileInfo.CreateListItem(Sender: TJvCustomAppStorage;
const Path: string; Index: Integer): TPersistent;
begin
Result := TFilePersistInfo.Create;
end;
destructor TPersistFileInfo.Destroy;
begin
fFileInfoList.Free;
inherited;
end;
class procedure TPersistFileInfo.WriteToAppStorage(
AppStorage: TJvCustomAppStorage; Path : String);
Var
PersistFileInfo : TPersistFileInfo;
begin
PersistFileInfo := TPersistFileInfo.Create;
try
PersistFileInfo.GetFileInfo;
AppStorage.WriteObjectList(Path, PersistFileInfo.fFileInfoList, 'File');
finally
PersistFileInfo.Free;
end;
end;
procedure TPersistFileInfo.GetFileInfo;
var
i : integer;
Editor : IEditor;
FilePersistInfo : TFilePersistInfo;
begin
for i := 0 to GI_EditorFactory.Count - 1 do begin
Editor := GI_EditorFactory.Editor[i];
if Editor.FileName <> '' then begin
FilePersistInfo := TFilePersistInfo.CreateFromEditor(Editor);
fFileInfoList.Add(FilePersistInfo)
end;
end;
end;
end.
|
program DrawTextTest;
uses SwinGame, sgTypes;
procedure Main();
var
fnt: Font;
bmp: Bitmap;
opts: DrawingOptions;
begin
OpenGraphicsWindow('Draw Text Test', 800, 600);
fnt := LoadFontNamed('arial:14', 'arial.ttf', 14);
LoadFontNamed('arial:32', 'arial.ttf', 32);
LoadFontNamed(FontNameFor('arial', 10), 'arial.ttf', 10);
opts := OptionRotateBmp(0);
bmp := DrawTextToBitmap(FontNamed('arial:32'), 'Text On' + LineEnding + 'Bitmap', ColorWhite, ColorBlue);
repeat
ClearScreen(ColorWhite);
DrawFramerate(0, 0);
DrawText('With Font', ColorBlack, fnt, 0, 20);
DrawText('With Font Name and Size', ColorBlack, 'arial', 10, 0, 40);
DrawText('With Font File Name and Size', ColorBlack, 'arial.ttf', 14, 0, 60);
DrawText('Hello' + LineEnding + LineEnding + 'World', ColorBlack, fnt, 0, 80);
opts.angle += 1;
if opts.angle > 360 then opts.angle -= 360;
DrawBitmap(bmp, 100, 100, opts);
RefreshScreen(60);
ProcessEvents();
until WindowCloseRequested();
end;
begin
Main();
end. |
(*----------------------------------------------------------------------------*
* Direct3D sample from DirectX 9.0 SDK December 2006 *
* Delphi adaptation by Alexey Barkovoy (e-mail: directx@clootie.ru) *
* *
* Supported compilers: Delphi 5,6,7,9; FreePascal 2.0 *
* *
* Latest version can be downloaded from: *
* http://www.clootie.ru *
* http://sourceforge.net/projects/delphi-dx9sdk *
*----------------------------------------------------------------------------*
* $Id: PickUnit.pas,v 1.6 2007/02/05 22:21:11 clootie Exp $
*----------------------------------------------------------------------------*)
//--------------------------------------------------------------------------------------
// File: Pick.cpp
//
// Basic starting point for new Direct3D samples
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
{$I DirectX.inc}
unit PickUnit;
interface
uses
Windows, Messages, SysUtils, StrSafe,
DXTypes, Direct3D9, D3DX9,
DXUT, DXUTcore, DXUTenum, DXUTmisc, DXUTgui, DXUTMesh, DXUTSettingsDlg;
{.$DEFINE DEBUG_VS} // Uncomment this line to debug vertex shaders
{.$DEFINE DEBUG_PS} // Uncomment this line to debug pixel shaders
//--------------------------------------------------------------------------------------
// Vertex format
//--------------------------------------------------------------------------------------
type
PD3DVertex = ^TD3DVertex;
TD3DVertex = record
p: TD3DXVector3;
n: TD3DXVector3;
tu, tv: Single;
end;
const
TD3DVertex_FVF = D3DFVF_XYZ or D3DFVF_NORMAL or D3DFVF_TEX1;
type
PIntersectionType = ^TIntersection;
TIntersection = record
dwFace: DWORD; // mesh face that was intersected
fBary1, fBary2: Single; // barycentric coords of intersection
fDist: Single; // distance from ray origin to intersection
tu, tv: Single; // texture coords of intersection
end;
// For simplicity's sake, we limit the number of simultaneously intersected
// triangles to 16
const
MAX_INTERSECTIONS = 16;
CAMERA_DISTANCE = 3.5;
//--------------------------------------------------------------------------------------
// Global variables
//--------------------------------------------------------------------------------------
var
g_pFont: ID3DXFont; // Font for drawing text
g_pTextSprite: ID3DXSprite; // Sprite for batching draw text calls
g_pEffect: ID3DXEffect; // D3DX effect interface
g_Mesh: CDXUTMesh; // The mesh to be rendered
g_Camera: CModelViewerCamera; // A model viewing camera
g_dwNumIntersections: DWORD; // Number of faces intersected
g_IntersectionArray: array[0..MAX_INTERSECTIONS-1] of TIntersection; // Intersection info
g_pVB: IDirect3DVertexBuffer9; // VB for picked triangles
g_bShowHelp: Boolean = True; // If true, it renders the UI control text
g_bUseD3DXIntersect: Boolean = True; // Whether to use D3DXIntersect
g_bAllHits: Boolean = True; // Whether to just get the first "hit" or all "hits"
g_DialogResourceManager: CDXUTDialogResourceManager; // manager for shared resources of dialogs
g_SettingsDlg: CD3DSettingsDlg; // Device settings dialog
g_HUD: CDXUTDialog; // dialog for standard controls
g_SampleUI: CDXUTDialog; // dialog for sample specific controls
//--------------------------------------------------------------------------------------
// UI control IDs
//--------------------------------------------------------------------------------------
const
IDC_TOGGLEFULLSCREEN = 1;
IDC_TOGGLEREF = 2;
IDC_CHANGEDEVICE = 3;
IDC_USED3DX = 4;
IDC_ALLHITS = 5;
//--------------------------------------------------------------------------------------
// Forward declarations
//--------------------------------------------------------------------------------------
function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall;
function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall;
function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall;
procedure KeyboardProc(nChar: LongWord; bKeyDown, bAltDown: Boolean; pUserContext: Pointer); stdcall;
procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall;
procedure OnLostDevice(pUserContext: Pointer); stdcall;
procedure OnDestroyDevice(pUserContext: Pointer); stdcall;
procedure InitApp;
procedure RenderText;
function Pick: HRESULT;
function IntersectTriangle(const orig: TD3DXVector3; const dir: TD3DXVector3;
out v0, v1, v2: TD3DXVector3;
out t, u, v: Single): Boolean;
procedure CreateCustomDXUTobjects;
procedure DestroyCustomDXUTobjects;
implementation
//--------------------------------------------------------------------------------------
// Initialize the app
//--------------------------------------------------------------------------------------
procedure InitApp;
var
iY: Integer;
begin
// Initialize dialogs
g_SettingsDlg.Init(g_DialogResourceManager);
g_HUD.Init(g_DialogResourceManager);
g_SampleUI.Init(g_DialogResourceManager);
g_HUD.SetCallback(OnGUIEvent); iY := 10;
g_HUD.AddButton(IDC_TOGGLEFULLSCREEN, 'Toggle full screen', 35, iY, 125, 22); Inc(iY, 24);
g_HUD.AddButton(IDC_TOGGLEREF, 'Toggle REF (F3)', 35, iY, 125, 22); Inc(iY, 24);
g_HUD.AddButton(IDC_CHANGEDEVICE, 'Change device (F2)', 35, iY, 125, 22, VK_F2); Inc(iY, 24);
g_HUD.AddCheckBox(IDC_USED3DX, 'Use D3DXIntersect', 35, iY, 125, 22, g_bUseD3DXIntersect, VK_F4); Inc(iY, 24);
g_HUD.AddCheckBox(IDC_ALLHITS, 'Show All Hits', 35, iY, 125, 22, g_bAllHits, VK_F5);
g_SampleUI.SetCallback(OnGUIEvent); // iY := 10;
end;
//--------------------------------------------------------------------------------------
// Called during device initialization, this code checks the device for some
// minimum set of capabilities, and rejects those that don't pass by returning E_FAIL.
//--------------------------------------------------------------------------------------
function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall;
var
pD3D: IDirect3D9;
begin
Result := False;
// Skip backbuffer formats that don't support alpha blending
pD3D := DXUTGetD3DObject;
if FAILED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType,
AdapterFormat, D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING,
D3DRTYPE_TEXTURE, BackBufferFormat))
then Exit;
// No fallback defined by this app, so reject any device that
// doesn't support at least ps2.0
if (pCaps.PixelShaderVersion < D3DPS_VERSION(2,0)) then Exit;
Result := True;
end;
//--------------------------------------------------------------------------------------
// This callback function is called immediately before a device is created to allow the
// application to modify the device settings. The supplied pDeviceSettings parameter
// contains the settings that the framework has selected for the new device, and the
// application can make any desired changes directly to this structure. Note however that
// DXUT will not correct invalid device settings so care must be taken
// to return valid device settings, otherwise IDirect3D9::CreateDevice() will fail.
//--------------------------------------------------------------------------------------
{static} var s_bFirstTime: Boolean = True;
function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall;
begin
// If device doesn't support HW T&L or doesn't support 2.0 vertex shaders in HW
// then switch to SWVP.
if (pCaps.DevCaps and D3DDEVCAPS_HWTRANSFORMANDLIGHT = 0) or
(pCaps.VertexShaderVersion < D3DVS_VERSION(2,0))
then pDeviceSettings.BehaviorFlags := D3DCREATE_SOFTWARE_VERTEXPROCESSING;
// Debugging vertex shaders requires either REF or software vertex processing
// and debugging pixel shaders requires REF.
{$IFDEF DEBUG_VS}
if (pDeviceSettings.DeviceType <> D3DDEVTYPE_REF) then
with pDeviceSettings do
begin
BehaviorFlags := BehaviorFlags and not D3DCREATE_HARDWARE_VERTEXPROCESSING;
BehaviorFlags := BehaviorFlags and not D3DCREATE_PUREDEVICE;
BehaviorFlags := BehaviorFlags or D3DCREATE_SOFTWARE_VERTEXPROCESSING;
end;
{$ENDIF}
{$IFDEF DEBUG_PS}
pDeviceSettings.DeviceType := D3DDEVTYPE_REF;
{$ENDIF}
// For the first device created if its a REF device, optionally display a warning dialog box
if s_bFirstTime then
begin
s_bFirstTime := False;
if (pDeviceSettings.DeviceType = D3DDEVTYPE_REF) then DXUTDisplaySwitchingToREFWarning;
end;
Result:= True;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has been
// created, which will happen during application initialization and windowed/full screen
// toggles. This is the best location to create D3DPOOL_MANAGED resources since these
// resources need to be reloaded whenever the device is destroyed. Resources created
// here should be released in the OnDestroyDevice callback.
//--------------------------------------------------------------------------------------
function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
var
dwShaderFlags: DWORD;
str: array [0..MAX_PATH-1] of WideChar;
colorMtrl: TD3DXColor;
vLightDir: TD3DXVector3;
vLightDiffuse: TD3DXColor;
vecEye, vecAt: TD3DXVector3;
mWorld: TD3DXMatrix;
begin
Result:= g_DialogResourceManager.OnCreateDevice(pd3dDevice);
if V_Failed(Result) then Exit;
Result:= g_SettingsDlg.OnCreateDevice(pd3dDevice);
if V_Failed(Result) then Exit;
// Initialize the font
Result := D3DXCreateFont(pd3dDevice, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH or FF_DONTCARE,
'Arial', g_pFont);
if V_Failed(Result) then Exit;
// Load the mesh with D3DX and get back a ID3DXMesh*. For this
// sample we'll ignore the X file's embedded materials since we know
// exactly the model we're loading. See the mesh samples such as
// "OptimizedMesh" for a more generic mesh loading example.
Result:= DXUTFindDXSDKMediaFile(str, MAX_PATH, 'scanner\scannerarm.x');
if V_Failed(Result) then Exit;
Result:= g_Mesh.CreateMesh(pd3dDevice, str);
if V_Failed(Result) then Exit;
Result:= g_Mesh.SetFVF(pd3dDevice, TD3DVertex_FVF);
if V_Failed(Result) then Exit;
// Create the vertex buffer
Result := pd3dDevice.CreateVertexBuffer(3*MAX_INTERSECTIONS*SizeOf(TD3DVertex),
D3DUSAGE_WRITEONLY, TD3DVertex_FVF,
D3DPOOL_MANAGED, g_pVB, nil);
if Failed(Result) then
begin
Result:= E_FAIL;
Exit;
end;
// Define DEBUG_VS and/or DEBUG_PS to debug vertex and/or pixel shaders with the
// shader debugger. Debugging vertex shaders requires either REF or software vertex
// processing, and debugging pixel shaders requires REF. The
// D3DXSHADER_FORCE_*_SOFTWARE_NOOPT flag improves the debug experience in the
// shader debugger. It enables source level debugging, prevents instruction
// reordering, prevents dead code elimination, and forces the compiler to compile
// against the next higher available software target, which ensures that the
// unoptimized shaders do not exceed the shader model limitations. Setting these
// flags will cause slower rendering since the shaders will be unoptimized and
// forced into software. See the DirectX documentation for more information about
// using the shader debugger.
dwShaderFlags := D3DXFX_NOT_CLONEABLE;
{$IFDEF DEBUG}
// Set the D3DXSHADER_DEBUG flag to embed debug information in the shaders.
// Setting this flag improves the shader debugging experience, but still allows
// the shaders to be optimized and to run exactly the way they will run in
// the release configuration of this program.
dwShaderFlags := dwShaderFlags or D3DXSHADER_DEBUG;
{$ENDIF}
{$IFDEF DEBUG_VS}
dwShaderFlags := dwShaderFlags or D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT;
{$ENDIF}
{$IFDEF DEBUG_PS}
dwShaderFlags := dwShaderFlags or D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT;
{$ENDIF}
// Read the D3DX effect file
Result := DXUTFindDXSDKMediaFile(str, MAX_PATH, WideString('Pick.fx'));
if V_Failed(Result) then Exit;
// If this fails, there should be debug output as to
// why the .fx file failed to compile
Result := D3DXCreateEffectFromFileW(pd3dDevice, str, nil, nil, dwShaderFlags, nil, g_pEffect, nil);
if V_Failed(Result) then Exit;
// Set effect variables as needed
colorMtrl := D3DXColor(1.0, 1.0, 1.0, 1.0);
vLightDir := D3DXVector3(0.1, -1.0, 0.1);
vLightDiffuse := D3DXColor(1,1,1,1);
Result:= g_pEffect.SetValue('g_MaterialAmbientColor', @colorMtrl, SizeOf(TD3DXColor));
if V_Failed(Result) then Exit;
Result:= g_pEffect.SetValue('g_MaterialDiffuseColor', @colorMtrl, SizeOf(TD3DXColor));
if V_Failed(Result) then Exit;
Result:= g_pEffect.SetValue('g_LightDir', @vLightDir, SizeOf(TD3DXVector3));
if V_Failed(Result) then Exit;
Result:= g_pEffect.SetValue('g_LightDiffuse', @vLightDiffuse, SizeOf(TD3DXVector4));
if V_Failed(Result) then Exit;
Result:= g_pEffect.SetTexture('g_MeshTexture', g_Mesh.m_pTextures[0]);
if V_Failed(Result) then Exit;
// Setup the camera's view parameters
// Setup the camera's view parameters
vecEye := D3DXVector3(-CAMERA_DISTANCE, 0.0, -15.0);
vecAt := D3DXVector3(0.0, 0.0, -0.0);
g_Camera.SetViewParams(vecEye, vecAt);
// Setup the world matrix of the camera
// Change this to see how picking works with a translated object
D3DXMatrixTranslation(mWorld, 0.0, -1.7, 0.0);
g_Camera.SetWorldMatrix(mWorld);
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has been
// reset, which will happen after a lost device scenario. This is the best location to
// create D3DPOOL_DEFAULT resources since these resources need to be reloaded whenever
// the device is lost. Resources created here should be released in the OnLostDevice
// callback.
//--------------------------------------------------------------------------------------
function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
var
fAspectRatio: Single;
begin
Result:= g_DialogResourceManager.OnResetDevice;
if V_Failed(Result) then Exit;
Result:= g_SettingsDlg.OnResetDevice;
if V_Failed(Result) then Exit;
Result:= g_Mesh.RestoreDeviceObjects(pd3dDevice);
if V_Failed(Result) then Exit;
if Assigned(g_pFont) then
begin
Result:= g_pFont.OnResetDevice;
if V_Failed(Result) then Exit;
end;
if Assigned(g_pEffect) then
begin
Result:= g_pEffect.OnResetDevice;
if V_Failed(Result) then Exit;
end;
// Create a sprite to help batch calls when drawing many lines of text
Result:= D3DXCreateSprite(pd3dDevice, g_pTextSprite);
if V_Failed(Result) then Exit;
// Setup the camera's projection parameters
fAspectRatio := pBackBufferSurfaceDesc.Width / pBackBufferSurfaceDesc.Height;
g_Camera.SetProjParams(D3DX_PI/4, fAspectRatio, 0.1, 1000.0);
g_Camera.SetWindow(pBackBufferSurfaceDesc.Width, pBackBufferSurfaceDesc.Height);
g_Camera.SetButtonMasks(MOUSE_LEFT_BUTTON, MOUSE_WHEEL, MOUSE_MIDDLE_BUTTON);
g_HUD.SetLocation(pBackBufferSurfaceDesc.Width-170, 0);
g_HUD.SetSize(170, 170);
g_SampleUI.SetLocation(pBackBufferSurfaceDesc.Width-170, pBackBufferSurfaceDesc.Height-350);
g_SampleUI.SetSize(170, 300);
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called once at the beginning of every frame. This is the
// best location for your application to handle updates to the scene, but is not
// intended to contain actual rendering calls, which should instead be placed in the
// OnFrameRender callback.
//--------------------------------------------------------------------------------------
procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
var
vFromPt: TD3DXVector3;
vLookatPt: TD3DXVector3;
begin
// Rotate the camera about the y-axis
vFromPt := D3DXVector3Zero;
vLookatPt := D3DXVector3Zero;
vFromPt.x := -cos(fTime/3.0) * CAMERA_DISTANCE;
vFromPt.y := 1.0;
vFromPt.z := sin(fTime/3.0) * CAMERA_DISTANCE;
// Update the camera's position based on time
g_Camera.SetViewParams(vFromPt, vLookatPt);
end;
//--------------------------------------------------------------------------------------
// This callback function will be called at the end of every frame to perform all the
// rendering calls for the scene, and it will also be called if the window needs to be
// repainted. After this function has returned, DXUT will call
// IDirect3DDevice9::Present to display the contents of the next buffer in the swap chain
//--------------------------------------------------------------------------------------
procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
var
mWorldViewProjection: TD3DXMatrixA16;
iPass, cPasses: LongWord;
m, mWorld, mView, mProj: TD3DXMatrixA16;
begin
// If the settings dialog is being shown, then
// render it instead of rendering the app's scene
if g_SettingsDlg.Active then
begin
g_SettingsDlg.OnRender(fElapsedTime);
Exit;
end;
// Check for picked triangles
Pick;
// Clear the render target and the zbuffer
V(pd3dDevice.Clear(0, nil, D3DCLEAR_TARGET or D3DCLEAR_ZBUFFER, D3DCOLOR_ARGB(0, 45, 50, 170), 1.0, 0));
// Render the scene
if SUCCEEDED(pd3dDevice.BeginScene) then
begin
// Get the projection & view matrix from the camera class
mWorld:= g_Camera.GetWorldMatrix^;
mProj := g_Camera.GetProjMatrix^;
mView := g_Camera.GetViewMatrix^;
// mWorldViewProjection = mWorld * mView * mProj;
D3DXMatrixMultiply(m, mView, mProj);
D3DXMatrixMultiply(mWorldViewProjection, mWorld, m);
V(g_pEffect.SetTechnique('RenderScene'));
// Update the effect's variables. Instead of using strings, it would
// be more efficient to cache a handle to the parameter by calling
// ID3DXEffect::GetParameterByName
V(g_pEffect.SetMatrix('g_mWorldViewProjection', mWorldViewProjection));
V(g_pEffect.SetMatrix('g_mWorld', mWorld));
V(g_pEffect.SetFloat('g_fTime', fTime));
V(g_pEffect._Begin(@cPasses, 0));
// Set render mode to lit, solid triangles
pd3dDevice.SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
pd3dDevice.SetRenderState(D3DRS_LIGHTING, iTrue);
if (g_dwNumIntersections > 0) then
begin
for iPass := 0 to cPasses - 1 do
begin
V(g_pEffect.BeginPass(iPass));
// Draw the picked triangle
pd3dDevice.SetFVF(TD3DVertex_FVF);
pd3dDevice.SetStreamSource(0, g_pVB, 0, SizeOf(TD3DVertex));
pd3dDevice.DrawPrimitive(D3DPT_TRIANGLELIST, 0, g_dwNumIntersections);
V(g_pEffect.EndPass);
end;
// Set render mode to unlit, wireframe triangles
pd3dDevice.SetRenderState(D3DRS_FILLMODE, D3DFILL_WIREFRAME);
pd3dDevice.SetRenderState(D3DRS_LIGHTING, iFalse);
end;
V(g_pEffect._End);
// Render the mesh
V(g_Mesh.Render(g_pEffect));
DXUT_BeginPerfEvent(DXUT_PERFEVENTCOLOR, 'HUD / Stats'); // These events are to help PIX identify what the code is doing
RenderText;
g_HUD.OnRender(fElapsedTime);
g_SampleUI.OnRender(fElapsedTime);
DXUT_EndPerfEvent;
V(pd3dDevice.EndScene);
end;
end;
//--------------------------------------------------------------------------------------
// Render the help and statistics text. This function uses the ID3DXFont interface for
// efficient text rendering.
//--------------------------------------------------------------------------------------
procedure RenderText;
var
txtHelper: CDXUTTextHelper;
dwIndex: DWORD;
wstrHitStat: array[0..255] of WideChar;
begin
// The helper object simply helps keep track of text position, and color
// and then it calls pFont->DrawText( m_pSprite, strMsg, -1, &rc, DT_NOCLIP, m_clr );
// If NULL is passed in as the sprite object, then it will work fine however the
// pFont->DrawText() will not be batched together. Batching calls will improves perf.
txtHelper:= CDXUTTextHelper.Create(g_pFont, g_pTextSprite, 15);
try
// Output statistics
txtHelper._Begin;
txtHelper.SetInsertionPos(5, 0);
txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 0.0, 1.0));
txtHelper.DrawTextLine(DXUTGetFrameStats);
txtHelper.DrawTextLine(DXUTGetDeviceStats);
txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 1.0, 1.0));
if(g_dwNumIntersections < 1) then
begin
txtHelper.DrawTextLine('Use mouse to pick a polygon');
end else
begin
for dwIndex := 0 to g_dwNumIntersections - 1 do
begin
StringCchFormat(wstrHitStat, 256,
//'Face=%d, tu=%3.02f, tv=%3.02f', //Clootie: pre Delphi9 bug
'Face=%d, tu=%f, tv=%f',
[g_IntersectionArray[dwIndex].dwFace,
g_IntersectionArray[dwIndex].tu,
g_IntersectionArray[dwIndex].tv]);
txtHelper.DrawTextLine(wstrHitStat);
end;
end;
txtHelper._End;
finally
txtHelper.Free;
end;
end;
//--------------------------------------------------------------------------------------
// Before handling window messages, DXUT passes incoming windows
// messages to the application through this callback function. If the application sets
// *pbNoFurtherProcessing to TRUE, then DXUT will not process this message.
//--------------------------------------------------------------------------------------
function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall;
begin
Result:= 0;
// Always allow dialog resource manager calls to handle global messages
// so GUI state is updated correctly
pbNoFurtherProcessing := g_DialogResourceManager.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
if g_SettingsDlg.IsActive then
begin
g_SettingsDlg.MsgProc(hWnd, uMsg, wParam, lParam);
Exit;
end;
// Give the dialogs a chance to handle the message first
pbNoFurtherProcessing := g_HUD.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
pbNoFurtherProcessing := g_SampleUI.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
// Pass all remaining windows messages to camera so it can respond to user input
//g_Camera.HandleMessages(hWnd, uMsg, wParam, lParam);
case uMsg of
WM_LBUTTONDOWN:
begin
// Capture the mouse, so if the mouse button is
// released outside the window, we'll get the WM_LBUTTONUP message
DXUTGetGlobalTimer.Stop;
SetCapture(hWnd);
Result:= iTrue;
Exit;
end;
WM_LBUTTONUP:
begin
ReleaseCapture;
DXUTGetGlobalTimer.Start;
end;
WM_CAPTURECHANGED:
begin
if (Cardinal(lParam) <> hWnd) then
begin
ReleaseCapture;
DXUTGetGlobalTimer.Start;
end;
end;
end;
end;
//--------------------------------------------------------------------------------------
// As a convenience, DXUT inspects the incoming windows messages for
// keystroke messages and decodes the message parameters to pass relevant keyboard
// messages to the application. The framework does not remove the underlying keystroke
// messages, which are still passed to the application's MsgProc callback.
//--------------------------------------------------------------------------------------
procedure KeyboardProc(nChar: LongWord; bKeyDown, bAltDown: Boolean; pUserContext: Pointer); stdcall;
begin
if bKeyDown then
begin
case nChar of
VK_F1: g_bShowHelp := not g_bShowHelp;
end;
end;
end;
//--------------------------------------------------------------------------------------
// Handles the GUI events
//--------------------------------------------------------------------------------------
procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall;
begin
case nControlID of
IDC_TOGGLEFULLSCREEN: DXUTToggleFullScreen;
IDC_TOGGLEREF: DXUTToggleREF;
IDC_CHANGEDEVICE: with g_SettingsDlg do Active := not Active;
IDC_USED3DX: g_bUseD3DXIntersect := not g_bUseD3DXIntersect;
IDC_ALLHITS: g_bAllHits := not g_bAllHits;
end;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has
// entered a lost state and before IDirect3DDevice9::Reset is called. Resources created
// in the OnResetDevice callback should be released here, which generally includes all
// D3DPOOL_DEFAULT resources. See the "Lost Devices" section of the documentation for
// information about lost devices.
//--------------------------------------------------------------------------------------
procedure OnLostDevice; stdcall;
begin
g_DialogResourceManager.OnLostDevice;
g_SettingsDlg.OnLostDevice;
CDXUTDirectionWidget.StaticOnLostDevice;
if Assigned(g_pFont) then g_pFont.OnLostDevice;
if Assigned(g_pEffect) then g_pEffect.OnLostDevice;
SAFE_RELEASE(g_pTextSprite);
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has
// been destroyed, which generally happens as a result of application termination or
// windowed/full screen toggles. Resources created in the OnCreateDevice callback
// should be released here, which generally includes all D3DPOOL_MANAGED resources.
//--------------------------------------------------------------------------------------
procedure OnDestroyDevice; stdcall;
begin
g_DialogResourceManager.OnDestroyDevice;
g_SettingsDlg.OnDestroyDevice;
g_Mesh.DestroyMesh;
SAFE_RELEASE(g_pVB);
SAFE_RELEASE(g_pEffect);
SAFE_RELEASE(g_pFont);
end;
//--------------------------------------------------------------------------------------
// Checks if mouse point hits geometry the scene.
//--------------------------------------------------------------------------------------
function Pick: HRESULT;
type
PD3DXIntersectInfoArray = ^TD3DXIntersectInfoArray;
TD3DXIntersectInfoArray = array [0..MaxInt div SizeOf(TD3DXIntersectInfo)-1] of TD3DXIntersectInfo;
PD3DVertexArray = ^TD3DVertexArray;
TD3DVertexArray = array [0..MaxInt div SizeOf(TD3DVertex)-1] of TD3DVertex;
var
vPickRayDir: TD3DXVector3;
vPickRayOrig: TD3DXVector3;
pD3Device: IDirect3DDevice9;
pd3dsdBackBuffer: PD3DSurfaceDesc;
pmatProj: PD3DXMatrix;
ptCursor: TPoint;
v: TD3DXVector3;
matView: TD3DXMatrix;
matWorld: TD3DXMatrix;
mWorldView: TD3DXMatrix;
m: TD3DXMatrix;
pMesh: ID3DXMesh;
pVB: IDirect3DVertexBuffer9;
pIB: IDirect3DIndexBuffer9;
pIndices: PWordArray;
pVertices: PD3DVertexArray;
bHit: BOOL;
dwFace: DWORD;
fBary1, fBary2, fDist: Single;
pBuffer: ID3DXBuffer;
pIntersectInfoArray: PD3DXIntersectInfoArray;
iIntersection: Integer;
dwNumFaces: DWORD;
i: Integer;
v0, v1, v2: TD3DXVector3;
vtx: PD3DVertexArray;
vThisTri: PD3DVertexArray;
iThisTri: PWordArray;
pIntersection: PIntersectionType;
dtu1: Single;
dtu2: Single;
dtv1: Single;
dtv2: Single;
begin
pD3Device := DXUTGetD3DDevice;
pd3dsdBackBuffer := DXUTGetBackBufferSurfaceDesc;
g_dwNumIntersections := 0;
// Get the pick ray from the mouse position
if (GetCapture <> 0) then
begin
pmatProj := g_Camera.GetProjMatrix;
GetCursorPos(ptCursor);
ScreenToClient(DXUTGetHWND, ptCursor);
// Compute the vector of the pick ray in screen space
v.x := ( ( ( 2.0 * ptCursor.x ) / pd3dsdBackBuffer.Width ) - 1 ) / pmatProj._11;
v.y := -( ( ( 2.0 * ptCursor.y ) / pd3dsdBackBuffer.Height ) - 1 ) / pmatProj._22;
v.z := 1.0;
// Get the inverse view matrix
matView := g_Camera.GetViewMatrix^;
matWorld := g_Camera.GetWorldMatrix^;
// mWorldView = matWorld * matView;
D3DXMatrixMultiply(mWorldView, matWorld, matView);
D3DXMatrixInverse(m, nil, mWorldView);
// Transform the screen space pick ray into 3D space
vPickRayDir.x := v.x*m._11 + v.y*m._21 + v.z*m._31;
vPickRayDir.y := v.x*m._12 + v.y*m._22 + v.z*m._32;
vPickRayDir.z := v.x*m._13 + v.y*m._23 + v.z*m._33;
vPickRayOrig.x := m._41;
vPickRayOrig.y := m._42;
vPickRayOrig.z := m._43;
end;
// Get the picked triangle
if (GetCapture <> 0) then
begin
g_Mesh.Mesh.CloneMeshFVF(D3DXMESH_MANAGED,
g_Mesh.Mesh.GetFVF, pD3Device, pMesh);
pMesh.GetVertexBuffer(pVB);
pMesh.GetIndexBuffer(pIB);
pIB.Lock(0, 0, Pointer(pIndices), 0);
pVB.Lock(0, 0, Pointer(pVertices), 0);
if g_bUseD3DXIntersect then
begin
// When calling D3DXIntersect, one can get just the closest intersection and not
// need to work with a D3DXBUFFER. Or, to get all intersections between the ray and
// the mesh, one can use a D3DXBUFFER to receive all intersections. We show both
// methods.
if not g_bAllHits then
begin
// Collect only the closest intersection
D3DXIntersect(pMesh, vPickRayOrig, vPickRayDir, bHit, @dwFace, @fBary1, @fBary2, @fDist, nil, nil);
if bHit then
begin
g_dwNumIntersections := 1;
g_IntersectionArray[0].dwFace := dwFace;
g_IntersectionArray[0].fBary1 := fBary1;
g_IntersectionArray[0].fBary2 := fBary2;
g_IntersectionArray[0].fDist := fDist;
end else
begin
g_dwNumIntersections := 0;
end;
end else
begin
// Collect all intersections
Result := D3DXIntersect(pMesh, vPickRayOrig, vPickRayDir, bHit, nil, nil, nil, nil, @pBuffer, @g_dwNumIntersections);
if Failed(Result) then Exit;
{begin
SAFE_RELEASE(pMesh);
SAFE_RELEASE(pVB);
SAFE_RELEASE(pIB);
Result:= hr;
end;}
if (g_dwNumIntersections > 0) then
begin
pIntersectInfoArray := PD3DXIntersectInfoArray(pBuffer.GetBufferPointer);
if (g_dwNumIntersections > MAX_INTERSECTIONS) then g_dwNumIntersections := MAX_INTERSECTIONS;
for iIntersection := 0 to g_dwNumIntersections - 1 do
begin
g_IntersectionArray[iIntersection].dwFace := pIntersectInfoArray[iIntersection].FaceIndex;
g_IntersectionArray[iIntersection].fBary1 := pIntersectInfoArray[iIntersection].U;
g_IntersectionArray[iIntersection].fBary2 := pIntersectInfoArray[iIntersection].V;
g_IntersectionArray[iIntersection].fDist := pIntersectInfoArray[iIntersection].Dist;
end;
end;
SAFE_RELEASE(pBuffer);
end;
end else
begin
// Not using D3DX
dwNumFaces := g_Mesh.Mesh.GetNumFaces;
for i := 0 to dwNumFaces - 1 do
begin
v0 := pVertices[pIndices[3*i+0]].p;
v1 := pVertices[pIndices[3*i+1]].p;
v2 := pVertices[pIndices[3*i+2]].p;
// Check if the pick ray passes through this point
if IntersectTriangle(vPickRayOrig, vPickRayDir, v0, v1, v2, fDist, fBary1, fBary2) then
begin
if (g_bAllHits or (g_dwNumIntersections = 0) or (fDist < g_IntersectionArray[0].fDist)) then
begin
if not g_bAllHits then g_dwNumIntersections := 0;
g_IntersectionArray[g_dwNumIntersections].dwFace := i;
g_IntersectionArray[g_dwNumIntersections].fBary1 := fBary1;
g_IntersectionArray[g_dwNumIntersections].fBary2 := fBary2;
g_IntersectionArray[g_dwNumIntersections].fDist := fDist;
Inc(g_dwNumIntersections);
if (g_dwNumIntersections = MAX_INTERSECTIONS) then Break;
end;
end;
end;
end;
// Now, for each intersection, add a triangle to g_pVB and compute texture coordinates
if (g_dwNumIntersections > 0) then
begin
g_pVB.Lock(0, 0, Pointer(vtx), 0);
for iIntersection := 0 to g_dwNumIntersections - 1 do
begin
pIntersection := @g_IntersectionArray[iIntersection];
vThisTri := @vtx[iIntersection * 3];
iThisTri := @pIndices[3*pIntersection.dwFace];
// get vertices hit
vThisTri[0] := pVertices[iThisTri[0]];
vThisTri[1] := pVertices[iThisTri[1]];
vThisTri[2] := pVertices[iThisTri[2]];
// If all you want is the vertices hit, then you are done. In this sample, we
// want to show how to infer texture coordinates as well, using the BaryCentric
// coordinates supplied by D3DXIntersect
dtu1 := vThisTri[1].tu - vThisTri[0].tu;
dtu2 := vThisTri[2].tu - vThisTri[0].tu;
dtv1 := vThisTri[1].tv - vThisTri[0].tv;
dtv2 := vThisTri[2].tv - vThisTri[0].tv;
pIntersection.tu := vThisTri[0].tu + pIntersection.fBary1 * dtu1 + pIntersection.fBary2 * dtu2;
pIntersection.tv := vThisTri[0].tv + pIntersection.fBary1 * dtv1 + pIntersection.fBary2 * dtv2;
end;
g_pVB.Unlock;
end;
pVB.Unlock;
pIB.Unlock;
SAFE_RELEASE(pMesh);
SAFE_RELEASE(pVB);
SAFE_RELEASE(pIB);
end;
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// Given a ray origin (orig) and direction (dir), and three vertices of a triangle, this
// function returns TRUE and the interpolated texture coordinates if the ray intersects
// the triangle
//--------------------------------------------------------------------------------------
function IntersectTriangle(const orig: TD3DXVector3; const dir: TD3DXVector3;
out v0, v1, v2: TD3DXVector3;
out t, u, v: Single): Boolean;
var
edge1: TD3DXVector3;
edge2: TD3DXVector3;
pvec: TD3DXVector3;
det: Single;
tvec: TD3DXVector3;
qvec: TD3DXVector3;
fInvDet: Single;
begin
Result:= False;
// Find vectors for two edges sharing vert0
//edge1 := v1 - v0;
//edge2 := v2 - v0;
D3DXVec3Subtract(edge1, v1, v0);
D3DXVec3Subtract(edge2, v2, v0);
// Begin calculating determinant - also used to calculate U parameter
D3DXVec3Cross(pvec, dir, edge2);
// If determinant is near zero, ray lies in plane of triangle
det := D3DXVec3Dot(edge1, pvec);
if (det > 0) then
begin
// tvec := orig - v0;
D3DXVec3Subtract(tvec, orig, v0);
end else
begin
// tvec := v0 - orig;
D3DXVec3Subtract(tvec, v0, orig);
det := -det;
end;
if (det < 0.0001) then Exit;
// Calculate U parameter and test bounds
u := D3DXVec3Dot(tvec, pvec);
if (u < 0.0) or (u > det) then Exit;
// Prepare to test V parameter
D3DXVec3Cross(qvec, tvec, edge1);
// Calculate V parameter and test bounds
v := D3DXVec3Dot(dir, qvec);
if (v < 0.0) or (u + v > det) then Exit;
// Calculate t, scale parameters, ray intersects triangle
t := D3DXVec3Dot(edge2, qvec);
fInvDet := 1.0 / det;
t := t * fInvDet;
u := u * fInvDet;
v := v * fInvDet;
Result:= True;
end;
procedure CreateCustomDXUTobjects;
begin
g_Mesh:= CDXUTMesh.Create; // The mesh to be rendered
g_Camera:= CModelViewerCamera.Create; // A model viewing camera
g_DialogResourceManager:= CDXUTDialogResourceManager.Create; // manager for shared resources of dialogs
g_SettingsDlg:= CD3DSettingsDlg.Create; // Device settings dialog
g_HUD:= CDXUTDialog.Create; // manages the 3D UI
g_SampleUI:= CDXUTDialog.Create; // dialog for sample specific controls
end;
procedure DestroyCustomDXUTobjects;
begin
FreeAndNil(g_Mesh);
FreeAndNil(g_Camera);
FreeAndNil(g_DialogResourceManager);
FreeAndNil(g_SettingsDlg);
FreeAndNil(g_HUD);
FreeAndNil(g_SampleUI);
end;
end.
|
{: GLSViewer main form.<p>
Requires RxLib to compile
(go to http://sourceforge.net/projects/rxlib for Delphi6 version)
and Mike Lischke's GraphicEx
(http://www.delphi-gems.com/)
}
unit FMain;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, ActnList, Menus, ImgList, ToolWin, ComCtrls, GLMaterial,
GLScene, GLWin32Viewer, GLVectorFileObjects, GLObjects, VectorGeometry,
GLTexture, OpenGL1x, GLContext, ExtDlgs, VectorLists, GLCadencer,
ExtCtrls, GLCoordinates, GLCrossPlatform, BaseClasses;
type
TMain = class(TForm)
MainMenu: TMainMenu;
ActionList: TActionList;
ImageList: TImageList;
ToolBar: TToolBar;
MIFile: TMenuItem;
MIAbout: TMenuItem;
ACOpen: TAction;
ACExit: TAction;
Open1: TMenuItem;
N1: TMenuItem;
Exit1: TMenuItem;
ToolButton1: TToolButton;
StatusBar: TStatusBar;
GLSceneViewer: TGLSceneViewer;
GLScene: TGLScene;
MIOptions: TMenuItem;
MIAntiAlias: TMenuItem;
MIAADefault: TMenuItem;
MSAA2X: TMenuItem;
MSAA4X: TMenuItem;
ACSaveAs: TAction;
ACZoomIn: TAction;
ACZoomOut: TAction;
ToolButton2: TToolButton;
ToolButton3: TToolButton;
ToolButton4: TToolButton;
MIView: TMenuItem;
ZoomIn1: TMenuItem;
ZoomOut1: TMenuItem;
FreeForm: TGLFreeForm;
OpenDialog: TOpenDialog;
GLLightSource: TGLLightSource;
GLMaterialLibrary: TGLMaterialLibrary;
CubeExtents: TGLCube;
ACResetView: TAction;
Resetview1: TMenuItem;
ToolButton5: TToolButton;
ACShadeSmooth: TAction;
ACFlatShading: TAction;
ACWireframe: TAction;
ACHiddenLines: TAction;
ToolButton6: TToolButton;
ToolButton7: TToolButton;
ToolButton8: TToolButton;
ToolButton9: TToolButton;
N2: TMenuItem;
Smoothshading1: TMenuItem;
Flatshading1: TMenuItem;
Hiddenlines1: TMenuItem;
Wireframe1: TMenuItem;
ToolButton10: TToolButton;
ACCullFace: TAction;
Faceculling1: TMenuItem;
N3: TMenuItem;
MIBgColor: TMenuItem;
ColorDialog: TColorDialog;
MITexturing: TMenuItem;
ACTexturing: TAction;
ToolButton11: TToolButton;
ToolButton12: TToolButton;
OpenPictureDialog: TOpenPictureDialog;
MIPickTexture: TMenuItem;
DCTarget: TGLDummyCube;
GLCamera: TGLCamera;
DCAxis: TGLDummyCube;
ACFlatLined: TAction;
ToolButton13: TToolButton;
FlatShadingwithlines1: TMenuItem;
ACInvertNormals: TAction;
MIActions: TMenuItem;
InvertNormals1: TMenuItem;
N4: TMenuItem;
Saveas1: TMenuItem;
SaveDialog: TSaveDialog;
ACReverseRenderingOrder: TAction;
ReverseRenderingOrder1: TMenuItem;
ACConvertToIndexedTriangles: TAction;
ConverttoIndexedTriangles1: TMenuItem;
ACFPS: TAction;
FramesPerSecond1: TMenuItem;
GLCadencer: TGLCadencer;
Timer: TTimer;
GLLightmapLibrary: TGLMaterialLibrary;
ACSaveTextures: TAction;
SDTextures: TSaveDialog;
Savetextures1: TMenuItem;
MIOpenTexLib: TMenuItem;
ODTextures: TOpenDialog;
Optimize1: TMenuItem;
N5: TMenuItem;
ACOptimize: TAction;
Stripify1: TMenuItem;
ACStripify: TAction;
N6: TMenuItem;
ACLighting: TAction;
Lighting1: TMenuItem;
TBLighting: TToolButton;
MSAA8X: TMenuItem;
MSAA16X: TMenuItem;
CSAA8X: TMenuItem;
CSAA16X: TMenuItem;
procedure MIAboutClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ACOpenExecute(Sender: TObject);
procedure GLSceneViewerMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure GLSceneViewerMouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
procedure FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
procedure GLSceneViewerMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure ACZoomInExecute(Sender: TObject);
procedure ACZoomOutExecute(Sender: TObject);
procedure ACExitExecute(Sender: TObject);
procedure ACShadeSmoothExecute(Sender: TObject);
procedure GLSceneViewerBeforeRender(Sender: TObject);
procedure MIAADefaultClick(Sender: TObject);
procedure GLSceneViewerAfterRender(Sender: TObject);
procedure ACResetViewExecute(Sender: TObject);
procedure ACCullFaceExecute(Sender: TObject);
procedure MIBgColorClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure GLMaterialLibraryTextureNeeded(Sender: TObject;
var textureFileName: String);
procedure ACTexturingExecute(Sender: TObject);
procedure MIPickTextureClick(Sender: TObject);
procedure MIFileClick(Sender: TObject);
procedure ACInvertNormalsExecute(Sender: TObject);
procedure ACSaveAsExecute(Sender: TObject);
procedure ACSaveAsUpdate(Sender: TObject);
procedure ACReverseRenderingOrderExecute(Sender: TObject);
procedure ACConvertToIndexedTrianglesExecute(Sender: TObject);
procedure GLCadencerProgress(Sender: TObject; const deltaTime,
newTime: Double);
procedure ACFPSExecute(Sender: TObject);
procedure TimerTimer(Sender: TObject);
procedure ACSaveTexturesExecute(Sender: TObject);
procedure MIOpenTexLibClick(Sender: TObject);
procedure ACOptimizeExecute(Sender: TObject);
procedure ACStripifyExecute(Sender: TObject);
procedure ACLightingExecute(Sender: TObject);
private
{ Private declarations }
procedure DoResetCamera;
procedure SetupFreeFormShading;
procedure ApplyShadeModeToMaterial(aMaterial : TGLMaterial);
procedure ApplyShadeMode;
procedure ApplyFSAA;
procedure ApplyFaceCull;
procedure ApplyBgColor;
procedure ApplyTexturing;
procedure ApplyFPS;
procedure DoOpen(const fileName : String);
public
{ Public declarations }
md, nthShow : Boolean;
mx, my : Integer;
hlShader : TGLShader;
lastFileName : String;
lastLoadWithTextures : Boolean;
end;
var
Main: TMain;
implementation
{$R *.dfm}
uses GLColor, GLKeyBoard, GLGraphics, Registry, PersistentClasses, MeshUtils,
GLFileOBJ, GLFileSTL, GLFileLWO, GLFileQ3BSP, GLFileOCT, GLFileMS3D,
GLFileNMF, GLFileMD3, GLFile3DS, GLFileMD2, GLFileSMD, GLFileTIN,
GLFilePLY, GLFileGTS, GLFileVRML, GLFileMD5, GLMeshOptimizer, GLState,
GLRenderContextInfo, GLTextureFormat;
type
// Hidden line shader (specific implem for the viewer, *not* generic)
THiddenLineShader = class (TGLShader)
private
LinesColor : TColorVector;
BackgroundColor : TColorVector;
PassCount : Integer;
public
procedure DoApply(var rci : TRenderContextInfo; Sender : TObject); override;
function DoUnApply(var rci : TRenderContextInfo) : Boolean; override;
end;
procedure THiddenLineShader.DoApply(var rci : TRenderContextInfo; Sender : TObject);
begin
PassCount:=1;
with rci.GLStates do
begin
PolygonMode := pmFill;
GL.Color3fv(@BackgroundColor);
ActiveTextureEnabled[ttTexture2D] := False;
Enable(stPolygonOffsetFill);
PolygonOffsetFactor := 1;
PolygonOffsetUnits := 2;
end;
end;
function THiddenLineShader.DoUnApply(var rci : TRenderContextInfo) : Boolean;
begin
case PassCount of
1 : with rci.GLStates do
begin
PassCount:=2;
PolygonMode := pmLines;
GL.Color3fv(@LinesColor);
Disable(stLighting);
Result:=True;
end;
2 : begin
rci.GLStates.Disable(stPolygonOffsetFill);
Result:=False;
end;
else
// doesn't hurt to be cautious
Assert(False);
Result:=False;
end;
end;
procedure TMain.FormCreate(Sender: TObject);
var
reg : TRegistry;
shellCmd : String;
keyOkay : Boolean;
const
cKeyName : String = 'Applications\GLSViewer.exe\shell\open\command';
cFriendlyKeyName : String = 'Applications\GLSViewer.exe';
begin
// instantiate our specific hidden-lines shader
hlShader:=THiddenLineShader.Create(Self);
FreeForm.IgnoreMissingTextures:=True;
// register as an application that handles arbitrary file classes
try
reg:=TRegistry.Create;
try
shellCmd:='"'+Application.ExeName+'" "%1"';
reg.RootKey:=HKEY_CLASSES_ROOT;
keyOkay:=False;
if reg.OpenKeyReadOnly(cKeyName) then
keyOkay:=(reg.ReadString('')=shellCmd);
if not keyOkay then begin
reg.CloseKey;
if reg.OpenKey(cKeyName, True) then
reg.WriteString('', shellCmd);
reg.CloseKey;
if reg.OpenKey(cFriendlyKeyName, True) then
reg.WriteString('FriendlyAppName', 'GLSViewer, OpenGL 3D Files Viewer');
end;
finally
reg.Free;
end;
except
// ignore all registry issues (not critical)
end;
end;
procedure TMain.FormShow(Sender: TObject);
var
i : Integer;
begin
if not nthShow then begin
OpenDialog.Filter:=VectorFileFormatsFilter;
SaveDialog.Filter:=VectorFileFormatsSaveFilter;
with ActionList do for i:=0 to ActionCount-1 do
if Actions[i] is TCustomAction then
with TCustomAction(Actions[i]) do Hint:=Caption;
ApplyFSAA;
ApplyFaceCull;
ApplyBgColor;
ApplyFPS;
if ParamCount>0 then
DoOpen(ParamStr(1));
nthShow:=True;
end;
end;
procedure TMain.GLSceneViewerBeforeRender(Sender: TObject);
begin
THiddenLineShader(hlShader).LinesColor:=VectorMake(107/256, 123/256, 173/256, 1);
THiddenLineShader(hlShader).BackgroundColor:=ConvertWinColor(GLSceneViewer.Buffer.BackgroundColor);
if not GL.ARB_multisample then begin
MIAADefault.Checked:=True;
MSAA2x.Enabled:=False;
MSAA4X.Enabled:=False;
MSAA8X.Enabled:=False;
MSAA16X.Enabled:=False;
CSAA8X.Enabled:=False;
CSAA16X.Enabled:=False;
end;
end;
procedure TMain.GLSceneViewerAfterRender(Sender: TObject);
begin
ApplyFSAA;
Screen.Cursor:=crDefault;
end;
procedure TMain.MIAboutClick(Sender: TObject);
begin
ShowMessage( 'GLSViewer - Simple OpenGL Mesh Viewer'#13#10
+'Copyright 2002 Eric Grange'#13#10#13#10
+'A freeware Delphi program based on...'#13#10#13#10
+'GLScene: 3D view, 3D file formats support'#13#10
+'http://glscene.org'#13#10#13#10
+'GraphicEx: 2D image file formats support'#13#10
+'http://www.delphi-gems.com/')
end;
procedure TMain.DoResetCamera;
var
objSize : Single;
begin
DCTarget.Position.AsVector:=NullHmgPoint;
GLCamera.Position.SetPoint(7, 3, 5);
FreeForm.Position.AsVector:=NullHmgPoint;
FreeForm.Up.Assign(DCAxis.Up);
FreeForm.Direction.Assign(DCAxis.Direction);
objSize:=FreeForm.BoundingSphereRadius;
if objSize>0 then begin
if objSize<1 then begin
GLCamera.SceneScale:=1/objSize;
objSize:=1;
end else GLCamera.SceneScale:=1;
GLCamera.AdjustDistanceToTarget(objSize*0.27);
GLCamera.DepthOfView:=1.5*GLCamera.DistanceToTarget+2*objSize;
end;
end;
procedure TMain.ApplyShadeModeToMaterial(aMaterial : TGLMaterial);
begin
with aMaterial do begin
if ACShadeSmooth.Checked then begin
GLSceneViewer.Buffer.Lighting:=True;
GLSceneViewer.Buffer.ShadeModel:=smSmooth;
aMaterial.PolygonMode:=pmFill;
end else if ACFlatShading.Checked then begin
GLSceneViewer.Buffer.Lighting:=True;
GLSceneViewer.Buffer.ShadeModel:=smFlat;
aMaterial.PolygonMode:=pmFill;
end else if ACFlatLined.Checked then begin
GLSceneViewer.Buffer.Lighting:=True;
GLSceneViewer.Buffer.ShadeModel:=smFlat;
aMaterial.PolygonMode:=pmLines;
end else if ACHiddenLines.Checked then begin
GLSceneViewer.Buffer.Lighting:=False;
GLSceneViewer.Buffer.ShadeModel:=smSmooth;
aMaterial.PolygonMode:=pmLines;
end else if ACWireframe.Checked then begin
GLSceneViewer.Buffer.Lighting:=False;
GLSceneViewer.Buffer.ShadeModel:=smSmooth;
aMaterial.PolygonMode:=pmLines;
end;
end;
end;
procedure TMain.ApplyShadeMode;
var
i : Integer;
begin
with GLMaterialLibrary.Materials do for i:=0 to Count-1 do begin
ApplyShadeModeToMaterial(Items[i].Material);
if (ACHiddenLines.Checked) or (ACFlatLined.Checked) then
Items[i].Shader:=hlShader
else Items[i].Shader:=nil;
end;
GLSceneViewer.Buffer.Lighting:=ACLighting.Checked;
FreeForm.StructureChanged;
end;
procedure TMain.ApplyFSAA;
begin
with GLSceneViewer.Buffer do begin
if MIAADefault.Checked then
AntiAliasing:=aaDefault
else if MSAA2X.Checked then
AntiAliasing:=aa2x
else if MSAA4X.Checked then
AntiAliasing:=aa4x
else if MSAA8X.Checked then
AntiAliasing:=aa8x
else if MSAA16X.Checked then
AntiAliasing:=aa16x
else if CSAA8X.Checked then
AntiAliasing:=csa8x
else if CSAA16X.Checked then
AntiAliasing:=csa16x;
end;
end;
procedure TMain.ApplyFaceCull;
begin
with GLSceneViewer.Buffer do begin
if ACCullFace.Checked then begin
FaceCulling:=True;
ContextOptions:=ContextOptions-[roTwoSideLighting];
end else begin
FaceCulling:=False;
ContextOptions:=ContextOptions+[roTwoSideLighting];
end;
end;
end;
procedure TMain.ApplyBgColor;
var
bmp : TBitmap;
col : TColor;
begin
bmp:=TBitmap.Create;
try
bmp.Width:=16;
bmp.Height:=16;
col:=ColorToRGB(ColorDialog.Color);
GLSceneViewer.Buffer.BackgroundColor:=col;
with bmp.Canvas do begin
Pen.Color:=col xor $FFFFFF;
Brush.Color:=col;
Rectangle(0, 0, 16, 16);
end;
MIBgColor.Bitmap:=bmp;
finally
bmp.Free;
end;
end;
procedure TMain.ApplyTexturing;
var
i : Integer;
begin
with GLMaterialLibrary.Materials do for i:=0 to Count-1 do begin
with Items[i].Material.Texture do begin
if Enabled then
Items[i].Tag:=Integer(True);
Enabled:=Boolean(Items[i].Tag) and ACTexturing.Checked;
end;
end;
FreeForm.StructureChanged;
end;
procedure TMain.ApplyFPS;
begin
if ACFPS.Checked then begin
Timer.Enabled:=True;
GLCadencer.Enabled:=True;
end else begin
Timer.Enabled:=False;
GLCadencer.Enabled:=False;
StatusBar.Panels[1].Text:='--- FPS';
end;
end;
procedure TMain.SetupFreeFormShading;
var
i : Integer;
libMat : TGLLibMaterial;
begin
with GLMaterialLibrary do begin
if Materials.Count=0 then begin
FreeForm.Material.MaterialLibrary:=GLMaterialLibrary;
libMat:=Materials.Add;
FreeForm.Material.LibMaterialName:=libMat.Name;
libMat.Material.FrontProperties.Diffuse.Red:=0;
end;
for i:=0 to Materials.Count-1 do
with Materials[i].Material do BackProperties.Assign(FrontProperties);
end;
ApplyShadeMode;
ApplyTexturing;
ApplyFPS;
end;
procedure TMain.DoOpen(const fileName : String);
var
min, max : TAffineVector;
begin
if not FileExists(fileName) then Exit;
Screen.Cursor:=crHourGlass;
Caption:='GLSViewer - '+ExtractFileName(fileName);
FreeForm.MeshObjects.Clear;
GLMaterialLibrary.Materials.Clear;
FreeForm.LoadFromFile(fileName);
SetupFreeFormShading;
StatusBar.Panels[0].Text:=IntToStr(FreeForm.MeshObjects.TriangleCount)+' tris';
StatusBar.Panels[2].Text:=fileName;
ACSaveTextures.Enabled:=(GLMaterialLibrary.Materials.Count>0);
MIOpenTexLib.Enabled:=(GLMaterialLibrary.Materials.Count>0);
lastFileName:=fileName;
lastLoadWithTextures:=ACTexturing.Enabled;
FreeForm.GetExtents(min, max);
with CubeExtents do begin
CubeWidth:=max[0]-min[0];
CubeHeight:=max[1]-min[1];
CubeDepth:=max[2]-min[2];
Position.AsAffineVector:=VectorLerp(min, max, 0.5);
end;
DoResetCamera;
end;
procedure TMain.ACOpenExecute(Sender: TObject);
begin
if OpenDialog.Execute then
DoOpen(OpenDialog.FileName);
end;
procedure TMain.GLSceneViewerMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
mx:=x; my:=y;
md:=True;
end;
procedure TMain.GLSceneViewerMouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
var
d : Single;
begin
if md and (Shift<>[]) then begin
if ssLeft in Shift then
if ssShift in Shift then
GLCamera.MoveAroundTarget((my-y)*0.1, (mx-x)*0.1)
else GLCamera.MoveAroundTarget(my-y, mx-x)
else if ssRight in Shift then begin
d:=GLCamera.DistanceToTarget*0.01*(x-mx+y-my);
if IsKeyDown('x') then
FreeForm.Translate(d, 0, 0)
else if IsKeyDown('y') then
FreeForm.Translate(0, d, 0)
else if IsKeyDown('z') then
FreeForm.Translate(0, 0, d)
else begin
if ssShift in Shift then
GLCamera.RotateObject(FreeForm, (my-y)*0.1, (mx-x)*0.1)
else GLCamera.RotateObject(FreeForm, my-y, mx-x);
end;
end;
mx:=x; my:=y;
end;
end;
procedure TMain.GLSceneViewerMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
md:=False;
end;
procedure TMain.FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
begin
if FreeForm.MeshObjects.Count>0 then begin
GLCamera.AdjustDistanceToTarget(Power(1.05, WheelDelta/120));
GLCamera.DepthOfView:=2*GLCamera.DistanceToTarget+2*FreeForm.BoundingSphereRadius;
end;
Handled:=True;
end;
procedure TMain.ACZoomInExecute(Sender: TObject);
var
h : Boolean;
begin
FormMouseWheel(Self, [], -120*4, Point(0, 0), h);
end;
procedure TMain.ACZoomOutExecute(Sender: TObject);
var
h : Boolean;
begin
FormMouseWheel(Self, [], 120*4, Point(0, 0), h);
end;
procedure TMain.ACExitExecute(Sender: TObject);
begin
Close;
end;
procedure TMain.ACShadeSmoothExecute(Sender: TObject);
begin
ApplyShadeMode;
end;
procedure TMain.MIAADefaultClick(Sender: TObject);
begin
(Sender as TMenuItem).Checked:=True;
ApplyFSAA;
end;
procedure TMain.ACResetViewExecute(Sender: TObject);
begin
DoResetCamera;
end;
procedure TMain.ACCullFaceExecute(Sender: TObject);
begin
ACCullFace.Checked:=not ACCullFace.Checked;
ApplyFaceCull;
end;
procedure TMain.MIBgColorClick(Sender: TObject);
begin
if ColorDialog.Execute then
ApplyBgColor;
end;
procedure TMain.GLMaterialLibraryTextureNeeded(Sender: TObject;
var textureFileName: String);
begin
if not ACTexturing.Enabled then
textureFileName:='';
end;
procedure TMain.ACTexturingExecute(Sender: TObject);
begin
ACTexturing.Checked:=not ACTexturing.Checked;
if ACTexturing.Checked then
if lastLoadWithTextures then
ApplyTexturing
else begin
DoOpen(lastFileName);
end
else ApplyTexturing;
end;
procedure TMain.MIFileClick(Sender: TObject);
begin
MIPickTexture.Enabled:=(GLMaterialLibrary.Materials.Count>0);
end;
procedure TMain.MIPickTextureClick(Sender: TObject);
begin
if OpenPictureDialog.Execute then begin
with GLMaterialLibrary.Materials do begin
with Items[Count-1] do begin
Tag:=1;
Material.Texture.Image.LoadFromFile(OpenPictureDialog.FileName);
Material.Texture.Enabled:=True;
end;
end;
ApplyTexturing;
end;
end;
procedure TMain.MIOpenTexLibClick(Sender: TObject);
var
i : Integer;
begin
if ODTextures.Execute then with GLMaterialLibrary do begin
LoadFromFile(ODTextures.FileName);
for i:=0 to Materials.Count-1 do
with Materials[i].Material do BackProperties.Assign(FrontProperties);
ApplyShadeMode;
ApplyTexturing;
end;
end;
procedure TMain.ACInvertNormalsExecute(Sender: TObject);
var
i : Integer;
begin
with FreeForm.MeshObjects do
for i:=0 to Count-1 do
Items[i].Normals.Scale(-1);
FreeForm.StructureChanged;
end;
procedure TMain.ACReverseRenderingOrderExecute(Sender: TObject);
var
i, j, n : Integer;
fg : TFaceGroup;
begin
with FreeForm.MeshObjects do begin
// invert meshobjects order
for i:=0 to (Count div 2) do
Exchange(i, Count-1-i);
// for each mesh object
for i:=0 to Count-1 do with Items[i] do begin
// invert facegroups order
n:=FaceGroups.Count;
for j:=0 to (n div 2) do
Exchange(j, n-1-j);
// for each facegroup
for j:=0 to n-1 do begin
fg:=FaceGroups[j];
fg.Reverse;
end;
end;
end;
FreeForm.StructureChanged;
end;
procedure TMain.ACSaveAsExecute(Sender: TObject);
var
ext : String;
begin
if SaveDialog.Execute then begin
ext:=ExtractFileExt(SaveDialog.FileName);
if ext='' then
SaveDialog.FileName:=ChangeFileExt(SaveDialog.FileName,
'.'+GetVectorFileFormats.FindExtByIndex(SaveDialog.FilterIndex, False, True));
if GetVectorFileFormats.FindFromFileName(SaveDialog.FileName)=nil then
ShowMessage('Unsupported or unspecified file extension.')
else FreeForm.SaveToFile(SaveDialog.FileName);
end;
end;
procedure TMain.ACSaveAsUpdate(Sender: TObject);
begin
ACSaveAs.Enabled:=(FreeForm.MeshObjects.Count>0);
end;
procedure TMain.ACConvertToIndexedTrianglesExecute(Sender: TObject);
var
v : TAffineVectorList;
i : TIntegerList;
m : TMeshObject;
fg : TFGVertexIndexList;
begin
v:=FreeForm.MeshObjects.ExtractTriangles;
try
i:=BuildVectorCountOptimizedIndices(v);
try
RemapAndCleanupReferences(v, i);
IncreaseCoherency(i, 12);
i.Capacity:=i.Count;
FreeForm.MeshObjects.Clean;
m:=TMeshObject.CreateOwned(FreeForm.MeshObjects);
m.Vertices:=v;
m.BuildNormals(i, momTriangles);
m.Mode:=momFaceGroups;
fg:=TFGVertexIndexList.CreateOwned(m.FaceGroups);
fg.VertexIndices:=i;
fg.Mode:=fgmmTriangles;
FreeForm.StructureChanged;
finally
i.Free;
end;
finally
v.Free;
end;
GLMaterialLibrary.Materials.Clear;
SetupFreeFormShading;
end;
procedure TMain.ACStripifyExecute(Sender: TObject);
var
i : Integer;
mo : TMeshObject;
fg : TFGVertexIndexList;
strips : TPersistentObjectList;
begin
ACConvertToIndexedTriangles.Execute;
mo:=FreeForm.MeshObjects[0];
fg:=(mo.FaceGroups[0] as TFGVertexIndexList);
strips:=StripifyMesh(fg.VertexIndices, mo.Vertices.Count, True);
try
fg.Free;
for i:=0 to strips.Count-1 do begin
fg:=TFGVertexIndexList.CreateOwned(mo.FaceGroups);
fg.VertexIndices:=(strips[i] as TIntegerList);
if i=0 then
fg.Mode:=fgmmTriangles
else fg.Mode:=fgmmTriangleStrip;
end;
finally
strips.Free;
end;
end;
procedure TMain.ACOptimizeExecute(Sender: TObject);
begin
OptimizeMesh(FreeForm.MeshObjects, [mooVertexCache, mooSortByMaterials]);
FreeForm.StructureChanged;
SetupFreeFormShading;
end;
procedure TMain.GLCadencerProgress(Sender: TObject; const deltaTime,
newTime: Double);
begin
if Self.Focused then
GLSceneViewer.Invalidate;
end;
procedure TMain.ACFPSExecute(Sender: TObject);
begin
ACFPS.Checked:=not ACFPS.Checked;
ApplyFPS;
end;
procedure TMain.ACLightingExecute(Sender: TObject);
begin
ACLighting.Checked:=not ACLighting.Checked;
// TBLighting
ApplyShadeMode;
end;
procedure TMain.TimerTimer(Sender: TObject);
begin
StatusBar.Panels[1].Text:=Format('%.1f FPS', [GLSceneViewer.FramesPerSecond]);
GLSceneViewer.ResetPerformanceMonitor;
end;
procedure TMain.ACSaveTexturesExecute(Sender: TObject);
begin
if SDTextures.Execute then
GLMaterialLibrary.SaveToFile(SDTextures.FileName);
end;
end.
|
(*----------------------------------------------------------------------------*
* Direct3D sample from DirectX 9.0 SDK December 2006 *
* Delphi adaptation by Alexey Barkovoy (e-mail: directx@clootie.ru) *
* *
* Supported compilers: Delphi 5,6,7,9; FreePascal 2.0 *
* *
* Latest version can be downloaded from: *
* http://www.clootie.ru *
* http://sourceforge.net/projects/delphi-dx9sdk *
*----------------------------------------------------------------------------*
* $Id: PostProcessUnit.pas,v 1.8 2007/02/05 22:21:11 clootie Exp $
*----------------------------------------------------------------------------*)
//--------------------------------------------------------------------------------------
// File: PostProcess.cpp
//
// Starting point for new Direct3D applications
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
{$I DirectX.inc}
unit PostProcessUnit;
interface
uses
Windows, Messages, SysUtils, Math, StrSafe,
DXTypes, Direct3D9, D3DX9,
DXUT, DXUTcore, DXUTenum, DXUTmisc, DXUTgui, DXUTmesh, DXUTSettingsDlg;
const
// NUM_PARAMS is the maximum number of changeable parameters supported
// in an effect.
NUM_PARAMS = 2;
// RT_COUNT is the number of simultaneous render targets used in the sample.
RT_COUNT = 3;
// Name of the postprocess .fx files
g_aszFxFile: array[0..16] of PWideChar =
(
'PP_ColorMonochrome.fx',
'PP_ColorInverse.fx',
'PP_ColorGBlurH.fx',
'PP_ColorGBlurV.fx',
'PP_ColorBloomH.fx',
'PP_ColorBloomV.fx',
'PP_ColorBrightPass.fx',
'PP_ColorToneMap.fx',
'PP_ColorEdgeDetect.fx',
'PP_ColorDownFilter4.fx',
'PP_ColorUpFilter4.fx',
'PP_ColorCombine.fx',
'PP_ColorCombine4.fx',
'PP_NormalEdgeDetect.fx',
'PP_DofCombine.fx',
'PP_NormalMap.fx',
'PP_PositionMap.fx'
);
// PPCOUNT is the number of postprocess effects supported
PPCOUNT = High(g_aszFxFile) + 1;
// Description of each postprocess supported
g_aszPpDesc: array[0..16] of PWideChar =
(
'[Color] Monochrome',
'[Color] Inversion',
'[Color] Gaussian Blur Horizonta',
'[Color] Gaussian Blur Vertica',
'[Color] Bloom Horizonta',
'[Color] Bloom Vertica',
'[Color] Bright Pass',
'[Color] Tone Mapping',
'[Color] Edge Detection',
'[Color] Down Filter 4x',
'[Color] Up Filter 4x',
'[Color] Combine',
'[Color] Combine 4x',
'[Normal] Edge Detection',
'DOF Combine',
'Normal Map',
'Position Map'
);
type
//--------------------------------------------------------------------------------------
// This is the vertex format used for the meshes.
TMeshVert = packed record
x, y, z: Single; // Position
nx, ny, nz: Single; // Normal
tu, tv: Single; // Texcoord
// const static D3DVERTEXELEMENT9 Decl[4];
end;
const
TMeshVert_Decl: array[0..3] of TD3DVertexElement9 =
(
(Stream: 0; Offset: 0; _Type: D3DDECLTYPE_FLOAT3; Method: D3DDECLMETHOD_DEFAULT; Usage: D3DDECLUSAGE_POSITION; UsageIndex: 0),
(Stream: 0; Offset: 12; _Type: D3DDECLTYPE_FLOAT3; Method: D3DDECLMETHOD_DEFAULT; Usage: D3DDECLUSAGE_NORMAL; UsageIndex: 0),
(Stream: 0; Offset: 24; _Type: D3DDECLTYPE_FLOAT2; Method: D3DDECLMETHOD_DEFAULT; Usage: D3DDECLUSAGE_TEXCOORD; UsageIndex: 0),
{D3DDECL_END()}(Stream:$FF; Offset:0; _Type:D3DDECLTYPE_UNUSED; Method:TD3DDeclMethod(0); Usage:TD3DDeclUsage(0); UsageIndex:0)
);
type
//--------------------------------------------------------------------------------------
// This is the vertex format used for the skybox.
TSkyboxVert = packed record
x, y, z: Single; // Position
tex: TD3DXVector3; // Texcoord
// const static D3DVERTEXELEMENT9 Decl[3];
end;
const
TSkyboxVert_Decl: array[0..2] of TD3DVertexElement9 =
(
(Stream: 0; Offset: 0; _Type: D3DDECLTYPE_FLOAT3; Method: D3DDECLMETHOD_DEFAULT; Usage: D3DDECLUSAGE_POSITION; UsageIndex: 0),
(Stream: 0; Offset: 12; _Type: D3DDECLTYPE_FLOAT3; Method: D3DDECLMETHOD_DEFAULT; Usage: D3DDECLUSAGE_TEXCOORD; UsageIndex: 0),
{D3DDECL_END()}(Stream:$FF; Offset:0; _Type:D3DDECLTYPE_UNUSED; Method:TD3DDeclMethod(0); Usage:TD3DDeclUsage(0); UsageIndex:0)
);
type
//--------------------------------------------------------------------------------------
// This is the vertex format used with the quad during post-process.
PppVert = ^TppVert;
TppVert = packed record
x, y, z, rhw: Single;
tu, tv: Single; // Texcoord for post-process source
tu2, tv2: Single; // Texcoord for the original scene
// const static D3DVERTEXELEMENT9 Decl[4];
end;
const
// Vertex declaration for post-processing
TppVert_Decl: array[0..3] of TD3DVertexElement9 =
(
(Stream: 0; Offset: 0; _Type: D3DDECLTYPE_FLOAT4; Method: D3DDECLMETHOD_DEFAULT; Usage: D3DDECLUSAGE_POSITIONT; UsageIndex: 0),
(Stream: 0; Offset: 16; _Type: D3DDECLTYPE_FLOAT2; Method: D3DDECLMETHOD_DEFAULT; Usage: D3DDECLUSAGE_TEXCOORD; UsageIndex: 0),
(Stream: 0; Offset: 24; _Type: D3DDECLTYPE_FLOAT2; Method: D3DDECLMETHOD_DEFAULT; Usage: D3DDECLUSAGE_TEXCOORD; UsageIndex: 1),
{D3DDECL_END()}(Stream:$FF; Offset:0; _Type:D3DDECLTYPE_UNUSED; Method:TD3DDeclMethod(0); Usage:TD3DDeclUsage(0); UsageIndex:0)
);
type
//--------------------------------------------------------------------------------------
// struct CPostProcess
// A struct that encapsulates aspects of a render target postprocess
// technique.
//--------------------------------------------------------------------------------------
CPostProcess = class
private
m_pEffect: ID3DXEffect; // Effect object for this technique
m_hTPostProcess: TD3DXHandle; // PostProcess technique handle
m_nRenderTarget: Integer; // Render target channel this PP outputs
m_hTexSource: array[0..3] of TD3DXHandle; // Handle to the post-process source textures
m_hTexScene: array[0..3] of TD3DXHandle; // Handle to the saved scene texture
m_bWrite: array[0..3] of Boolean; // Indicates whether the post-process technique
// outputs data for this render target.
m_awszParamName: array[0..NUM_PARAMS-1, 0..MAX_PATH-1] of WideChar; // Names of changeable parameters
m_awszParamDesc: array[0..NUM_PARAMS-1, 0..MAX_PATH-1] of WideChar; // Names of changeable parameters
m_ahParam: array[0..NUM_PARAMS-1] of TD3DXHandle; // Handles to the changeable parameters
m_anParamSize: array[0..NUM_PARAMS-1] of Integer; // Size of the parameter. Indicates
// how many components of float4
// are used.
m_avParamDef: array[0..NUM_PARAMS-1] of TD3DXVector4; // Parameter default
public
// constructor Create; // ZEROing is done automatically in Delphi
destructor Destroy; override; // ~CPostProcess() { Cleanup(); }
function Init(const pDev: IDirect3DDevice9; dwShaderFlags: DWORD; wszName: PWideChar): HRESULT;
procedure Cleanup; { SAFE_RELEASE( m_pEffect ); }
function OnLostDevice: HRESULT;
function OnResetDevice(dwWidth, dwHeight: DWORD): HRESULT;
end;
//--------------------------------------------------------------------------------------
// struct CPProcInstance
// A class that represents an instance of a post-process to be applied
// to the scene.
//--------------------------------------------------------------------------------------
CPProcInstance = class
protected
m_avParam: array[0..NUM_PARAMS-1] of TD3DXVector4;
m_nFxIndex: Integer;
public
constructor Create;
end;
CRenderTargetChain = class
m_nNext: Integer;
m_bFirstRender: Boolean;
m_pRenderTarget: array[0..1] of IDirect3DTexture9;
public
constructor Create;
destructor Destroy; override;
procedure Init(const pRT: array of IDirect3DTexture9);
procedure Cleanup;
procedure Flip;
function GetPrevTarget: IDirect3DTexture9; { return m_pRenderTarget[1 - m_nNext]; }
function GetPrevSource: IDirect3DTexture9; { return m_pRenderTarget[m_nNext]; }
function GetNextTarget: IDirect3DTexture9; { return m_pRenderTarget[m_nNext]; }
function GetNextSource: IDirect3DTexture9; { return m_pRenderTarget[1 - m_nNext]; }
end;
// An CRenderTargetSet object dictates what render targets
// to use in a pass of scene rendering.
TRenderTargetSet = record
pRT: array[0..RT_COUNT-1] of IDirect3DSurface9;
end;
//--------------------------------------------------------------------------------------
// Global variables
//--------------------------------------------------------------------------------------
var
g_pFont: ID3DXFont; // Font for drawing text
g_pTextSprite: ID3DXSprite; // Sprite for batching draw text calls
g_pEffect: ID3DXEffect; // D3DX effect interface
g_Camera: CModelViewerCamera; // A model viewing camera
g_bShowHelp: Boolean = True; // If true, it renders the UI control text
g_DialogResourceManager: CDXUTDialogResourceManager; // manager for shared resources of dialogs
g_SettingsDlg: CD3DSettingsDlg; // Device settings dialog
g_HUD: CDXUTDialog; // dialog for standard controls
g_SampleUI: CDXUTDialog; // dialog for sample specific controls
g_pEnvTex: IDirect3DCubeTexture9; // Texture for environment mapping
g_pVertDecl: IDirect3DVertexDeclaration9; // Vertex decl for scene rendering
g_pSkyBoxDecl: IDirect3DVertexDeclaration9; // Vertex decl for Skybox rendering
g_pVertDeclPP: IDirect3DVertexDeclaration9; // Vertex decl for post-processing
g_mMeshWorld: TD3DXMatrixA16; // World matrix (xlate and scale) for the mesh
g_nScene: Integer = 0; // Indicates the scene # to render
g_aPostProcess: array[0..PPCOUNT-1] of CPostProcess; // Effect object for postprocesses
g_hTRenderScene: TD3DXHandle; // Handle to RenderScene technique
g_hTRenderEnvMapScene: TD3DXHandle; // Handle to RenderEnvMapScene technique
g_hTRenderNoLight: TD3DXHandle; // Handle to RenderNoLight technique
g_hTRenderSkyBox: TD3DXHandle; // Handle to RenderSkyBox technique
g_SceneMesh: array[0..1] of CDXUTMesh; // Mesh objects in the scene
g_Skybox: CDXUTMesh; // Skybox mesh
g_TexFormat: TD3DFormat; // Render target texture format
g_pSceneSave: array[0..RT_COUNT-1] of IDirect3DTexture9; // To save original scene image before postprocess
g_RTChain: array[0..RT_COUNT-1] of CRenderTargetChain; // Render target chain (4 used in sample)
g_bEnablePostProc: Boolean = True; // Whether or not to enable post-processing
g_nPasses: Integer = 0; // Number of passes required to render scene
g_nRtUsed: Integer = 0; // Number of simultaneous RT used to render scene
g_aRtTable: array[0..RT_COUNT-1] of TRenderTargetSet; // Table of which RT to use for all passes
//--------------------------------------------------------------------------------------
// UI control IDs
//--------------------------------------------------------------------------------------
const
IDC_TOGGLEFULLSCREEN = 1;
IDC_TOGGLEREF = 3;
IDC_CHANGEDEVICE = 4;
IDC_SELECTSCENE = 5;
IDC_AVAILABLELIST = 6;
IDC_ACTIVELIST = 7;
IDC_AVAILABLELISTLABEL = 8;
IDC_ACTIVELISTLABEL = 9;
IDC_PARAM0NAME = 10;
IDC_PARAM1NAME = 11;
IDC_PARAM0 = 12;
IDC_PARAM1 = 13;
IDC_MOVEUP = 14;
IDC_MOVEDOWN = 15;
IDC_CLEAR = 16;
IDC_ENABLEPP = 17;
IDC_PRESETLABEL = 18;
IDC_PREBLUR = 19;
IDC_PREBLOOM = 20;
IDC_PREDOF = 21;
IDC_PREEDGE = 22;
//--------------------------------------------------------------------------------------
// Forward declarations
//--------------------------------------------------------------------------------------
function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall;
function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall;
function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall;
procedure KeyboardProc(nChar: LongWord; bKeyDown, bAltDown: Boolean; pUserContext: Pointer); stdcall;
procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall;
procedure OnLostDevice(pUserContext: Pointer); stdcall;
procedure OnDestroyDevice(pUserContext: Pointer); stdcall;
procedure InitApp;
//todo: Fill Bug report to MS: LoadMesh
//function LoadMesh(const pd3dDevice: IDirect3DDevice9; strFileName: PWideChar; out ppMesh: ID3DXMesh): HRESULT; overload;
procedure RenderText;
//todo: Fill Bug report to MS: different param lists in forward and in implementation
function PerformSinglePostProcess(const pd3dDevice: IDirect3DDevice9;
const PP: CPostProcess; const Inst: CPProcInstance;
pVB: IDirect3DVertexBuffer9; var aQuad: array of TppVert; var fExtentX, fExtentY: Single): HRESULT;
function PerformPostProcess(const pd3dDevice: IDirect3DDevice9): HRESULT;
function ComputeMeshWorldMatrix(pMesh: ID3DXMesh): HRESULT;
procedure CreateCustomDXUTobjects;
procedure DestroyCustomDXUTobjects;
procedure ClearActiveList;
implementation
//--------------------------------------------------------------------------------------
// Empty the active effect list except the last (blank) item.
procedure ClearActiveList;
var
pListBox: CDXUTListBox;
pItem: PDXUTListBoxItem;
i: Integer;
begin
// Clear all items in the active list except the last one.
pListBox := g_SampleUI.GetListBox(IDC_ACTIVELIST);
if (pListBox = nil) then Exit;
i := pListBox.Size - 1;
while (i > 0) do
begin
Dec(i);
pItem := pListBox.GetItem(0);
FreeMem(pItem.pData);
pListBox.RemoveItem(0);
end;
end;
//--------------------------------------------------------------------------------------
// Initialize the app
//--------------------------------------------------------------------------------------
procedure InitApp;
var
pMultiSampleTypeList: TD3DMultiSampleTypeArray;
i, iY: Integer;
pListBox: CDXUTListBox;
pEditBox: CDXUTEditBox;
pComboBox: CDXUTComboBox;
begin
// This sample does not do multisampling.
SetLength(pMultiSampleTypeList, 1);
pMultiSampleTypeList[0]:= D3DMULTISAMPLE_NONE;
DXUTGetEnumeration.PossibleMultisampleTypeList:= pMultiSampleTypeList;
DXUTGetEnumeration.SetMultisampleQualityMax(0);
// Initialize dialogs
g_SettingsDlg.Init(g_DialogResourceManager);
g_HUD.Init(g_DialogResourceManager);
g_SampleUI.Init(g_DialogResourceManager);
g_HUD.SetCallback(OnGUIEvent);
iY := 0; g_HUD.AddButton(IDC_TOGGLEFULLSCREEN, 'Toggle full screen', 0, iY, 125, 22);
Inc(iY, 24); g_HUD.AddButton(IDC_TOGGLEREF, 'Toggle REF (F3)', 0, iY, 125, 22);
Inc(iY, 24); g_HUD.AddButton(IDC_CHANGEDEVICE, 'Change device (F2)', 0, iY , 125, 22, VK_F2);
g_SampleUI.SetCallback(OnGUIEvent); iY := 5;
g_SampleUI.EnableCaption := True;
g_SampleUI.SetCaptionText('Effect Manager');
g_SampleUI.SetBackgroundColors(D3DCOLOR_ARGB(100, 255, 255, 255));
// Initialize sample-specific UI controls
g_SampleUI.AddStatic(IDC_AVAILABLELISTLABEL, 'Available effects (Dbl click inserts effect):', 10, iY, 210, 16);
g_SampleUI.GetStatic(IDC_AVAILABLELISTLABEL).Element[0].dwTextFormat := DT_LEFT or DT_TOP;
Inc(iY, 18); g_SampleUI.AddListBox(IDC_AVAILABLELIST, 10, iY, 200, 82, NORMAL, @pListBox);
if Assigned(pListBox) then
begin
// Populate ListBox items
for i := 0 to PPCOUNT - 1 do
pListBox.AddItem(g_aszPpDesc[i], Pointer(size_t(i)));
end;
Inc(iY, 87); g_SampleUI.AddStatic(IDC_ACTIVELISTLABEL, 'Active effects (Dbl click removes effect):', 10, iY, 210, 16);
g_SampleUI.GetStatic(IDC_ACTIVELISTLABEL).Element[0].dwTextFormat := DT_LEFT or DT_TOP;
Inc(iY, 18); g_SampleUI.AddListBox(IDC_ACTIVELIST, 10, iY, 200, 82, NORMAL, @pListBox);
if Assigned(pListBox) then
begin
// Add a blank entry for users to add effect to the end of list.
//todo: function StringCopyWorkerW(pszDest: PWideChar; cchDest: size_t; {pointer to const} pszSrc: PWideChar): HRESULT;
{begin
Assert(Assigned(pszSrc));}
pListBox.AddItem('', nil);
end;
Inc(iY, 92);
g_SampleUI.AddButton(IDC_MOVEUP, 'Move Up', 0, iY, 70, 22);
g_SampleUI.AddButton(IDC_MOVEDOWN, 'Move Down', 72, iY, 75, 22);
g_SampleUI.AddButton(IDC_CLEAR, 'Clear Al', 149, iY, 65, 22);
Inc(iY, 24);
g_SampleUI.AddStatic(IDC_PARAM0NAME, 'Select an active effect to set its parameter.', 5, iY, 215, 15);
g_SampleUI.GetStatic(IDC_PARAM0NAME).Element[0].dwTextFormat := DT_LEFT or DT_TOP;
Inc(iY, 15);
g_SampleUI.AddEditBox(IDC_PARAM0, '', 5, iY, 210, 20, False, @pEditBox);
if Assigned(pEditBox) then
begin
pEditBox.BorderWidth:= 1;
pEditBox.Spacing:= 2;
end;
Inc(iY, 20);
g_SampleUI.AddStatic(IDC_PARAM1NAME, 'Select an active effect to set its parameter.', 5, 20, 215, 15);
g_SampleUI.GetStatic(IDC_PARAM1NAME).Element[0].dwTextFormat := DT_LEFT or DT_TOP;
Inc(iY, 15);
g_SampleUI.AddEditBox(IDC_PARAM1, '', 5, iY, 210, 20, False, @pEditBox);
if Assigned(pEditBox) then
begin
pEditBox.BorderWidth := 1;
pEditBox.Spacing := 2;
end;
// Disable the edit boxes and 2nd static control by default.
g_SampleUI.GetControl(IDC_PARAM0).Enabled := False;
g_SampleUI.GetControl(IDC_PARAM0).Visible := False;
g_SampleUI.GetControl(IDC_PARAM1).Enabled := False;
g_SampleUI.GetControl(IDC_PARAM1).Visible := False;
g_SampleUI.GetControl(IDC_PARAM1NAME).Enabled := False;
g_SampleUI.GetControl(IDC_PARAM1NAME).Visible := False;
Inc(iY, 25);
g_SampleUI.AddCheckBox(IDC_ENABLEPP, '(E)nable post-processing', 5, iY, 200, 24, true, Ord('E'));
Inc(iY, 25);
g_SampleUI.AddComboBox(IDC_SELECTSCENE, 5, iY, 210, 24, Ord('C'), False, @pComboBox);
if Assigned(pComboBox) then
begin
pComboBox.AddItem('(C)urrent Mesh: Dwarf', Pointer(0));
pComboBox.AddItem('(C)urrent Mesh: Skull', Pointer(1));
end;
Inc(iY, 28);
g_SampleUI.AddStatic(IDC_PRESETLABEL, 'Predefined post-process combinations:', 5, iY, 210, 22);
g_SampleUI.GetControl(IDC_PRESETLABEL).Element[0].dwTextFormat := DT_LEFT or DT_TOP;
Inc(iY, 22);
g_SampleUI.AddButton(IDC_PREBLUR, 'Blur', 5, iY, 100, 22);
g_SampleUI.AddButton(IDC_PREBLOOM, 'Bloom', 115, iY, 100, 22);
Inc(iY, 24);
g_SampleUI.AddButton(IDC_PREDOF, 'Depth of Field', 5, iY, 100, 22);
g_SampleUI.AddButton(IDC_PREEDGE, 'Edge Glow', 115, iY, 100, 22);
// Initialize camera parameters
g_Camera.SetModelCenter(D3DXVector3(0.0, 0.0, 0.0));
g_Camera.SetRadius(2.8);
g_Camera.SetEnablePositionMovement(False);
end;
//--------------------------------------------------------------------------------------
// Compute the translate and scale transform for the current mesh.
function ComputeMeshWorldMatrix(pMesh: ID3DXMesh): HRESULT;
var
pVB: IDirect3DVertexBuffer9;
pVBData: Pointer;
vCtr: TD3DXVector3;
fRadius: Single;
m: TD3DXMatrixA16;
begin
if FAILED(pMesh.GetVertexBuffer(pVB)) then
begin
Result:= E_FAIL;
Exit;
end;
if SUCCEEDED(pVB.Lock(0, 0, pVBData, D3DLOCK_READONLY)) then
begin
D3DXComputeBoundingSphere(PD3DXVector3(pVBData), pMesh.GetNumVertices,
D3DXGetFVFVertexSize(pMesh.GetFVF),
vCtr, fRadius);
D3DXMatrixTranslation(g_mMeshWorld, -vCtr.x, -vCtr.y, -vCtr.z);
D3DXMatrixScaling(m, 1/fRadius, 1/fRadius, 1/fRadius);
D3DXMatrixMultiply(g_mMeshWorld, g_mMeshWorld, m);
pVB.Unlock;
end;
pVB := nil;
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// Called during device initialization, this code checks the device for some
// minimum set of capabilities, and rejects those that don't pass by returning false.
//--------------------------------------------------------------------------------------
function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall;
var
pD3D: IDirect3D9;
begin
Result:= False;
// Skip backbuffer formats that don't support alpha blending
pD3D := DXUTGetD3DObject;
if FAILED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType,
AdapterFormat, D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING,
D3DRTYPE_TEXTURE, BackBufferFormat))
then Exit;
// Check 32 bit integer format support
if FAILED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType,
AdapterFormat, D3DUSAGE_RENDERTARGET,
D3DRTYPE_CUBETEXTURE, D3DFMT_A8R8G8B8))
then Exit;
// Must support pixel shader 2.0
if (pCaps.PixelShaderVersion < D3DPS_VERSION(2,0)) then Exit;
Result:= True;
end;
//--------------------------------------------------------------------------------------
// This callback function is called immediately before a device is created to allow the
// application to modify the device settings. The supplied pDeviceSettings parameter
// contains the settings that the framework has selected for the new device, and the
// application can make any desired changes directly to this structure. Note however that
// DXUT will not correct invalid device settings so care must be taken
// to return valid device settings, otherwise IDirect3D9::CreateDevice() will fail.
//--------------------------------------------------------------------------------------
{static} var s_bFirstTime: Boolean = True;
function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall;
begin
// Turn vsync off
pDeviceSettings.pp.PresentationInterval := D3DPRESENT_INTERVAL_IMMEDIATE;
g_SettingsDlg.DialogControl.GetComboBox(DXUTSETTINGSDLG_PRESENT_INTERVAL ).Enabled := False;
// If device doesn't support HW T&L or doesn't support 1.1 vertex shaders in HW
// then switch to SWVP.
if (pCaps.DevCaps and D3DDEVCAPS_HWTRANSFORMANDLIGHT = 0) or
(pCaps.VertexShaderVersion < D3DVS_VERSION(1,1))
then pDeviceSettings.BehaviorFlags := D3DCREATE_SOFTWARE_VERTEXPROCESSING;
// Debugging vertex shaders requires either REF or software vertex processing
// and debugging pixel shaders requires REF.
{$IFDEF DEBUG_VS}
if (pDeviceSettings.DeviceType <> D3DDEVTYPE_REF) then
with pDeviceSettings do
begin
BehaviorFlags := BehaviorFlags and not D3DCREATE_HARDWARE_VERTEXPROCESSING;
BehaviorFlags := BehaviorFlags and not D3DCREATE_PUREDEVICE;
BehaviorFlags := BehaviorFlags or D3DCREATE_SOFTWARE_VERTEXPROCESSING;
end;
{$ENDIF}
{$IFDEF DEBUG_PS}
pDeviceSettings.DeviceType := D3DDEVTYPE_REF;
{$ENDIF}
// For the first device created if its a REF device, optionally display a warning dialog box
if s_bFirstTime then
begin
s_bFirstTime := False;
if (pDeviceSettings.DeviceType = D3DDEVTYPE_REF) then DXUTDisplaySwitchingToREFWarning;
end;
Result:= True;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has been
// created, which will happen during application initialization and windowed/full screen
// toggles. This is the best location to create D3DPOOL_MANAGED resources since these
// resources need to be reloaded whenever the device is destroyed. Resources created
// here should be released in the OnDestroyDevice callback.
//--------------------------------------------------------------------------------------
function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
var
Caps: TD3DCaps9;
pD3D: IDirect3D9;
DisplayMode: TD3DDisplayMode;
dwShaderFlags: DWORD;
str: array[0..MAX_PATH-1] of WideChar;
i: Integer;
begin
Result:= g_DialogResourceManager.OnCreateDevice(pd3dDevice);
if V_Failed(Result) then Exit;
Result:= g_SettingsDlg.OnCreateDevice(pd3dDevice);
if V_Failed(Result) then Exit;
// Query multiple RT setting and set the num of passes required
pd3dDevice.GetDeviceCaps(Caps);
if (Caps.NumSimultaneousRTs > 2) then
begin
// One pass of 3 RTs
g_nPasses := 1;
g_nRtUsed := 3;
end else
if (Caps.NumSimultaneousRTs > 1) then
begin
// Two passes of 2 RTs. The 2nd pass uses only one.
g_nPasses := 2;
g_nRtUsed := 2;
end else
begin
// Three passes of single RT.
g_nPasses := 3;
g_nRtUsed := 1;
end;
// Determine which of D3DFMT_A16B16G16R16F or D3DFMT_A8R8G8B8
// to use for scene-rendering RTs.
pd3dDevice.GetDirect3D(pD3D);
pd3dDevice.GetDisplayMode(0, DisplayMode);
if FAILED(pD3D.CheckDeviceFormat(Caps.AdapterOrdinal, Caps.DeviceType,
DisplayMode.Format, D3DUSAGE_RENDERTARGET,
D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F))
then g_TexFormat := D3DFMT_A8R8G8B8
else g_TexFormat := D3DFMT_A16B16G16R16F;
pD3D := nil;
// Initialize the font
Result:= D3DXCreateFont(pd3dDevice, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH or FF_DONTCARE,
'Arial', g_pFont);
if V_Failed(Result) then Exit;
// Define DEBUG_VS and/or DEBUG_PS to debug vertex and/or pixel shaders with the
// shader debugger. Debugging vertex shaders requires either REF or software vertex
// processing, and debugging pixel shaders requires REF. The
// D3DXSHADER_FORCE_*_SOFTWARE_NOOPT flag improves the debug experience in the
// shader debugger. It enables source level debugging, prevents instruction
// reordering, prevents dead code elimination, and forces the compiler to compile
// against the next higher available software target, which ensures that the
// unoptimized shaders do not exceed the shader model limitations. Setting these
// flags will cause slower rendering since the shaders will be unoptimized and
// forced into software. See the DirectX documentation for more information about
// using the shader debugger.
dwShaderFlags := D3DXFX_NOT_CLONEABLE;
{$IFDEF DEBUG}
// Set the D3DXSHADER_DEBUG flag to embed debug information in the shaders.
// Setting this flag improves the shader debugging experience, but still allows
// the shaders to be optimized and to run exactly the way they will run in
// the release configuration of this program.
dwShaderFlags := dwShaderFlags or D3DXSHADER_DEBUG;
{$ENDIF}
{$IFDEF DEBUG_VS}
dwShaderFlags := dwShaderFlags or D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT;
{$ENDIF}
{$IFDEF DEBUG_PS}
dwShaderFlags := dwShaderFlags or D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT;
{$ENDIF}
// Read the D3DX effect file
Result:= DXUTFindDXSDKMediaFile(str, MAX_PATH, 'Scene.fx');
if V_Failed(Result) then Exit;
// If this fails, there should be debug output as to
// they the .fx file failed to compile
Result:= D3DXCreateEffectFromFileW(pd3dDevice, str, nil, nil, dwShaderFlags,
nil, g_pEffect, nil);
if V_Failed(Result) then Exit;
// Initialize the postprocess objects
for i := 0 to PPCOUNT - 1 do
begin
Result := g_aPostProcess[i].Init(pd3dDevice, dwShaderFlags, g_aszFxFile[i]);
if FAILED(Result) then Exit;
end;
// Obtain the technique handles
case g_nPasses of
1:
begin
g_hTRenderScene := g_pEffect.GetTechniqueByName('RenderScene');
g_hTRenderEnvMapScene := g_pEffect.GetTechniqueByName('RenderEnvMapScene');
g_hTRenderSkyBox := g_pEffect.GetTechniqueByName('RenderSkyBox');
end;
2:
begin
g_hTRenderScene := g_pEffect.GetTechniqueByName('RenderSceneTwoPasses');
g_hTRenderEnvMapScene := g_pEffect.GetTechniqueByName('RenderEnvMapSceneTwoPasses');
g_hTRenderSkyBox := g_pEffect.GetTechniqueByName('RenderSkyBoxTwoPasses');
end;
3:
begin
g_hTRenderScene := g_pEffect.GetTechniqueByName('RenderSceneThreePasses');
g_hTRenderEnvMapScene := g_pEffect.GetTechniqueByName('RenderEnvMapSceneThreePasses');
g_hTRenderSkyBox := g_pEffect.GetTechniqueByName('RenderSkyBoxThreePasses');
end;
end;
g_hTRenderNoLight := g_pEffect.GetTechniqueByName('RenderNoLight');
// Create vertex declaration for scene
Result := pd3dDevice.CreateVertexDeclaration(@TMeshVert_Decl, g_pVertDecl);
if FAILED(Result) then Exit;
// Create vertex declaration for skybox
Result := pd3dDevice.CreateVertexDeclaration(@TSkyboxVert_Decl, g_pSkyBoxDecl);
if FAILED(Result) then Exit;
// Create vertex declaration for post-process
Result := pd3dDevice.CreateVertexDeclaration(@TppVert_Decl, g_pVertDeclPP);
if FAILED(Result) then Exit;
// Load the meshes
Result:= DXUTERR_MEDIANOTFOUND;
if FAILED(g_SceneMesh[0].CreateMesh(pd3dDevice, 'dwarf\\dwarf.x')) then Exit;
g_SceneMesh[0].SetVertexDecl(pd3dDevice, @TMeshVert_Decl);
if FAILED(g_SceneMesh[1].CreateMesh(pd3dDevice, 'misc\\skullocc.x')) then Exit;
g_SceneMesh[1].SetVertexDecl(pd3dDevice, @TMeshVert_Decl);
if FAILED(g_Skybox.CreateMesh(pd3dDevice, 'alley_skybox.x')) then Exit;
g_Skybox.SetVertexDecl(pd3dDevice, @TSkyboxVert_Decl);
// Initialize the mesh's world matrix
ComputeMeshWorldMatrix(g_SceneMesh[g_nScene].Mesh);
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has been
// reset, which will happen after a lost device scenario. This is the best location to
// create D3DPOOL_DEFAULT resources since these resources need to be reloaded whenever
// the device is lost. Resources created here should be released in the OnLostDevice
// callback.
//--------------------------------------------------------------------------------------
function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
var
i, p, t: Integer;
fAspectRatio: Single;
pRT: array[0..1] of IDirect3DTexture9;
str: array[0..MAX_PATH-1] of WideChar;
pSurf: IDirect3DSurface9;
begin
Result:= g_DialogResourceManager.OnResetDevice;
if V_Failed(Result) then Exit;
Result:= g_SettingsDlg.OnResetDevice;
if V_Failed(Result) then Exit;
if Assigned(g_pFont) then g_pFont.OnResetDevice;
if Assigned(g_pEffect) then g_pEffect.OnResetDevice;
for p := 0 to PPCOUNT - 1 do
begin
Result := g_aPostProcess[p].OnResetDevice(pBackBufferSurfaceDesc.Width, pBackBufferSurfaceDesc.Height);
if V_Failed(Result) then Exit;
end;
// Create a sprite to help batch calls when drawing many lines of text
Result:= D3DXCreateSprite(pd3dDevice, g_pTextSprite);
if V_Failed(Result) then Exit;
// Setup the camera's projection parameters
fAspectRatio := pBackBufferSurfaceDesc.Width / pBackBufferSurfaceDesc.Height;
g_Camera.SetProjParams(D3DX_PI/4, fAspectRatio, 0.1, 1000.0);
g_pEffect.SetMatrix('g_mProj', g_Camera.GetProjMatrix^);
g_Camera.SetWindow(pBackBufferSurfaceDesc.Width, pBackBufferSurfaceDesc.Height);
g_SceneMesh[0].RestoreDeviceObjects(pd3dDevice);
g_SceneMesh[1].RestoreDeviceObjects(pd3dDevice);
g_Skybox.RestoreDeviceObjects(pd3dDevice);
// Create scene save texture
for i := 0 to RT_COUNT - 1 do
begin
Result:= pd3dDevice.CreateTexture(pBackBufferSurfaceDesc.Width,
pBackBufferSurfaceDesc.Height,
1,
D3DUSAGE_RENDERTARGET,
g_TexFormat,
D3DPOOL_DEFAULT,
g_pSceneSave[i],
nil);
if V_Failed(Result) then Exit;
// Create the textures for this render target chains
ZeroMemory(@pRT, SizeOf(pRT));
for t := 0 to 1 do
begin
Result:= pd3dDevice.CreateTexture(pBackBufferSurfaceDesc.Width,
pBackBufferSurfaceDesc.Height,
1,
D3DUSAGE_RENDERTARGET,
D3DFMT_A8R8G8B8,
D3DPOOL_DEFAULT,
pRT[t],
nil);
if V_Failed(Result) then Exit;
end;
g_RTChain[i].Init(pRT);
pRT[0] := nil;
pRT[1] := nil;
end;
// Create the environment mapping texture
Result:= DXUTFindDXSDKMediaFile(str, MAX_PATH, 'Light Probes\uffizi_cross.dds');
if V_Failed(Result) then Exit;
if FAILED(D3DXCreateCubeTextureFromFileW(pd3dDevice, str, g_pEnvTex)) then
begin
Result:= DXUTERR_MEDIANOTFOUND;
Exit;
end;
// Initialize the render target table based on how many simultaneous RTs
// the card can support.
case g_nPasses of
1:
begin
g_pSceneSave[0].GetSurfaceLevel(0, pSurf);
g_aRtTable[0].pRT[0] := pSurf;
g_pSceneSave[1].GetSurfaceLevel(0, pSurf);
g_aRtTable[0].pRT[1] := pSurf;
g_pSceneSave[2].GetSurfaceLevel(0, pSurf);
g_aRtTable[0].pRT[2] := pSurf;
// Passes 1 and 2 are not used
g_aRtTable[1].pRT[0] := nil;
g_aRtTable[1].pRT[1] := nil;
g_aRtTable[1].pRT[2] := nil;
g_aRtTable[2].pRT[0] := nil;
g_aRtTable[2].pRT[1] := nil;
g_aRtTable[2].pRT[2] := nil;
end;
2:
begin
g_pSceneSave[0].GetSurfaceLevel(0, pSurf);
g_aRtTable[0].pRT[0] := pSurf;
g_pSceneSave[1].GetSurfaceLevel(0, pSurf);
g_aRtTable[0].pRT[1] := pSurf;
g_aRtTable[0].pRT[2] := nil; // RT 2 of pass 0 not used
g_pSceneSave[2].GetSurfaceLevel(0, pSurf);
g_aRtTable[1].pRT[0] := pSurf;
// RT 1 & 2 of pass 1 not used
g_aRtTable[1].pRT[1] := nil;
g_aRtTable[1].pRT[2] := nil;
// Pass 2 not used
g_aRtTable[2].pRT[0] := nil;
g_aRtTable[2].pRT[1] := nil;
g_aRtTable[2].pRT[2] := nil;
end;
3:
begin
g_pSceneSave[0].GetSurfaceLevel(0, pSurf);
g_aRtTable[0].pRT[0] := pSurf;
// RT 1 & 2 of pass 0 not used
g_aRtTable[0].pRT[1] := nil;
g_aRtTable[0].pRT[2] := nil;
g_pSceneSave[1].GetSurfaceLevel(0, pSurf);
g_aRtTable[1].pRT[0] := pSurf;
// RT 1 & 2 of pass 1 not used
g_aRtTable[1].pRT[1] := nil;
g_aRtTable[1].pRT[2] := nil;
g_pSceneSave[2].GetSurfaceLevel(0, pSurf);
g_aRtTable[2].pRT[0] := pSurf;
// RT 1 & 2 of pass 2 not used
g_aRtTable[2].pRT[1] := nil;
g_aRtTable[2].pRT[2] := nil;
end;
end;
g_HUD.SetLocation(0, 100);
g_HUD.SetSize(170, 170);
g_SampleUI.SetLocation( pBackBufferSurfaceDesc.Width-225, 5);
g_SampleUI.SetSize(220, 470);
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called once at the beginning of every frame. This is the
// best location for your application to handle updates to the scene, but is not
// intended to contain actual rendering calls, which should instead be placed in the
// OnFrameRender callback.
//--------------------------------------------------------------------------------------
procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
begin
// Update the camera's position based on user input
g_Camera.FrameMove(fElapsedTime);
end;
//--------------------------------------------------------------------------------------
// Name: PerformSinglePostProcess()
// Desc: Perform post-process by setting the previous render target as a
// source texture and rendering a quad with the post-process technique
// set.
// This method changes render target without saving any. The caller
// should ensure that the default render target is saved before calling
// this.
// When this method is invoked, m_dwNextTarget is the index of the
// rendertarget of this post-process. 1 - m_dwNextTarget is the index
// of the source of this post-process.
function PerformSinglePostProcess(const pd3dDevice: IDirect3DDevice9;
const PP: CPostProcess; const Inst: CPProcInstance;
pVB: IDirect3DVertexBuffer9; var aQuad: array of TppVert; var fExtentX, fExtentY: Single): HRESULT;
var
i: Integer;
cPasses, p: LongWord;
bUpdateVB: Boolean; // Inidicates whether the vertex buffer
fScaleX, fScaleY: Single;
hPass: TD3DXHandle;
hExtentScaleX: TD3DXHandle;
hExtentScaleY: TD3DXHandle;
pVBData: Pointer;
pTarget: IDirect3DTexture9;
pTexSurf: IDirect3DSurface9;
begin
//
// The post-process effect may require that a copy of the
// originally rendered scene be available for use, so
// we initialize them here.
//
for i := 0 to RT_COUNT - 1 do
PP.m_pEffect.SetTexture(PP.m_hTexScene[i], g_pSceneSave[i]);
//
// If there are any parameters, initialize them here.
//
for i := 0 to NUM_PARAMS - 1 do
if Assigned(PP.m_ahParam[i]) then
PP.m_pEffect.SetVector(PP.m_ahParam[i], Inst.m_avParam[i]);
// Render the quad
if SUCCEEDED(pd3dDevice.BeginScene) then
begin
PP.m_pEffect.SetTechnique('PostProcess');
// Set the vertex declaration
pd3dDevice.SetVertexDeclaration(g_pVertDeclPP);
// Draw the quad
PP.m_pEffect._Begin(@cPasses, 0);
for p := 0 to cPasses - 1 do
begin
bUpdateVB := False; // Inidicates whether the vertex buffer
// needs update for this pass.
//
// If the extents has been modified, the texture coordinates
// in the quad need to be updated.
//
if (aQuad[1].tu <> fExtentX) then
begin
aQuad[1].tu := fExtentX; aQuad[3].tu := fExtentX;
bUpdateVB := True;
end;
if (aQuad[2].tv <> fExtentY) then
begin
aQuad[2].tv := fExtentY; aQuad[3].tv := fExtentY;
bUpdateVB := True;
end;
//
// Check if the pass has annotation for extent info. Update
// fScaleX and fScaleY if it does. Otherwise, default to 1.0f.
//
fScaleX := 1.0; fScaleY := 1.0;
hPass := PP.m_pEffect.GetPass( PP.m_hTPostProcess, p);
hExtentScaleX := PP.m_pEffect.GetAnnotationByName(hPass, 'fScaleX');
if Assigned(hExtentScaleX) then
PP.m_pEffect.GetFloat(hExtentScaleX, fScaleX);
hExtentScaleY := PP.m_pEffect.GetAnnotationByName(hPass, 'fScaleY');
if Assigned(hExtentScaleY) then
PP.m_pEffect.GetFloat(hExtentScaleY, fScaleY);
//
// Now modify the quad according to the scaling values specified for
// this pass
//
if (fScaleX <> 1.0) then
begin
aQuad[1].x := (aQuad[1].x + 0.5) * fScaleX - 0.5;
aQuad[3].x := (aQuad[3].x + 0.5) * fScaleX - 0.5;
bUpdateVB := True;
end;
if (fScaleY <> 1.0) then
begin
aQuad[2].y := (aQuad[2].y + 0.5) * fScaleY - 0.5;
aQuad[3].y := (aQuad[3].y + 0.5) * fScaleY - 0.5;
bUpdateVB := True;
end;
if bUpdateVB then
begin
// Scaling requires updating the vertex buffer.
if SUCCEEDED(pVB.Lock(0, 0, pVBData, D3DLOCK_DISCARD)) then
begin
CopyMemory(pVBData, @aQuad[0], 4 * SizeOf(TppVert));
pVB.Unlock;
end;
end;
fExtentX := fExtentX * fScaleX;
fExtentY := fExtentY * fScaleY;
// Set up the textures and the render target
//
for i := 0 to RT_COUNT - 1 do
begin
// If this is the very first post-process rendering,
// obtain the source textures from the scene.
// Otherwise, initialize the post-process source texture to
// the previous render target.
//
if (g_RTChain[i].m_bFirstRender)
then PP.m_pEffect.SetTexture(PP.m_hTexSource[i], g_pSceneSave[i])
else PP.m_pEffect.SetTexture(PP.m_hTexSource[i], g_RTChain[i].GetNextSource);
end;
//
// Set up the new render target
//
pTarget := g_RTChain[PP.m_nRenderTarget].GetNextTarget;
Result := pTarget.GetSurfaceLevel(0, pTexSurf);
if FAILED(Result) then
begin
Result:= DXUT_ERR('GetSurfaceLevel', Result);
Exit;
end;
pd3dDevice.SetRenderTarget( 0, pTexSurf);
pTexSurf := nil;
// We have output to this render target. Flag it.
g_RTChain[PP.m_nRenderTarget].m_bFirstRender := False;
//
// Clear the render target
//
pd3dDevice.Clear(0, nil, D3DCLEAR_TARGET, $00000000, 1.0, 0);
//
// Render
//
PP.m_pEffect.BeginPass(p);
pd3dDevice.SetStreamSource(0, pVB, 0, SizeOf(TppVert));
pd3dDevice.DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2);
PP.m_pEffect.EndPass;
// Update next rendertarget index
g_RTChain[PP.m_nRenderTarget].Flip;
end;
PP.m_pEffect._End;
// End scene
pd3dDevice.EndScene;
end;
Result:= S_OK;
end;
function ppVert(
x, y, z, rhw: Single;
tu, tv: Single; // Texcoord for post-process source
tu2, tv2: Single // Texcoord for the original scene
): TppVert;
begin
Result.x:= x;
Result.y:= y;
Result.z:= z;
Result.rhw:= rhw;
Result.tu:= tu;
Result.tv:= tv;
Result.tu2:= tu2;
Result.tv2:= tv2;
end;
//--------------------------------------------------------------------------------------
// PerformPostProcess()
// Perform all active post-processes in order.
function PerformPostProcess(const pd3dDevice: IDirect3DDevice9): HRESULT;
var
fExtentX , fExtentY: Single;
pd3dsdBackBuffer: PD3DSurfaceDesc;
Quad: array[0..3] of TppVert;
pVB: IDirect3DVertexBuffer9;
pVBData: Pointer;
i: Integer;
pListBox: CDXUTListBox;
nEffIndex: Integer;
pItem: PDXUTListBoxItem;
pInstance: CPProcInstance;
begin
//
// Extents are used to control how much of the rendertarget is rendered
// during postprocess. For example, with the extent of 0.5 and 0.5, only
// the upper left quarter of the rendertarget will be rendered during
// postprocess.
//
fExtentX := 1.0; fExtentY := 1.0;
pd3dsdBackBuffer := DXUTGetBackBufferSurfaceDesc;
//
// Set up our quad
//
Quad[0] := ppVert(-0.5, -0.5, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0);
Quad[1] := ppVert(pd3dsdBackBuffer.Width-0.5, -0.5, 1.0, 1.0, 1.0, 0.0, 1.0, 0.0);
Quad[2] := ppVert(-0.5, pd3dsdBackBuffer.Height-0.5, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0);
Quad[3] := ppVert(pd3dsdBackBuffer.Width-0.5, pd3dsdBackBuffer.Height-0.5, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0);
//
// Create a vertex buffer out of the quad
//
Result := pd3dDevice.CreateVertexBuffer(SizeOf(TppVert) * 4,
D3DUSAGE_WRITEONLY or D3DUSAGE_DYNAMIC,
0,
D3DPOOL_DEFAULT,
pVB,
nil);
if FAILED(Result) then
begin
Result:= DXUT_ERR('CreateVertexBuffer', Result);
Exit;
end;
// Fill in the vertex buffer
if SUCCEEDED(pVB.Lock(0, 0, pVBData, D3DLOCK_DISCARD)) then
begin
CopyMemory(pVBData, @Quad[0], SizeOf(Quad));
pVB.Unlock;
end;
// Clear first-time render flags
for i := 0 to RT_COUNT - 1 do
g_RTChain[i].m_bFirstRender := True;
// Perform post processing
pListBox := g_SampleUI.GetListBox(IDC_ACTIVELIST);
if Assigned(pListBox) then
begin
// The last (blank) item has special purpose so do not process it.
for nEffIndex := 0 to pListBox.Size - 2 do
begin
pItem := pListBox.GetItem(nEffIndex);
if Assigned(pItem) then
begin
pInstance := CPProcInstance(pItem.pData);
PerformSinglePostProcess(pd3dDevice,
g_aPostProcess[pInstance.m_nFxIndex],
pInstance,
pVB,
Quad,
fExtentX,
fExtentY);
end;
end;
end;
// Release the vertex buffer
pVB := nil;
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called at the end of every frame to perform all the
// rendering calls for the scene, and it will also be called if the window needs to be
// repainted. After this function has returned, DXUT will call
// IDirect3DDevice9::Present to display the contents of the next buffer in the swap chain
//--------------------------------------------------------------------------------------
procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
var
cPass: LongWord;
pMeshObj: ID3DXMesh;
mWorldView: TD3DXMatrixA16;
pOldRT: IDirect3DSurface9;
mRevView: TD3DXMatrix;
p, rt, m: Integer;
mView: TD3DXMatrixA16;
i: Integer;
pListBox: CDXUTListBox;
bPerformPostProcess: Boolean;
pd3dsdBackBuffer: PD3DSurfaceDesc;
Quad: array[0..3] of TppVert;
pPrevTarget: IDirect3DTexture9;
cPasses: LongWord;
begin
// If the settings dialog is being shown, then
// render it instead of rendering the app's scene
if g_SettingsDlg.Active then
begin
g_SettingsDlg.OnRender(fElapsedTime);
Exit;
end;
// Clear the render target and the zbuffer
V(pd3dDevice.Clear(0, nil, D3DCLEAR_TARGET or D3DCLEAR_ZBUFFER, D3DCOLOR_ARGB(0, 45, 50, 170), 1.0, 0));
// Save render target 0 so we can restore it later
pd3dDevice.GetRenderTarget(0, pOldRT);
// Render the scene
if SUCCEEDED(pd3dDevice.BeginScene) then
begin
// Set the vertex declaration
V(pd3dDevice.SetVertexDeclaration(g_pVertDecl));
// Render the mesh
D3DXMatrixMultiply(mWorldView, g_mMeshWorld, g_Camera.GetWorldMatrix^);
D3DXMatrixMultiply(mWorldView, mWorldView, g_Camera.GetViewMatrix^);
V(g_pEffect.SetMatrix('g_mWorldView', mWorldView));
V(g_pEffect.SetTexture('g_txEnvMap', g_pEnvTex));
mRevView := g_Camera.GetViewMatrix^;
mRevView._41 := 0.0; mRevView._42 := 0.0; mRevView._43 := 0.0;
D3DXMatrixInverse(mRevView, nil, mRevView);
V(g_pEffect.SetMatrix('g_mRevView', mRevView));
case g_nScene of
0: V(g_pEffect.SetTechnique(g_hTRenderScene));
1: V(g_pEffect.SetTechnique(g_hTRenderEnvMapScene));
end;
pMeshObj := g_SceneMesh[g_nScene].Mesh;
V(g_pEffect._Begin(@cPass, 0));
for p := 0 to cPass - 1 do
begin
// Set the render target(s) for this pass
for rt := 0 to g_nRtUsed - 1 do
V(pd3dDevice.SetRenderTarget(rt, g_aRtTable[p].pRT[rt]));
V(g_pEffect.BeginPass(p));
// Iterate through each subset and render with its texture
for m := 0 to g_SceneMesh[g_nScene].m_dwNumMaterials - 1 do
begin
V(g_pEffect.SetTexture('g_txScene', g_SceneMesh[g_nScene].m_pTextures[m]));
V(g_pEffect.CommitChanges);
V(pMeshObj.DrawSubset(m));
end;
V(g_pEffect.EndPass);
end;
V(g_pEffect._End);
// Render the skybox as if the camera is at center
V(g_pEffect.SetTechnique(g_hTRenderSkyBox));
V(pd3dDevice.SetVertexDeclaration(g_pSkyBoxDecl));
mView := g_Camera.GetViewMatrix^;
mView._41 := 0.0; mView._42 := 0.0; mView._43 := 0.0;
D3DXMatrixScaling(mWorldView, 100.0, 100.0, 100.0);
D3DXMatrixMultiply(mWorldView, mWorldView, mView);
V(g_pEffect.SetMatrix('g_mWorldView', mWorldView));
pMeshObj := g_Skybox.Mesh;
V(g_pEffect._Begin(@cPass, 0));
for p := 0 to cPass - 1 do
begin
// Set the render target(s) for this pass
for rt := 0 to g_nRtUsed - 1 do
V(pd3dDevice.SetRenderTarget(rt, g_aRtTable[p].pRT[rt]));
V(g_pEffect.BeginPass(p));
// Iterate through each subset and render with its texture
for m := 0 to g_Skybox.m_dwNumMaterials - 1 do
begin
V(g_pEffect.SetTexture('g_txScene', g_Skybox.m_pTextures[m]));
V(g_pEffect.CommitChanges);
V(pMeshObj.DrawSubset(m));
end;
V(g_pEffect.EndPass);
end;
V(g_pEffect._End);
V(pd3dDevice.EndScene);
end;
//
// Swap the chains
//
for i := 0 to RT_COUNT - 1 do g_RTChain[i].Flip;
// Reset all render targets used besides RT 0
for i := 1 to g_nRtUsed - 1 do
V(pd3dDevice.SetRenderTarget(i, nil));
//
// Perform post-processes
//
pListBox := g_SampleUI.GetListBox(IDC_ACTIVELIST);
bPerformPostProcess := g_bEnablePostProc and Assigned(pListBox) and (pListBox.Size > 1);
if bPerformPostProcess then PerformPostProcess(pd3dDevice);
// Restore old render target 0 (back buffer)
V(pd3dDevice.SetRenderTarget(0, pOldRT));
pOldRT := nil;
//
// Get the final result image onto the backbuffer
//
pd3dsdBackBuffer := DXUTGetBackBufferSurfaceDesc;
if SUCCEEDED(pd3dDevice.BeginScene) then
begin
// Render a screen-sized quad
Quad[0] := ppVert(-0.5, -0.5, 0.5, 1.0, 0.0, 0.0, 0.0, 0.0);
Quad[1] := ppVert(pd3dsdBackBuffer.Width-0.5, -0.5, 0.5, 1.0, 1.0, 0.0, 0.0, 0.0);
Quad[2] := ppVert(-0.5, pd3dsdBackBuffer.Height-0.5, 0.5, 1.0, 0.0, 1.0, 0.0, 0.0);
Quad[3] := ppVert(pd3dsdBackBuffer.Width-0.5, pd3dsdBackBuffer.Height-0.5, 0.5, 1.0, 1.0, 1.0, 0.0, 0.0);
if bPerformPostProcess then pPrevTarget := g_RTChain[0].GetPrevTarget
else pPrevTarget := g_pSceneSave[0];
V(pd3dDevice.SetVertexDeclaration(g_pVertDeclPP));
V(g_pEffect.SetTechnique(g_hTRenderNoLight));
V(g_pEffect.SetTexture('g_txScene', pPrevTarget));
V(g_pEffect._Begin(@cPasses, 0 ));
for p := 0 to cPasses - 1 do
begin
V(g_pEffect.BeginPass(p));
V(pd3dDevice.DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, quad, SizeOf(TppVert)));
V(g_pEffect.EndPass);
end;
V(g_pEffect._End);
// Render text
RenderText;
// Render dialogs
V(g_HUD.OnRender(fElapsedTime));
V(g_SampleUI.OnRender(fElapsedTime));
V(pd3dDevice.EndScene);
end;
end;
//--------------------------------------------------------------------------------------
// Render the help and statistics text. This function uses the ID3DXFont interface for
// efficient text rendering.
//--------------------------------------------------------------------------------------
procedure RenderText;
var
txtHelper: CDXUTTextHelper;
pd3dsdBackBuffer: PD3DSurfaceDesc;
begin
// The helper object simply helps keep track of text position, and color
// and then it calls pFont->DrawText( m_pSprite, strMsg, -1, &rc, DT_NOCLIP, m_clr );
// If NULL is passed in as the sprite object, then it will work however the
// pFont->DrawText() will not be batched together. Batching calls will improves performance.
txtHelper := CDXUTTextHelper.Create(g_pFont, g_pTextSprite, 15);
pd3dsdBackBuffer := DXUTGetBackBufferSurfaceDesc;
// Output statistics
txtHelper._Begin;
txtHelper.SetInsertionPos(5, 5);
txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 0.0, 1.0));
txtHelper.DrawTextLine(DXUTGetFrameStats(True)); // Show FPS
txtHelper.DrawTextLine(DXUTGetDeviceStats);
// If floating point rendertarget is not supported, display a warning
// message to the user that some effects may not work correctly.
if (D3DFMT_A16B16G16R16F <> g_TexFormat) then
begin
txtHelper.SetForegroundColor(D3DXColor(1.0, 0.0, 0.0, 1.0));
txtHelper.SetInsertionPos(5, 45);
txtHelper.DrawTextLine('Floating-point render target not supported'#10 +
'by the 3D device. Some post-process effects'#10 +
'may not render correctly.');
end;
// Draw help
if g_bShowHelp then
begin
txtHelper.SetInsertionPos(10, pd3dsdBackBuffer.Height-15*4);
txtHelper.SetForegroundColor(D3DXColor(1.0, 0.75, 0.0, 1.0));
txtHelper.DrawTextLine('Controls (F1 to hide):');
txtHelper.SetInsertionPos(40, pd3dsdBackBuffer.Height-15*3);
txtHelper.DrawTextLine('Mesh Movement: Left drag mouse'#10 +
'Camera Movement: Right drag mouse');
end else
begin
txtHelper.SetInsertionPos(10, pd3dsdBackBuffer.Height-15*2);
txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 1.0, 1.0));
txtHelper.DrawTextLine('Press F1 for help');
end;
txtHelper._End;
txtHelper.Free;
end;
//--------------------------------------------------------------------------------------
// Before handling window messages, DXUT passes incoming windows
// messages to the application through this callback function. If the application sets
// *pbNoFurtherProcessing to TRUE, then DXUT will not process this message.
//--------------------------------------------------------------------------------------
function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall;
begin
Result:= 0;
// Always allow dialog resource manager calls to handle global messages
// so GUI state is updated correctly
pbNoFurtherProcessing := g_DialogResourceManager.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
if g_SettingsDlg.IsActive then
begin
g_SettingsDlg.MsgProc(hWnd, uMsg, wParam, lParam);
Exit;
end;
// Give the dialogs a chance to handle the message first
pbNoFurtherProcessing := g_HUD.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
pbNoFurtherProcessing := g_SampleUI.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
// Pass all remaining windows messages to camera so it can respond to user input
g_Camera.HandleMessages(hWnd, uMsg, wParam, lParam);
end;
//--------------------------------------------------------------------------------------
// As a convenience, DXUT inspects the incoming windows messages for
// keystroke messages and decodes the message parameters to pass relevant keyboard
// messages to the application. The framework does not remove the underlying keystroke
// messages, which are still passed to the application's MsgProc callback.
//--------------------------------------------------------------------------------------
procedure KeyboardProc(nChar: LongWord; bKeyDown, bAltDown: Boolean; pUserContext: Pointer); stdcall;
begin
if bKeyDown then
begin
case nChar of
VK_F1: g_bShowHelp := not g_bShowHelp;
end;
end;
end;
//#define IN_FLOAT_CHARSET( c ) \
// ( (c) == L'-' || (c) == L'.' || ( (c) >= L'0' && (c) <= L'9' ) )
function IN_FLOAT_CHARSET(c: WideChar): Boolean;
begin
Result := (c = '-') or (c = '.') or ((c >= '0') and (c <= '9'));
end;
//--------------------------------------------------------------------------------------
// Parse a string that contains a list of floats separated by space, and store
// them in the array of float pointed to by pBuffer.
// Parses up to 4 floats.
procedure ParseFloatList(const pwszText: PWideChar; pBuffer: PSingle);
var
nWritten: Integer; // Number of floats written
pToken, pEnd: PWideChar;
wszToken: array[0..29] of WideChar;
nTokenLen: Integer;
begin
nWritten := 0; // Number of floats written
pToken := pwszText;
while (nWritten < 4) and (pToken^ <> #0) do
begin
// Skip leading spaces
while (pToken^ = ' ') do Inc(pToken);
// Locate the end of number
pEnd := pToken;
while IN_FLOAT_CHARSET(pEnd^) do Inc(pEnd);
// Copy the token to our buffer
nTokenLen := min(High(wszToken), Integer(pEnd - pToken)) + 1;
StringCchCopy(wszToken, nTokenLen, pToken);
pBuffer^ := StrToFloat(WideCharToString(wszToken));
Inc(nWritten);
Inc(pBuffer);
pToken := pEnd;
end;
end;
//--------------------------------------------------------------------------------------
// Inserts the postprocess effect identified by the index nEffectIndex into the
// active list.
procedure InsertEffect(nEffectIndex: Integer);
var
nInsertPosition: Integer;
pNewInst: CPProcInstance;
p: Integer;
nSelected: Integer;
begin
nInsertPosition := g_SampleUI.GetListBox(IDC_ACTIVELIST).SelectedIndex;
if (nInsertPosition = -1) then
nInsertPosition := g_SampleUI.GetListBox(IDC_ACTIVELIST).Size - 1;
// Create a new CPProcInstance object and set it as the data field of the
// newly inserted item.
pNewInst := CPProcInstance.Create;
//todo: In Delphi constructors raise an error.., not return nil.
if Assigned(pNewInst) then
begin
pNewInst.m_nFxIndex := nEffectIndex;
ZeroMemory(@pNewInst.m_avParam, SizeOf(pNewInst.m_avParam));
for p := 0 to NUM_PARAMS - 1 do
pNewInst.m_avParam[p] := g_aPostProcess[pNewInst.m_nFxIndex].m_avParamDef[p];
g_SampleUI.GetListBox(IDC_ACTIVELIST).InsertItem(nInsertPosition, g_aszPpDesc[nEffectIndex], pNewInst);
// Set selection to the item after the inserted one.
nSelected := g_SampleUI.GetListBox(IDC_ACTIVELIST).SelectedIndex;
if (nSelected >= 0) then
g_SampleUI.GetListBox(IDC_ACTIVELIST).SelectItem(nSelected + 1);
end;
end;
//--------------------------------------------------------------------------------------
// Handles the GUI events
//--------------------------------------------------------------------------------------
procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall;
type
PFloatArray = ^TFloatArray;
TFloatArray = array [0..3] of Single;
var
pItem: PDXUTComboBoxItem;
pLBItem: PDXUTListBoxItem;
nSelected: Integer;
pInstance: CPProcInstance;
PP: CPostProcess;
i, p: Integer;
ParamText: WideString;
pListBox: CDXUTListBox;
pPrevItem, pNextItem: PDXUTListBoxItem;
Temp: TDXUTListBoxItem;
nParamIndex: Integer;
v: TD3DXVector4;
begin
case nControlID of
IDC_TOGGLEFULLSCREEN: DXUTToggleFullScreen;
IDC_TOGGLEREF: DXUTToggleREF;
IDC_CHANGEDEVICE: with g_SettingsDlg do Active := not Active;
IDC_SELECTSCENE:
begin
//todo: Change GetSelectedItem to property
pItem := (pControl as CDXUTComboBox).GetSelectedItem;
if Assigned(pItem) then
begin
g_nScene := Integer(size_t(pItem.pData));
// Scene mesh has chanaged. Re-initialize the world matrix
// for the mesh.
ComputeMeshWorldMatrix(g_SceneMesh[g_nScene].Mesh);
end;
end;
IDC_AVAILABLELIST:
begin
case nEvent of
EVENT_LISTBOX_ITEM_DBLCLK:
begin
pLBItem := (pControl as CDXUTListBox).GetSelectedItem;
if Assigned(pLBItem) then
begin
// Inserts the selected effect in available list to the active list
// before its selected item.
InsertEffect(Integer(size_t(pLBItem.pData)));
end;
end;
end;
end;
IDC_ACTIVELIST:
begin
case nEvent of
EVENT_LISTBOX_ITEM_DBLCLK:
begin
nSelected := CDXUTListBox(pControl).GetSelectedIndex;
// Do not remove the last (blank) item
if (nSelected <> CDXUTListBox(pControl).Size - 1) then
begin
pLBItem := CDXUTListBox(pControl).GetSelectedItem;
// if Assigned(pItem) then FreeMem(pLBItem.pData); //Clootie: this is checked automatically in Delphi RTL
FreeMem(pLBItem.pData);
CDXUTListBox(pControl).RemoveItem(nSelected);
end;
end;
EVENT_LISTBOX_SELECTION:
begin
// Selection changed in the active list. Update the parameter
// controls.
nSelected := CDXUTListBox(pControl).GetSelectedIndex;
if (nSelected >= 0) and (nSelected < Integer(CDXUTListBox(pControl).Size) - 1) then
begin
pLBItem := CDXUTListBox(pControl).GetSelectedItem;
pInstance := CPProcInstance(pLBItem.pData);
PP := g_aPostProcess[pInstance.m_nFxIndex];
if Assigned(pInstance) and (PP.m_awszParamName[0][0] <> #0) then
begin
g_SampleUI.GetStatic(IDC_PARAM0NAME).Text := PP.m_awszParamName[0];
// Fill the editboxes with the parameter values
for p := 0 to NUM_PARAMS - 1 do
begin
if (PP.m_awszParamName[p][0] <> #0) then
begin
// Enable the label and editbox for this parameter
g_SampleUI.GetControl(IDC_PARAM0 + p).Enabled := True;
g_SampleUI.GetControl(IDC_PARAM0 + p).Visible := True;
g_SampleUI.GetControl(IDC_PARAM0NAME + p).Enabled := True;
g_SampleUI.GetControl(IDC_PARAM0NAME + p).Visible := True;
for i := 0 to PP.m_anParamSize[p]-1 do
begin
ParamText:= ParamText + WideFormat('%.5f ', [PFloatArray(@pInstance.m_avParam[p])[i]]);
end;
// Remove trailing space
if (ParamText[Length(ParamText)-1] = ' ') then
SetLength(ParamText, Length(ParamText)-1);
{$IFDEF FPC}
//todo: FPC "inline" related bug
g_SampleUI.GetEditBox(IDC_PARAM0 + p).SetText(PWideChar(ParamText));
{$ELSE}
g_SampleUI.GetEditBox(IDC_PARAM0 + p).Text := PWideChar(ParamText);
{$ENDIF}
end;
end;
end else
begin
g_SampleUI.GetStatic(IDC_PARAM0NAME).Text := 'Selected effect has no parameters.';
// Disable the edit boxes and 2nd parameter static
g_SampleUI.GetControl(IDC_PARAM0).Enabled := False;
g_SampleUI.GetControl(IDC_PARAM0).Visible := False;
g_SampleUI.GetControl(IDC_PARAM1).Enabled := False;
g_SampleUI.GetControl(IDC_PARAM1).Visible := False;
g_SampleUI.GetControl(IDC_PARAM1NAME).Enabled := False;
g_SampleUI.GetControl(IDC_PARAM1NAME).Visible := False;
end;
end else
begin
g_SampleUI.GetStatic(IDC_PARAM0NAME).Text := 'Select an active effect to set its parameter.';
// Disable the edit boxes and 2nd parameter static
g_SampleUI.GetControl(IDC_PARAM0).Enabled := False;
g_SampleUI.GetControl(IDC_PARAM0).Visible := False;
g_SampleUI.GetControl(IDC_PARAM1).Enabled := False;
g_SampleUI.GetControl(IDC_PARAM1).Visible := False;
g_SampleUI.GetControl(IDC_PARAM1NAME).Enabled := False;
g_SampleUI.GetControl(IDC_PARAM1NAME).Visible := False;
end;
end;
end;
end;
IDC_CLEAR: ClearActiveList;
IDC_MOVEUP:
begin
pListBox := g_SampleUI.GetListBox(IDC_ACTIVELIST);
if (pListBox = nil) then Exit;
nSelected := pListBox.GetSelectedIndex;
if (nSelected < 0) then Exit;
// Cannot move up the first item or the last (blank) item.
if (nSelected <> 0) and (nSelected <> pListBox.Size - 1) then
begin
pPrevItem := pListBox.GetItem(nSelected - 1);
pLBItem := pListBox.GetItem(nSelected);
// Swap
Temp := pLBItem^;
pLBItem^ := pPrevItem^;
pPrevItem^ := Temp;
pListBox.SelectItem(nSelected - 1);
end;
end;
IDC_MOVEDOWN:
begin
pListBox := g_SampleUI.GetListBox(IDC_ACTIVELIST);
if (pListBox = nil) then Exit;
nSelected := pListBox.GetSelectedIndex;
if (nSelected < 0) then Exit;
// Cannot move down either of the last two item.
if (nSelected < pListBox.Size - 2) then
begin
pNextItem := pListBox.GetItem(nSelected + 1);
pLBItem := pListBox.GetItem(nSelected);
// Swap
if Assigned(pLBItem) and Assigned(pNextItem) then
begin
Temp := pLBItem^;
pLBItem^ := pNextItem^;
pNextItem^ := Temp;
end;
pListBox.SelectItem(nSelected + 1);
end;
end;
IDC_PARAM0,
IDC_PARAM1:
begin
if (nEvent = EVENT_EDITBOX_CHANGE) then
begin
case nControlID of
IDC_PARAM0: nParamIndex := 0;
IDC_PARAM1: nParamIndex := 1;
else
Exit;
end;
pLBItem := g_SampleUI.GetListBox(IDC_ACTIVELIST).GetSelectedItem;
pInstance := nil;
if Assigned(pLBItem) then pInstance := CPProcInstance(pLBItem.pData);
if Assigned(pInstance) then
begin
ZeroMemory(@v, SizeOf(v));
ParseFloatList(CDXUTEditBox(pControl).Text, @v);
// We parsed the values. Now save them in the instance data.
pInstance.m_avParam[nParamIndex] := v;
end;
end;
end;
IDC_ENABLEPP: g_bEnablePostProc := CDXUTCheckBox(pControl).Checked;
IDC_PREBLUR:
begin
// Clear the list
ClearActiveList;
// Insert effects
InsertEffect(9);
InsertEffect(2);
InsertEffect(3);
InsertEffect(2);
InsertEffect(3);
InsertEffect(10);
end;
IDC_PREBLOOM:
begin
// Clear the list
ClearActiveList;
// Insert effects
InsertEffect(9);
InsertEffect(9);
InsertEffect(6);
InsertEffect(4);
InsertEffect(5);
InsertEffect(4);
InsertEffect(5);
InsertEffect(10);
InsertEffect(12);
end;
IDC_PREDOF:
begin
// Clear the list
ClearActiveList;
// Insert effects
InsertEffect(9);
InsertEffect(2);
InsertEffect(3);
InsertEffect(2);
InsertEffect(3);
InsertEffect(10);
InsertEffect(14);
end;
IDC_PREEDGE:
begin
// Clear the list
ClearActiveList;
// Insert effects
InsertEffect(13);
InsertEffect(9);
InsertEffect(4);
InsertEffect(5);
InsertEffect(12);
end;
end;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has
// entered a lost state and before IDirect3DDevice9::Reset is called. Resources created
// in the OnResetDevice callback should be released here, which generally includes all
// D3DPOOL_DEFAULT resources. See the "Lost Devices" section of the documentation for
// information about lost devices.
//--------------------------------------------------------------------------------------
procedure OnLostDevice; stdcall;
var
i, p, rt: Integer;
begin
g_DialogResourceManager.OnLostDevice;
g_SettingsDlg.OnLostDevice;
if Assigned(g_pFont) then g_pFont.OnLostDevice;
if Assigned(g_pEffect) then g_pEffect.OnLostDevice;
g_pTextSprite := nil;
for p := 0 to PPCOUNT - 1 do
g_aPostProcess[p].OnLostDevice;
// Release the scene save and render target textures
for i := 0 to RT_COUNT - 1 do
begin
g_pSceneSave[i] := nil;
g_RTChain[i].Cleanup;
end;
g_SceneMesh[0].InvalidateDeviceObjects;
g_SceneMesh[1].InvalidateDeviceObjects;
g_Skybox.InvalidateDeviceObjects;
// Release the RT table's references
for p := 0 to RT_COUNT-1 do
for rt := 0 to RT_COUNT-1 do
g_aRtTable[p].pRT[rt] := nil;
g_pEnvTex := nil;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has
// been destroyed, which generally happens as a result of application termination or
// windowed/full screen toggles. Resources created in the OnCreateDevice callback
// should be released here, which generally includes all D3DPOOL_MANAGED resources.
//--------------------------------------------------------------------------------------
procedure OnDestroyDevice; stdcall;
var
p: Integer;
begin
g_DialogResourceManager.OnDestroyDevice;
g_SettingsDlg.OnDestroyDevice;
g_pEffect := nil;
g_pFont := nil;
g_pVertDecl := nil;
g_pSkyBoxDecl := nil;
g_pVertDeclPP := nil;
g_SceneMesh[0].DestroyMesh;
g_SceneMesh[1].DestroyMesh;
g_Skybox.DestroyMesh;
for p := 0 to PPCOUNT-1 do
g_aPostProcess[p].Cleanup;
end;
{ CPostProcess }
destructor CPostProcess.Destroy;
begin
Cleanup;
inherited;
end;
procedure CPostProcess.Cleanup;
begin
m_pEffect := nil;
end;
function CPostProcess.Init(const pDev: IDirect3DDevice9; dwShaderFlags: DWORD; wszName: PWideChar): HRESULT;
var
wszPath: array[0..MAX_PATH-1] of WideChar;
techdesc: TD3DXTechniqueDesc;
i: Integer;
passdesc: TD3DXPassDesc;
aSem: array[0..MAXD3DDECLLENGTH-1] of TD3DXSemantic;
uCount: LongWord;
hAnno: TD3DXHandle;
Name: AnsiString;
szParamName: PAnsiChar;
begin
Result:= DXUTFindDXSDKMediaFile(wszPath, MAX_PATH, wszName);
if Failed(Result) then Exit;
Result := D3DXCreateEffectFromFileW(pDev, wszPath, nil, nil, dwShaderFlags,
nil, m_pEffect, nil);
if Failed(Result) then Exit;
// Get the PostProcess technique handle
m_hTPostProcess := m_pEffect.GetTechniqueByName('PostProcess');
// Obtain the handles to all texture objects in the effect
m_hTexScene[0] := m_pEffect.GetParameterByName(nil, 'g_txSceneColor');
m_hTexScene[1] := m_pEffect.GetParameterByName(nil, 'g_txSceneNormal');
m_hTexScene[2] := m_pEffect.GetParameterByName(nil, 'g_txScenePosition');
m_hTexScene[3] := m_pEffect.GetParameterByName(nil, 'g_txSceneVelocity');
m_hTexSource[0] := m_pEffect.GetParameterByName(nil, 'g_txSrcColor');
m_hTexSource[1] := m_pEffect.GetParameterByName(nil, 'g_txSrcNormal');
m_hTexSource[2] := m_pEffect.GetParameterByName(nil, 'g_txSrcPosition');
m_hTexSource[3] := m_pEffect.GetParameterByName(nil, 'g_txSrcVelocity');
// Find out what render targets the technique writes to.
if FAILED(m_pEffect.GetTechniqueDesc(m_hTPostProcess, techdesc)) then
begin
Result:= D3DERR_INVALIDCALL;
Exit;
end;
for i := 0 to techdesc.Passes - 1 do
begin
if SUCCEEDED(m_pEffect.GetPassDesc(m_pEffect.GetPass(m_hTPostProcess, i), passdesc)) then
begin
if SUCCEEDED(D3DXGetShaderOutputSemantics(passdesc.pPixelShaderFunction, @aSem, @uCount)) then
begin
// Semantics received. Now examine the content and
// find out which render target this technique
// writes to.
Dec(uCount);
while (uCount <> 0) do
begin
if (D3DDECLUSAGE_COLOR = TD3DDeclUsage(aSem[uCount].Usage)) and (RT_COUNT > aSem[uCount].UsageIndex)
then m_bWrite[uCount] := True;
Dec(uCount);
end;
end;
end;
end;
// Obtain the render target channel
hAnno := m_pEffect.GetAnnotationByName(m_hTPostProcess, 'nRenderTarget');
if Assigned(hAnno) then m_pEffect.GetInt(hAnno, m_nRenderTarget);
// Obtain the handles to the changeable parameters, if any.
for i := 0 to NUM_PARAMS-1 do
begin
Name:= Format('Parameter%d', [i]);
hAnno := m_pEffect.GetAnnotationByName(m_hTPostProcess, PAnsiChar(Name));
if Assigned(hAnno) and
SUCCEEDED(m_pEffect.GetString(hAnno, szParamName)) then
begin
m_ahParam[i] := m_pEffect.GetParameterByName(nil, szParamName);
MultiByteToWideChar(CP_ACP, 0, szParamName, -1, m_awszParamName[i], MAX_PATH);
end;
// Get the parameter description
Name:= Format('Parameter%dDesc', [i]);
hAnno := m_pEffect.GetAnnotationByName(m_hTPostProcess, PAnsiChar(Name));
if Assigned(hAnno) and
SUCCEEDED(m_pEffect.GetString(hAnno, szParamName)) then
begin
MultiByteToWideChar(CP_ACP, 0, szParamName, -1, m_awszParamDesc[i], MAX_PATH);
end;
// Get the parameter size
Name:= Format('Parameter%dSize', [i]);
hAnno := m_pEffect.GetAnnotationByName(m_hTPostProcess, PAnsiChar(Name));
if Assigned(hAnno) then
m_pEffect.GetInt(hAnno, m_anParamSize[i]);
// Get the parameter default
Name:= Format('Parameter%dDef', [i]);
hAnno := m_pEffect.GetAnnotationByName(m_hTPostProcess, PAnsiChar(Name));
if Assigned(hAnno) then
m_pEffect.GetVector(hAnno, m_avParamDef[i]);
end;
Result:= S_OK;
end;
function CPostProcess.OnLostDevice: HRESULT;
begin
Assert(Assigned(m_pEffect));
m_pEffect.OnLostDevice;
Result:= S_OK;
end;
function CPostProcess.OnResetDevice(dwWidth, dwHeight: DWORD): HRESULT;
var
hParamToConvert: TD3DXHandle;
hAnnotation: TD3DXHandle;
uParamIndex: LongWord;
szSource: PAnsiChar;
hConvertSource: TD3DXHandle;
desc: TD3DXParameterDesc;
cKernel: DWORD;
pvKernel: array of TD3DXVector4;
i: Integer;
begin
Assert(Assigned(m_pEffect));
m_pEffect.OnResetDevice;
// If one or more kernel exists, convert kernel from
// pixel space to texel space.
// First check for kernels. Kernels are identified by
// having a string annotation of name "ConvertPixelsToTexels"
uParamIndex := 0;
// If a top-level parameter has the "ConvertPixelsToTexels" annotation,
// do the conversion.
while (nil <> m_pEffect.GetParameter(nil, uParamIndex)) do
begin
hParamToConvert := m_pEffect.GetParameter(nil, uParamIndex);
Inc(uParamIndex);
hAnnotation := m_pEffect.GetAnnotationByName(hParamToConvert, 'ConvertPixelsToTexels');
if (nil <> hAnnotation) then
begin
m_pEffect.GetString(hAnnotation, szSource);
hConvertSource := m_pEffect.GetParameterByName(nil, szSource);
if Assigned(hConvertSource) then
begin
// Kernel source exists. Proceed.
// Retrieve the kernel size
m_pEffect.GetParameterDesc( hConvertSource, desc);
// Each element has 2 floats
cKernel := desc.Bytes div (2 * SizeOf(Single));
try
SetLength(pvKernel, cKernel);
except
Result:= E_OUTOFMEMORY;
Exit;
end;
m_pEffect.GetVectorArray(hConvertSource, @pvKernel[0], cKernel);
// Convert
for i := 0 to cKernel - 1 do
begin
pvKernel[i].x := pvKernel[i].x / dwWidth;
pvKernel[i].y := pvKernel[i].y / dwHeight;
end;
// Copy back
m_pEffect.SetVectorArray(hParamToConvert, @pvKernel[0], cKernel);
pvKernel := nil;
end;
end;
end;
Result:= S_OK;
end;
{ CPProcInstance }
constructor CPProcInstance.Create;
begin
m_nFxIndex:= -1;
// ZeroMemory( m_avParam, sizeof( m_avParam ) ); //Clootie: auto done in Delphi
end;
{ CRenderTargetChain }
constructor CRenderTargetChain.Create;
begin
m_bFirstRender := True;
// ZeroMemory(m_pRenderTarget, sizeof(m_pRenderTarget) );
end;
destructor CRenderTargetChain.Destroy;
begin
Cleanup;
inherited;
end;
procedure CRenderTargetChain.Cleanup;
begin
m_pRenderTarget[0] := nil;
m_pRenderTarget[1] := nil;
end;
procedure CRenderTargetChain.Flip;
begin
m_nNext := 1 - m_nNext;
end;
function CRenderTargetChain.GetPrevTarget: IDirect3DTexture9;
begin
Result:= m_pRenderTarget[1 - m_nNext];
end;
function CRenderTargetChain.GetPrevSource: IDirect3DTexture9;
begin
Result:= m_pRenderTarget[m_nNext];
end;
function CRenderTargetChain.GetNextTarget: IDirect3DTexture9;
begin
Result:= m_pRenderTarget[m_nNext];
end;
function CRenderTargetChain.GetNextSource: IDirect3DTexture9;
begin
Result:= m_pRenderTarget[1 - m_nNext];
end;
procedure CRenderTargetChain.Init(const pRT: array of IDirect3DTexture9);
var
i: Integer;
begin
for i := 0 to 1 do m_pRenderTarget[i] := pRT[i];
end;
procedure CreateCustomDXUTobjects;
var
i: Integer;
begin
g_DialogResourceManager:= CDXUTDialogResourceManager.Create; // manager for shared resources of dialogs
g_SettingsDlg:= CD3DSettingsDlg.Create; // Device settings dialog
g_Camera:= CModelViewerCamera.Create;
g_HUD:= CDXUTDialog.Create;
g_SampleUI:= CDXUTDialog.Create;
for i:= 0 to PPCOUNT-1 do g_aPostProcess[i]:= CPostProcess.Create;
g_SceneMesh[0]:= CDXUTMesh.Create;
g_SceneMesh[1]:= CDXUTMesh.Create;
g_Skybox:= CDXUTMesh.Create;
for i:= 0 to RT_COUNT-1 do g_RTChain[i]:= CRenderTargetChain.Create;
end;
procedure DestroyCustomDXUTobjects;
var
i: Integer;
begin
FreeAndNil(g_DialogResourceManager);
FreeAndNil(g_SettingsDlg);
FreeAndNil(g_Camera);
FreeAndNil(g_HUD);
FreeAndNil(g_SampleUI);
for i:= 0 to PPCOUNT-1 do FreeAndNil(g_aPostProcess[i]);
FreeAndNil(g_SceneMesh[0]);
FreeAndNil(g_SceneMesh[1]);
FreeAndNil(g_Skybox);
for i:= 0 to RT_COUNT-1 do FreeAndNil(g_RTChain[i]);
end;
end.
|
unit Packdlgs;
interface
uses WinTypes, WinProcs, Classes, Graphics, Forms, Controls, Buttons,
StdCtrls, db, dbtables, dialogs, sysutils, ExtCtrls;
type
TGetTablesForm = class(TForm)
OKBtn: TBitBtn;
CancelBtn: TBitBtn;
Bevel1: TBevel;
TableListBox: TListBox;
Label1: TLabel;
Label2: TLabel;
DBListBox: TComboBox;
SelectedTables: TListBox;
Label3: TLabel;
IncludeBtn: TBitBtn;
ExcludeBtn: TBitBtn;
procedure DBListBoxClick(Sender: TObject);
procedure IncludeBtnClick(Sender: TObject);
procedure ExcludeBtnClick(Sender: TObject);
procedure TableListDblClick(Sender: TObject);
procedure SelectedTablesDblClick(Sender: TObject);
procedure SelectedTablesClick(Sender: TObject);
private
{ Private declarations }
procedure IncludeItems;
{ procedure IncludeAllItems;}
procedure ExcludeItems;
{ procedure ExcludeAllItems;}
function InDestList(Value: string): Boolean;
function InSrcList(Value: string): Boolean;
procedure SelectDest(index: integer);
public
{ Public declarations }
end;
function wwGetTablesDlg(
var databaseName: string;
tableNames: TStrings): Boolean;
implementation
{$R *.DFM}
function wwGetTablesDlg(
var databaseName: string;
tableNames: TStrings): Boolean;
var i, thisIndex: integer;
begin
with TGetTablesForm.create(Application) do
try
Session.getDatabaseNames(DBListBox.Items);
DBListBox.itemIndex:= DBListBox.items.indexof(databaseName);
if DBListBox.itemIndex>=0 then begin
TableListBox.clear;
Session.getTableNames(DBListBox.Items[DBListBox.itemIndex],
'', True {Extensions}, False, TableListBox.items);
{ remove tableNames form list }
for i:= 0 to tableNames.count-1 do begin
SelectedTables.items.add(tableNames[i]);
thisIndex:= TableListBox.items.indexOf(tableNames[i]);
TableListBox.items.delete(thisIndex);
end;
end;
Result := ShowModal = IDOK;
if Result then begin
databaseName:= DBListBox.items[DBListBox.itemIndex];
tableNames.assign(SelectedTables.items);
end;
finally
Free;
end
end;
procedure TGetTablesForm.DBListBoxClick(Sender: TObject);
var lastIndex: integer;
begin
lastIndex:= DBListBox.itemIndex;
TableListBox.clear;
Session.getTableNames(DBListBox.Items[DBListBox.itemIndex], '', True {Extensions}, False,
TableListBox.items);
SelectedTables.items.clear;
{ A Delphi bug FT5 makes the following line necessary to }
{ properly retain highlight on selected object! }
DBListBox.itemIndex:= lastIndex;
end;
procedure TGetTablesForm.IncludeItems;
var
I, LastPicked: Integer;
begin
LastPicked:= 0; {Make compiler happy}
with TableListBox do
begin
I := 0;
while I < Items.Count do
begin
if Selected[I] and (not InDestList(Items[I])) then
begin
LastPicked := I;
SelectedTables.Items.Add(Items[I]);
Items.Delete(I); {comment out to Copy items instead of Move}
end
else
Inc(I);
end;
if Items.Count > 0 then
if LastPicked = Items.Count then
Selected[LastPicked-1] := True
else
Selected[LastPicked] := True;
{ ExAllBtn.Enabled := True;}
end;
end;
procedure TGetTablesForm.ExcludeItems;
var
I: Integer;
begin
with SelectedTables do
begin
I := 0;
while SelCount > 0 do
begin
if Selected[I] then
begin
TableListBox.Items.Add(Items[I]); {comment out to Copy items instead of Move}
Items.Delete(I);
end
else
Inc(I);
end;
ExcludeBtn.Enabled := False;
if Items.Count = 0 then begin
{ ExAllBtn.Enabled := False;}
end
else begin
SelectedTables.ItemIndex:= 0;
SelectDest(i); { Select close to last entry }
end
end;
end;
procedure TGetTablesForm.SelectDest(index: integer);
begin
if SelectedTables.items.count=0 then index:= -1;
if (index>=0) then begin
with SelectedTables do begin
if (items.count>0) and (index>=items.count) then
index:= items.count-1; {Limit to range }
if not Selected[index] then
Selected[index]:= True;
end;
ExcludeBtn.Enabled := True;
end
end;
function TGetTablesform.InDestList(Value: string): Boolean;
begin
Result := False;
if SelectedTables.Items.IndexOf(Value) > -1 then
Result := True;
end;
function TGetTablesForm.InSrcList(Value: string): Boolean;
begin
Result := False;
if TableListBox.Items.IndexOf(Value) > -1 then
Result := True;
end;
procedure TGetTablesForm.IncludeBtnClick(Sender: TObject);
begin
IncludeItems;
end;
procedure TGetTablesForm.ExcludeBtnClick(Sender: TObject);
begin
ExcludeItems;
end;
procedure TGetTablesForm.TableListDblClick(Sender: TObject);
var LastPicked : integer;
begin
LastPicked:= 0; {Make compiler happy}
with TableListBox do
begin
if (ItemIndex<0) then exit;
if (not InDestList(Items[ItemIndex])) then
begin
begin
LastPicked := ItemIndex;
SelectedTables.Items.Add(Items[ItemIndex]);
Items.Delete(ItemIndex); {comment out to Copy items instead of Move}
end
end;
if Items.Count > 0 then
if LastPicked = Items.Count then
Selected[LastPicked-1] := True
else
Selected[LastPicked] := True;
{ ExAllBtn.Enabled := True;}
end;
end;
procedure TGetTablesForm.SelectedTablesDblClick(Sender: TObject);
var LastPicked : integer;
begin
LastPicked:= 0;
with SelectedTables do
begin
if (ItemIndex<0) then exit;
if (not InSrcList(Items[ItemIndex])) then
begin
begin
LastPicked := ItemIndex;
TableListBox.Items.Add(Items[ItemIndex]);
Items.Delete(ItemIndex); {comment out to Copy items instead of Move}
end
end;
if Items.Count > 0 then
if LastPicked = Items.Count then
Selected[LastPicked-1] := True
else
Selected[LastPicked] := True;
{ ExAllBtn.Enabled := True;}
end;
end;
procedure TGetTablesForm.SelectedTablesClick(Sender: TObject);
begin
SelectDest(SelectedTables.itemIndex)
end;
end.
|
unit FFindEmpty;
(*====================================================================
Progress window for searching disks according to the size of disks,
implements the searching in the Run procedure
======================================================================*)
interface
uses
SysUtils,
{$ifdef mswindows}
WinTypes,WinProcs,
{$ELSE}
LCLIntf, LCLType, LMessages,
{$ENDIF}
Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, ExtCtrls, Grids, ATGauge,
UApiTypes, UTypes;
type
{ TFormSearchEmpty }
TFormSearchEmpty = class(TForm)
ButtonStop: TButton;
Gauge1: TGauge;
//Gauge1: TPanel;
procedure FormCreate(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure ButtonStopClick(Sender: TObject);
private
CanRun : boolean;
public
StopIt : boolean;
DBaseHandle: PDBaseHandle;
procedure Run(var Info); message WM_User + 102;
procedure UpdateCounters;
end;
var
FormSearchEmpty: TFormSearchEmpty;
implementation
uses FFindEmptyDlg, UApi, UBaseTypes, ULang;
{$R *.dfm}
//-----------------------------------------------------------------------------
procedure CallBackWhenChange(var Stop: boolean); far;
begin
FormSearchEmpty.UpdateCounters;
Application.ProcessMessages;
Stop := FormSearchEmpty.StopIt;
end;
//-----------------------------------------------------------------------------
procedure TFormSearchEmpty.FormCreate(Sender: TObject);
begin
CanRun := false;
end;
//-----------------------------------------------------------------------------
procedure TFormSearchEmpty.FormActivate(Sender: TObject);
begin
StopIt := false;
CanRun := true;
// this causes to execure the Run procedure after the window is displayed
PostMessage(Self.Handle, WM_User + 102, 0, 0);
end;
//-----------------------------------------------------------------------------
procedure TFormSearchEmpty.ButtonStopClick(Sender: TObject);
begin
StopIt := true;
CanRun := false;
if QI_SearchItemsAvail(DBaseHandle)
then ModalResult := mrOK
else ModalResult := mrCancel;
end;
//-----------------------------------------------------------------------------
procedure TFormSearchEmpty.Run (var Info);
var
Success: boolean;
begin
if not CanRun then exit;
CanRun := false;
Success := false;
try
QI_ClearTreeStruct(DBaseHandle);
QI_ClearSearchCol (DBaseHandle);
QI_SetSearchCallback(DBaseHandle, CallBackWhenChange);
QI_FindEmpties(DBaseHandle);
QI_DelSearchCallback(DBaseHandle);
Success := true;
if not QI_SearchItemsAvail(DBaseHandle) then
begin
Application.MessageBox(lsNoDiskFound,
lsInformation, mb_OK or mb_IconInformation);
Success := false;
end;
finally
if Success
then ModalResult := mrOk
else ModalResult := mrCancel;
end;
end;
//-----------------------------------------------------------------------------
procedure TFormSearchEmpty.UpdateCounters;
var
Percent: Integer;
DisksCount, DirsCount, FilesCount: longint;
begin
QI_GetSearchProgress (DBaseHandle, Percent, DisksCount, DirsCount, FilesCount);
Gauge1.Progress := Percent;
end;
//-----------------------------------------------------------------------------
end.
|
AUTOR: Musetescu Mircea
Grupa: 225
Data predarii: 19.12.2001
Laborator Nr.3
PROBLEMA:
Avand data problema ordonantarii si graful potentiale-etape (PERT) asociat
acestei probleme, descrieti un algoritm pentru a determina toate drumurile
critice din acest graf.
PROIECTARE:
In aceasta problema avem pentru , determinat toate drumurile de lungime maxima din graful Pert de la varful p la varful q ( unde p - etapa initiala de realizare a proiectului, iar q - ultima etapa de realizare a proiectului respectiv).
In graful PERT varfurile reprezinta etape ale realizarii proiectului
iar arcele grafului reprezinta activitati (valoarea arcelor codificand
durata de desfasurare a activitatilor respective). Pentru determinarea
valorii maxime a drumurilor de dintre varful 1 si varful n voi folosi algoritmul lui Ford.
(*
procedure Ford(n,p:integer; v:mat; var lambda:tab);
var i,j:integer;
lambda1:tab;
begin
lambda1:=lambda;
repeat
lambda:=lambda1;
for j:=1 to n do
if j<>p then
for i:=1 to n do
if arc(i,j,v)
then if lambda1[i]+v[i,j] > lambda1[j]
then lambda1[j]:=lambda1[i]+v[i,j]
until egal(n,lambda,lambda1)
end;
*)
Presupunand format vectorul lambda cu semnificatia lambda[i] = valoarea
maxima a drumurilor de la varful 1 la varful i, ramane de rezolvat problema
reconstituirii tuturor drumurilor de valoare maxima de la varful 1 la
varful n.
Pentru reconstituirea acestor drumuri voi folosi metoda BACKTRACKING.
Consider potrivita folosirea acestei metode de programare deoarece se cer
'toate' drumurile de lungime maxima. Metoda de parcurgere a acestor drumuri
nu difera in totalitate de metoda de reconstituire a unui singur drum de
valoare maxima (TEMA2), diferenta constand in faptul ca trebuie realizata o
parcurgere cu reveniri (pentru determinarea tuturor variantelor).
Subalgoritmul Back(k) este:
Daca (* Am ajuns in varful p)
| atunci (* Tipareste drumul)
| altfel Pentru (* Fiecare i, predecesor al lui d[k-1]) executa
| | d[k]:=i
| | Daca (lambda(d(k))+v(d(k),d(k-1)) = lambda(d(k-1)))
| | | atunci Cheama Back(k+1)
| | SfDaca
| SfPentru
SfDaca
SfBack
Subalgoritmul se va apela cu Back(2), presupunand ca inainte s-a facut
initializarea d[1]:=q.
const MAX=20;
INFINIT=99999;
type tab=array[1..MAX] of integer;
mat=array[1..MAX] of tab;
function egal(n:integer; a,b:tab):boolean;
var i:integer;
begin
i:=1;
while (i<=n) and (a[i]=b[i]) do inc(i);
egal:= (i>n)
end;
function arc(i,j:integer; v:mat):boolean;
begin
arc:= (i<>j) and (v[i,j]<>-INFINIT)
end;
procedure InitCit(s:string;
var n:integer; var v:mat;
var lambda:tab; var p,q:integer);
var i,j,k:integer;
f:text;
begin
assign(f,s);
reset(f);
for i:=1 to MAX do
for j:=1 to MAX do v[i,j]:=-INFINIT;
for i:=1 to n do v[i,i]:=0;
readln(f,n);
readln(f,p,q);
readln(f,i,j,k);
while i<>0 do begin
v[i,j]:=k;
readln(f,i,j,k)
end;
lambda[p]:=0;
for i:=1 to n do
if i<>p then lambda[i]:=v[i,1];
close(f)
end;
procedure Ford(n,p:integer; v:mat; var lambda:tab);
var i,j:integer;
lambda1:tab;
begin
lambda1:=lambda;
repeat
lambda:=lambda1;
for j:=1 to n do
if j<>p then
for i:=1 to n do
if arc(i,j,v)
then if lambda1[i]+v[i,j] > lambda1[j]
then lambda1[j]:=lambda1[i]+v[i,j]
until egal(n,lambda,lambda1)
end;
procedure Tip(n:integer; v:mat; lambda:tab; p,q:integer);
var i,j:integer;
gata:boolean;
d:tab;
procedure Solutie(n:integer);
var i:integer;
begin
write('drum: ',d[n]);
for i:=n-1 downto 1 do
write('-(',v[d[i+1],d[i]],')-',d[i]);
writeln
end;
procedure Back(k:integer);
var i:integer;
begin
if d[k-1]=p
then Solutie(k-1)
else for i:=1 to n do begin
d[k]:=i;
if arc(d[k],d[k-1],v) and
(lambda[d[k]]+v[d[k],d[k-1]]=lambda[d[k-1]])
then Back(k+1)
end
end;
begin
if lambda[q]=-INFINIT then begin
writeln('nu exista drum de la ',p,' la ',q);
halt
end;
write('valoarea maxima a lungimilor drumurilor ');
writeln('de la ',p,' la ',q,' este ',lambda[q]);
d[1]:=q; Back(2)
end;
var n,p,q:integer;
v:mat;
lambda:tab;
begin
InitCit('tema3.dat',n,v,lambda,p,q);
Ford(n,p,v,lambda);
Tip(n,v,lambda,p,q)
end.
|
unit theframefour;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, TAGraph, TASeries, TAFuncSeries, Forms, Controls,
ExtCtrls, StdCtrls, Dialogs, ComCtrls, ParseMath, metodos_cerrados;
type
{ TTheFrame4 }
TTheFrame4 = class(TFrame)
Chart1: TChart;
Puntos: TLineSeries;
PlotLine: TLineSeries;
EjeX: TConstantLine;
EjeY: TConstantLine;
ColorButton1: TColorButton;
Edit1: TEdit;
Edit2: TEdit;
Edit3: TEdit;
Panel1: TPanel;
ScrollBox1: TScrollBox;
TrackBar1: TTrackBar;
private
FunctionList,
EditList: TList;
ActiveFunction: Integer;
public
procedure graficar(s:string; xmin,xmax,h:real);
procedure graficar2(s:string; xmin,xmax,h:real);
function evaluar(x:real):real;
end;
implementation
{$R *.lfm}
function f(valor:real;s:string):real;
var MiParse: TParseMath;
begin
MiParse:= TParseMath.create();
MiParse.AddVariable('x',valor);
MiParse.Expression:= s;
//check:=false;
try
result:=MiParse.Evaluate();
except
begin
ShowMessage('La funcion no es continua en el punto '+FloatToStr(valor));
//check:=true;
end;
end;
MiParse.destroy;
end;
procedure TTheFrame4.graficar(s:string; xmin,xmax,h:real);
var MiParse: TParseMath;
x:Real;
begin
x:=xmin;
MiParse:= TParseMath.create();
//PlotLine.Clear;
with PlotLine do repeat
AddXY(x,f(x,s));
x:=x+h
until(x>=xmax) ;
end;
function TTheFrame4.evaluar(x:real):real;
var parse :TParseMath;
begin
try
parse.NewValue('x',x);
Result:=parse.Evaluate();
except
showmessage('la f no es continua');
end;
end;
procedure TTheFrame4.graficar2(s:string; xmin,xmax,h:real);
var x:real ;
parse:TParseMath;
begin
x:= xmin;
parse:= TParseMath.create();
parse.AddVariable('x', 0.0);
parse.Expression:= s;
//plotLines.Clear;
with PlotLine do repeat
AddXY(x, evaluar(x));
x:=x+h
until(x>=xmax);
end;
end.
|
unit ShowExt;
{ Exports procedure ShowExtension which shows the content of
a GIF extension. See units GifUnit and GifDecl for the data structures
and FmAPPE, FmGCE and Fmmemo for the forms/dialogs.
Reinier Sterkenburg, Delft, The Netherlands.
5 Apr 97: - created
}
interface
uses
GifDecl; { Imports TExtension }
procedure ShowExtension(Caption: String; Extension: TExtension);
implementation
uses
Classes, { Imports TStringList }
Controls, { Imports mrOK }
FmAPPE, { Imports TAPPEDialog }
FmGCE, { Imports TGCEDialog }
FmMemo, { Imports TMemoForm }
SysUtils; { Imports IntToStr }
procedure ShowGCE(Caption: String; var GCE: TGraphicControlExtension);
var GCEDialog: TGCEDialog;
begin { ShowGCE }
GCEDialog := TGCEDialog.Create(GCE);
GCEDialog.Caption := Caption;
GCEDialog.Show;
{if GCEDialog.ModalResult = mrOK
then GCE := GCEDialog.GetGCE;
GCEDialog.Free;}
end; { ShowGCE }
procedure ShowCE(Caption: String; var Comment: TStringlist);
var MemoForm: TMemoForm;
begin { ShowCE }
MemoForm := TMemoForm.Create(nil);
MemoForm.Caption := Caption;
MemoForm.Memo.Lines.Assign(Comment);
MemoForm.Show;
end; { ShowCE }
procedure ShowAPPE(Caption: String; var APPE: TApplicationExtension);
var APPEDialog: TAPPEDialog;
begin { ShowAPPE }
APPEDialog := TAPPEDialog.Create(APPE);
APPEDialog.Caption := Caption;
APPEDialog.Show;
{if APPEDialog.ModalResult = mrOK
then APPE := APPEDialog.GetAPPE;
APPEDialog.Free;}
end; { ShowAPPE }
procedure ShowPTE(Caption: String; var PTE: TPlainTextExtension);
var MemoForm: TMemoForm;
begin { ShowPTE }
MemoForm := TMemoForm.Create(nil);
MemoForm.Caption := Caption;
MemoForm.Memo.Lines.Add('Left = ' + IntToStr(PTE.Left));
MemoForm.Memo.Lines.Add('Top = ' + IntToStr(PTE.Top));
MemoForm.Memo.Lines.Add('Width = ' + IntToStr(PTE.Width));
MemoForm.Memo.Lines.Add('Height = ' + IntToStr(PTE.Height));
MemoForm.Memo.Lines.Add('CellWidth = ' + IntToStr(PTE.CellWidth));
MemoForm.Memo.Lines.Add('CellHeight = ' + IntToStr(PTE.CellHeight));
MemoForm.Memo.Lines.Add('FGColorIndex = ' + IntToStr(PTE.TextFGColorIndex));
MemoForm.Memo.Lines.Add('BGCOlorIndex = ' + IntToStr(PTE.TextBGCOlorIndex));
MemoForm.Memo.Lines.Add('PlainText Data:');
MemoForm.Memo.Lines.AddStrings(PTE.PlainTextData);
MemoForm.Show;
end; { ShowPTE }
procedure ShowExtension(Caption: String; Extension: TExtension);
begin { TExtension.Edit }
with Extension.ExtRec do
case ExtensionType of
etGCE: ShowGCE(Caption, GCE);
etCE: ShowCE(Caption, Comment);
etAPPE: ShowAPPE(Caption, APPE);
etPTE: ShowPTE(Caption, PTE);
else raise Exception.Create('Unknown Extension type');
end;
end; { TExtension.Edit }
end.
|
unit Contracts_Payer_AE;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, StdCtrls, cxButtons, cxRadioGroup,
cxControls, cxGroupBox, ibase,
cnConsts, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxButtonEdit,
cxLabel, cxCurrencyEdit, cxDropDownEdit,
cn_Common_Types, cn_Common_Loader,
DogLoaderUnit, Buttons, cxDBEdit, DM, DBCtrls, cxLookupEdit,
cxDBLookupEdit, cxDBLookupComboBox, AllPeopleUnit;
type
Tfrm_Contracts_Payer_AE = class(TForm)
OkButton: TcxButton;
CancelButton: TcxButton;
Frame_GroupBox: TcxGroupBox;
Type_Payer_GroupBox: TcxGroupBox;
FizPayer_RadioButton: TcxRadioButton;
YurPayer_RadioButton: TcxRadioButton;
Payer_Label: TLabel;
Payer_Edit: TcxButtonEdit;
PercentEdit: TcxCurrencyEdit;
pLabel: TcxLabel;
Percent_Label: TLabel;
Periodichnost_Label: TLabel;
MFO_Edit: TcxTextEdit;
RasSchet_Edit: TcxTextEdit;
MFO_Label: TLabel;
RasSchet_Label: TLabel;
Periodichnost_Edit: TcxButtonEdit;
EditFizLizo_Btn: TSpeedButton;
LookupComboBox: TcxLookupComboBox;
Osoba_Label: TLabel;
SpeedButton1: TSpeedButton;
procedure CancelButtonClick(Sender: TObject);
procedure OkButtonClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FizPayer_RadioButtonKeyPress(Sender: TObject; var Key: Char);
procedure YurPayer_RadioButtonKeyPress(Sender: TObject; var Key: Char);
procedure Payer_EditKeyPress(Sender: TObject; var Key: Char);
procedure PercentEditKeyPress(Sender: TObject; var Key: Char);
procedure Periodichnost_ComboBoxKeyPress(Sender: TObject;
var Key: Char);
procedure Percent_RadioButtonClick(Sender: TObject);
procedure Summa_RadioButtonClick(Sender: TObject);
procedure YurPayer_RadioButtonClick(Sender: TObject);
procedure FizPayer_RadioButtonClick(Sender: TObject);
procedure Payer_EditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure Periodichnost_EditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure Periodichnost_EditKeyPress(Sender: TObject; var Key: Char);
procedure EditFizLizo_BtnClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure SpeedButton1Click(Sender: TObject);
private
PLanguageIndex:byte;
DM:TDM_Contracts;
DB_sp_Handle:TISC_DB_HANDLE;
procedure FormIniLanguage;
public
ID_PAYER :int64;
ID_TYPE_STAGE :int64;
ID_RATE_ACCOUNT :int64;
ID_CUST_MEN :int64;
IS_ADMIN :Boolean;
constructor Create(AOwner:TComponent; LanguageIndex : byte; DB_Handle:TISC_DB_HANDLE);reintroduce;
end;
implementation
{$R *.dfm}
constructor Tfrm_Contracts_Payer_AE.Create(AOwner:TComponent; LanguageIndex : byte; DB_Handle:TISC_DB_HANDLE);
begin
Screen.Cursor:=crHourGlass;
inherited Create(AOwner);
PLanguageIndex:= LanguageIndex;
DB_sp_Handle:= DB_Handle;
FormIniLanguage();
Dm := TDM_Contracts.Create(self);
Dm.DB.Handle := DB_sp_Handle;
dm.ReadTransaction.StartTransaction;
Screen.Cursor:=crDefault;
end;
procedure Tfrm_Contracts_Payer_AE.FormIniLanguage;
begin
Type_Payer_GroupBox.Caption:= cnConsts.cn_PayerType[PLanguageIndex];
FizPayer_RadioButton.Caption:= cnConsts.cn_FizOsoba[PLanguageIndex];
YurPayer_RadioButton.Caption:= cnConsts.cn_YurOsoba[PLanguageIndex];
Percent_Label.Caption:= cnConsts.cn_Persent_Column[PLanguageIndex];
Periodichnost_Label.Caption:= cnConsts.cn_Period_Column[PLanguageIndex];
Payer_Label.Caption:= cnConsts.cn_Payer_Column[PLanguageIndex];
OkButton.Caption:= cnConsts.cn_Accept[PLanguageIndex];
CancelButton.Caption:= cnConsts.cn_Cancel[PLanguageIndex];
MFO_Label.Caption:= cnConsts.cn_MFO_Caption[PLanguageIndex];
RasSchet_Label.Caption:= cnConsts.cn_RasSchet_Caption[PLanguageIndex];
Osoba_Label.Caption:= cnConsts.cn_OsosbaCustomer[PLanguageIndex];
EditFizLizo_Btn.Hint := cnConsts.cn_FizLizoEdit[PLanguageIndex];
end;
procedure Tfrm_Contracts_Payer_AE.CancelButtonClick(Sender: TObject);
begin
close;
end;
procedure Tfrm_Contracts_Payer_AE.OkButtonClick(Sender: TObject);
begin
if Payer_Edit.text = '' then
begin
showmessage(cnConsts.cn_Payer_Need[PLanguageIndex]);
Payer_Edit.SetFocus;
exit;
end;
if PercentEdit.Value = 0 then
begin
showmessage(cnConsts.cn_Percent_Need[PLanguageIndex]);
PercentEdit.SetFocus;
exit;
end;
if Periodichnost_Edit.text = '' then
begin
showmessage(cnConsts.cn_Period_Need[PLanguageIndex]);
Periodichnost_Edit.SetFocus;
exit;
end;
if YurPayer_RadioButton.Checked then
if LookupComboBox.Text <> '' then
ID_CUST_MEN := Dm.DataSet['ID_CUST_MEN'];
ModalResult:=mrOk;
end;
procedure Tfrm_Contracts_Payer_AE.FormShow(Sender: TObject);
begin
Payer_Edit.setFocus;
if FizPayer_RadioButton.Checked then
begin
MFO_Edit.Enabled:=false;
RasSchet_Edit.Enabled:=false;
LookupComboBox.Enabled:=false;
end
else
if Caption = cnConsts.cn_EditBtn_Caption[PLanguageIndex] then
if ID_CUST_MEN <> -1 then
begin
Dm.DataSet.Close;
Dm.Dataset.SelectSQL.Clear;
Dm.Dataset.SelectSQL.Text := 'select * from CN_FIO_BY_ID_CUSTOMER_SLT(' + inttostr(ID_PAYER) + ')';
Dm.Dataset.Open;
Dm.Dataset.FetchAll;
Dm.Dataset.Locate('ID_CUST_MEN', ID_CUST_MEN, []);
LookupComboBox.Properties.ListSource :=Dm.DataSource;
LookupComboBox.Text := Dm.Dataset['FIO'];
end;
end;
procedure Tfrm_Contracts_Payer_AE.FizPayer_RadioButtonKeyPress(
Sender: TObject; var Key: Char);
begin
if key =#13 then YurPayer_RadioButton.SetFocus;
end;
procedure Tfrm_Contracts_Payer_AE.YurPayer_RadioButtonKeyPress(
Sender: TObject; var Key: Char);
begin
if key =#13 then Payer_Edit.SetFocus;
end;
procedure Tfrm_Contracts_Payer_AE.Payer_EditKeyPress(Sender: TObject;
var Key: Char);
begin
if key =#13 then PercentEdit.SetFocus;
end;
procedure Tfrm_Contracts_Payer_AE.PercentEditKeyPress(Sender: TObject;
var Key: Char);
begin
if key =#13 then Periodichnost_Edit.SetFocus;
end;
procedure Tfrm_Contracts_Payer_AE.Periodichnost_ComboBoxKeyPress(
Sender: TObject; var Key: Char);
begin
if key =#13 then OkButton.SetFocus;
end;
procedure Tfrm_Contracts_Payer_AE.Percent_RadioButtonClick(
Sender: TObject);
begin
Percent_Label.Caption:= cnConsts.cn_Persent_Column[PLanguageIndex];
pLabel.Caption:='%';
if PercentEdit.CanFocusEx then
PercentEdit.SetFocus;
end;
procedure Tfrm_Contracts_Payer_AE.Summa_RadioButtonClick(Sender: TObject);
begin
Percent_Label.Caption:= cnConsts.cn_Summa_Column[PLanguageIndex];
pLabel.Caption:='грн.';
if PercentEdit.CanFocusEx then
PercentEdit.SetFocus;
end;
procedure Tfrm_Contracts_Payer_AE.YurPayer_RadioButtonClick(
Sender: TObject);
begin
MFO_Edit.Enabled:=true;
RasSchet_Edit.Enabled:=true;
LookupComboBox.Enabled := True;
if Payer_Edit.CanFocusEx then Payer_Edit.SetFocus;
end;
procedure Tfrm_Contracts_Payer_AE.FizPayer_RadioButtonClick(
Sender: TObject);
begin
MFO_Edit.Enabled:=false;
RasSchet_Edit.Enabled:=false;
LookupComboBox.Enabled := false;
if Payer_Edit.CanFocusEx then
Payer_Edit.SetFocus;
end;
procedure Tfrm_Contracts_Payer_AE.Payer_EditPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
Massiv : variant;
i, o : TSpravParams;
begin
if FizPayer_RadioButton.Checked then
begin
Massiv:=AllPeopleUnit.GetManForASUP(Self, DB_sp_Handle ,False,True, -1);
if VarArrayDimCount(Massiv)>0 then
begin
ID_PAYER := -1; // обнуление
ID_PAYER := Massiv[0];
Payer_Edit.text := Massiv[1];
MFO_Edit.Text:='';
RasSchet_Edit.Text:='';
end;
end
else
begin
i := TSpravParams.Create;
o := TSpravParams.Create;
i['DataBase'] := Integer(DB_sp_Handle);
i['FormStyle'] := fsNormal;
i['bMultiSelect'] := false;
i['id_session'] := -1;
i['SelectMode'] := SelCustomer;
LoadSprav('Customer\CustPackage.bpl', Self, i, o);
if o['ModalResult'] = mrOk then
begin
ID_PAYER := -1; // обнуление
ID_RATE_ACCOUNT := -1; // обнуление
ID_PAYER := o['ID_CUSTOMER'];
if o['ID_RATE_ACCOUNT']=null then
ID_RATE_ACCOUNT:=-1
else
ID_RATE_ACCOUNT := o['ID_RATE_ACCOUNT'];
Payer_Edit.text := o['NAME_CUSTOMER'];
if o['MFO']=null then
MFO_Edit.text := ''
else
MFO_Edit.text := o['MFO'];
if o['RATE_ACCOUNT']=null then
RasSchet_Edit.text := ''
else
RasSchet_Edit.text := o['RATE_ACCOUNT'];
end;
i.Free;
o.Free;
// забираю ФИО по кастомеру
Dm.DataSet.Close;
Dm.Dataset.SelectSQL.Clear;
Dm.Dataset.SelectSQL.Text := 'select * from CN_FIO_BY_ID_CUSTOMER_SLT(' + inttostr(ID_PAYER) + ')';
Dm.Dataset.Open;
if Dm.Dataset.RecordCount > 0 then
begin
Dm.Dataset.FetchAll;
Dm.Dataset.First;
LookupComboBox.Properties.ListSource :=Dm.DataSource;
LookupComboBox.Text := Dm.Dataset['FIO'];
end;
end;
end;
procedure Tfrm_Contracts_Payer_AE.Periodichnost_EditPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
AParameter:TcnSimpleParams;
res: Variant;
begin
AParameter:= TcnSimpleParams.Create;
AParameter.Owner:=self;
AParameter.Db_Handle:= DB_sp_Handle;
AParameter.Formstyle:=fsNormal;
AParameter.is_admin:=IS_ADMIN;
if ID_TYPE_STAGE <> -1 then
AParameter.ID_Locate := ID_TYPE_STAGE;
res:= RunFunctionFromPackage(AParameter, 'Contracts\cn_ini_TypeStage.bpl','ShowIniTypeStage');
AParameter.Free;
if VarArrayDimCount(res)>0 then
begin
ID_TYPE_STAGE := res[0];
Periodichnost_Edit.Text:= vartostr(res[1]);
end;
end;
procedure Tfrm_Contracts_Payer_AE.Periodichnost_EditKeyPress(
Sender: TObject; var Key: Char);
begin
if key = #13 then OkButton.SetFocus;
end;
procedure Tfrm_Contracts_Payer_AE.EditFizLizo_BtnClick(Sender: TObject);
begin
if ((ID_PAYER <> -1) and (FizPayer_RadioButton.Checked))
then ShowManEditForm(Self, DB_sp_Handle , ID_PAYER, True);
end;
procedure Tfrm_Contracts_Payer_AE.FormDestroy(Sender: TObject);
begin
Dm.DataSet.Close;
Dm.Free;
end;
procedure Tfrm_Contracts_Payer_AE.SpeedButton1Click(Sender: TObject);
begin
LookupComboBox.Text := '';
ID_CUST_MEN := -1;
end;
end.
|
{
Laz-Model
Copyright (C) 2002 Eldean AB, Peter Söderman, Ville Krumlinde
Portions (C) 2016 Peter Dyson. Initial Lazarus port
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 uFeedback;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,
ExtCtrls;
type
IEldeanFeedback = interface(IUnknown)
['{130C7331-3B65-4D90-BF5C-07DF47B17317}']
procedure Message(const M : string);
end;
TGuiFeedback = class(TInterfacedObject,IEldeanFeedback)
private
P : TPanel;
T : TTimer;
private
procedure OnTimer(Sender : TObject);
public
constructor Create(APanel : TPanel);
destructor Destroy; override;
procedure Message(const M : string);
end;
var
NilFeedback : IEldeanFeedback;
implementation
{ TGuiFeedback }
constructor TGuiFeedback.Create(APanel: TPanel);
begin
Self.P := APanel;
T := TTimer.Create(nil);
T.OnTimer := @OnTimer;
end;
destructor TGuiFeedback.Destroy;
begin
FreeAndNil(T);
inherited;
end;
procedure TGuiFeedback.Message(const M: string);
begin
P.Caption := M;
P.Visible := True;
P.Height := 20;
P.Refresh;
T.Enabled := False;
T.Interval := 5000;
T.Enabled := True;
end;
procedure TGuiFeedback.OnTimer(Sender: TObject);
begin
// P.Caption := '';
// P.Refresh;
if P.Height>=0 then
begin
P.Height := P.Height - 5;
T.Interval := 25;
end
else
begin
P.Visible := False;
T.Enabled := False;
end;
end;
{ TNilFeedback }
type
TNilFeedback = class(TInterfacedObject,IEldeanFeedback)
procedure Message(const M : string);
end;
procedure TNilFeedback.Message(const M: string);
begin
//
end;
initialization
NilFeedBack := TNilFeedback.Create;
finalization
end.
|
{ IHX (Intel Hex format) to TZX (ZX Spectrum tape file format) convertor tool
This is the main program of the tool.
Copyright (C) 2020 Nikolay Nikolov <nickysn@users.sourceforg.net>
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., 51 Franklin Street - Fifth Floor,
Boston, MA 02110-1335, USA.
}
program ihx2tzx;
{$mode objfpc}{$H+}
uses
Classes, SysUtils, CustApp, ihxreader, tzxwriter, zxbasic
{ you can add units after this };
const
ShortOptions = 'hb:c:';
LongOptions: array [0..0] of string = (
'help'
);
type
{ TIHX2TZX }
TIHX2TZX = class(TCustomApplication)
private
FInputFileName: string;
FOutputFileName: string;
FBasicProgramName: string;
FBinaryProgramName: string;
FInputImage: TIHXReader;
FOutputFile: TStream;
FTapeWriter: TTZXWriter;
protected
procedure DoRun; override;
public
constructor Create(TheOwner: TComponent); override;
destructor Destroy; override;
procedure WriteHelp; virtual;
end;
{ TIHX2TZX }
procedure TIHX2TZX.DoRun;
var
ErrorMsg: String;
NonOptions: TStringArray;
BasicProgram: AnsiString;
begin
if ParamCount = 0 then
begin
WriteHelp;
Terminate;
Exit;
end;
// quick check parameters
ErrorMsg:=CheckOptions(ShortOptions, LongOptions);
if ErrorMsg<>'' then begin
ShowException(Exception.Create(ErrorMsg));
Terminate;
Exit;
end;
// parse parameters
if HasOption('h', 'help') then begin
WriteHelp;
Terminate;
Exit;
end;
if HasOption('b', '') then
FBasicProgramName := GetOptionValue('b', '');
if HasOption('c', '') then
FBinaryProgramName := GetOptionValue('c', '');
NonOptions := GetNonOptions(ShortOptions, LongOptions);
if Length(NonOptions) = 0 then
begin
ShowException(Exception.Create('Missing input file'));
Terminate;
Exit;
end;
if Length(NonOptions) > 2 then
begin
ShowException(Exception.Create('Too many files specified'));
Terminate;
Exit;
end;
FInputFileName := NonOptions[0];
if Length(NonOptions) >= 2 then
FOutputFileName := NonOptions[1]
else
FOutputFileName := ChangeFileExt(FInputFileName, '.tzx');
{ add your program here }
FInputImage.ReadIHXFile(FInputFileName);
FOutputFile := TFileStream.Create(FOutputFileName, fmCreate);
FTapeWriter := TTZXWriter.Create(FOutputFile);
BasicProgram := BAS_EncodeLine(10, ' '+BC_LOAD+'"" '+BC_CODE) +
BAS_EncodeLine(20, ' '+BC_PRINT+BC_USR+BAS_EncodeNumber(FInputImage.Origin));
FTapeWriter.AppendProgramFile(FBasicProgramName, 10, Length(BasicProgram), BasicProgram[1], Length(BasicProgram));
FTapeWriter.AppendCodeFile(FBinaryProgramName, FInputImage.Origin, FInputImage.Data[0], Length(FInputImage.Data));
// stop program loop
Terminate;
end;
constructor TIHX2TZX.Create(TheOwner: TComponent);
begin
inherited Create(TheOwner);
StopOnException:=True;
FInputImage := TIHXReader.Create;
FBasicProgramName := 'basic';
FBinaryProgramName := 'test';
end;
destructor TIHX2TZX.Destroy;
begin
FreeAndNil(FInputImage);
FreeAndNil(FTapeWriter);
FreeAndNil(FOutputFile);
inherited Destroy;
end;
procedure TIHX2TZX.WriteHelp;
begin
{ add your help code here }
writeln('Usage: ', ExeName, ' [options] ihx_file [tzx_file]');
Writeln('Options: -b <name> specify the name of the BASIC loader program on the tape');
Writeln(' -c <name> specify the name of the machine code program on the tape');
Writeln(' -h display this help');
Writeln(' --help display this help');
end;
var
Application: TIHX2TZX;
begin
Application:=TIHX2TZX.Create(nil);
Application.Title:='ihx2tzx';
Application.Run;
Application.Free;
end.
|
unit Compute.Test;
interface
procedure RunTests;
implementation
uses
System.SysUtils,
System.DateUtils,
System.Math,
Compute,
Compute.Common,
Compute.Functions,
Compute.ExprTrees;
function ReferenceTransform(const Input: TArray<double>): TArray<double>;
var
i: integer;
x: double;
begin
SetLength(result, Length(input));
for i := 0 to High(input) do
begin
x := input[i];
result[i] := (1 / 256) * (((((46189 * x * x) - 109395) * x * x + 90090) * x * x - 30030) * x * x + 3465) * x * x - 63;
end;
end;
function CompareOutputs(const data1, data2: TArray<double>): boolean;
var
i: integer;
err: double;
begin
result := True;
for i := 0 to High(data1) do
begin
err := Abs(data1[i] - data2[i]);
if (err > 1e-6) then
begin
Writeln(Format('%d val %.15g ref %.15g (error: %g)', [i, data1[i], data2[i], err]));
result := False;
exit;
end;
end;
end;
procedure AsyncTransformTest;
var
logger: TLogProc;
st: TDateTime;
i: integer;
input, output, outputRef: TArray<double>;
f: Future<TArray<double>>;
P10: Expr;
sqr: Expr.Func1;
begin
logger :=
procedure(const msg: string)
begin
WriteLn(msg);
end;
// load OpenCL platform
InitializeCompute(PreferCPUDevice, logger, logger);
// initialize input
SetLength(input, 20000000);
// input values are in [-1, 1]
for i := 0 to High(input) do
input[i] := 2 * i / High(input) - 1;
WriteLn('start compute');
st := Now;
sqr := Func.Sqr;
// Legendre polynomial P_n(x) for n = 10
P10 :=
(1 / 256) *
(((((46189 * sqr(_1)) - 109395) * sqr(_1) + 90090) * sqr(_1) - 30030) * sqr(_1) + 3465) * sqr(_1) - 63;
// computes output[i] := P10(input[i])
// by default it tries to select a GPU device
// so this can run async while the CPU does other things
f := Compute.AsyncTransform(input, P10);
// wait for computations to finish
f.Wait;
// and get the result
output := f.Value;
WriteLn(Format('done compute, %.3f seconds', [MilliSecondsBetween(Now, st) / 1000]));
WriteLn('start reference');
st := Now;
outputRef := ReferenceTransform(input);
WriteLn(Format('done reference, %.3f seconds', [MilliSecondsBetween(Now, st) / 1000]));
if CompareOutputs(output, outputRef) then
WriteLn('data matches')
else
WriteLn('======== DATA DIFFERS ========');
end;
procedure AsyncTransformBufferTest;
var
st: TDateTime;
i: integer;
input, output, outputRef: TArray<double>;
inputBuf: Buffer<double>;
f: Future<Buffer<double>>;
P10: Expr;
sqr: Expr.Func1;
begin
// load OpenCL platform
InitializeCompute;
// initialize input
SetLength(input, 200000000);
// input values are in [-1, 1]
for i := 0 to High(input) do
input[i] := 2 * i / High(input) - 1;
WriteLn('start compute');
st := Now;
sqr := Func.Sqr;
// Legendre polynomial P_n(x) for n = 10
P10 :=
(1 / 256) *
(((((46189 * sqr(_1)) - 109395) * sqr(_1) + 90090) * sqr(_1) - 30030) * sqr(_1) + 3465) * sqr(_1) - 63;
// initialize buffer
inputBuf := Buffer<double>.Create(input);
// computes output[i] := P10(input[i])
// by default it tries to select a GPU device
// so this can run async while the CPU does other things
f := Compute.AsyncTransform(inputBuf, P10);
// wait for computations to finish
f.Wait;
// and get the result
output := f.Value.ToArray();
WriteLn(Format('done compute, %.3f seconds', [MilliSecondsBetween(Now, st) / 1000]));
WriteLn('start reference');
st := Now;
outputRef := ReferenceTransform(input);
WriteLn(Format('done reference, %.3f seconds', [MilliSecondsBetween(Now, st) / 1000]));
if CompareOutputs(output, outputRef) then
WriteLn('data matches')
else
WriteLn('======== DATA DIFFERS ========');
end;
procedure OutputData(const Filename: string; const radius, mass, rho: TArray<double>);
var
i: integer;
f: TextFile;
begin
Assign(f, Filename);
Rewrite(f);
WriteLn(f, 'r'#9'm'#9'rho');
for i := 0 to High(radius) do
WriteLn(f, Format('%.15g'#9'%.15g'#9'%.15g', [radius[i], mass[i], rho[i]]));
CloseFile(f);
end;
function gamma_ref(const rho: double): double; inline;
var
x2: double;
begin
x2 := Power(rho, 2.0 / 3.0);
result := x2 / (3 * sqrt(1 + x2));
end;
procedure dydx_ref(const x: double; const y0, y1: double; out dy0dx, dy1dx: double);
var
rho: double;
x2: double;
begin
x2 := x * x;
rho := Max(1e-9, y1);
dy0dx := x2 * rho; // dm/dr
dy1dx := -(y0 * rho) / (gamma_ref(rho) * x2); // drho/dr
end;
procedure euler_ref(const h, y0, dydx: double; out y: double); inline;
begin
y := y0 + h * dydx;
end;
procedure ODEReference(const N: integer; const r0, h: double; out radius, mass, rho: TArray<double>);
var
i, j: integer;
x, r, rho_c: double;
dy0dx, dy1dx: double;
y0t, y1t: double;
y0, y1: TArray<double>;
done: boolean;
st, ft: double;
begin
WriteLn;
WriteLn('Computing reference');
radius := nil;
SetLength(radius, N);
mass := nil;
SetLength(mass, N);
rho := nil;
SetLength(rho, N);
y0 := mass;
y1 := rho;
// initialize
x := r0;
for i := 0 to N-1 do
begin
rho_c := Power(10, -1 + 7 * (i / (N-1)));
r := r0;
y0[i] := rho_c * r*r*r / 3;
y1[i] := (gamma_ref(rho_c)*rho_c)/(gamma_ref(rho_c) + r*r*rho_c/3);
end;
st := Now;
j := 0;
done := False;
while not done do
begin
done := True;
for i := 0 to N-1 do
begin
if (radius[i] > 0) then
continue;
dydx_ref(x, y0[i], y1[i], dy0dx, dy1dx);
euler_ref(h, y0[i], dy0dx, y0t);
y0[i] := y0t;
euler_ref(h, y1[i], dy1dx, y1t);
if (y1[i] > 1e-9) and (y1t <= 1e-9) then
begin
radius[i] := x;
end;
y1[i] := y1t;
done := done and (y1t <= 1e-9);
end;
x := x + h;
j := j + 1;
end;
ft := Now;
WriteLn(Format('Done, steps: %d, time: %.3fs', [j, MilliSecondsBetween(ft, st) / 1000]));
end;
procedure ODETest;
const
N = 100000;
r0 = 1e-9;
h = 1e-4;
var
logger: TLogProc;
sqr: Expr.Func1;
ifthen: Expr.Func3;
gamma, gamma_x2, get_rho: Expr.Func1;
euler: Expr.Func2;
dy0dx, dy1dx: Expr.Func3;
rho_c: TArray<double>;
i: integer;
max_rho: double;
// state
x: Future<Buffer<double>>; // r
xt: Future<Buffer<double>>;
y0, dy0: Future<Buffer<double>>; // m
y0t: Future<Buffer<double>>; // temp
y1, dy1: Future<Buffer<double>>; // rho
y1t: Future<Buffer<double>>; // temp
radius, mass, rho: TArray<double>;
st, ft: double;
begin
logger :=
procedure(const msg: string)
begin
WriteLn(msg);
end;
// load OpenCL platform
InitializeCompute(PreferCPUDevice, logger, logger);
sqr := Func.Sqr;
ifthen := Func.IfThen;
// euler integration step
// _1 = y
// _2 = dydx
euler := Func2('euler', _1 + h * _2);
// gamma function
gamma_x2 := Func1('gamma_x2', _1 / (3 * Func.Sqrt(1 + _1)));
gamma := Func1('gamma', gamma_x2(Func.Pow(_1, 2.0 / 3.0)));
// helper
get_rho := Func1('get_rho', Func.Max(1e-9, _1));
// derivative functions
// _1 = x
// _2 = y0
// _3 = y1
dy0dx := Func3('dy0dx', sqr(_1) * get_rho(_3)); // dm/dr
dy1dx := Func3('dy1dx', -(_2 * get_rho(_3)) / (gamma(get_rho(_3)) * sqr(_1))); // drho/dr
SetLength(rho_c, N);
// vary central density \rho_c from 10^-1 to 10^6
for i := 0 to N-1 do
begin
rho_c[i] := Power(10, -1 + 7 * (i / (N-1)));
end;
// initialize x
x := Buffer<double>.Create(N);
// simply fill with r0
x := AsyncTransform(x, x, r0);
// compute initial state from rho_c
y0 := Buffer<double>.Create(rho_c);
y1 := Buffer<double>.Create(rho_c);
// temporary buffers
xt := Buffer<double>.Create(N);
dy0 := Buffer<double>.Create(N);
y0t := Buffer<double>.Create(N);
dy1 := Buffer<double>.Create(N);
y1t := Buffer<double>.Create(N);
// y0 = rho_c * r*r*r / 3;
y0 := AsyncTransform(y0, y0, _1 * r0 * r0 * r0 / 3);
// y1 = (gamma(rho_c) * rho_c) / (gamma(rho_c) + r*r * rho_c / 3)
y1 := AsyncTransform(y1, y1, (gamma(_1) * _1) / (gamma(_1) + r0 * r0 * _1 / 3));
st := Now;
i := 1;
while True do
begin
// get derivatives
dy0 := AsyncTransform(x, y0, y1, dy0, dy0dx(_1, _2, _3));
dy1 := AsyncTransform(x, y0, y1, dy1, dy1dx(_1, _2, _3));
// integration step
y0t := AsyncTransform(y0, y1, dy0, y0t, ifthen(_2 < 1e-9, _1, euler(_1, _3))); // y0t = y0 + h*dy0dx
y1t := AsyncTransform(y0, y1, dy1, y1t, ifthen(_2 < 1e-9, _2, euler(_2, _3))); // y1t = y1 + h*dy1dx
xt := AsyncTransform(x, y1, xt, ifthen(_2 < 1e-9, _1, _1 + h));
// y0t holds new values and y0 is ready
// so swap them for next round
y0t.SwapWith(y0);
y1t.SwapWith(y1);
xt.SwapWith(x);
// every 1000 steps, check if we're done
if (i mod 1000 = 0) then
begin
WriteLn('step: ', i);
rho := y1.Value.ToArray();
max_rho := Functional.Reduce<double>(rho,
function(const v1, v2: double): double
begin
result := Max(v1, v2);
end);
if (max_rho <= 1e-9) then
break;
end;
i := i + 1;
end;
ft := Now;
WriteLn(Format('Done, steps: %d, time: %.3fs', [i, MilliSecondsBetween(ft, st) / 1000]));
radius := x.Value.ToArray();
mass := y0.Value.ToArray();
rho := y1.Value.ToArray();
OutputData('data.txt', radius, mass, rho);
ODEReference(N, r0, h, radius, mass, rho);
OutputData('data_ref.txt', radius, mass, rho);
end;
procedure RunTests;
begin
AsyncTransformTest;
// AsyncTransformBufferTest;
// ODETest;
end;
end.
|
program TiketingParkir;
uses crt, sysutils;
const
maks = 1000;
namafile = 'TiketingParkir.DAT';
type
TPark = record
nama:string[20];
noKendaraan:string[10];
jenisKendaraan:string[10];
lamaParkir:integer;
bayarParkir:real;
statusHapus:boolean;
end;
TParkList = array[1..maks] of TPark;
var
tiket:TParkList;
banyakData:integer;
pilihanMenu:byte;
pilihUrut:byte;
found: boolean;
namaCari,noCari:string;
ulangi : char;
function index (namaCari, noCari : string) : integer;
var
i: integer;
begin
found:=false;
i:=0;
while (i<=banyakData) AND (not(found)) do
begin
i:=i+1;
if(tiket[i].nama = namaCari) AND (tiket[i].noKendaraan = noCari) then
found:=true;
end;
if found then
index :=i;
end;
function searchData(namaCari, noCari : string): boolean;
var
i:integer;
begin
found:=false;
namaCari:=upcase(namaCari);
noCari:=upcase(noCari);
i:=0;
while (i<=banyakData) AND (not(found)) do
begin
i:=i+1;
if(tiket[i].nama = namaCari) AND (tiket[i].noKendaraan = noCari) then
found:=true;
end;
if found then
searchData:=found;
end;
procedure urutAsc;
var
i,j : integer;
temp : TParkList;
begin
for i:= 1 to (banyakData-1) do
begin
for j:=banyakData downto (i+1) do
begin
if pilihUrut = 1 then
begin
if tiket[j].bayarParkir < tiket[j-1].bayarParkir then
begin
temp[j] := tiket[j];
tiket[j] := tiket[j-1];
tiket[j-1] := temp[j];
end;
end
else if pilihUrut = 2 then
begin
if tiket[j].lamaParkir < tiket[j-1].lamaParkir then
begin
temp[j] := tiket[j];
tiket[j] := tiket[j-1];
tiket[j-1] := temp[j];
end;
end;
end;
end;
end;
procedure urutDec;
var
i,j : integer;
temp : TParkList;
begin
for i:= 1 to (banyakData-1) do
begin
for j:=banyakData downto (i+1) do
begin
if pilihUrut = 1 then
begin
if tiket[j].bayarParkir > tiket[j-1].bayarParkir then
begin
temp[j] := tiket[j];
tiket[j] := tiket[j-1];
tiket[j-1] := temp[j];
end;
end
else if pilihUrut = 2 then
begin
if tiket[j].lamaParkir > tiket[j-1].lamaParkir then
begin
temp[j] := tiket[j];
tiket[j] := tiket[j-1];
tiket[j-1] := temp[j];
end;
end;
end;
end;
end;
procedure tabel;
var
i : integer;
begin
clrscr;
writeln('************************************* DATA HASIL PENGURUTAN ***********************************');
writeln(' Jl.Kenangan mantan no.123 ');
writeln('-----------------------------------------------------------------------------------------------');
writeln('| NO | NAMA | NOMER KENDARAAN | JENIS KENDARAAN | DURASI[jam] | BAYAR |');
writeln('-----------------------------------------------------------------------------------------------');
for i:=1 to banyakData do
begin
writeln('| ',i:2,' ',
'| ',format('%-15s',[tiket[i].nama]),' ',
'| ',format('%-17s',[tiket[i].noKendaraan]),' ',
'| ',format('%-17s',[tiket[i].jenisKendaraan]),' ',
'| ',format('%-13d',[tiket[i].lamaParkir]),' ',
'| ',format('%-10g',[tiket[i].bayarParkir]), ' |');
end;
writeln('-----------------------------------------------------------------------------------------------');
end;
procedure tampilUrut;
var
formatPilih : byte;
begin
repeat
clrscr;
writeln('====================================== PENGURUTAN DATA =======================================');
writeln('----------------------------------------------------------------------------------------------');
writeln;
gotoxy(41,5);writeln('1.Ascending');
gotoxy(41,6);writeln('2.Descending');
gotoxy(40,7);write('Pilih [1/2] : ');readln(formatPilih);
writeln;
gotoxy(37,10);writeln('Pilih data yang diurutkan');
gotoxy(38,11);writeln('1. Bayar Parkir');
gotoxy(38,12);writeln('2. Lama Parkir');
gotoxy(37,13);write('Pilihan Anda [1/2] : ');readln(pilihUrut);
if formatPilih = 1 then
begin
if pilihUrut = 1 then
begin
urutAsc;
tabel;
end
else if pilihUrut = 2 then
begin
urutAsc;
tabel;
end;
end
else if formatPilih = 2 then
begin
if pilihUrut = 1 then
begin
urutDec;
tabel;
end
else if pilihUrut = 2 then
begin
urutDec;
tabel;
end;
end;
write('Urut data kembali?[Y/N] : ');readln(ulangi);
until (upcase(ulangi) = 'N');
end;
procedure kotak;
var
i:integer;
begin
clrscr;
gotoxy(29,5);write('+');
for i:=1 to 40 do
begin
gotoxy(29+i,5);write('-');
end;
write('+');
for i:= 1 to 14 do
begin
gotoxy(70,5+i);writeln('|');
end;
gotoxy(70,20);write('+');
for i:=1 to 40 do
begin
gotoxy(29+i,20);write('-');
end;
for i:= 1 to 14 do
begin
gotoxy(29,5+i);writeln('|');
end;
gotoxy(29,20);write('+');
end;
procedure simpanDataKeFile;
var
f:file of TPark;
i:integer;
begin
clrscr;
kotak;
assign(f, namafile);
rewrite(f);
for i:=1 to banyakData do
write(f, tiket[i]);
close(f);
textcolor(green);
gotoxy(35,12);writeln(' BERHASIL MENYIMPAN ', banyakData, ' DATA');
gotoxy(32,13);writeln(' TEKAN ENTER UNTUK MENUTUP PROGRAM ');
readln;
end;
procedure hapusData;
var
i:integer;
begin
repeat
clrscr;
writeln('************************************** HAPUS DATA KENDARAAN ***********************************');
writeln(' HAPUS BERDASARKAN NAMA DAN NO KENDARAAN ');
gotoxy(35,10);write('Masukkan nama : ');readln(namaCari);
gotoxy(35,11);write('Masukkan no kendaraan : ');readln(noCari);
namaCari := upcase(namaCari);
noCari := upcase(noCari);
i:=index(namaCari,noCari);
if searchData(namaCari, noCari) then
begin
for i := index(namaCari,noCari) to banyakData - 1 do
begin
tiket[i]:=tiket[i+1];
end;
banyakData:=banyakData - 1;
tiket[i].statusHapus := true;
gotoxy(40,13);writeln('DATA BERHASIL DIHAPUS!!!');
end
else if searchData(namaCari, noCari) = false then
begin
gotoxy(42,13);writeln('DATA INVALID!!!');
end;
gotoxy(37,14);write('Hapus data kembali?[Y/N] : ');readln(ulangi);
until (upcase(ulangi) = 'N');
end;
{function duplikasi(nama, noKendaraan : string):boolean;
var i : integer;
begin
i:=0;
found:=false;
while (tiket[i].nama <> nama) or (tiket[i].noKendaraan <> noKendaraan)do
begin
i:=i+1;
if (tiket[i].nama = nama) or (tiket[i].noKendaraan = noKendaraan) then
begin
banyakData := banyakData -1;
found:=true;
end
else
banyakData := banyakData;
end;
if found then
duplikasi := found
else
duplikasi:=false;
end;}
procedure tambahData;
var i:integer;
begin
repeat
clrscr;
if banyakData < maks then
begin
banyakData := banyakData + 1;
writeln('========================================== TAMBAH DATA ========================================');
gotoxy(38,3);writeln('Penambahan data ke - ',banyakData);
writeln;
with tiket[banyakData] do
begin
//i:=index(nama, noKendaraan);
//repeat
write('Nama : ');readln(nama);
write('Nomer Kendaraan : ');readln(noKendaraan);
noKendaraan:=upcase(noKendaraan);
nama:=upcase(nama);
//until (searchData(nama,noKendaraan)=true) and (tiket[i].nama <> nama) or (tiket[i].noKendaraan <> noKendaraan);
repeat
write('Jenis Kendaraan [motor,mobil,truk,bus] : ');readln(jenisKendaraan);
jenisKendaraan := upcase(jenisKendaraan);
until (jenisKendaraan = 'MOTOR') or (jenisKendaraan = 'MOBIL') or (jenisKendaraan = 'TRUK') or (jenisKendaraan = 'BUS');
write('Lama Parkir per jam : ');readln(lamaParkir);
if jenisKendaraan = 'MOTOR' then
bayarParkir := 2000*lamaParkir
else if jenisKendaraan = 'MOBIL' then
bayarParkir := 3000*lamaParkir
else if jenisKendaraan = 'TRUK' then
bayarParkir := 4000*lamaParkir
else if jenisKendaraan = 'BUS' then
bayarParkir := 5000*lamaParkir;
end;
end
else
writeln('Data telah penuh.');
gotoxy(38,11);writeln('DATA BERHASIL DI TAMBAH!!');
gotoxy(36,12);write('Tambah data kembali?[Y/N] : ');readln(ulangi);
until (upcase(ulangi) = 'N');
end;
procedure viewData;
var
i:integer;
begin
clrscr;
for i:= 1 to banyakData do
begin
if tiket[i].statusHapus <> false then
begin
writeln('********************************DATA TIKET PARKIR MALL APA ADANYA******************************');
writeln(' Jl.Kenangan mantan no.123 ');
writeln('-----------------------------------------------------------------------------------------------');
writeln('| NO | NAMA | NOMER KENDARAAN | JENIS KENDARAAN | DURASI[jam] | BAYAR |');
writeln('-----------------------------------------------------------------------------------------------');
for i:=1 to banyakData do
begin
writeln('| ',i:2,' ',
'| ',format('%-15s',[tiket[i].nama]),' ',
'| ',format('%-17s',[tiket[i].noKendaraan]),' ',
'| ',format('%-17s',[tiket[i].jenisKendaraan]),' ',
'| ',format('%-13d',[tiket[i].lamaParkir]),' ',
'| ',format('%-10g',[tiket[i].bayarParkir]), ' |');
end;
writeln('-----------------------------------------------------------------------------------------------');
writeln('TEKAN ENTER UNTUK KEMBALI');
readln;
end;
end;
end;
procedure bacaDataDariFile;
var
f:file of TPark;
begin
clrscr;
kotak;
gotoxy(30,11);writeln(' SELAMAT DATANG DI MALL APA ADANYA ');
gotoxy(30,12);writeln(' Jl.Kenangan Mantan no.123 Bandung ');
gotoxy(30,13);writeln(' Buka Setiap Hari 7x24 Jam ');
gotoxy(30,14);writeln(' TEKAN ENTER UNTUK MEMULAI ');
assign(f, namaFile);
{$i-}
reset(f);
{$i+}
if IOResult <> 0 then
rewrite(f);
banyakData:=0;
while not eof(f) do
begin
banyakData:=banyakData + 1;
read(f,tiket[banyakData]);
end;
close(f);
readln;
end;
procedure cariKendaraan;
var
i:integer;
begin
repeat
clrscr;
writeln('====================================== CARI DATA KENDARAAN ====================================');
writeln(' Pihak Mall Tidak Bertanggung Jawab Atas Kehilangan Kendaraan Anda ');
writeln('-----------------------------------------------------------------------------------------------');
writeln;
gotoxy(26,7);writeln('Cari data berdasarkan nama dan nomor kendaraan');
gotoxy(37,9);write('Masukkan nama : ');readln(namaCari);
gotoxy(37,10);write('Masukkan no kendaraan : ');readln(noCari);
namaCari:=upcase(namaCari);
noCari:=upcase(noCari);
i:=index(namaCari, noCari);
if searchData(namaCari, noCari) then
begin
clrscr;
writeln('================================= DATA KENDARAAN DITEMUKAN !!! ================================');
writeln('| NO | NAMA | NOMER KENDARAAN | JENIS KENDARAAN | DURASI[jam] | BAYAR |');
writeln('-----------------------------------------------------------------------------------------------');
writeln('| ',i:2,' ',
'| ',format('%-15s',[tiket[i].nama]),' ',
'| ',format('%-17s',[tiket[i].noKendaraan]),' ',
'| ',format('%-17s',[tiket[i].jenisKendaraan]),' ',
'| ',format('%-13d',[tiket[i].lamaParkir]),' ',
'| ',format('%-10g',[tiket[i].bayarParkir]), ' |');
writeln('-----------------------------------------------------------------------------------------------');
end
else if searchData(namaCari, noCari) = false then
begin
gotoxy(42,12);writeln('DATA INVALID!!!');
end;
write('Cari data kembali?[Y/N] : ');readln(ulangi);
until (upcase(ulangi) = 'N');
end;
procedure editData;
var
i:integer;
begin
repeat
clrscr;
writeln('========================================== EDIT DATA ==========================================');
writeln(' EDIT DATA SESUAI DENGAN KRITERIA ');
writeln('-----------------------------------------------------------------------------------------------');
writeln;
gotoxy(21,8);writeln('ISI DATA MANA YANG MAU DIUBAH MENGGUNAKAN NAMA DAN NOMOR');
gotoxy(35,10);write('Masukkan nama : ');readln(namaCari);
gotoxy(35,11);write('Masukkan no kendaraan : ');readln(noCari);
namaCari:=upcase(namaCari);
noCari:=upcase(noCari);
i:=index(namaCari, noCari);
if searchData(namaCari, noCari) then
begin
clrscr;
writeln('================================= DATA KENDARAAN DIUBAH !!! ===================================');
writeln(' SILAHKAN EDIT DATANYA ');
writeln('-----------------------------------------------------------------------------------------------');
with tiket[i] do
begin
write('Masukkan Nama Pengguna : ');readln(nama);
write('Masukkan No Kendaraan : ');readln(noKendaraan);
write('Masukkan Jenis Kendaraan [motor,mobil,truk,bus] : ');readln(jenisKendaraan);
write('Masukkan Durasi[jam] : ');readln(lamaParkir);
nama:=upcase(nama);
noKendaraan:=upcase(noKendaraan);
jenisKendaraan:=upcase(jenisKendaraan);
if jenisKendaraan = 'MOTOR' then
bayarParkir := 2000*lamaParkir
else if jenisKendaraan = 'MOBIL' then
bayarParkir := 3000*lamaParkir
else if jenisKendaraan = 'TRUK' then
bayarParkir := 4000*lamaParkir
else if jenisKendaraan = 'BUS' then
bayarParkir := 5000*lamaParkir;
writeln('Bayar Parkir Anda Yang Baru : ', bayarParkir:0:0);
end;
writeln('==================================== DATA BERHASIL DIUBAH !!! =================================');
writeln('-----------------------------------------------------------------------------------------------');
end
else if searchData(namaCari, noCari) = false then
begin
gotoxy(40,13);writeln('DATA INVALID!!!');
end;
write('Edit data kembali?[Y/N] : ');readln(ulangi);
until (upcase(ulangi) = 'N');
end;
begin
textcolor(11);
banyakData:=0;
bacaDataDariFile;
repeat
clrscr;
writeln('=================================== PROGRAM TIKETING PARKIR ===================================');
writeln(' MALL APA ADANYA ');
writeln(' Jl.Kenangan mantan no.123 Bandung ');
writeln('===============================================================================================');
writeln;
gotoxy(40,8);writeln('1. Penambahan Data');
gotoxy(40,9);writeln('2. View Data');
gotoxy(40,10);writeln('3. Hapus Data Perorang');
gotoxy(40,11);writeln('4. Edit Data');
gotoxy(40,12);writeln('5. Cari Data');
gotoxy(40,13);writeln('6. Urutkan Data');
gotoxy(40,14);writeln('0. Keluar dari Aplikasi');
gotoxy(40,15);write('Pilihan Anda : ');readln(pilihanMenu);
case pilihanMenu of
1: tambahData;
2: viewData;
3: hapusData;
4: editData;
5: cariKendaraan;
6: tampilUrut;
end;
until pilihanMenu = 0;
simpanDataKeFile;
end.
|
unit VSoft.CommandLine.Utils;
interface
function GetConsoleWidth : integer;
implementation
uses
{$IFDEF MSWINDOWS}
Windows,
{$ENDIF}
System.SysUtils,
System.StrUtils;
{$IFDEF MSWINDOWS}
function GetConsoleWidth : integer;
var
info : CONSOLE_SCREEN_BUFFER_INFO;
hStdOut : THandle;
begin
Result := High(Integer); // Default is unlimited width
hStdOut := GetStdHandle(STD_OUTPUT_HANDLE);
if GetConsoleScreenBufferInfo(hStdOut, info) then
Result := info.dwSize.X;
end;
{$ENDIF}
{$IFDEF MACOS}
function GetConsoleWidth : integer;
begin
result := 80;
//TODO : Find a way to get the console width on osx
end;
{$ENDIF}
end.
|
unit ibSHDDLHistory;
interface
uses
SysUtils, Classes,
SHDesignIntf, SHOptionsIntf,
pSHSqlTxtRtns, pSHStrUtil,
ibSHMessages, ibSHConsts, ibSHDesignIntf, ibSHTool, ibSHComponent, ibSHValues;
type
TibSHDDLHistory = class(TibBTTool, IibSHDDLHistory, IibSHBranch, IfbSHBranch)
private
FItems: TStringList;
FNewItems: TStringList;
FActive: Boolean;
protected
procedure SetOwnerIID(Value: TGUID); override;
{ IibSHDDLHistory }
function GetActive: Boolean;
procedure SetActive(const Value: Boolean);
function GetHistoryFileName: string;
function Count: Integer;
procedure Clear;
function Statement(Index: Integer): string;
function Item(Index: Integer): string;
function AddStatement(AStatement: string): Integer;
procedure CommitNewStatements;
procedure RollbackNewStatements;
procedure LoadFromFile;
procedure SaveToFile;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Active: Boolean read GetActive write SetActive;
end;
TibSHDDLHistoryFactory = class(TibBTComponentFactory)
function SupportComponent(const AClassIID: TGUID): Boolean; override;
function CreateComponent(const AOwnerIID, AClassIID: TGUID; const ACaption: string): TSHComponent; override;
end;
procedure Register;
implementation
uses
ibSHDDLHistoryActions,
ibSHDDLHistoryEditors;
procedure Register;
begin
SHRegisterImage(GUIDToString(IibSHDDLHistory), 'DDLHistory.bmp');
SHRegisterImage(TibSHDDLHistoryPaletteAction.ClassName, 'DDLHistory.bmp');
SHRegisterImage(TibSHDDLHistoryFormAction.ClassName, 'Form_DDLText.bmp');
SHRegisterImage(TibSHDDLHistoryToolbarAction_Run.ClassName, 'Button_Run.bmp');
SHRegisterImage(TibSHDDLHistoryToolbarAction_Pause.ClassName, 'Button_Stop.bmp');
SHRegisterImage(TibSHDDLHistoryToolbarAction_Region.ClassName, 'Button_Tree.bmp');
SHRegisterImage(TibSHDDLHistoryToolbarAction_Refresh.ClassName, 'Button_Refresh.bmp');
SHRegisterImage(TibSHDDLHistoryToolbarAction_Save.ClassName, 'Button_Save.bmp');
SHRegisterImage(SCallDDLStatements, 'Form_DDLText.bmp');
SHRegisterComponents([
TibSHDDLHistory,
TibSHDDLHistoryFactory]);
SHRegisterActions([
// Palette
TibSHDDLHistoryPaletteAction,
// Forms
TibSHDDLHistoryFormAction,
// Toolbar
TibSHDDLHistoryToolbarAction_Run,
TibSHDDLHistoryToolbarAction_Pause,
TibSHDDLHistoryToolbarAction_Region,
TibSHDDLHistoryToolbarAction_Refresh,
TibSHDDLHistoryToolbarAction_Save,
// Editors
TibSHDDLHistoryEditorAction_SendToSQLEditor,
TibSHDDLHistoryEditorAction_ShowDDLHistory]);
end;
{ TibSHDDLHistory }
constructor TibSHDDLHistory.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FItems := TStringList.Create;
FNewItems := TStringList.Create;
end;
destructor TibSHDDLHistory.Destroy;
begin
FItems.Free;
FNewItems.Free;
inherited;
end;
procedure TibSHDDLHistory.SetOwnerIID(Value: TGUID);
var
vDatabaseAliasOptionsInt: IibSHDatabaseAliasOptionsInt;
begin
if not IsEqualGUID(OwnerIID, Value) then
begin
inherited SetOwnerIID(Value);
if Supports(BTCLDatabase, IibSHDatabaseAliasOptionsInt, vDatabaseAliasOptionsInt) then
Active := vDatabaseAliasOptionsInt.DDLHistoryActive
else
Active := True;
LoadFromFile;
end;
end;
function TibSHDDLHistory.GetActive: Boolean;
begin
Result := FActive;
end;
procedure TibSHDDLHistory.SetActive(const Value: Boolean);
begin
FActive := Value;
end;
function TibSHDDLHistory.GetHistoryFileName: string;
var
vDir: string;
begin
Result := EmptyStr;
if Assigned(BTCLDatabase) then
begin
vDir := BTCLDatabase.DataRootDirectory;
if SysUtils.DirectoryExists(vDir) then
Result := vDir + DDLHistoryFile;
vDir := ExtractFilePath(Result);
if not SysUtils.DirectoryExists(vDir) then
ForceDirectories(vDir);
end;
end;
function TibSHDDLHistory.Count: Integer;
begin
Result := FItems.Count;
end;
procedure TibSHDDLHistory.Clear;
var
I: Integer;
vDDLHistoryForm: IibSHDDLHistoryForm;
begin
FItems.Clear;
SaveToFile;
for I := 0 to Pred(ComponentForms.Count) do
if Supports(ComponentForms[I], IibSHDDLHistoryForm, vDDLHistoryForm) then
begin
vDDLHistoryForm.FillEditor;
end;
end;
function TibSHDDLHistory.Statement(Index: Integer): string;
var
vPosFirstLineEnd: Integer;
begin
Result := EmptyStr;
if (Index >= 0) and (Index < Count) then
begin
vPosFirstLineEnd := Pos(sLineBreak, FItems[Index]);
if vPosFirstLineEnd > 0 then
Result := Copy(FItems[Index], vPosFirstLineEnd + Length(sLineBreak), MaxInt);
end;
end;
function TibSHDDLHistory.Item(Index: Integer): string;
begin
Result := EmptyStr;
if (Index >= 0) and (Index < Count) then
Result := FItems[Index];
end;
function TibSHDDLHistory.AddStatement(AStatement: string): Integer;
var
vItem: string;
// I: Integer;
// vDDLHistoryForm: IibSHDDLHistoryForm;
vFirstWord: string;
vSecondWord: string;
vStatement: string;
begin
Result := -1;
if Active then
begin
vStatement := Trim(AStatement);
vFirstWord := ExtractWord(1, vStatement, CharsAfterClause);
vSecondWord := ExtractWord(2, vStatement, CharsAfterClause);
if (not SameText(vFirstWord, 'DROP')) and
(SameText(vSecondWord, 'PROCEDURE') or SameText(vSecondWord, 'TRIGGER')) then
begin
while (Length(vStatement) > 0) and (vStatement[Length(vStatement)] in [';', '^']) do
Delete(vStatement, Length(vStatement), 1);
vStatement := Format('SET TERM ^ ;' + sLineBreak + sLineBreak + '%s^' + sLineBreak + sLineBreak + 'SET TERM ; ^', [vStatement]);
end
else
if (Length(vStatement) > 0) and (vStatement[Length(vStatement)] <> ';') then
vStatement := vStatement + ';';
vItem := Format(sHistorySQLHeader + sHistorySQLHeaderSuf, [DateTimeToStr(Now)]) +
sLineBreak +
vStatement +
sLineBreak + sLineBreak;
// Result := FItems.Add(vItem);
Result := FNewItems.Add(vItem);
// for I := 0 to Pred(ComponentForms.Count) do
// if Supports(ComponentForms[I], IibSHDDLHistoryForm, vDDLHistoryForm) then
// begin
// vDDLHistoryForm.ChangeNotification;
// Break;
// end;
//Если есть форма, то она, проверив ручные изменения сама добавит новый сиквел к файлу истории
//Если формы нет, добавляем сиквел здесь к файлу истории
// if not Assigned(vDDLHistoryForm) then
// begin
// vFileName := GetHistoryFileName;
// if Length(vFileName) > 0 then
// AddToTextFile(vFileName, vItem);
// end;
end;
end;
procedure TibSHDDLHistory.CommitNewStatements;
var
I: Integer;
vDDLHistoryForm: IibSHDDLHistoryForm;
vFileName: string;
begin
for I := 0 to Pred(FNewItems.Count) do
FItems.Add(FNewItems[I]);
if GetComponentFormIntf(IibSHDDLHistoryForm, vDDLHistoryForm) then
vDDLHistoryForm.ChangeNotification
else
//Если есть форма, то она, проверив ручные изменения сама добавит новый сиквел к файлу истории
//Если формы нет, добавляем сиквелы здесь к файлу истории
begin
vFileName := GetHistoryFileName;
if Length(vFileName) > 0 then
for I := 0 to Pred(FNewItems.Count) do
AddToTextFile(vFileName, FNewItems[I]);
end;
FNewItems.Clear;
end;
procedure TibSHDDLHistory.RollbackNewStatements;
begin
FNewItems.Clear;
end;
procedure TibSHDDLHistory.LoadFromFile;
var
vFileName: string;
vTextFile: TextFile;
vItem: TStringList;
S: string;
begin
vFileName := GetHistoryFileName;
if FileExists(vFileName) then
begin
FItems.Clear;
vItem := TStringList.Create;
try
AssignFile(vTextFile, vFileName);
try
Reset(vTextFile);
while not Eof(vTextFile) do
begin
Readln(vTextFile, S);
if Pos(sHistorySQLHeader, S) > 0 then
begin
if vItem.Count = 0 then vItem.Add(S)
else
begin
FItems.Add(vItem.Text);
vItem.Clear;
vItem.Add(S)
end;
end
else
if vItem.Count > 0 then
vItem.Add(S);
end;
if vItem.Count > 0 then
FItems.Add(vItem.Text);
finally
CloseFile(vTextFile);
end;
finally
vItem.Free;
end;
end;
end;
procedure TibSHDDLHistory.SaveToFile;
var
I: Integer;
vFileName: string;
vTextFile: TextFile;
vSaved: Boolean;
begin
vSaved := False;
for I := 0 to Pred(ComponentForms.Count) do
if Supports(ComponentForms[I], IibSHDDLHistoryForm) and
Supports(ComponentForms[I], ISHFileCommands) then
begin
(ComponentForms[I] as ISHFileCommands).Save;
vSaved := True;
end;
if (not vSaved) then
begin
if (Count > 0) then
begin
vFileName := GetHistoryFileName;
if Length(vFileName) > 0 then
begin
AssignFile(vTextFile, vFileName);
try
Rewrite(vTextFile);
for I := 0 to Pred(Count) do
Writeln(vTextFile, FItems[I]);
finally
CloseFile(vTextFile);
end;
end;
end
else
begin
vFileName := GetHistoryFileName;
if (Length(vFileName) > 0) and FileExists(vFileName) then
DeleteFile(vFileName);
end;
end;
end;
{ TibSHDDLHistoryFactory }
function TibSHDDLHistoryFactory.CreateComponent(const AOwnerIID,
AClassIID: TGUID; const ACaption: string): TSHComponent;
var
BTCLDatabase: IibSHDatabase;
vSHSystemOptions: ISHSystemOptions;
begin
if IsEqualGUID(AOwnerIID, IUnknown) then
begin
Supports(Designer.CurrentDatabase, IibSHDatabase, BTCLDatabase);
if not Assigned(BTCLDatabase) and IsEqualGUID(AOwnerIID, IUnknown) and (Length(ACaption) = 0) then
Designer.AbortWithMsg(Format('%s', [SDatabaseIsNotInterBase]));
Result := Designer.FindComponent(Designer.CurrentDatabase.InstanceIID, AClassIID);
if not Assigned(Result) then
begin
Result := Designer.GetComponent(AClassIID).Create(nil);
Result.OwnerIID := Designer.CurrentDatabase.InstanceIID;
Result.Caption := Designer.GetComponent(AClassIID).GetHintClassFnc;
if Assigned(BTCLDatabase) and
Supports(Designer.GetOptions(ISHSystemOptions), ISHSystemOptions, vSHSystemOptions) and
(not vSHSystemOptions.UseWorkspaces) then
Result.Caption := Format('%s for %s', [Result.Caption, BTCLDatabase.Alias]);
end;
Designer.ChangeNotification(Result, SCallDDLStatements, opInsert);
end
else
begin
if Supports(Designer.FindComponent(AOwnerIID), IibSHDatabase, BTCLDatabase) then
begin
Result := Designer.FindComponent(AOwnerIID, AClassIID);
if not Assigned(Result) then
begin
Result := Designer.GetComponent(AClassIID).Create(nil);
Result.OwnerIID := AOwnerIID;
Result.Caption := Designer.GetComponent(AClassIID).GetHintClassFnc;
if Assigned(BTCLDatabase) and
Supports(Designer.GetOptions(ISHSystemOptions), ISHSystemOptions, vSHSystemOptions) and
(not vSHSystemOptions.UseWorkspaces) then
Result.Caption := Format('%s for %s', [Result.Caption, BTCLDatabase.Alias]);
end;
Designer.ChangeNotification(Result, SCallDDLStatements, opInsert);
end
else
Designer.AbortWithMsg(Format('%s', [SDatabaseIsNotInterBase]));
end;
end;
function TibSHDDLHistoryFactory.SupportComponent(
const AClassIID: TGUID): Boolean;
begin
Result := IsEqualGUID(AClassIID, IibSHDDLHistory);
end;
initialization
Register;
end.
|
namespace org.me.openglsquare;
{$define LOG_FPS}
interface
uses
android.content,
android.opengl,
android.util,
java.nio,
javax.microedition.khronos.opengles,
javax.microedition.khronos.egl;
type
GLSquareRenderer = public class(GLSurfaceView.Renderer)
private
const Tag = 'GLSquareRenderer';
var mVertexBuffer: FloatBuffer;
var mColorBuffer: ByteBuffer;
var startTime: Int64;
{$ifdef LOG_FPS}
var numFrames: Integer;
var fpsStartTime : Int64;
{$endif}
public
constructor;
method OnSurfaceCreated(gl: GL10; config: EGLConfig);
method OnSurfaceChanged(gl: GL10; width, height: Integer);
method OnDrawFrame(gl: GL10);
end;
implementation
constructor GLSquareRenderer;
begin
// Buffers to be passed to gl*Pointer() functions must be
// direct, i.e., they must be placed on the native heap
// where the garbage collector cannot move them.
//
// Buffers with multi-SByte data types (e.g., short, int,
// float) must have their SByte order set to native order
var vertices: array of Single := [
-1, -1,
1, -1,
-1, 1,
1, 1];
var vbb := ByteBuffer.allocateDirect(vertices.length * 4);
vbb.order(ByteOrder.nativeOrder());
mVertexBuffer := vbb.asFloatBuffer();
mVertexBuffer.put(vertices);
mVertexBuffer.position(0);
var colors: array of SByte := [
255 as Integer, 255 as Integer, 0, 255 as Integer, //yellow
0, 255 as Integer, 255 as Integer, 255 as Integer, //cyan
0, 0, 0, 255 as Integer, //black
255 as Integer, 0, 255 as Integer, 255 as Integer]; //purple
mColorBuffer := ByteBuffer.allocateDirect(colors.length);
mColorBuffer.order(ByteOrder.nativeOrder());
mColorBuffer.put(colors);
mColorBuffer.position(0);
end;
method GLSquareRenderer.OnSurfaceCreated(gl: GL10; config: EGLConfig);
begin
startTime := System.currentTimeMillis();
{$ifdef LOG_FPS}
fpsStartTime := startTime;
numFrames := 0;
{$endif}
// Set up any OpenGL options we need
//Enable depth-testing
gl.glEnable(GL10.GL_DEPTH_TEST);
//Specifically <= type depth-testing
gl.glDepthFunc(GL10.GL_LEQUAL);
//Set clearing colour to grey
gl.glClearColor(0.5, 0.5, 0.5, 1);
// Optional: disable dither to boost performance
// gl.glDisable(GL10.GL_DITHER);
end;
//Called e.g. if device rotated
method GLSquareRenderer.OnSurfaceChanged(gl: GL10; width, height: Integer);
begin
//Set current view port to new size
gl.glViewport(0, 0, width, height);
//Select projection matrix
gl.glMatrixMode(GL10.GL_PROJECTION);
//Reset projection matrix
gl.glLoadIdentity();
var ratio := Single(width) / height;
//Calculate window aspect ratio
gl.glFrustumf(-ratio, ratio, -1, 1, 1, 10);
end;
method GLSquareRenderer.OnDrawFrame(gl: GL10);
begin
var elapsed := System.currentTimeMillis() - startTime;
// Clear the screen
gl.glClear(GL10.GL_COLOR_BUFFER_BIT or GL10.GL_DEPTH_BUFFER_BIT);
// Position model so we can see it, and spin it
//Select model view matrix
gl.glMatrixMode(GL10.GL_MODELVIEW);
//Reset model view matrix
gl.glLoadIdentity();
//Move viewpoint 3 steps out of the screen
gl.glTranslatef(0, 0, -3);
//Rotate view 40 degrees per second
gl.glRotatef(elapsed * (40.0/1000), 0, 0, 1);
// Draw the shape
//Enable vertex buffer for writing to and to be used during render
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
//Identify vertex buffer and its format
gl.glVertexPointer(2, GL10.GL_FLOAT, 0, mVertexBuffer);
//Enable colour array buffer for use in rendering
gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
//Identify the colour array buffer
gl.glColorPointer(4, GL10.GL_UNSIGNED_BYTE, 0, mColorBuffer);
//Draw triangle strips from the 4 coordinates - 2 triangles
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4);
{$ifdef LOG_FPS}
// Keep track of number of frames drawn
inc(numFrames);
var fpsElapsed := System.currentTimeMillis() - fpsStartTime;
if fpsElapsed > 5 * 1000 then
begin
// every 5 seconds
var fps := (numFrames * 1000) / fpsElapsed;
Log.d(Tag, 'Frames per second: ' + fps + ' (' + numFrames + ' frames in ' + fpsElapsed + ' ms)');
fpsStartTime := System.currentTimeMillis();
numFrames := 0
end
{$endif}
end;
end. |
unit CFBalloonHint;
interface
uses
Windows, Classes, Controls, Messages, SysUtils, Graphics, CFMMTimer;
type
TBalloonAlignment = (cbaCenter, cbaFollowMouse);
TCFBalloonHint = class(TObject)
private
FHintWindow: HWND;
FTimer: TCFMMTimer;
FAlignment: TBalloonAlignment;
FText: string;
FColor: TColor;
FAlpha: Byte;
//FOnDely: TNotifyEvent;
procedure IniFont(var AFont: TLogFont);
function GetDelay: Cardinal;
procedure SetDelay(const Value: Cardinal);
procedure DoDelayTimer(Sender: TObject);
procedure DoPaintHint(const ADC: HDC);
procedure SetText(const AText: string);
protected
procedure RegFormClass;
procedure CreateHandle;
procedure WndProc(var Message: TMessage); virtual;
public
constructor Create(const AAlpha: Byte = 255); virtual;
destructor Destroy; override;
procedure ShowHint; overload;
procedure ShowHint(const AControl: TWinControl); overload;
property Delay: Cardinal read GetDelay write SetDelay;
property Text: string read FText write SetText;
property Color: TColor read FColor write FColor;
property Alpha: Byte read FAlpha;
end;
procedure BalloonMessage(const AText: string; const AWarning: Boolean = False;
const ADelay: Cardinal = 1500); overload;
procedure BalloonMessage(const AControl: TWinControl; const AText: string;
const ADelay: Cardinal = 1500); overload;
implementation
uses
TypInfo, MMSystem;
var
FMouseHook: HHOOK;
FHW: HWND;
procedure BalloonMessage(const AText: string; const AWarning: Boolean = False;
const ADelay: Cardinal = 1500);
{procedure DoBalloonOnDely(Sender: TObject);
begin
FreeAndNil(TCFBalloonHint(Sender));
end;}
var
vBalloonHint: TCFBalloonHint;
//vMth: TMethod;
begin
vBalloonHint := TCFBalloonHint.Create(200);
vBalloonHint.Delay := ADelay;
vBalloonHint.Text := AText;
if AWarning then
vBalloonHint.Color := $008080FF
else
vBalloonHint.Color := $00A6D268;
//vMth.Data := vBalloonHint;
//vMth.Code := @DoBalloonOnDely;
//SetMethodProp(vBalloonHint, 'OnDely', vMth);
//System.TypInfo.SetMethodProp(vBalloonHint, 'OnDely', vMth);
vBalloonHint.ShowHint;
end;
procedure BalloonMessage(const AControl: TWinControl; const AText: string;
const ADelay: Cardinal = 1500);
var
vBalloonHint: TCFBalloonHint;
begin
vBalloonHint := TCFBalloonHint.Create;
vBalloonHint.Delay := ADelay;
vBalloonHint.Text := AText;
vBalloonHint.ShowHint(AControl);
end;
{ TCFBalloonHint }
constructor TCFBalloonHint.Create(const AAlpha: Byte = 255);
begin
inherited Create;
FHintWindow := 0;
FMouseHook := 0;
FColor := $00E1FFFF; // clInfoBK
FAlpha := AAlpha;
FText := '';
RegFormClass;
CreateHandle;
FHW := FHintWindow;
FAlignment := cbaFollowMouse;
FTimer := TCFMMTimer.Create;
FTimer.OnTimer := DoDelayTimer;
end;
procedure TCFBalloonHint.CreateHandle;
var
vClassName: string;
begin
if not IsWindow(FHintWindow) then // 如果提示窗体没有创建
begin
vClassName := ClassName;
FHintWindow := CreateWindowEx(
WS_EX_TOPMOST or WS_EX_TOOLWINDOW{顶层窗口} or WS_EX_LAYERED,
PChar(vClassName),
nil,
WS_POPUP or WS_DISABLED, // 弹出式窗口,支持双击
0, 0, 100, 20, 0, 0, HInstance, nil);
SetLayeredWindowAttributes(FHintWindow, 0, FAlpha, LWA_ALPHA);
SetWindowLong(FHintWindow, GWL_WNDPROC, Longint(MakeObjectInstance(WndProc))); // 窗口函数替换为类方法
end;
end;
destructor TCFBalloonHint.Destroy;
begin
if FMouseHook<> 0 then
UnhookWindowsHookEx(FMouseHook);
FreeAndNil(FTimer);
//SendMessage(FPopupWindow, WM_DESTROY, 0, 0);
if IsWindow(FHintWindow) then
begin
if DestroyWindow(FHintWindow) then
FHintWindow := 0
else
raise Exception.Create('释放出错:' + IntToStr(GetLastError));
end;
FHW := FHintWindow;
inherited Destroy;
end;
procedure TCFBalloonHint.DoDelayTimer(Sender: TObject);
begin
//FreeAndNil(Self); // 自己里面释放自己不行,是因为创建窗体和释放不在同一线程而导致无法释放吗?
// 利用了WM_CLOSE消息里释放
SendMessage(FHintWindow, WM_CLOSE, 0, 0);
end;
procedure TCFBalloonHint.DoPaintHint(const ADC: HDC);
var
vRect: TRect;
//vCanvas: TCanvas;
vBrush: HBRUSH;
vLogFont: TLogFont;
vFont, vFontOld: HFONT;
vIcon: TIcon;
begin
GetClientRect(FHintWindow, vRect);
{vCanvas := TCanvas.Create;
try
vCanvas.Handle := ADC;
DrawText(ADC, FText, -1, vRect, DT_SINGLELINE or DT_CENTER);
finally
FreeAndNil(vCanvas);
end;}
vBrush := CreateSolidBrush(FColor);
try
FillRect(ADC, vRect, vBrush);
finally
DeleteObject(vBrush)
end;
vIcon := TIcon.Create;
try
vIcon.Handle := LoadIcon(MainInstance, 'MAINICON');
DrawIconEx(ADC, vRect.Left + 4, vRect.Top + (vRect.Bottom - vRect.Top - 16) div 2, vIcon.Handle, 16, 16, 0, 0, DI_NORMAL);
//DrawIcon(ADC, vRect.Left, vRect.Top, FIcon.Handle);
vRect.Left := vRect.Left + 20;
finally
vIcon.Free;
end;
IniFont(vLogFont);
vFont := CreateFontIndirect(vLogFont);
vFontOld := SelectObject(ADC, vFont);
try
//SetTextColor(ADC, clBlue);
//if FTransparent then
SetBkMode(ADC, Windows.TRANSPARENT); { 文本背景透明模式 }
DrawText(ADC, FText, -1, vRect, DT_SINGLELINE or DT_CENTER or DT_VCENTER);
finally
DeleteObject(vFont);
DeleteObject(vFontOld);
end;
end;
function TCFBalloonHint.GetDelay: Cardinal;
begin
Result := FTimer.Internal;
end;
procedure TCFBalloonHint.IniFont(var AFont: TLogFont);
begin
AFont.lfHeight := -16;
AFont.lfWidth := 0;
AFont.lfEscapement := 0;
AFont.lfWeight := 600;
AFont.lfItalic := 0;
AFont.lfUnderline := 0;
AFont.lfStrikeOut := 0;
AFont.lfFaceName := '宋体';
end;
procedure TCFBalloonHint.RegFormClass;
var
vWndCls: TWndClassEx;
vClassName: string;
begin
vClassName := ClassName;
if not GetClassInfoEx(HInstance, PChar(vClassName), vWndCls) then
begin
vWndCls.cbSize := SizeOf(TWndClassEx);
vWndCls.lpszClassName := PChar(vClassName);
vWndCls.style := CS_VREDRAW or CS_HREDRAW
or CS_DROPSHADOW or CS_DBLCLKS; // 通过此样式实现窗口边框阴影效果,只能在注册窗口类时使用此属性,注册后可通过SetClassLong(Handle, GCL_STYLE, GetClassLong(Handle, GCL_STYLE) or CS_DROPSHADOW);再增加
vWndCls.hInstance := HInstance;
vWndCls.lpfnWndProc := @DefWindowProc;
vWndCls.cbClsExtra := 0;
vWndCls.cbWndExtra := SizeOf(DWord) * 2;
vWndCls.hIcon := LoadIcon(hInstance,MakeIntResource('MAINICON'));
vWndCls.hIconSm := LoadIcon(hInstance,MakeIntResource('MAINICON'));
vWndCls.hCursor := LoadCursor(0, IDC_ARROW);
vWndCls.hbrBackground := GetStockObject(white_Brush);
vWndCls.lpszMenuName := nil;
if RegisterClassEx(vWndCls) = 0 then
raise Exception.Create('异常:注册类' + vClassName + '错误!');
end;
end;
procedure TCFBalloonHint.SetDelay(const Value: Cardinal);
begin
FTimer.Internal := Value;
end;
procedure TCFBalloonHint.SetText(const AText: string);
var
vDC: HDC;
vSize: TSize;
vLogFont: TLogFont;
vFont, vFontOld: HFONT;
vRgn: HRGN;
begin
if FText <> AText then
begin
FText := AText;
vDC := CreateCompatibleDC(0);
try
IniFont(vLogFont);
vFont := CreateFontIndirect(vLogFont);
vFontOld := SelectObject(vDC, vFont);
try
Windows.GetTextExtentPoint32(vDC, FText, Length(FText), vSize);
finally
DeleteObject(vFont);
DeleteObject(vFontOld);
end;
SetWindowPos(FHintWindow, 0, 0, 0, vSize.cx + 10 + 20, vSize.cy + 10, SWP_NOACTIVATE{无焦点} or SWP_NOZORDER);
vRgn := CreateRoundRectRgn(0, 0, vSize.cx + 10 + 20, vSize.cy + 10, 5, 5);
try
SetWindowRgn(FHintWindow, vRgn, True);
finally
DeleteObject(vRgn);
end;
finally
DeleteDC(vDC);
end;
end;
end;
procedure TCFBalloonHint.ShowHint(const AControl: TWinControl);
var
vBound: TRect;
vX, vY, vW, vH: Integer;
begin
GetWindowRect(AControl.Handle, vBound);
vW := vBound.Right - vBound.Left;
vH := vBound.Bottom - vBound.Top;
vX := vBound.Left + vW div 2;
vY := vBound.Top - 20;
//
MoveWindow(FHintWindow, vX, vY, vW, vH, True);
ShowWindow(FHintWindow, SW_SHOWNOACTIVATE);
FTimer.Enable := True;
end;
{钩子函数, 鼠标消息太多(譬如鼠标移动), 必须要有选择, 这里选择了鼠标左键按下}
function MouseHook(nCode: Integer; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall;
var
vBound: TRect;
vX, vY, vW, vH: Integer;
begin
if wParam = WM_MOUSEMOVE then
begin
GetWindowRect(FHW, vBound);
vW := vBound.Right - vBound.Left;
vH := vBound.Bottom - vBound.Top;
GetCursorPos(vBound.TopLeft);
vX := vBound.Left + 20;
vY := vBound.Top;
MoveWindow(FHW, vX, vY, vW, vH, False);
end;
Result := CallNextHookEx(FMouseHook, nCode, wParam, lParam);
end;
procedure TCFBalloonHint.ShowHint;
var
vBound: TRect;
vX, vY, vW, vH: Integer;
//vCursorInfo: TCursorInfo;
//vIconInfo: TIconInfo;
//vBITMPA: BITMAP;
begin
GetWindowRect(FHintWindow, vBound);
vW := vBound.Right - vBound.Left;
vH := vBound.Bottom - vBound.Top;
if FAlignment = cbaCenter then // 屏幕居中
begin
SystemParametersInfo(SPI_GETWORKAREA, 0, vBound, 0);
vX := ((vBound.Right - vBound.Left) - vW) div 2;
vY := ((vBound.Bottom - vBound.Top) - vH) div 2;
end
else // 鼠标跟随
begin
GetCursorPos(vBound.TopLeft);
{vCursorInfo.cbSize := SizeOf(vCursorInfo);
GetCursorInfo(vCursorInfo);
GetIconInfo(vCursorInfo.hCursor, vIconInfo);
GetObject(vIconInfo.hbmColor, sizeof(vBITMPA), @vBITMPA);}
vX := vBound.Left + 20; // + vBITMPA.bmWidth;
vY := vBound.Top; // + (vBITMPA.bmHeight - vH) div 2;
end;
//
MoveWindow(FHintWindow, vX, vY, vW, vH, True);
ShowWindow(FHintWindow, SW_SHOWNOACTIVATE);
FTimer.Enable := True;
FMouseHook := SetWindowsHookEx(WH_MOUSE, Addr(MouseHook), HInstance, GetCurrentThreadId);
end;
procedure TCFBalloonHint.WndProc(var Message: TMessage);
var
vDC: HDC;
vPS: PAINTSTRUCT;
begin
case Message.Msg of
WM_PAINT:
begin
vDC := BeginPaint(FHintWindow, vPS);
try
DoPaintHint(vDC);
finally
EndPaint(FHintWindow, vPS);
end;
end;
// WM_ACTIVATE:
// Message.Result := MA_NOACTIVATE;
WM_MOUSEACTIVATE:
Message.Result := MA_NOACTIVATE;
WM_NCACTIVATE:
Message.Result := 1;
WM_CLOSE:
begin
FreeAndNil(Self);
//Message.Result := DefWindowProc(FPopupWindow, Message.Msg, Message.WParam, Message.LParam);
end
else
Message.Result := DefWindowProc(FHintWindow, Message.Msg, Message.WParam, Message.LParam);
end;
end;
end.
|
unit uPais;
interface
uses
System.SysUtils;
type
TPais = class
private
FNomePais : String;
FPopulacao : Integer;
FDimensao : Extended;
function GetDimensao: Extended;
function GetNomePais: String;
function GetPopulacao: Integer;
procedure SetDimensao(const Value: Extended);
procedure SetNomePais(const Value: String);
procedure SetPopulacao(const Value: Integer);
public
property NomePais : String read GetNomePais write SetNomePais;
property Populacao : Integer read GetPopulacao write SetPopulacao;
property Dimensao : Extended read GetDimensao write SetDimensao;
function ToString : String; override;
end;
implementation
{ TPais }
function TPais.GetDimensao: Extended;
begin
Result := FDimensao;
end;
function TPais.GetNomePais: String;
begin
Result := FNomePais;
end;
function TPais.GetPopulacao: Integer;
begin
Result := FPopulacao;
end;
procedure TPais.SetDimensao(const Value: Extended);
begin
FDimensao := Value;
end;
procedure TPais.SetNomePais(const Value: String);
begin
FNomePais := Value;
end;
procedure TPais.SetPopulacao(const Value: Integer);
begin
FPopulacao := Value;
end;
function TPais.ToString: String;
begin
Result := 'Nome do país: ' + FNomePais + ' | '
+ 'População: ' + FPopulacao.ToString + ' | '
+ 'Dimensão: ' + FDimensao.ToString + sLineBreak
+ ' ' + sLineBreak;
end;
end.
|
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
{
Object with support for complex polygons.
}
{ TODO
And I reactivated the TVectorPool object. The VXS.VectorLists are not suitable for this job.
When the tesselator finds an intersection of edges it wants us to give him some storage
for this new vertex, and he wants a pointer (see tessCombine). The pointers taken from
TAffineVectorList become invalid after enlarging the capacity (makes a ReAllocMem), which
can happen implicitly while adding. The TVectorPool keeps all pointers valid until the
destruction itself.
If anyone feels responsible: it would be fine to have a method ImportFromFile (dxf?) in
the TVXContour and TVXMultiPolygonBase objects...
}
unit VXS.MultiPolygon;
interface
{$I VXScene.inc}
uses
System.Classes,
System.SysUtils,
VXS.OpenGL,
VXS.XOpenGL,
VXS.Spline,
VXS.Context,
VXS.VectorTypes,
VXS.VectorGeometry,
VXS.VectorLists,
VXS.PersistentClasses,
VXS.Scene,
VXS.Objects,
VXS.GeomObjects,
VXS.Nodes,
VXS.BaseClasses,
VXS.Coordinates,
VXS.RenderContextInfo;
type
TVXContourNodes = class(TVXNodes)
public
procedure NotifyChange; override;
end;
TVXContour = class(TCollectionItem)
private
FNodes: TVXContourNodes;
FDivision: Integer;
FSplineMode: TLineSplineMode;
FDescription: string;
procedure SetNodes(const Value: TVXContourNodes);
procedure SetDivision(Value: Integer);
procedure SetSplineMode(const Value: TLineSplineMode);
procedure SetDescription(const Value: string);
protected
procedure CreateNodes; virtual;
procedure NodesChanged(Sender: TObject);
function GetDisplayName: string; override;
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
published
property Description: string read FDescription write SetDescription;
{ The nodes list. }
property Nodes: TVXContourNodes read FNodes write SetNodes;
{ Number of divisions for each segment in spline modes.
Minimum 1 (disabled), ignored in lsmLines mode. }
property Division: Integer read FDivision write SetDivision default 10;
{ Default spline drawing mode.
This mode is used only for the curve, not for the rotation path. }
property SplineMode: TLineSplineMode read FSplineMode write SetSplineMode default lsmLines;
end;
TVXContourClass = class of TVXContour;
TVXContours = class(TVXNotifyCollection)
private
function GetItems(index: Integer): TVXContour;
procedure SetItems(index: Integer; const Value: TVXContour);
protected
public
constructor Create(AOwner: TComponent); overload;
function Add: TVXContour;
function FindItemID(ID: Integer): TVXContour;
property Items[index: Integer]: TVXContour read GetItems write SetItems; default;
procedure GetExtents(var min, max: TAffineVector);
end;
TPolygonList = class(TPersistentObjectList)
private
FAktList: TAffineVectorList;
function GetList(I: Integer): TAffineVectorList;
public
procedure Add;
property AktList: TAffineVectorList read FAktList;
property List[I: Integer]: TAffineVectorList read GetList;
end;
{ Multipolygon is defined with multiple contours.
The contours have to be in the X-Y plane, otherwise they are projected
to it (this is done automatically by the tesselator).
The plane normal is pointing in +Z. All contours are automatically closed,
so there is no need to specify the last node equal to the first one.
Contours should be defined counterclockwise, the first contour (index = 0)
is taken as is, all following are reversed. This means you can define the
outer contour first and the holes and cutouts after that. If you give the
following contours in clockwise order, the first contour is extended.
TMultiPolygonBase will take the input contours and let the tesselator
make an outline from it (this is done in RetreiveOutline). This outline is
used for Rendering. Only when there are changes in the contours, the
outline will be recalculated. The ouline in fact is a list of VXS.VectorLists. }
TMultiPolygonBase = class(TVXSceneObject)
private
FContours: TVXContours;
FOutline: TPolygonList;
FContoursNormal: TAffineVector;
FAxisAlignedDimensionsCache: TVector;
procedure SetContours(const Value: TVXContours);
function GetPath(i: Integer): TVXContourNodes;
procedure SetPath(i: Integer; const value: TVXContourNodes);
function GetOutline: TPolygonList;
procedure SetContoursNormal(const Value: TAffineVector);
protected
procedure RenderTesselatedPolygon(textured: Boolean;
normal: PAffineVector; invertNormals: Boolean);
procedure RetrieveOutline(List: TPolygonList);
procedure ContourChanged(Sender: TObject); virtual;
//property PNormal:PAffineVector read FPNormal;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure AddNode(const i: Integer; const coords: TVXCoordinates); overload;
procedure AddNode(const i: Integer; const X, Y, Z: Single); overload;
procedure AddNode(const i: Integer; const value: TVector); overload;
procedure AddNode(const i: Integer; const value: TAffineVector); overload;
property Path[i: Integer]: TVXContourNodes read GetPath write SetPath;
property Outline: TPolygonList read GetOutline;
property ContoursNormal: TAffineVector read FContoursNormal write SetContoursNormal;
function AxisAlignedDimensionsUnscaled: TVector; override;
procedure StructureChanged; override;
published
property Contours: TVXContours read FContours write SetContours;
end;
{ A polygon that can have holes and multiple contours.
Use the Path property to access a contour or one of the AddNode methods
to add a node to a contour (contours are allocated automatically). }
TVXMultiPolygon = class(TMultiPolygonBase)
private
FParts: TPolygonParts;
protected
procedure SetParts(const value: TPolygonParts);
public
constructor Create(AOwner: TComponent); override;
procedure Assign(Source: TPersistent); override;
procedure BuildList(var rci: TVXRenderContextInfo); override;
published
property Parts: TPolygonParts read FParts write SetParts default [ppTop, ppBottom];
end;
//============================================================
implementation
//============================================================
type
{ page oriented pointer array, with persistent pointer target memory.
In TVectorList a pointer to a vector will not be valid any more after
a call to SetCapacity, which might be done implicitely during Add.
The TVectorPool keeps memory in its original position during its
whole lifetime. }
// removed Notify (only D5)
// added Destroy (also working with D4)
TVectorPool = class(TList)
private
FEntrySize: Integer; // size of each entry
FPageSize: Integer; // number of entries per page
FArrSize: Integer; // size of one page
FUsedEntries: Integer; // used entries in actual page
FAktArray: PByteArray; // pointer to actual page
procedure CreatePage; // create new page
public
constructor Create(APageSize, AEntrySize: Integer);
destructor Destroy; override;
{ retrieve pointer to new entry. will create new page if needed }
procedure GetNewVector(var P: Pointer);
end;
//-----------------------------------------------
{ TVectorPool }
//-----------------------------------------------
constructor TVectorPool.Create(APageSize, AEntrySize: Integer);
begin
inherited Create;
Assert(APageSize > 0);
Assert(AEntrySize > 0);
FPageSize := APageSize;
FEntrySize := AEntrySize;
FArrSize := FPageSize * FEntrySize;
CreatePage;
end;
procedure TVectorPool.CreatePage;
begin
GetMem(FAktArray, FArrSize);
Add(FAktArray);
FUsedEntries := 0;
end;
destructor TVectorPool.Destroy;
var
i: Integer;
begin
for i := Count - 1 downto 0 do
FreeMem(Items[i], FArrSize);
inherited;
end;
procedure TVectorPool.GetNewVector(var P: Pointer);
begin
if FUsedEntries >= FPageSize then
CreatePage;
Inc(FUsedEntries);
P := @(FAktArray[(FUsedEntries - 1) * FEntrySize]);
end;
// ------------------
// ------------------ TPolygonList ------------------
// ------------------
procedure TPolygonList.Add;
begin
FAktList := TAffineVectorList.Create;
inherited Add(FAktList);
end;
function TPolygonList.GetList(i: Integer): TAffineVectorList;
begin
Result := TAffineVectorList(Items[i]);
end;
// ------------------
// ------------------ TVXContour ------------------
// ------------------
constructor TVXContour.Create(Collection: TCollection);
begin
inherited;
CreateNodes;
FDivision := 10;
FSplineMode := lsmLines;
end;
procedure TVXContour.CreateNodes;
begin
FNodes := TVXContourNodes.Create(Self);
end;
destructor TVXContour.Destroy;
begin
FNodes.Free;
inherited;
end;
procedure TVXContour.Assign(Source: TPersistent);
begin
if Source is TVXContour then
begin
FNodes.Assign(TVXContour(Source).FNodes);
FDivision := TVXContour(Source).FDivision;
FSplineMode := TVXContour(Source).FSplineMode;
FDescription := TVXContour(Source).FDescription;
end
else
inherited;
end;
function TVXContour.GetDisplayName: string;
begin
result := Description;
if result = '' then
result := Format('GLContour: %d nodes', [Nodes.Count]);
end;
procedure TVXContour.NodesChanged(Sender: TObject);
begin
Changed(false);
end;
procedure TVXContour.SetDescription(const Value: string);
begin
FDescription := Value;
end;
procedure TVXContour.SetDivision(Value: Integer);
begin
if Value < 1 then
Value := 1;
if Value <> FDivision then
begin
FDivision := value;
Changed(false);
end;
end;
procedure TVXContour.SetNodes(const Value: TVXContourNodes);
begin
FNodes.Assign(Value);
Changed(false);
end;
procedure TVXContour.SetSplineMode(const Value: TLineSplineMode);
begin
if FSplineMode <> value then
begin
FSplineMode := value;
Changed(false);
end;
end;
//--------------------------------------------
{ TVXContours }
//--------------------------------------------
function TVXContours.Add: TVXContour;
begin
Result := TVXContour(inherited Add);
end;
constructor TVXContours.Create(AOwner: TComponent);
begin
Create(AOwner, TVXContour);
end;
function TVXContours.FindItemID(ID: Integer): TVXContour;
begin
result := TVXContour(inherited FindItemId(Id));
end;
function TVXContours.GetItems(index: Integer): TVXContour;
begin
result := TVXContour(inherited Items[index]);
end;
procedure TVXContours.SetItems(index: Integer; const Value: TVXContour);
begin
inherited Items[index] := value;
end;
procedure TVXContours.GetExtents(var min, max: TAffineVector);
var
i, k: Integer;
lMin, lMax: TAffineVector;
const
cBigValue: Single = 1e30;
cSmallValue: Single = -1e30;
begin
SetVector(min, cBigValue, cBigValue, cBigValue);
SetVector(max, cSmallValue, cSmallValue, cSmallValue);
for i := 0 to Count - 1 do
begin
GetItems(i).Nodes.GetExtents(lMin, lMax);
for k := 0 to 2 do
begin
if lMin.V[k] < min.V[k] then
min.V[k] := lMin.V[k];
if lMax.V[k] > max.V[k] then
max.V[k] := lMax.V[k];
end;
end;
end;
//--------------------------------------------
{ TMultiPolygonBase }
//--------------------------------------------
constructor TMultiPolygonBase.Create(AOwner: TComponent);
begin
inherited;
FContours := TVXContours.Create(Self);
FContours.OnNotifyChange := ContourChanged;
FContoursNormal := AffineVectorMake(0, 0, 1);
FAxisAlignedDimensionsCache.X := -1;
end;
destructor TMultiPolygonBase.Destroy;
begin
if FOutline <> nil then
begin
FOutline.Clean;
FreeAndNil(FOutline);
end;
FContours.Free;
inherited;
end;
procedure TMultiPolygonBase.Assign(Source: TPersistent);
begin
if Source is TMultiPolygonBase then
begin
FContours.Assign(TMultiPolygonBase(Source).FContours);
end;
inherited;
end;
procedure TMultiPolygonBase.ContourChanged(Sender: TObject);
begin
if Assigned(FOutline) then
begin
// force a RetrieveOutline with next Render
FOutline.Clean;
FreeAndNil(FOutline);
StructureChanged;
end;
end;
procedure TMultiPolygonBase.AddNode(const i: Integer; const value: TVector);
begin
Path[i].AddNode(value);
end;
procedure TMultiPolygonBase.AddNode(const i: Integer; const x, y, z: Single);
begin
Path[i].AddNode(x, y, z);
end;
procedure TMultiPolygonBase.AddNode(const i: Integer; const coords: TVXCoordinates);
begin
Path[i].AddNode(coords);
end;
procedure TMultiPolygonBase.AddNode(const I: Integer; const value: TAffineVector);
begin
Path[i].AddNode(value);
end;
procedure TMultiPolygonBase.SetContours(const Value: TVXContours);
begin
FContours.Assign(Value);
end;
function TMultiPolygonBase.GetOutline: TPolygonList;
begin
if not Assigned(FOutline) then
begin
FOutline := TPolygonList.Create;
RetrieveOutline(FOutline);
end;
Result := FOutline;
end;
function TMultiPolygonBase.GetPath(i: Integer): TVXContourNodes;
begin
Assert(i >= 0);
while i >= Contours.Count do
Contours.Add;
Result := Contours[i].Nodes;
end;
procedure TMultiPolygonBase.SetPath(i: Integer; const value: TVXContourNodes);
begin
Assert(i >= 0);
while i >= Contours.Count do
Contours.Add;
Contours[i].Nodes.Assign(value);
end;
//
// Tessellation routines (OpenVX callbacks)
//
var
vVertexPool: TVectorPool;
procedure tessError(errno: GLEnum);
{$IFDEF Win32} stdcall;
{$ENDIF}{$IFDEF unix} cdecl;
{$ENDIF}
begin
Assert(False, IntToStr(errno) + ' : ' + string(gluErrorString(errno)));
end;
procedure tessIssueVertex(vertexData: Pointer);
{$IFDEF Win32} stdcall;
{$ENDIF}{$IFDEF unix} cdecl;
{$ENDIF}
begin
glTexCoord2fv(vertexData);
glVertex3fv(vertexData);
end;
procedure tessCombine(coords: PDoubleVector; vertex_data: Pointer;
weight: PGLFloat; var outData: Pointer);
{$IFDEF Win32} stdcall;
{$ENDIF}{$IFDEF unix} cdecl;
{$ENDIF}
begin
vVertexPool.GetNewVector(outData);
SetVector(PAffineVector(outData)^, coords^[0], coords^[1], coords^[2]);
end;
procedure tessBeginList(typ: GLEnum; polygonData: Pointer);
{$IFDEF Win32} stdcall;
{$ENDIF}{$IFDEF unix} cdecl;
{$ENDIF}
begin
TPolygonList(polygonData).Add;
end;
procedure tessIssueVertexList(vertexData: Pointer; polygonData: Pointer);
{$IFDEF Win32} stdcall;
{$ENDIF}{$IFDEF unix} cdecl;
{$ENDIF}
begin
TPolygonList(polygonData).AktList.Add(PAffineVector(vertexData)^);
end;
procedure TMultiPolygonBase.RetrieveOutline(List: TPolygonList);
var
i, n: Integer;
tess: PGLUTesselator;
procedure TesselatePath(contour: TVXContour; inverted: Boolean);
procedure IssueVertex(v: TAffineVector);
var
dblVector: TAffineDblVector;
p: PAffineVector;
begin
vVertexPool.GetNewVector(Pointer(p));
p^ := v;
SetVector(dblVector, v);
gluTessVertex(tess, dblVector, p);
end;
var
i, n: Integer;
spline: TCubicSpline;
f: Single;
splineDivisions: Integer;
nodes: TVXContourNodes;
begin
gluTessBeginContour(tess);
nodes := contour.Nodes;
if contour.SplineMode = lsmLines then
splineDivisions := 0
else
splineDivisions := contour.Division;
if splineDivisions > 1 then
begin
spline := nodes.CreateNewCubicSpline;
try
f := 1 / splineDivisions;
n := splineDivisions * (nodes.Count - 1);
if inverted then
begin
for i := n downto 0 do
IssueVertex(spline.SplineAffineVector(i * f))
end
else
begin
for i := 0 to n do
IssueVertex(spline.SplineAffineVector(i * f));
end;
finally
spline.Free;
end;
end
else
begin
n := nodes.Count - 1;
if inverted then
begin
for i := n downto 0 do
IssueVertex(nodes[i].AsAffineVector)
end
else
begin
for i := 0 to n do
IssueVertex(nodes[i].AsAffineVector);
end;
end;
gluTessEndContour(tess);
end;
begin
List.Clear;
if (Contours.Count > 0) and (Path[0].Count > 2) then
begin
// Vertex count
n := 0;
for i := 0 to Contours.Count - 1 do
n := n + Path[i].Count;
// Create and initialize the GLU tesselator
vVertexPool := TVectorPool.Create(n, SizeOf(TAffineVector));
tess := gluNewTess;
try
// register callbacks
gluTessCallback(tess, GLU_TESS_BEGIN_DATA, @tessBeginList);
gluTessCallback(tess, GLU_TESS_END_DATA, nil);
gluTessCallback(tess, GLU_TESS_VERTEX_DATA, @tessIssueVertexList);
gluTessCallback(tess, GLU_TESS_ERROR, @tessError);
gluTessCallback(tess, GLU_TESS_COMBINE, @tessCombine);
// issue normal
gluTessNormal(tess, FContoursNormal.X, FContoursNormal.Y, FContoursNormal.Z);
// set properties
gluTessProperty(Tess, GLU_TESS_WINDING_RULE, GLU_TESS_WINDING_POSITIVE);
gluTessProperty(Tess, GLU_TESS_BOUNDARY_ONLY, GL_TRUE);
gluTessBeginPolygon(tess, List);
// outside contour
TesselatePath(Contours[0], False);
// inside contours
for n := 1 to Contours.Count - 1 do
TesselatePath(Contours[n], True);
gluTessEndPolygon(tess);
finally
gluDeleteTess(tess);
vVertexPool.Free;
vVertexPool := nil;
end;
end;
end;
procedure TMultiPolygonBase.RenderTesselatedPolygon(textured: Boolean;
normal: PAffineVector;
invertNormals: Boolean);
var
tess: PGLUTesselator;
procedure IssueVertex(v: TAffineVector);
var
dblVector: TAffineDblVector;
p: PAffineVector;
begin
vVertexPool.GetNewVector(Pointer(p));
p^ := v;
SetVector(dblVector, v);
gluTessVertex(tess, dblVector, p);
end;
var
i, n: Integer;
begin
// call to Outline will call RetrieveOutline if necessary
if (Outline.Count = 0) or (Outline.List[0].Count < 2) then
Exit;
// Vertex count
n := 0;
for i := 0 to Outline.Count - 1 do
n := n + Outline.List[i].Count;
// Create and initialize a vertex pool and the GLU tesselator
vVertexPool := TVectorPool.Create(n, Sizeof(TAffineVector));
tess := gluNewTess;
try
gluTessCallback(tess, GLU_TESS_BEGIN, @glBegin);
if textured then
gluTessCallback(tess, GLU_TESS_VERTEX, @tessIssueVertex)
else
gluTessCallback(tess, GLU_TESS_VERTEX, @glVertex3fv);
gluTessCallback(tess, GLU_TESS_END, @glEnd);
gluTessCallback(tess, GLU_TESS_ERROR, @tessError);
gluTessCallback(tess, GLU_TESS_COMBINE, @tessCombine);
// Issue normal
if Assigned(normal) then
begin
glNormal3fv(PGLFloat(normal));
gluTessNormal(tess, normal^.X, normal^.Y, normal^.Z);
end;
gluTessProperty(Tess, GLU_TESS_WINDING_RULE, GLU_TESS_WINDING_POSITIVE);
// Issue polygon
gluTessBeginPolygon(tess, nil);
for n := 0 to Outline.Count - 1 do
begin
with Outline.List[n] do
begin
gluTessBeginContour(tess);
if invertNormals then
for i := Count - 1 downto 0 do
IssueVertex(Items[i])
else
for i := 0 to Count - 1 do
IssueVertex(Items[i]);
gluTessEndContour(tess);
end;
end;
gluTessEndPolygon(tess);
finally
gluDeleteTess(tess);
vVertexPool.Free;
vVertexPool := nil;
end;
end;
// ------------------
// ------------------ TVXMultiPolygon ------------------
// ------------------
constructor TVXMultiPolygon.Create(AOwner: TComponent);
begin
inherited;
FParts := [ppTop, ppBottom];
end;
procedure TVXMultiPolygon.Assign(Source: TPersistent);
begin
if Source is TVXMultiPolygon then
begin
FParts := TVXMultiPolygon(Source).FParts;
end;
inherited;
end;
procedure TVXMultiPolygon.BuildList(var rci: TVXRenderContextInfo);
var
normal: TAffineVector;
begin
if (Outline.Count < 1) then
Exit;
normal := ContoursNormal;
// Render
// tessellate top polygon
if ppTop in FParts then
RenderTesselatedPolygon(True, @normal, False);
// tessellate bottom polygon
if ppBottom in FParts then
begin
NegateVector(normal);
RenderTesselatedPolygon(True, @normal, True)
end;
end;
procedure TVXMultiPolygon.SetParts(const value: TPolygonParts);
begin
if FParts <> value then
begin
FParts := value;
StructureChanged;
end;
end;
procedure TMultiPolygonBase.SetContoursNormal(const Value: TAffineVector);
begin
FContoursNormal := Value;
end;
function TMultiPolygonBase.AxisAlignedDimensionsUnscaled: TVector;
var
dMin, dMax: TAffineVector;
begin
if FAxisAlignedDimensionsCache.X < 0 then
begin
Contours.GetExtents(dMin, dMax);
FAxisAlignedDimensionsCache.X := MaxFloat(Abs(dMin.X), Abs(dMax.X));
FAxisAlignedDimensionsCache.Y := MaxFloat(Abs(dMin.Y), Abs(dMax.Y));
FAxisAlignedDimensionsCache.Z := MaxFloat(Abs(dMin.Z), Abs(dMax.Z));
end;
SetVector(Result, FAxisAlignedDimensionsCache);
end;
procedure TMultiPolygonBase.StructureChanged;
begin
FAxisAlignedDimensionsCache.X := -1;
inherited;
end;
// ------------------
// ------------------ TVXContourNodes ------------------
// ------------------
procedure TVXContourNodes.NotifyChange;
begin
if (GetOwner <> nil) then
(GetOwner as TVXContour).Changed(False);
end;
//-------------------------------------------------------------
initialization
//-------------------------------------------------------------
RegisterClass(TVXMultiPolygon);
end.
|
unit fltPlatUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLabel, cxDropDownEdit, cxCalendar, cxTextEdit, cxMaskEdit,
cxButtonEdit, cxContainer, cxEdit, cxCheckBox, cxControls, cxGroupBox,
cxLookAndFeelPainters, StdCtrls, cxButtons, cxCurrencyEdit, Menus,
FIBDatabase, pFIBDatabase, cxMRUEdit, ActnList, DB, cxLookupEdit,
cxDBLookupEdit, cxDBLookupComboBox, FIBDataSet, pFIBDataSet, FIBQuery,
pFIBQuery, pFIBStoredProc;
type
TfltPlatForm = class(TForm)
cxGroupBox1: TcxGroupBox;
fltTipDogCheck: TcxCheckBox;
fltDatePeriodCheck: TcxCheckBox;
fltCustCheck: TcxCheckBox;
fltTipDogEdit: TcxButtonEdit;
fltDateBegEdit: TcxDateEdit;
fltDateEndEdit: TcxDateEdit;
cxLabel10: TcxLabel;
fltCustEdit: TcxButtonEdit;
OKButton: TcxButton;
cxButton2: TcxButton;
cxButton3: TcxButton;
fltRegNumCheck: TcxCheckBox;
fltRegNumEdit: TcxTextEdit;
fltSumCheck: TcxCheckBox;
Label1: TLabel;
fltSumFromEdit: TcxCurrencyEdit;
fltSumToEdit: TcxCurrencyEdit;
PopupMenu1: TPopupMenu;
N1: TMenuItem;
N2: TMenuItem;
N3: TMenuItem;
N4: TMenuItem;
N5: TMenuItem;
N6: TMenuItem;
N7: TMenuItem;
N8: TMenuItem;
i1: TMenuItem;
ActionList1: TActionList;
Action1: TAction;
chNumPlat: TcxCheckBox;
NumPlatEdit: TcxTextEdit;
cbType: TcxComboBox;
chType: TcxCheckBox;
chAcc: TcxCheckBox;
DataSet: TpFIBDataSet;
DataSource1: TDataSource;
cbAcc: TcxLookupComboBox;
depCheck: TcxCheckBox;
depEdit: TcxButtonEdit;
pFIBDatabase1: TpFIBDatabase;
StoredProc: TpFIBStoredProc;
procedure FormCreate(Sender: TObject);
procedure fltCustEditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure fltCustCheckClick(Sender: TObject);
procedure fltTipDogCheckClick(Sender: TObject);
procedure fltTipDogEditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure fltDatePeriodCheckClick(Sender: TObject);
procedure OKButtonClick(Sender: TObject);
procedure cxButton2Click(Sender: TObject);
procedure cxButton3Click(Sender: TObject);
procedure fltRegNumCheckClick(Sender: TObject);
procedure fltSumCheckClick(Sender: TObject);
procedure fltRegNumEditKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure fltCustEditKeyPress(Sender: TObject; var Key: Char);
procedure fltSumFromEditFocusChanged(Sender: TObject);
procedure fltTipDogEditKeyPress(Sender: TObject; var Key: Char);
procedure fltDateBegEditKeyPress(Sender: TObject; var Key: Char);
procedure fltDateEndEditKeyPress(Sender: TObject; var Key: Char);
procedure fltSumFromEditKeyPress(Sender: TObject; var Key: Char);
procedure fltSumToEditKeyPress(Sender: TObject; var Key: Char);
procedure FormShow(Sender: TObject);
procedure N1Click(Sender: TObject);
procedure N2Click(Sender: TObject);
procedure i1Click(Sender: TObject);
procedure Action1Execute(Sender: TObject);
procedure chTypeClick(Sender: TObject);
procedure chNumPlatClick(Sender: TObject);
procedure chAccClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure NumPlatEditKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure cbTypeKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure cbAccKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure cbAccPropertiesChange(Sender: TObject);
procedure depCheckClick(Sender: TObject);
procedure depEditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
public
id_Group : integer;
{ fltDateBeg : TDate;
fltDateEnd : TDate;}
fltId_tip_dog : integer;
flt_id_Customer : int64;
fltCustEdited : boolean;
id_rate_acc_native : Int64;
flt_id_department : int64;
flt_id_session_type : int64;
id_otdel : int64;
end;
var
fltDogForm: TfltPlatForm;
implementation
uses DogLoaderUnit, {DogFormUnit, }GlobalSPR, LoadDogManedger, DateUtils, LangUnit,
PlatFormUnit, uCommonSp, StrUtils;
{$R *.dfm}
procedure TfltPlatForm.FormCreate(Sender: TObject);
begin
if FileExists(SYS_APP_PATH + SYS_LANG_FILE) then LangPackApply(Self);
cbType.ItemIndex := 0;
id_rate_acc_native := -1;
// fltDateBeg := date - SYS_DOG_PERIOD;
// fltDateEnd := date;
fltId_tip_dog := -1;
flt_id_department := -1;
id_otdel := -1;
fltDateBegEdit.Date := now;
fltDateEndEdit.Date := now;
flt_id_Customer := -1;
flt_id_session_type := -1;
end;
procedure TfltPlatForm.fltCustEditPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
var
Res : Variant;
begin
Res := ShowCustomers(Self, TPlatForm(Owner).WorkDatabase.Handle, fsNormal, now, csmCustomers, flt_id_Customer, -1);
if VarArrayDimCount(Res) <> 0 then begin
flt_id_Customer := Res[0];
fltCustEdit.Text := Res[2];
fltCustCheck.Checked := true;
fltCustEdited := false;
end
else
fltCustCheck.Checked := false;
end;
procedure TfltPlatForm.fltCustCheckClick(Sender: TObject);
begin
fltCustEdit.Enabled := fltCustCheck.Checked;
if flt_id_Customer = -1 then fltCustEditPropertiesButtonClick(Self, 0);
if Visible then if fltCustEdit.Enabled then fltCustEdit.SetFocus;
end;
procedure TfltPlatForm.fltTipDogCheckClick(Sender: TObject);
begin
if (fltId_tip_dog = -1) and (fltTipDogCheck.Checked) then fltTipDogEditPropertiesButtonClick(Self, 0);
fltTipDogEdit.Enabled := fltTipDogCheck.Checked;
if Visible then if fltTipDogEdit.Enabled then fltTipDogEdit.SetFocus;
end;
procedure TfltPlatForm.fltTipDogEditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var
res : Variant;
cnt : integer;
i : integer;
begin
res := LoadDogManedger.WorkTypeDogSPR(Self, TPlatForm(Owner).WorkDatabase.Handle, fsNormal, 'select2', Nil, SYS_ID_GROUP_ZAYAV_VIEW, Nil);
{ if VarArrayDimCount(res) > 0 then begin
fltTipDogCheck.Checked := true;
fltId_tip_dog := res[0][0];
fltTipDogEdit.Text := res[0][2];
end else fltTipDogCheck.Checked := false;}
if VarArrayDimCount(res) = 0 then
begin
fltTipDogCheck.Checked := false;
exit;
end;
Cnt := VarArrayHighBound(res, 1);
if cnt = 0 then
begin
fltTipDogCheck.Checked := true;
fltId_tip_dog := res[0][0];
fltTipDogEdit.Text := res[0][2];
end
else
begin
fltTipDogEdit.Text := '< ДЕКІЛЬКА >';
StoredProc.StoredProcName := 'DOG_DT_DOCUMENT_GET_FILTER_SES';
StoredProc.Transaction.StartTransaction;
StoredProc.Prepare;
StoredProc.ExecProc;
flt_id_session_type := StoredProc['ID_SESSION'].AsInt64;
StoredProc.Transaction.Commit;
StoredProc.Close;
for i := 0 to Cnt do
begin
StoredProc.StoredProcName := 'DOG_DT_DOCUMENT_FILTER_TYPE_ADD';
StoredProc.Transaction.StartTransaction;
StoredProc.Prepare;
StoredProc.ParamByName('ID_SESSION').AsInt64 := flt_id_session_type;
StoredProc.ParamByName('ID_TYPE_DOG').AsInt64 := res[i][0];
StoredProc.ExecProc;
StoredProc.Transaction.Commit;
StoredProc.Close;
// t_id_tip_dog := Tip_dog[i][0];
// t_tip_dog := Tip_dog[i][1];
end;
end;
end;
procedure TfltPlatForm.fltDatePeriodCheckClick(Sender: TObject);
begin
fltDateBegEdit.Enabled := fltDatePeriodCheck.Checked;
fltDateEndEdit.Enabled := fltDatePeriodCheck.Checked;
if Visible then if fltDateBegEdit.Enabled then fltDateBegEdit.SetFocus;
end;
procedure TfltPlatForm.OKButtonClick(Sender: TObject);
begin
if chAcc.Checked then id_rate_acc_native := TFIBBCDField(DataSet.FBN('ID_RATE_ACCOUNT')).AsInt64;
ModalResult := mrOk;
end;
procedure TfltPlatForm.cxButton2Click(Sender: TObject);
begin
chType.Checked := False;
chAcc.Checked := False;
chNumPlat.Checked := False;
depCheck.Checked := False;
fltTipDogCheck.Checked := false;
fltCustCheck.Checked := false;
fltDatePeriodCheck.Checked := false;
fltSumCheck.Checked := false;
fltRegNumCheck.Checked := false;
ModalResult := mrOk;
end;
procedure TfltPlatForm.cxButton3Click(Sender: TObject);
begin
Close;
end;
procedure TfltPlatForm.fltRegNumCheckClick(Sender: TObject);
begin
fltRegNumEdit.Enabled := fltRegNumCheck.Checked;
if fltRegNumEdit.Enabled and Visible then fltRegNumEdit.SetFocus;
end;
procedure TfltPlatForm.fltSumCheckClick(Sender: TObject);
begin
fltSumFromEdit.Enabled := fltSumCheck.Checked;
fltSumToEdit.Enabled := fltSumCheck.Checked;
if fltSumFromEdit.Enabled and visible then fltSumFromEdit.SetFocus;
end;
procedure TfltPlatForm.fltRegNumEditKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_RETURN then begin
Key := 0;
OKButton.SetFocus;
end;
end;
procedure TfltPlatForm.fltCustEditKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then begin
Key := #0;
OKButton.SetFocus;
end else fltCustEdited := true;
end;
procedure TfltPlatForm.fltSumFromEditFocusChanged(Sender: TObject);
begin
if fltSumToEdit.Text = '' then fltSumToEdit.Text := fltSumFromEdit.Text;
end;
procedure TfltPlatForm.fltTipDogEditKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then begin
Key := #0;
OKButton.SetFocus;
end;
end;
procedure TfltPlatForm.fltDateBegEditKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then
begin
Key := #0;
fltDateEndEdit.SetFocus;
end;
end;
procedure TfltPlatForm.fltDateEndEditKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then begin
Key := #0;
OKButton.SetFocus;
end;
end;
procedure TfltPlatForm.fltSumFromEditKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then begin
Key := #0;
fltSumToEdit.SetFocus;
end;
end;
procedure TfltPlatForm.fltSumToEditKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then begin
Key := #0;
OKButton.SetFocus;
end;
end;
procedure TfltPlatForm.FormShow(Sender: TObject);
begin
DataSet.Open;
fltRegNumCheck.SetFocus;
end;
procedure TfltPlatForm.N1Click(Sender: TObject);
begin
fltDateBegEdit.Date := EncodeDate(YearOf(now), 1, 1);
fltDateEndEdit.Date := EncodeDate(YearOf(now), 12, 31);
end;
procedure TfltPlatForm.N2Click(Sender: TObject);
begin
fltDateBegEdit.Date := EncodeDate(YearOf(now) - 1, 1, 1);
fltDateEndEdit.Date := EncodeDate(YearOf(now) - 1, 12, 31);
end;
procedure TfltPlatForm.i1Click(Sender: TObject);
begin
fltDateBegEdit.Date := date;
fltDateEndEdit.Date := date;
end;
procedure TfltPlatForm.Action1Execute(Sender: TObject);
begin
OKButtonClick(Self);
end;
procedure TfltPlatForm.chTypeClick(Sender: TObject);
begin
cbType.Enabled := chType.Checked;
end;
procedure TfltPlatForm.chNumPlatClick(Sender: TObject);
begin
NumPlatEdit.Enabled := chNumPlat.Checked;
end;
procedure TfltPlatForm.chAccClick(Sender: TObject);
begin
cbAcc.Enabled := chAcc.Checked;
end;
procedure TfltPlatForm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
DataSet.Close;
end;
procedure TfltPlatForm.NumPlatEditKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_RETURN then begin
Key := 0;
OKButton.SetFocus;
end;
end;
procedure TfltPlatForm.cbTypeKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_RETURN then begin
Key := 0;
OKButton.SetFocus;
end;
end;
procedure TfltPlatForm.cbAccKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_RETURN then begin
Key := 0;
OKButton.SetFocus;
end;
end;
procedure TfltPlatForm.cbAccPropertiesChange(Sender: TObject);
begin
// id_rate_acc_native := StrToInt(cbAcc.Properties.Grid.DataController.Values[cbAcc.Properties.Grid.DataController.FocusedRecordIndex, 2]);
end;
procedure TfltPlatForm.depCheckClick(Sender: TObject);
begin
if (flt_id_department = -1) and (depCheck.Checked) then depEditPropertiesButtonClick(Self, 0);
depEdit.Enabled := depCheck.Checked;
end;
procedure TfltPlatForm.depEditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var
sp: TSprav;
begin
// создать справочник
sp := GetSprav('SpDepartment');
if sp <> nil then
begin
// заполнить входные параметры
with sp.Input do
begin
Append;
FieldValues['DBHandle'] := Integer(pFIBDatabase1.Handle);
// модальный показ
FieldValues['ShowStyle'] := 0;
// единичная выборка
FieldValues['Select'] := 1;
//FieldValues['Root_Department'] := 2612;
FieldValues['Actual_Date'] := Date;
Post;
end;
end;
// показать справочник и проанализировать результат (выбор одного подр.)
sp.Show;
if sp.Output = nil then ShowMessage('BUG: Output is NIL!!!')
else if not sp.Output.IsEmpty then
begin
flt_id_department := sp.Output['Id_Department'];
DepEdit.Text := sp.Output['Name_FULL'];
end;
sp.Free;
end;
end.
|
unit u_consts;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, u_imports, u_writers, u_common;
type
TConstantType = (
ctUnsigned64,
ctInt64,
ctDouble,
ctString,
ctStream
);
TConstant = class(TObject)
public
c_names: TStringList;
c_type: TConstantType;
c_value: TMemoryStream;
constructor Create;
destructor Destroy; override;
procedure GenerateCode(Stream: TStream);
end;
TConstantManager = class(TObject)
public
Constants: TList;
Lines: TStringList;
constructor Create(sl: TStringList);
destructor Destroy; override;
procedure AddConstCardinal(c_name: string; c: cardinal);
procedure Add(Cnst: TConstant);
function GetAddr(c_name: string): cardinal;
procedure ParseSection;
procedure AppendImports(ImportSection: TImportSection);
procedure GenerateCode(Stream: TStream);
end;
implementation
{** Constant **}
constructor TConstant.Create;
begin
c_value := TMemoryStream.Create;
c_names := TStringList.Create;
inherited Create;
end;
destructor TConstant.Destroy;
begin
c_value.Free;
inherited Destroy;
end;
procedure TConstant.GenerateCode(Stream: TStream);
begin
case c_type of
ctUnsigned64:
begin
Stream.WriteByte(byte(ctUnsigned64));
Stream.WriteBuffer(c_value.Memory^, c_value.size);
end;
ctInt64:
begin
Stream.WriteByte(byte(ctInt64));
Stream.WriteBuffer(c_value.Memory^, c_value.size);
end;
ctDouble:
begin
Stream.WriteByte(byte(ctDouble));
Stream.WriteBuffer(c_value.Memory^, c_value.size);
end;
ctString:
begin
Stream.WriteByte(byte(ctString));
St_WriteWord(Stream, c_value.Size);
Stream.WriteBuffer(c_value.Memory^, c_value.size);
end;
ctStream:
begin
Stream.WriteByte(byte(ctStream));
St_WriteCardinal(Stream, c_value.Size);
Stream.WriteBuffer(c_value.Memory^, c_value.Size);
end;
end;
end;
{** ConstantManager **}
constructor TConstantManager.Create(sl: TStringList);
begin
Lines := sl;
Constants := TList.Create;
inherited Create;
end;
destructor TConstantManager.Destroy;
var
c: cardinal;
begin
if Constants.Count > 0 then
for c := 0 to Constants.Count - 1 do
TConstant(Constants[c]).Free;
Constants.Free;
inherited Destroy;
end;
function CompareStreams(s1, s2: TMemoryStream): boolean;
var
c: cardinal;
begin
Result := False;
if (s1 <> nil) and (s2 <> nil) then
if s1.Size = s2.Size then
begin
c := 0;
Result := True;
while c < s1.Size do
begin
Result := Result and (PByte(Pointer(s1.Memory) + c)^ =
PByte(Pointer(s2.Memory) + c)^);
Inc(c);
end;
end;
end;
procedure TConstantManager.Add(Cnst: TConstant);
var
c: cardinal;
Cnst2: TConstant;
begin
c := 0;
while c < Constants.Count do
begin
Cnst2 := TConstant(Constants[c]);
if Cnst.c_type = Cnst2.c_type then
if CompareStreams(Cnst.c_value, Cnst2.c_value) then
begin
Cnst2.c_names.AddStrings(Cnst.c_names);
FreeAndNil(Cnst);
Exit;
end;
Inc(c);
end;
Constants.Add(Cnst);
end;
procedure TConstantManager.AddConstCardinal(c_name: string; c: cardinal);
var
Constant: TConstant;
begin
Constant := TConstant.Create;
Constant.c_names.Add(c_name);
Constant.c_type := ctUnsigned64;
St_WriteCardinal(Constant.c_value, c);
Constants.Add(Constant);
end;
function TConstantManager.GetAddr(c_name: string): cardinal;
var
c: cardinal;
Cnst: TConstant;
begin
if pos(sLineBreak, c_name) > 0 then
c_name := copy(c_name, 1, pos(slinebreak, c_name) - 1);
if Constants.Count = 0 then
AsmErr('Invalid constant call "' + c_name + '".');
for c := 0 to Constants.Count - 1 do
begin
Cnst := TConstant(Constants[c]);
if Cnst.c_names.IndexOf(c_name) <> -1 then
begin
Result := c;
break;
end
else
if c = Constants.Count - 1 then
AsmErr('Invalid constant call "' + c_name + '"');
end;
end;
procedure TConstantManager.ParseSection;
var
c: cardinal;
Constant: TConstant;
s, t: string;
begin
c := 0;
while c < Lines.Count do
begin
s := Trim(Lines[c]);
t := Tk(s, 1);
if t = 'word' then
begin
Constant := TConstant.Create;
Constant.c_names.Add(Tk(s, 2));
Constant.c_type := ctUnsigned64;
St_WriteCardinal(Constant.c_value, StrToQWord(Tk(s, 3)));
Self.Add(Constant);
Lines[c] := '';
end;
if t = 'int' then
begin
Constant := TConstant.Create;
Constant.c_names.Add(Tk(s, 2));
Constant.c_type := ctInt64;
St_WriteInt64(Constant.c_value, StrToInt(Tk(s, 3)));
Self.Add(Constant);
Lines[c] := '';
end;
if t = 'real' then
begin
Constant := TConstant.Create;
Constant.c_names.Add(Tk(s, 2));
Constant.c_type := ctDouble;
St_WriteDouble(Constant.c_value, double(StrToFloat(Tk(s, 3))));
Self.Add(Constant);
Lines[c] := '';
end;
if t = 'str' then
begin
Constant := TConstant.Create;
Constant.c_names.Add(Tk(s, 2));
Constant.c_type := ctString;
Constant.c_value.WriteBuffer(Tk(s, 3)[1], Length(Tk(s, 3)));
Self.Add(Constant);
Lines[c] := '';
end;
if t = 'stream' then
begin
Constant := TConstant.Create;
Constant.c_names.Add(Tk(s, 2));
Constant.c_type := ctStream;
Constant.c_value.LoadFromFile(ExtractFilePath(ParamStr(2)) + Tk(s, 3));
Self.Add(Constant);
Lines[c] := '';
end;
if t = 'api' then
begin
Constant := TConstant.Create;
Constant.c_names.Add(Tk(s, 2));
Constant.c_type := ctUnsigned64;
St_WriteCardinal(Constant.c_value, RgAPICnt);
inc(RgAPICnt);
Self.Add(Constant);
Lines[c] := '';
end;
Inc(c);
end;
end;
procedure TConstantManager.AppendImports(ImportSection: TImportSection);
var
w: word;
c, c2: cardinal;
Constant: TConstant;
begin
if ImportSection.Libs.Count > 0 then
begin
c := 0;
for w := 0 to ImportSection.Libs.Count - 1 do
begin
with TImportLibrary(ImportSection.Libs[w]) do
begin
if Methods.Count > 0 then
begin
for c2 := 0 to Methods.Count - 1 do
begin
Constant := TConstant.Create;
Constant.c_names.Add(Methods[c2]);
Constant.c_type := ctUnsigned64;
St_WriteCardinal(Constant.c_value, c + RgAPICnt);
Constants.Add(Constant);
Inc(c);
end;
end;
end;
end;
end;
end;
procedure TConstantManager.GenerateCode(Stream: TStream);
var
c: cardinal;
begin
St_WriteCardinal(Stream, Constants.Count);
if Constants.Count > 0 then
for c := 0 to Constants.Count - 1 do
TConstant(Constants[c]).GenerateCode(Stream);
end;
end.
|
unit OffSetAnim;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Dialogs,
GLVectorTypes,
GLCoordinates,
GLTexture, GLMaterial;
type
TAOffSet = record
x, y: Single;
end;
TOffSetAnim = class
private
OffSets: Array of TAOffSet;
ticker, qtick: double;
ScaleX, ScaleY: Single;
C, R: Integer;
Lib: TGLMaterialLibrary;
AnimReady: Boolean;
public
FPS: Integer;
Bind: Integer;
Mode: Integer;
CFrame: Integer;
procedure MakeAnim(TileWidth: Integer; TileHeight: Integer; sBind: Integer;
src: TGLMaterialLibrary; FrameRate: Integer; pm: Integer);
procedure NextFrame;
procedure SetFrame(Frame: Integer);
procedure Tick(Time: double);
Constructor Create;
Destructor Destroy; Override;
end;
const
apmNone = 111;
apmLoop = 112;
apmOnce = 113;
implementation
Constructor TOffSetAnim.Create;
begin
// initialise clock
qtick := ticker;
AnimReady := False;
end;
Destructor TOffSetAnim.Destroy;
begin
//
end;
procedure TOffSetAnim.Tick(Time: double);
begin
ticker := Time;
if ticker - qtick > 1 / FPS then
begin
qtick := ticker;
//
if (AnimReady = True) and (Mode <> apmNone) then
NextFrame;
end;
end;
procedure TOffSetAnim.MakeAnim(TileWidth: Integer; TileHeight: Integer;
sBind: Integer; src: TGLMaterialLibrary; FrameRate: Integer; pm: Integer);
var
i, i2, o: Integer;
x, y: Single;
begin
try
AnimReady := False;
FPS := FrameRate;
Bind := sBind;
Lib := (src as TGLMaterialLibrary);
C := Lib.Materials[Bind].Material.Texture.Image.Width div TileWidth;
R := Lib.Materials[Bind].Material.Texture.Image.Height div TileHeight;
ScaleX := 1 / C;
ScaleY := 1 / R;
x := 0;
y := ScaleY * R - 1;
for i := 0 to R - 1 do
begin
for i2 := 0 to C - 1 do
begin
SetLength(OffSets, Length(OffSets) + 1);
o := Length(OffSets) - 1;
OffSets[o].x := x;
OffSets[o].y := y;
x := x + ScaleX;
end;
x := 0;
y := y - ScaleY;
end;
Lib.Materials[Bind].TextureScale.x := ScaleX;
Lib.Materials[Bind].TextureScale.y := ScaleY;
Lib.Materials[Bind].TextureOffset.y := ScaleY * R - 1;
Mode := pm;
AnimReady := True;
except
SetLength(OffSets, 0);
ShowMessage('MakeAnim failed... Make sure your texture is Power of 2.');
end;
end;
procedure TOffSetAnim.NextFrame;
begin
Lib.Materials[Bind].TextureOffset.x := OffSets[CFrame].x;
Lib.Materials[Bind].TextureOffset.y := OffSets[CFrame].y;
if Mode = apmLoop then
begin
if CFrame = Length(OffSets) then
CFrame := 0
else
Inc(CFrame);
end
else
begin
if CFrame <> Length(OffSets) then
Inc(CFrame);
end;
end;
procedure TOffSetAnim.SetFrame(Frame: Integer);
begin
if (Frame >= 0) and (Frame < Length(OffSets)) then
begin
CFrame := Frame;
Lib.Materials[Bind].TextureOffset.x := OffSets[CFrame].x;
Lib.Materials[Bind].TextureOffset.y := OffSets[CFrame].y;
end;
end;
end.
|
unit ini_type_place_FORM_ADD;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, cxLookAndFeelPainters, cxButtons, cxControls, cxContainer,
cxEdit, cxTextEdit, ExtCtrls;
type
TFini_type_place_form_add = class(TForm)
Label1: TLabel;
FullNameEdit: TcxTextEdit;
OKButton: TcxButton;
CancelButton: TcxButton;
Label2: TLabel;
ShortNameEdit: TcxTextEdit;
Bevel1: TBevel;
procedure CancelButtonClick(Sender: TObject);
procedure OKButtonClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FullNameEditKeyPress(Sender: TObject; var Key: Char);
procedure ShortNameEditKeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
public
{ Public declarations }
end;
implementation
uses BaseTypes;
{$R *.DFM}
procedure TFini_type_place_form_add.CancelButtonClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure TFini_type_place_form_add.OKButtonClick(Sender: TObject);
begin
if FullNameEdit.Text = '' then begin
agShowMessage('Необходимо ввести полное название');
exit;
end;
if ShortNameEdit.Text = '' then begin
agShowMessage('Необходимо ввести сокращение');
exit;
end;
ModalResult := mrOK;
end;
procedure TFini_type_place_form_add.FormShow(Sender: TObject);
begin
FullNameEdit.SetFocus;
end;
procedure TFini_type_place_form_add.FullNameEditKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then ShortNameEdit.SetFocus;
end;
procedure TFini_type_place_form_add.ShortNameEditKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then OKButton.SetFocus;
end;
end.
|
{
Laz-Model
Copyright (C) 2002 Eldean AB, Peter Söderman, Ville Krumlinde
Portions (C) 2016 Peter Dyson. Initial Lazarus port
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 uClassTreeEditForm;
{$mode objfpc}{$H+}
interface
uses
Classes, Forms, typinfo,
RTTIGrids, ComCtrls, ExtCtrls,
uModel, uModelEntity, uIterators, uConst;
type
{ TClassTreeEditForm }
TClassTreeEditForm = class(TForm)
Splitter1: TSplitter;
TIPropertyGrid1: TTIPropertyGrid;
TreeView1: TTreeView;
procedure FormCloseQuery(Sender: TObject; var CanClose: boolean);
procedure TreeView1SelectionChanged(Sender: TObject);
private
FModel: TObjectModel;
FModelObject: TModelEntity;
procedure SetObject(AValue: TModelEntity);
procedure SetModel(AModel: TObjectModel);
procedure InitTreeFromModel;
procedure InitTreeFromClass;
procedure InitTreeFromUnit;
procedure InitTreeFromDataType;
procedure DisplayEnums(ParentNode: TTreeNode; Enum: TEnumeration);
public
property Model: TObjectModel write SetModel;
property ModelObject: TModelEntity write SetObject;
end;
var
ClassTreeEditForm: TClassTreeEditForm;
implementation
{$R *.lfm}
{ TClassTreeEditForm }
procedure TClassTreeEditForm.FormCloseQuery(Sender: TObject;
var CanClose: boolean);
begin
Self.Hide;
CanClose := False;
end;
procedure TClassTreeEditForm.TreeView1SelectionChanged(Sender: TObject);
begin
if Assigned(TreeView1.Selected) then
if (Assigned(TreeView1.Selected.Data)) and (TObject(TreeView1.Selected.Data) is TPersistent) then
TIPropertyGrid1.TIObject := TPersistent(TreeView1.Selected.Data);
end;
procedure TClassTreeEditForm.SetObject(AValue: TModelEntity);
begin
Self.FModelObject := AValue;
Self.TIPropertyGrid1.TIObject := AValue;
InitTreeFromModel;
end;
procedure TClassTreeEditForm.SetModel(AModel: TObjectModel);
begin
FModel := AModel;
end;
procedure TClassTreeEditForm.InitTreeFromModel;
begin
TreeView1.Items.Clear;
if (FModelObject is TClass) then
InitTreeFromClass;
if (FModelObject is TUnitPackage) then
InitTreeFromUnit;
if (FModelObject is TDataType) then
InitTreeFromDataType;
end;
procedure TClassTreeEditForm.InitTreeFromClass;
var
tp, tc, nod,nod1, nod2, nod3: TTreeNode;
Pi, Mi: IModelIterator;
ent: TModelEntity;
attr: TAttribute;
op: TOperation;
par: TParameter;
begin
with FModelObject as TClass do
begin
tp := TreeView1.Items.Add(nil, rsParent_ic + ': ' + Owner.Name);
If Assigned(Ancestor) then
begin
tc := TreeView1.Items.AddChildObject(tp, Name + ': ' + Ancestor.Name, Ancestor);
Mi := TModelIterator.Create(GetImplements, ioAlpha);
if Mi.Count > 0 then
begin
nod := TreeView1.Items.AddChildObject(tc, rsImplementors_lc, nil);
while Mi.HasNext do
begin
ent := Mi.Next;
TreeView1.Items.AddChildObject(nod, ent.Name, ent);
end;
end;
end
else
tc := TreeView1.Items.AddChild(tp, Name);
Mi := TModelIterator.Create(GetAttributes);
if Mi.Count > 0 then
begin
nod := TreeView1.Items.AddChildObject(tc, rsAttributes_ic, nil);
while Mi.HasNext do
begin
ent := Mi.Next;
case ent.ClassName of
'TAttribute','TProperty' :
begin
attr := TAttribute(ent);
nod1 := TreeView1.Items.AddChildObject(nod, attr.Name + ' : ' + attr.ClassName, attr);
if Assigned(attr.TypeClassifier) then
TreeView1.Items.AddChildObject(nod1, attr.TypeClassifier.Name + ' : ' + attr.TypeClassifier.ClassName, attr.TypeClassifier);
end;
else
Assert(True, 'Unhandled Attribute class ' + ent.ClassName);
end;
end;
end;
Mi := TModelIterator.Create(GetOperations);
if Mi.Count > 0 then
begin
nod := TreeView1.Items.AddChildObject(tc, rsOperations_ic, nil);
while Mi.HasNext do
begin
ent := Mi.Next;
nod1 := TreeView1.Items.AddChildObject(nod, ent.Name + ' : ' + ent.ClassName, ent);
op := TOperation(ent);
TreeView1.Items.AddChild(nod1,' ' + rsOperationType_ic + ': ' + GetEnumName(typeinfo(TOperationType), ord(op.OperationType)));
Pi := TModelIterator.Create(op.GetParameters);
if Pi.Count > 0 then
while Pi.HasNext do
begin
par := TParameter(Pi.Next);
nod2 := TreeView1.Items.AddChildObject(nod1, par.Name + ' : ' + par.ClassName, par);
if Assigned(par.TypeClassifier) then
nod3 := TreeView1.Items.AddChildObject(nod2, par.TypeClassifier.Name + ' : ' + par.TypeClassifier.ClassName, par.TypeClassifier);
end;
if (op.OperationType = otFunction) then
begin
TreeView1.Items.AddChildObject(nod1,rsReturn_ic + ': ' + op.ReturnValue.Name + ' : ' + op.ReturnValue.ClassName, op.ReturnValue);
end;
end;
end;
end;
end;
procedure TClassTreeEditForm.InitTreeFromUnit;
var
nod,nod1: TTreeNode;
clsf: TClassifier;
Mi: IModelIterator;
begin
nod := TreeView1.Items.AddChildObject(nil,FModelObject.Name, FModelObject);
with FModelObject as TUnitPackage do
begin
Mi := TModelIterator.Create(GetClassifiers);
if Mi.Count > 0 then
while Mi.HasNext do
begin
clsf := TClassifier(Mi.Next);
nod1 := TreeView1.Items.AddChildObject(nod, clsf.Name + ' : ' + clsf.ClassName, clsf);
case clsf.ClassName of
'TDataType':
begin
end;
'TClass':
begin
end;
'TInterface':
begin
end;
'TEnumeration':
DisplayEnums(nod1,TEnumeration(clsf));
else
Assert(true,'Unknown Classifier Type: ' + clsf.ClassName);
end;
end;
end;
end;
procedure TClassTreeEditForm.InitTreeFromDataType;
var
root: TTreeNode;
begin
root := TreeView1.Items.AddChildObject(nil, FModelObject.Name + ' : ' + FModelObject.ClassName, FModelObject);
case FModelObject.ClassName of
'TEnumeration':
begin
DisplayEnums(root, TEnumeration(FModelObject));
end;
'TStructuredDataType':;
'TDataType':;
end;
end;
procedure TClassTreeEditForm.DisplayEnums(ParentNode: TTreeNode;
Enum: TEnumeration);
var
Pi: TModelIterator;
tel: TEnumLiteral;
begin
Pi := TModelIterator.Create(Enum.GetFeatures);
if Pi.Count > 0 then
while Pi.HasNext do
begin
tel := TEnumLiteral(Pi.Next);
TreeView1.Items.AddChildObject(ParentNode, tel.Name + ' : ' + tel.ClassName,tel);
end;
Pi.Free;
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLFileLWO<p>
Support-code to load Lightwave LWO Files (v6.0+, partial support).<p>
<b>History : </b><font size=-1><ul>
<li>16/10/08 - UweR - Compatibility fix for Delphi 2009
<li>30/03/07 - DaStr - Added $I GLScene.inc$I GLScene.inc
<li>24/03/07 - DaStr - Added explicit pointer dereferencing
(thanks Burkhard Carstens) (Bugtracker ID = 1678644)
<li>14/11/02 - EG - Added header, fixed warnings
<li>16/11/02 - BJ - Added smooth normals with crease angle
<li>17/11/02 - BJ - Added 2 and 4 point ngons -> triangles
<li>17/11/02 - BJ - Added Enviroment Map Image -> Cubic Projection Map
</ul><p>
Original code: "Brian Johns" <brianjohns1@hotmail.com>
}
unit GLFileLWO;
interface
{$I GLScene.inc}
uses Classes, GLVectorFileObjects, LWObjects;
type
TGLLWOVectorFile = class (TVectorFile)
private
FLWO: TLWObjectFile;
FPnts: TLWPnts;
procedure AddLayr(Layr: TLWLayr; LWO: TLWObjectFile);
procedure AddSurf(Surf: TLWSurf; LWO: TLWObjectFile);
procedure AddPnts(Pnts: TLWPnts; Mesh: TMeshObject);
procedure AddPols(Pols: TLWPols; Mesh: TMeshObject);
procedure AddVMap(VMap: TLWVMap; Mesh: TMeshObject);
public
procedure LoadFromStream(aStream: TStream); override;
end;
implementation
uses SysUtils, GLVectorGeometry, GLTexture, GLMaterial, GLVectorTypes;
type
PVector3f = ^TVector3f;
function CalcTriNorm(v1,v2,v3: TVec12): TVector3f;
var
e1, e2: TVector3f;
begin
e1 := VectorSubtract(PVector3f(@v2)^,PVector3f(@v1)^);
e2 := VectorSubtract(PVector3f(@v3)^,PVector3f(@v1)^);
VectorCrossProduct(e1,e2,result);
result := VectorNormalize(result);
end;
type
TNormBuffer = record
count,lasttag: TU2;
end;
TNormBufferDynArray = array of TNormBuffer;
{ TGLLWOVectorFile }
{
******************************* TGLLWOVectorFile *******************************
}
procedure TGLLWOVectorFile.AddLayr(Layr: TLWLayr; LWO: TLWObjectFile);
var
Idx: Integer;
Mesh: TMeshObject;
Pnts: TLWPnts;
begin
// Add mesh
Mesh:=TMeshObject.CreateOwned(Owner.MeshObjects);
with Mesh do
begin
Name:=Layr.Name;
Mode:=momFaceGroups;
// pnts
Idx:=Layr.Items.FindChunk(@FindChunkById,@ID_PNTS);
Pnts:=TLWPnts(Layr.Items[Idx]);
if Idx<>-1 then
AddPnts(Pnts,Mesh);
// vertex maps
Idx:=TLWPnts(Layr.Items[Idx]).Items.FindChunk(@FindChunkById,@ID_VMAP);
while Idx<>-1 do
begin
AddVMap(TLWVMap(Pnts.Items[Idx]),Mesh);
Idx := Pnts.Items.FindChunk(@FindChunkById,@ID_VMAP,Idx + 1);
end;
// Polygons
Idx:=Layr.Items.FindChunk(@FindChunkById,@ID_POLS);
while Idx<>-1 do
begin
AddPols(TLWPols(Layr.Items[Idx]),Mesh);
Idx := Layr.Items.FindChunk(@FindChunkById,@ID_POLS, Idx + 1);
end;
// Normals.Normalize;
end;
FPnts:=nil;
end;
procedure TGLLWOVectorFile.AddPnts(Pnts: TLWPnts; Mesh: TMeshObject);
var
i: Integer;
begin
FPnts:=Pnts;
with Mesh do
begin
Vertices.Capacity:=Pnts.PntsCount;
TexCoords.Capacity:=Pnts.PntsCount;
TexCoords.AddNulls(Pnts.PntsCount);
for i := 0 to Pnts.PntsCount - 1 do
Vertices.Add(PAffineVector(@Pnts.Pnts[i])^);
end;
end;
procedure TGLLWOVectorFile.AddPols(Pols: TLWPols; Mesh: TMeshObject);
var
Idx: Integer;
i,j,k, PolyIdx, NormIdx: Integer;
TagPolys: TU2DynArray;
FaceGrp: TFGVertexNormalTexIndexList;
VertPolys: TU2DynArray;
begin
SetLength(VertPolys, 0);
with Pols do
begin
// face type pols chunk
if PolsType=POLS_TYPE_FACE then
begin
Idx:=Items.FindChunk(@FindChunkById,@ID_PTAG);
while Idx<>-1 do
begin
with TLWPTag(Items[Idx]) do
begin
if MapType=PTAG_TYPE_SURF then
begin
// for each tag
for i:=0 to TagCount-1 do
begin
// get polygons using this tag
if GetPolsByTag(Tags[i],TagPolys)>0 then
begin
// make the facegroup and set the material name
FaceGrp:=TFGVertexNormalTexIndexList.CreateOwned(Mesh.FaceGroups);
FaceGrp.MaterialName:=FLWO.SurfaceByTag[Tags[i]].Name;
FaceGrp.Mode:=fgmmTriangles;
// for each polygon in the current surface Tags[i]
for j:=0 to Length(TagPolys)-1 do
begin
PolyIdx:=PolsByIndex[TagPolys[j]];
// triple 2,3 and 4 point ngons
case Indices[PolyIdx] of
2: begin
// triangle line segment
NormIdx:=Mesh.Normals.Add(PVector3f(@PolsInfo[TagPolys[j]].vnorms[0])^);
FaceGrp.Add(Indices[PolyIdx + 1],NormIdx,Indices[PolyIdx + 1]);
NormIdx:=Mesh.Normals.Add(PVector3f(@PolsInfo[TagPolys[j]].vnorms[1])^);
FaceGrp.Add(Indices[PolyIdx + 2],NormIdx,Indices[PolyIdx + 1]);
NormIdx:=Mesh.Normals.Add(PVector3f(@PolsInfo[TagPolys[j]].vnorms[0])^);
FaceGrp.Add(Indices[PolyIdx + 1],NormIdx,Indices[PolyIdx + 1]);
end;
3: for k:=1 to 3 do begin
NormIdx:=Mesh.Normals.Add(PVector3f(@PolsInfo[TagPolys[j]].vnorms[k-1])^);
FaceGrp.Add(Indices[PolyIdx + k],NormIdx,Indices[PolyIdx + 1]);
end;
4: begin
// triangle A
NormIdx:=Mesh.Normals.Add(PVector3f(@PolsInfo[TagPolys[j]].vnorms[0])^);
FaceGrp.Add(Indices[PolyIdx + 1],NormIdx,Indices[PolyIdx + 1]);
NormIdx:=Mesh.Normals.Add(PVector3f(@PolsInfo[TagPolys[j]].vnorms[1])^);
FaceGrp.Add(Indices[PolyIdx + 2],NormIdx,Indices[PolyIdx + 1]);
NormIdx:=Mesh.Normals.Add(PVector3f(@PolsInfo[TagPolys[j]].vnorms[2])^);
FaceGrp.Add(Indices[PolyIdx + 3],NormIdx,Indices[PolyIdx + 1]);
// triangle B
NormIdx:=Mesh.Normals.Add(PVector3f(@PolsInfo[TagPolys[j]].vnorms[0])^);
FaceGrp.Add(Indices[PolyIdx + 1],NormIdx,Indices[PolyIdx + 1]);
NormIdx:=Mesh.Normals.Add(PVector3f(@PolsInfo[TagPolys[j]].vnorms[2])^);
FaceGrp.Add(Indices[PolyIdx + 3],NormIdx,Indices[PolyIdx + 1]);
NormIdx:=Mesh.Normals.Add(PVector3f(@PolsInfo[TagPolys[j]].vnorms[3])^);
FaceGrp.Add(Indices[PolyIdx + 4],NormIdx,Indices[PolyIdx + 1]);
end;
end;
end;
SetLength(TagPolys,0);
end;
end;
end else
if MapType=PTAG_TYPE_PART then
begin
{Todo: PTag PART}
end else
if MapType=PTAG_TYPE_SMGP then
begin
{Todo: PTag Smooth Group}
end;
Idx:=Items.FindChunk(@FindChunkById,@ID_PTAG,Idx + 1);
end;
end;
end else
// curv type pols chunk (catmull-rom splines)
if PolsType=POLS_TYPE_CURV then
begin
{Todo: CURV Pols import}
end else
// nurbs patch pols type chunk
if PolsType=POLS_TYPE_PTCH then
begin
{Todo: NURBS Patch Pols import}
end else
// metaball pols type chunk
if PolsType=POLS_TYPE_MBAL then
begin
{Todo: MetaBall type Pols import}
end else
// bone pols type chunk
if PolsType=POLS_TYPE_BONE then
begin
{Todo: Bone Pols import}
end;
SetLength(TagPolys,0);
end;
end;
procedure TGLLWOVectorFile.AddSurf(Surf: TLWSurf; LWO: TLWObjectFile);
var
matLib: TGLMaterialLibrary;
libMat: TGLLibMaterial;
tex2Mat: TGLLibMaterial;
colr: TColr12;
FloatParm,tran, refl: TF4;
WordParm: TU2;
StrParm: string;
Idx: integer;
begin
{DONE: implement surface inheritance}
if GetOwner is TGLBaseMesh then
begin
matLib:=TGLBaseMesh(GetOwner).MaterialLibrary;
if Assigned(matLib) then
begin
libMat:=matLib.Materials.GetLibMaterialByName(Surf.Name);
if not Assigned(libMat) then
begin
libMat:=matLib.Materials.Add;
libMat.Name:=Surf.Name;
with libMat.Material.FrontProperties do
begin
tran:=Surf.FloatParam[ID_TRAN];
if tran<>0 then
libMat.Material.BlendingMode := bmTransparency;
colr:=Surf.Vec3Param[ID_COLR];
// Ambient.Color := VectorMake(colr[0],colr[1],colr[2],1);
Ambient.Color:=VectorMake(0,0,0,1);
(* Diffuse *)
FloatParm:=Surf.FloatParam[ID_DIFF];
Diffuse.Color:=VectorMake(colr[0] * FloatParm,colr[1] * FloatParm,colr[2] * FloatParm,tran);
(* Luminosity -> Emission *)
FloatParm:=Surf.FloatParam[ID_LUMI];
Emission.Color:=VectorMake(colr[0] * FloatParm,colr[1] * FloatParm, colr[2] * FloatParm, 1);
(* Specularity *)
FloatParm:=Surf.FloatParam[ID_SPEC];
Specular.Color:=VectorMake(colr[0] * FloatParm,colr[1] * FloatParm, colr[2] * FloatParm, 1);
(* Glossiness -> Shininess *)
FloatParm:=Surf.FloatParam[ID_GLOS];
Shininess:=Round(Power(2,7*FloatParm));
(* Polygon sidedness *)
WordParm:=Surf.WordParam[ID_SIDE];
if (WordParm and SIDE_BACK)=SIDE_BACK then
AssignTo(libMat.Material.BackProperties);
(* Reflection settings *)
refl:=Surf.FloatParam[ID_REFL];
if refl>0 then
begin
// Check the reflection options
WordParm:=Surf.WordParam[ID_RFOP];
if WordParm>RFOP_RAYTRACEANDBACKDROP then
begin
WordParm:=Surf.VXParam[ID_RIMG];
Idx:=Surf.RootChunks.FindChunk(@FindClipByClipIndex,@WordParm);
if Idx<>-1 then
begin
StrParm:=PAnsiChar(TLWClip(Surf.RootChunks[Idx]).ParamAddr[ID_STIL]);
StrParm:=GetContentDir.FindContent(ToDosPath(StrParm));
if FileExists(StrParm) then
try
if (not libMat.Material.Texture.Enabled) then
tex2Mat:=libMat
else
tex2Mat:=matLib.Materials.Add;
with tex2Mat do
begin
Material.Texture.Image.LoadFromFile(StrParm);
Material.Texture.Disabled:=False;
with Material.Texture do
begin
MappingMode:=tmmCubeMapReflection;
if refl < 100 then
TextureMode:=tmBlend
else
TextureMode:=tmDecal;
end;
end;
libMat.Texture2Name:='REFL_'+ExtractFileName(StrParm);
except
on E: ETexture do begin
if not Self.Owner.IgnoreMissingTextures then
raise;
end;
end;
end;
end;
end;
end;
end;
end;
end;
end;
procedure TGLLWOVectorFile.AddVMap(VMap: TLWVMap; Mesh: TMeshObject);
var
i: integer;
begin
with VMap, Mesh do
begin
// texture coords
if VMapType = VMAP_TYPE_TXUV then
begin
for i := 0 to ValueCount - 1 do
TexCoords.Items[Value[i].vert] := AffineVectorMake(Value[i].values[0], Value[i].values[1], 0);
end else
// vertex weight map
if VMapType = VMAP_TYPE_WGHT then
begin
{Todo: WeightMap import}
end else
// vertex morph (relative)
if VMapType = VMAP_TYPE_MORF then
begin
{Todo: Morph target (relative) import}
end else
// vertex morph (absolute)
if VMapType = VMAP_TYPE_SPOT then
begin
{Todo: Morph target (absolute) import}
end;
end;
end;
procedure TGLLWOVectorFile.LoadFromStream(aStream: TStream);
var
Ind: Integer;
begin
FLWO := TLWObjectFile.Create;
with FLWO do
try
LoadFromStream(aStream);
// Add Surfaces to material list
Ind := Chunks.FindChunk(@FindChunkById,@ID_SURF,0);
while Ind <> -1 do
begin
AddSurf(TLWSurf(Chunks[Ind]), FLWO);
Ind := Chunks.FindChunk(@FindChunkById,@ID_SURF,Ind + 1);
end;
// Lw layer
Ind := Chunks.FindChunk(@FindChunkById,@ID_LAYR,0);
while Ind <> -1 do
begin
AddLayr(TLWLayr(Chunks[Ind]),FLWO);
Ind := Chunks.FindChunk(@FindChunkById,@ID_LAYR,Ind + 1);
end;
finally
FreeAndNil(FLWO);
end;
end;
initialization
RegisterVectorFileFormat('lwo', 'Lightwave3D object file (6.0 or above)', TGLLWOVectorFile);
finalization
end.
|
unit uSynopseJSON;
// mORMot has its own UTF-8 JSON engine: let's use it for the process
interface
uses
System.SysUtils,
SynCommons;
// first method using a TDocVariantData document
function ProcessJsonMormotDocVariant(const input: RawUtf8): RawUtf8;
// second method using RTTI over records (as golang does)
function ProcessJsonMormotRtti(const input: RawUtf8): RawUtf8;
implementation
function ProcessJsonMormotDocVariant(const input: RawUtf8): RawUtf8;
var
json: TDocVariantData;
group, dates: PDocVariantData;
minDate, maxDate, dt: TDateTime;
n: PtrInt;
begin
json.InitJsonInPlace(pointer(input), JSON_OPTIONS_FAST);
group := json.O['group'];
dates := group.A['dates'];
minDate := MaxDateTime;
maxDate := MinDateTime;
for n := 0 to dates.Count - 1 do
begin
dt := Iso8601ToDateTime(VariantToUtf8(dates.Values[n]));
if dt < minDate then
minDate := dt;
if dt > maxDate then
maxDate := dt;
end;
result := JsonEncode([
'product', json.U['product'],
'requestId', json.U['requestId'],
'client', '{',
'balance', group.U['balance'],
'minDate', DateTimeToIso8601Text(minDate, 'T', true) + 'Z',
'maxDate', DateTimeToIso8601Text(maxDate, 'T', true) + 'Z',
'}']);
end;
// second method using RTTI over records (as golang does)
type
TRequest = packed record
product: RawUtf8;
requestId: RawUtf8;
group: packed record
kind: RawUtf8;
default: boolean;
balance: currency;
dates: TDateTimeMSDynArray;
end;
end;
TResponse = packed record
product: RawUtf8;
requestId: RawUtf8;
client: packed record
balance: currency;
minDate, maxDate: TDateTimeMS;
end;
end;
function ProcessJsonMormotRtti(const input: RawUtf8): RawUtf8;
var
req: TRequest;
resp: TResponse;
dt: TDateTime;
n: PtrInt;
begin
RecordLoadJson(req, pointer(input), TypeInfo(TRequest));
resp.product := req.product;
resp.requestId := req.requestId;
resp.client.minDate := MaxDateTime;
resp.client.maxDate := MinDateTime;
resp.client.balance := req.group.balance;
for n := 0 to high(req.group.dates) do
begin
dt := req.group.dates[n];
if dt < resp.client.minDate then
resp.client.minDate := dt;
if dt > resp.client.maxDate then
resp.client.maxDate := dt;
end;
SaveJson(resp, TypeInfo(TResponse), [twoDateTimeWithZ], result);
end;
end.
|
unit uHelicoptero;
interface
uses
Windows,
SysUtils,
uIAeroNave;
type
THelicoptero = Class(TInterfacedObject, IAeroNave)
private
FNome:String;
public
function GetNome:string;
procedure Decolar;
procedure Pousar;
property Nome:String read GetNome;
constructor Create();
end;
implementation
{THelicoptero}
constructor THelicoptero.Create();
begin
FNome := Self.ClassName;
end;
function THelicoptero.GetNome:string;
begin
result := FNome;
end;
procedure THelicoptero.Decolar;
begin
WriteLn('Ligar rotores');
WriteLn('Aguardar rotacao necessaria');
WriteLn('Subir');
end;
procedure THelicoptero.Pousar;
begin
WriteLn('Diminur velocidade dos rotores');
WriteLn('Abaixar');
WriteLn('Pousar');
WriteLn('Desligar rotores');
end;
end.
|
{Виконав Мельник Олександр}
{$OPTIMIZATION OFF} {Зниження похибки на 2-3%. Програму необхідно запускати через `# nice -n -20 ./tmp` для ще більшого уточнення.}
unit LinuxTime;
interface
uses Global;
function SortingTime(Sort: TProc):longint;
implementation
uses linux,unixtype, Contain;
(*Функція GetLinTime.
*Викликає процедуру Sort для масиву А (оголошеного в Global) і вимірює
*конкретний час її виконання;
*ОТРИМУЄ: процедуру Sort типу TProc;
*ПОВЕРТАЄ: кількість затрачених на виконання процедури наносекунд у вигляді
*64-бітного цілого беззнакового типу QWord;
*ОЧІКУЄ: імпортовані модулі Global, linux, unixtype.*)
function GetLinTime(Sort: TProc):Qword;
const clockid=0; {ID таймера, з якого отримувати значення часу.}
var {Змінні типу PTimespec (вказівник на Timespec, що є записом з двох 32-бітних полів tv_sec і tv_nsec — для>}
StartTime, {<секунд й наносекунд відповідно) з модуля unixtype, що використовується процедурою clock_gettime модуля>}
FinishTime: PTimespec; {<linux для копіювання даних з системного таймера.}
begin
new(StartTime); new(FinishTime);
clock_gettime(clockid,StartTime);
Sort(A);
clock_gettime(clockid,FinishTime); {Отримує дані початку й кінця сортування.}
FinishTime^.tv_nsec:=FinishTime^.tv_nsec-StartTime^.tv_nsec;
FinishTime^.tv_sec:=FinishTime^.tv_sec-StartTime^.tv_sec; {Вираховує різницю по секундам і наносекундам,>}
GetLinTime:=(FinishTime^.tv_nsec) + FinishTime^.tv_sec*1000000000; {<після чого повертає приведений до мілісекунд результат.}
dispose(StartTime); dispose(FinishTime);
end;
(*Функція SortingTime
*Створює вибірку з count (див. Globdl) результатів запуску GetLinTime для одного й того ж
*методу сортування Sort одного і того ж масиву А, статистично усереднює її та
*переводить результат усереднення у мілісекунди;
*ОТРИМУЄ: процедуру Sort типу TProc;
*ПОВЕРТАЄ: кількість затрачених на виконання процедури наносекунд у вигляді
*32-бітного цілого беззнакового типу longword;
*ОЧІКУЄ: імпортований модуль Global.*)
function SortingTime(Sort: TProc):longint;
const MaxRealativeDiffDivisor=200; {Обернене (1/x) максимальне допустиме відхилення кроку — 0.5%.}
var z,i,k:word; {Індекси-лічильники.}
TimeStatSum, {64-бітні (на випадок суми вибірки більш як 4.2 секунди) змінні, що зберігають часові дані у>}
TmpTimeContainer, {<мілісекундах. Відповідно загальна сума вибірки, тимчасова змінна для проміжних обрахунків>}
MedianTime:Qword; {<і медіана.}
StatisticTimeArray:array[0..count] of Qword; {Масив (64 біт на випадок сортування довше ніж 4.2 секунди) змінного розміру для збереження всієї вибірки.}
begin
TimeStatSum:=0;
for z:=0 to count do
begin
TmpTimeContainer:=GetLinTime(Sort); {У цей масив набирається вибірка й відразу обраховується ії сума> }
if z<>0 then TimeStatSum:=TimeStatSum+TmpTimeContainer; {<Перше значення не включається до суми на цьому этапі, бо зазвичай є завищеним.}
StatisticTimeArray[z]:=TmpTimeContainer;
end;
i:=count;
for k:=1 to 3 do {Три кроки статистичного "причісування" вибірки — оптимальна цифра для отриманих при тестах похибок.}
if i<>0 then {Врахування випадку неіснування навіть єдиного елементу в потрібних межах відхилення&}
begin
MedianTime:=TimeStatSum div i;
TmpTimeContainer:=MedianTime div MaxRealativeDiffDivisor;
TimeStatSum:=0; i:=0;
for z:=0 to count do {На цьому етапі перше значення вибірки може бути врахованим, якщо потрапить в задані межі відхилення.}
if (StatisticTimeArray[z]>MedianTime-TmpTimeContainer) and
(StatisticTimeArray[z]<MedianTime+TmpTimeContainer) then
begin
TimeStatSum:=TimeStatSum+StatisticTimeArray[z]; {Елементи вибірки в межах відхилення сумуються>}
inc(i); {<з зазначенням їх кількості>}
end
else
StatisticTimeArray[z]:=0; {<інші обнуляються.}
end;
if i<>0 then
MedianTime:=TimeStatSum div i; {&Завершення вищезгаданого врахування.}
SortingTime:=round(MedianTime/1000000); {Повертає час в мілісекундах.}
end;
end.
|
///<summary>Fluent XML builder.</para>
///</summary>
///<author>Primoz Gabrijelcic</author>
///<remarks><para>
/// (c) 2009 Primoz Gabrijelcic
/// Free for personal and commercial use. No rights reserved.
///
/// Author : Primoz Gabrijelcic
/// Creation date : 2009-03-30
/// Last modification : 2009-10-04
/// Version : 0.2
///</para><para>
/// History:
/// 0.2: 2009-10-04
/// - Added node value-setting overloads for AddChild and AddSibling.
/// 0.1: 2009-03-30
/// - Created.
///</para></remarks>
unit GpFluentXml;
interface
uses
OmniXML_Types,
OmniXML;
type
IGpFluentXmlBuilder = interface ['{91F596A3-F5E3-451C-A6B9-C5FF3F23ECCC}']
function GetXml: IXmlDocument;
//
function AddChild(const name: XmlString): IGpFluentXmlBuilder; overload;
function AddChild(const name: XmlString; value: Variant): IGpFluentXmlBuilder; overload;
function AddComment(const comment: XmlString): IGpFluentXmlBuilder;
function AddProcessingInstruction(const target, data: XmlString): IGpFluentXmlBuilder;
function AddSibling(const name: XmlString): IGpFluentXmlBuilder; overload;
function AddSibling(const name: XmlString; value: Variant): IGpFluentXmlBuilder; overload;
function Anchor(var node: IXMLNode): IGpFluentXmlBuilder;
function Mark: IGpFluentXmlBuilder;
function Return: IGpFluentXmlBuilder;
function SetAttrib(const name, value: XmlString): IGpFluentXmlBuilder;
function Up: IGpFluentXmlBuilder;
property Attrib[const name, value: XmlString]: IGpFluentXmlBuilder
read SetAttrib; default;
property Xml: IXmlDocument read GetXml;
end; { IGpFluentXmlBuilder }
function CreateFluentXml: IGpFluentXmlBuilder;
implementation
uses
SysUtils,
Classes,
OmniXMLUtils;
type
TGpFluentXmlBuilder = class(TInterfacedObject, IGpFluentXmlBuilder)
private
fxbActiveNode : IXMLNode;
fxbMarkedNodes: IInterfaceList;
fxbXmlDoc : IXMLDocument;
protected
function ActiveNode: IXMLNode;
protected
function GetXml: IXmlDocument;
public
constructor Create;
destructor Destroy; override;
function AddChild(const name: XmlString): IGpFluentXmlBuilder; overload;
function AddChild(const name: XmlString; value: Variant): IGpFluentXmlBuilder; overload;
function AddComment(const comment: XmlString): IGpFluentXmlBuilder;
function AddProcessingInstruction(const target, data: XmlString): IGpFluentXmlBuilder;
function AddSibling(const name: XmlString): IGpFluentXmlBuilder; overload;
function AddSibling(const name: XmlString; value: Variant): IGpFluentXmlBuilder; overload;
function Anchor(var node: IXMLNode): IGpFluentXmlBuilder;
function Mark: IGpFluentXmlBuilder;
function Return: IGpFluentXmlBuilder;
function SetAttrib(const name, value: XmlString): IGpFluentXmlBuilder;
function Up: IGpFluentXmlBuilder;
end; { TGpFluentXmlBuilder }
{ globals }
function CreateFluentXml: IGpFluentXmlBuilder;
begin
Result := TGpFluentXmlBuilder.Create;
end; { CreateFluentXml }
{ TGpFluentXmlBuilder }
constructor TGpFluentXmlBuilder.Create;
begin
inherited Create;
fxbXmlDoc := CreateXMLDoc;
fxbMarkedNodes := TInterfaceList.Create;
end; { TGpFluentXmlBuilder.Create }
destructor TGpFluentXmlBuilder.Destroy;
begin
if fxbMarkedNodes.Count > 0 then
raise Exception.Create('''Mark'' stack is not completely empty');
inherited;
end; { TGpFluentXmlBuilder.Destroy }
function TGpFluentXmlBuilder.ActiveNode: IXMLNode;
begin
if assigned(fxbActiveNode) then
Result := fxbActiveNode
else begin
Result := DocumentElement(fxbXmlDoc);
if not assigned(Result) then
Result := fxbXmlDoc;
end;
end; { TGpFluentXmlBuilder.ActiveNode }
function TGpFluentXmlBuilder.AddChild(const name: XmlString): IGpFluentXmlBuilder;
begin
fxbActiveNode := AppendNode(ActiveNode, name);
Result := Self;
end; { TGpFluentXmlBuilder.AddChild }
function TGpFluentXmlBuilder.AddChild(const name: XmlString;
value: Variant): IGpFluentXmlBuilder;
begin
Result := AddChild(name);
SetTextChild(fxbActiveNode, XMLVariantToStr(value));
end; { TGpFluentXmlBuilder.AddChild }
function TGpFluentXmlBuilder.AddComment(const comment: XmlString): IGpFluentXmlBuilder;
begin
ActiveNode.AppendChild(fxbXmlDoc.CreateComment(comment));
Result := Self;
end; { TGpFluentXmlBuilder.AddComment }
function TGpFluentXmlBuilder.AddProcessingInstruction(const target, data: XmlString):
IGpFluentXmlBuilder;
begin
ActiveNode.AppendChild(fxbXmlDoc.CreateProcessingInstruction(target, data));
Result := Self;
end; { TGpFluentXmlBuilder.AddProcessingInstruction }
function TGpFluentXmlBuilder.AddSibling(const name: XmlString;
value: Variant): IGpFluentXmlBuilder;
begin
Result := AddSibling(name);
SetTextChild(fxbActiveNode, XMLVariantToStr(value));
end; { TGpFluentXmlBuilder.AddSibling }
function TGpFluentXmlBuilder.AddSibling(const name: XmlString): IGpFluentXmlBuilder;
begin
Result := Up;
fxbActiveNode := AppendNode(ActiveNode, name);
end; { TGpFluentXmlBuilder.AddSibling }
function TGpFluentXmlBuilder.Anchor(var node: IXMLNode): IGpFluentXmlBuilder;
begin
node := fxbActiveNode;
Result := Self;
end; { TGpFluentXmlBuilder.Anchor }
function TGpFluentXmlBuilder.GetXml: IXmlDocument;
begin
Result := fxbXmlDoc;
end; { TGpFluentXmlBuilder.GetXml }
function TGpFluentXmlBuilder.Mark: IGpFluentXmlBuilder;
begin
fxbMarkedNodes.Add(ActiveNode);
Result := Self;
end; { TGpFluentXmlBuilder.Mark }
function TGpFluentXmlBuilder.Return: IGpFluentXmlBuilder;
begin
fxbActiveNode := fxbMarkedNodes.Last as IXMLNode;
fxbMarkedNodes.Delete(fxbMarkedNodes.Count - 1);
Result := Self;
end; { TGpFluentXmlBuilder.Return }
function TGpFluentXmlBuilder.SetAttrib(const name, value: XmlString): IGpFluentXmlBuilder;
begin
SetNodeAttrStr(ActiveNode, name, value);
Result := Self;
end; { TGpFluentXmlBuilder.SetAttrib }
function TGpFluentXmlBuilder.Up: IGpFluentXmlBuilder;
begin
if not assigned(fxbActiveNode) then
raise Exception.Create('Cannot access a parent at the root level')
else if fxbActiveNode = DocumentElement(fxbXmlDoc) then
raise Exception.Create('Cannot create a parent at the document element level')
else
fxbActiveNode := ActiveNode.ParentNode;
Result := Self;
end; { TGpFluentXmlBuilder.Up }
end.
|
unit BuildIndexPackageOptFrm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls,
Vcl.Buttons, Vcl.FileCtrl, System.IOUtils, UnicodeMixedLib, PascalStrings;
type
TBuildIndexPackageOptForm = class(TForm)
DestDBEdit: TLabeledEdit;
DataPathEdit: TLabeledEdit;
OkButton: TButton;
CancelButton: TButton;
BrowseDestButton: TSpeedButton;
BrowseDataPathButton: TSpeedButton;
SaveDialog: TSaveDialog;
procedure FormCreate(Sender: TObject);
procedure BrowseDataPathButtonClick(Sender: TObject);
procedure BrowseDestButtonClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
public
{ Public declarations }
end;
var
BuildIndexPackageOptForm: TBuildIndexPackageOptForm;
implementation
{$R *.dfm}
procedure TBuildIndexPackageOptForm.FormCreate(Sender: TObject);
begin
DestDBEdit.Text := umlCombineFileName(TPath.GetDocumentsPath, 'temp.ox');
DataPathEdit.Text := umlCombinePath(TPath.GetDocumentsPath, 'DataCache\');
end;
procedure TBuildIndexPackageOptForm.BrowseDataPathButtonClick(Sender: TObject);
var
d: string;
begin
d := DataPathEdit.Text;
if not SelectDirectory('Data directory', '', d, [sdNewFolder, sdNewUI]) then
Exit;
DataPathEdit.Text := d;
end;
procedure TBuildIndexPackageOptForm.BrowseDestButtonClick(Sender: TObject);
begin
SaveDialog.FileName := DestDBEdit.Text;
if not SaveDialog.Execute() then
Exit;
DestDBEdit.Text := SaveDialog.FileName;
end;
procedure TBuildIndexPackageOptForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caHide;
end;
end.
|
unit uDMPetCenter;
interface
uses
SysUtils, Classes, DB, DBClient, MConnect, cxContainer, cxEdit, Variants, SyncObjs,
IdBaseComponent, IdComponent, IdTCPServer, IdSocketHandle, uMRParam, uPetCenterCli,
Dialogs, ADODB, Provider;
const
PET_STATUS_AVAILABLE = 1;
PET_STATUS_ONHOLD = 2;
PET_STATUS_ISOLATION = 3;
PET_STATUS_RETURN = 4;
PET_STATUS_SOLD = 5;
PET_STATUS_EXCEPTION = 6;
STATE_WAITING_HEADER = 0;
STATE_WAITING_BODY = 1;
type
TMRPetConnectionData = class
FState: Integer;
FStreamSizeExpected: LongInt;
FActualHeader: TInvoiceStreamHeader;
FConnectionParams: TMRParams;
FReportData : OleVariant;
FDefaultPrinter : String;
FPreview : Boolean;
end;
TDMPetCenter = class(TDataModule)
cxStyleController: TcxEditStyleController;
cdsRepWarranty: TClientDataSet;
cdsRepWarrantyIDWarrantyReport: TIntegerField;
cdsRepWarrantyIDSpecies: TIntegerField;
cdsRepWarrantyReport: TBlobField;
cdsRepWarrantyReportDate: TDateTimeField;
cdsRepWarrantyReportName: TStringField;
cdsLoadRepWarranty: TClientDataSet;
cdsLoadRepWarrantyIDWarrantyReport: TIntegerField;
cdsLoadRepWarrantyIDSpecies: TIntegerField;
cdsLoadRepWarrantyReport: TBlobField;
cdsLoadRepWarrantyReportDate: TDateTimeField;
cdsLoadRepWarrantyReportName: TStringField;
IdTCPServer: TIdTCPServer;
cdsSpecies: TClientDataSet;
cdsSpeciesIDSpecies: TIntegerField;
cdsSpeciesSpecies: TStringField;
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
procedure cdsLoadRepWarrantyBeforeGetRecords(Sender: TObject;
var OwnerData: OleVariant);
procedure IdTCPServerConnect(AThread: TIdPeerThread);
procedure IdTCPServerDisconnect(AThread: TIdPeerThread);
procedure IdTCPServerException(AThread: TIdPeerThread;
AException: Exception);
procedure IdTCPServerExecute(AThread: TIdPeerThread);
private
FReportsLoaded : Boolean;
FRepID : Integer;
FRepField : String;
//CS: TCriticalSection;
procedure LoadAllReports;
public
function GetWarrantyReport(AFieldName: String; AID : Integer) : TMemoryStream;
function FormatAddress(AAddress, ACity, AState, AZip : Variant) : String;
procedure StartPrinterServer;
procedure StopPrinterServer;
function SendInventoryDate: Boolean;
function PrintSale(AIDPreSale : Integer) : Boolean;
end;
var
DMPetCenter: TDMPetCenter;
implementation
uses uMRSQLParam, uDMWarrantyPrintThread, uNTierConsts, uDMPet;
{$R *.dfm}
{ TDMPetCenter }
function TDMPetCenter.GetWarrantyReport(AFieldName: String; AID : Integer): TMemoryStream;
begin
//CS.Enter;
try
Result := nil;
cdsRepWarranty.First;
FRepField := AFieldName;
FRepID := AID;
cdsRepWarranty.First;
if cdsRepWarranty.Locate(AFieldName, AID, []) then
begin
Result := TMemoryStream.Create();
TBlobField(cdsRepWarranty.FieldByName('Report')).SaveToStream(Result);
Result.seek(0, soFromBeginning);
end
else
try
cdsLoadRepWarranty.Open;
if not cdsLoadRepWarranty.IsEmpty then
begin
Result := TMemoryStream.Create();
TBlobField(cdsLoadRepWarranty.FieldByName('Report')).SaveToStream(Result);
Result.seek(0, soFromBeginning);
cdsRepWarranty.Append;
cdsRepWarranty.FieldByName('IDWarrantyReport').Value := cdsLoadRepWarranty.FieldByName('IDWarrantyReport').Value;
cdsRepWarranty.FieldByName('IDSpecies').Value := cdsLoadRepWarranty.FieldByName('IDSpecies').Value;
cdsRepWarranty.FieldByName('ReportDate').Value := cdsLoadRepWarranty.FieldByName('ReportDate').Value;
cdsRepWarranty.FieldByName('ReportName').Value := cdsLoadRepWarranty.FieldByName('ReportName').Value;
TBlobField(cdsRepWarranty.FieldByName('Report')).LoadFromStream(Result);
cdsRepWarranty.Post;
end;
finally
cdsLoadRepWarranty.Close;
end;
finally
//CS.Leave;
end;
end;
procedure TDMPetCenter.DataModuleCreate(Sender: TObject);
begin
FReportsLoaded := False;
//CS := TCriticalSection.Create;
cdsRepWarranty.CreateDataSet;
end;
procedure TDMPetCenter.DataModuleDestroy(Sender: TObject);
begin
StopPrinterServer;
cdsRepWarranty.Close;
//CS.Free;
end;
procedure TDMPetCenter.cdsLoadRepWarrantyBeforeGetRecords(Sender: TObject;
var OwnerData: OleVariant);
begin
with TMRSQLParam.Create do
try
if (FRepID <> 0) then
begin
AddKey(FRepField).AsInteger := FRepID;
KeyByName(FRepField).Condition := tcEquals;
end;
OwnerData := ParamString;
finally
Free;
end;
end;
function TDMPetCenter.FormatAddress(AAddress, ACity, AState,
AZip: Variant): String;
var
sAddress, sCity, sState, sZip : String;
begin
if (AAddress <> Null) then
sAddress := AAddress;
if (ACity <> Null) then
sCity := ACity;
if (AState <> Null) then
sState := AState;
if (AZip <> Null) then
sZip := AZip;
Result := sAddress + ' ' + sCity;
if sState <> '' then
Result := Result + ', ' + sState;
Result := Result + ' ' + sZip;
end;
procedure TDMPetCenter.IdTCPServerConnect(AThread: TIdPeerThread);
begin
AThread.Data := TMRPetConnectionData.Create;
with TMRPetConnectionData(AThread.Data) do
begin
FState := STATE_WAITING_HEADER;
FDefaultPrinter := DMPet.GetAppProperty('WarrantyRep', 'PrinterName');
FPreview := False;
FConnectionParams := TMRParams.Create;
FConnectionParams.AddKey(CON_PARAM_TYPE);
FConnectionParams.KeyByName(CON_PARAM_TYPE).AsString := DMPet.FConType;
FConnectionParams.AddKey(CON_PARAM_CLIENT_ID);
FConnectionParams.KeyByName(CON_PARAM_CLIENT_ID).AsString := DMPet.FClientID;
FConnectionParams.AddKey(CON_PARAM_HOST);
FConnectionParams.KeyByName(CON_PARAM_HOST).AsString := DMPet.FHost;
FConnectionParams.AddKey(CON_PARAM_PORT);
FConnectionParams.KeyByName(CON_PARAM_PORT).AsString := DMPet.FPort;
FConnectionParams.AddKey(CON_PARAM_SOFTWARE);
FConnectionParams.KeyByName(CON_PARAM_SOFTWARE).AsString := DMPet.FSoftware;
FReportData := cdsRepWarranty.Data;
end;
end;
procedure TDMPetCenter.IdTCPServerDisconnect(AThread: TIdPeerThread);
var
ThreadData : TMRPetConnectionData;
begin
ThreadData := TMRPetConnectionData(AThread.Data);
FreeAndNil(ThreadData.FConnectionParams);
AThread.Data := nil;
FreeAndNil(ThreadData);
end;
procedure TDMPetCenter.IdTCPServerException(AThread: TIdPeerThread;
AException: Exception);
begin
if AException.Message = 'EIdConnClosedGracefully' then
begin
//process some code here if you want.
end;
end;
procedure TDMPetCenter.IdTCPServerExecute(AThread: TIdPeerThread);
var
ReceivingStream : TMemoryStream;
ConData : TMRPetConnectionData;
FInvoiceInfo : TInvoiceInfo;
FDMThread : TDMWarrantyPrintThread;
begin
ConData := TMRPetConnectionData(AThread.Data);
if AThread.Connection.Connected then
case ConData.FState of
STATE_WAITING_HEADER:
begin
ReceivingStream := TMemoryStream.Create;
try
AThread.Connection.ReadStream(ReceivingStream, SizeOf(TInvoiceStreamHeader));
ReceivingStream.Seek(0, soFromBeginning);
ConData.FActualHeader := TInvoiceStreamHeader(ReceivingStream.Memory^);
finally
FreeAndNil(ReceivingStream);
end;
ConData.FState := STATE_WAITING_BODY;
end;
STATE_WAITING_BODY:
begin
ReceivingStream := TMemoryStream.Create;
try
AThread.Connection.ReadStream(ReceivingStream, ConData.FActualHeader.ByteCount);
ReceivingStream.Seek(0, soFromBeginning);
case ConData.FActualHeader.PCComponentType of
ictInvoice:
begin
FInvoiceInfo := TInvoiceInfo(ReceivingStream.Memory^);
FDMThread := TDMWarrantyPrintThread.Create(nil);
try
with FDMThread do
try
Preview := ConData.FPreview;
DefaulPrinter := ConData.FDefaultPrinter;
cdsRepWarranty.Data := ConData.FReportData;
ConnectionParams := ConData.FConnectionParams;
PrintWarrantyFromMainRetail(FInvoiceInfo.IDPreSale);
except
//on e: exception do
// Writeln(e.message);
end;
finally
FreeAndNil(FDMThread);
end;
end;
end;
finally
FreeAndNil(ReceivingStream);
end;
ConData.FState := STATE_WAITING_HEADER;
end;
end;
end;
procedure TDMPetCenter.StartPrinterServer;
var
Binding : TIdSocketHandle;
begin
{
if IdTCPServer.Active then
IdTCPServer.Active := False;
IdTCPServer.Bindings.Clear;
try
Binding := IdTCPServer.Bindings.Add;
Binding.IP := DMPet.GetAppProperty('PrintServer', 'ServerIP');
Binding.Port := StrToIntDef(DMPet.GetAppProperty('PrintServer', 'ServerPort'), 1555);
IdTCPServer.Active := True;
LoadAllReports;
except
on E : Exception do
begin
ShowMessage(E.Message);
end;
end;
}
try
LoadAllReports;
except
on E : Exception do
begin
ShowMessage(E.Message);
end;
end;
end;
procedure TDMPetCenter.StopPrinterServer;
var
i: Integer;
Binding: TIdSocketHandle;
begin
{if IdTCPServer.Threads <> nil then
begin
with IdTCPServer.Threads.LockList do
try
for i := 0 to Count - 1 do
TIdPeerThread(Items[i]).Connection.DisconnectSocket;
finally
IdTCPServer.Threads.UnlockList;
end;
end;
if IdTCPServer.Active then
begin
IdTCPServer.Active := False;
while IdTCPServer.Bindings.Count > 0 do
begin
Binding := IdTCPServer.Bindings.Items[0];
FreeAndNil(Binding);
end;
IdTCPServer.Bindings.Clear;
end;
}
end;
procedure TDMPetCenter.LoadAllReports;
var
MS : TMemoryStream;
begin
if not FReportsLoaded then
begin
FReportsLoaded := True;
with cdsSpecies do
try
if not Active then
Open;
First;
while not EOF do
begin
MS := GetWarrantyReport('IDSpecies', FieldByName('IDSpecies').AsInteger);
try
finally
MS.Free;
end;
Next;
end;
finally
Close;
end;
end;
end;
function TDMPetCenter.SendInventoryDate: Boolean;
begin
end;
function TDMPetCenter.PrintSale(AIDPreSale : Integer): Boolean;
var
FDMThread : TDMWarrantyPrintThread;
FConnectionParams: TMRParams;
begin
Result := False;
FConnectionParams := TMRParams.Create;
try
FConnectionParams.AddKey(CON_PARAM_TYPE);
FConnectionParams.KeyByName(CON_PARAM_TYPE).AsString := DMPet.FConType;
FConnectionParams.AddKey(CON_PARAM_CLIENT_ID);
FConnectionParams.KeyByName(CON_PARAM_CLIENT_ID).AsString := DMPet.FClientID;
FConnectionParams.AddKey(CON_PARAM_HOST);
FConnectionParams.KeyByName(CON_PARAM_HOST).AsString := DMPet.FHost;
FConnectionParams.AddKey(CON_PARAM_PORT);
FConnectionParams.KeyByName(CON_PARAM_PORT).AsString := DMPet.FPort;
FConnectionParams.AddKey(CON_PARAM_SOFTWARE);
FConnectionParams.KeyByName(CON_PARAM_SOFTWARE).AsString := DMPet.FSoftware;
FDMThread := TDMWarrantyPrintThread.Create(nil);
try
with FDMThread do
try
Preview := False;
DefaulPrinter := DMPet.GetAppProperty('WarrantyRep', 'PrinterName');
cdsRepWarranty.Data := Self.cdsRepWarranty.Data;
ConnectionParams := FConnectionParams;
Result := PrintWarrantyFromMainRetail(AIDPreSale);
except
//on e: exception do
// Writeln(e.message);
end;
finally
FreeAndNil(FDMThread);
end;
finally
freeAndNil(FConnectionParams);
end;
end;
end.
|
{******************************************************************}
{ SVG types }
{ }
{ home page : http://www.mwcs.de }
{ email : martin.walter@mwcs.de }
{ }
{ date : 05-04-2008 }
{ }
{ Use of this file is permitted for commercial and non-commercial }
{ use, as long as the author is credited. }
{ This file (c) 2005, 2008 Martin Walter }
{ }
{ }
{ Thanks to: }
{ Kiriakos Vlahos (New Types) }
{ Kiriakos Vlahos (Enhanced TSVG attributes) }
{ Kiriakos Vlahos (added TSVGElementFeature) }
{ Kiriakos Vlahos (Added TSVGElementFeatures) }
{ }
{ This Software is distributed on an "AS IS" basis, WITHOUT }
{ WARRANTY OF ANY KIND, either express or implied. }
{ }
{ *****************************************************************}
unit SVGTypes;
interface
uses
System.Math,
System.Types,
System.UITypes,
Winapi.GDIPOBJ;
{$IF CompilerVersion >= 24.0 }
{$LEGACYIFEND ON}
{$IFEND}
const
SVG_INHERIT_COLOR = TColors.SysDefault;
SVG_NONE_COLOR = TColors.SysNone;
FontNormal = 0;
FontItalic = 1;
MaxTFloat = MaxSingle;
UndefinedFloat = -340282346638528859811704183484516925440.0; //Single.MinValue
UndefinedInt = -2147483648; // Integer.MinValue
type
//Redefine to compile with older Delphi Versions
{$IFDEF NEXTGEN}
PUTF8Char = _PAnsiChar;
{$ELSE}
PUTF8Char = PAnsiChar;
{$ENDIF}
TFloat = single;
TSVGElementFeature = (sefMayHaveChildren, sefNeedsPainting, sefChildrenNeedPainting, sefHasPath);
TSVGElementFeatures = set of TSVGElementFeature;
TListOfPoints = array of TPointF;
TRectarray = packed array of TRectF;
PRectArray = ^TRectArray;
TTextDecoration = set of (tdInherit, tdUnderLine, tdOverLine, tdStrikeOut);
TTextPathMethod = (tpmAlign, tpmStretch);
TTextPathSpacing = (tpsAuto, tpsExact);
TSVGUnit = (suNone, suPX, suPT, suPC, suMM, suCM, suIN, suEM, suEX, suPercent);
TGradientUnits = (guObjectBoundingBox, guUserSpaceOnUse);
TLengthType = (ltHorz, ltVert, ltOther);
TTriStateBoolean = (tbFalse, tbTrue, tbInherit);
TSVGAttribute = (saId,
saX,
saY,
saX1,
saY1,
saX2,
saY2,
saCx,
saCy,
saD,
saDx,
saDy,
saFx,
saFy,
saR,
saRx,
saRy,
saStyle,
saClass,
saXlinkHref,
saHref,
saPoints,
saGradientUnits,
saGradientTransform,
saVisibility,
saVersion,
saWidth,
saHeight,
saViewBox,
saTransform,
saOffset,
saStopOpacity,
saStopColor,
saSpacing,
saStartOffset,
saMethod,
saStrokeWidth,
saLineWidth,
saOpacity,
saStrokeOpacity,
saFillOpacity,
saColor,
saStroke,
saFill,
saClipPath,
saStrokeLinejoin,
saStrokeLinecap,
saStrokeMiterlimit,
saStrokeDashoffset,
saStrokeDasharray,
saFillRule,
saFontFamily,
saFontWeight,
saFontSize,
saTextDecoration,
saFontStyle,
saDisplay);
TAffineMatrix = record
public
m11: Single;
m12: Single;
m21: Single;
m22: Single;
dx: Single;
dy: Single;
constructor Create(_m11, _m12, _m21, _m22, _dx, _dy: Single);
constructor FromGPMatrix(GPMatrix: TGPMatrix);
function IsEmpty: Boolean;
function IsIdentity: Boolean;
function ToGPMatrix: TGPMatrix;
class function CreateRotation(const AAngle: Single): TAffineMatrix; static;
class function CreateScaling(const AScaleX, AScaleY: Single): TAffineMatrix; static;
class function CreateTranslation(const ADeltaX, ADeltaY: Single): TAffineMatrix; static;
class operator Multiply(const AMatrix1, AMatrix2: TAffineMatrix): TAffineMatrix;
class operator Multiply(const APoint: TPointF; const AMatrix: TAffineMatrix): TPointF;
end;
const AffineMatrixEmpty: TAffineMatrix = (m11: 0; m12: 0; m21: 0; m22: 0; dx: 0; dy: 0);
const AffineMatrixIdentity: TAffineMatrix = (m11: 1; m12: 0; m21: 0; m22: 1; dx: 0; dy: 0);
implementation
Uses
System.SysUtils;
{ TAffineMatrix }
constructor TAffineMatrix.Create(_m11, _m12, _m21, _m22, _dx, _dy: Single);
begin
Self.m11 := _m11;
Self.m12 := _m12;
Self.m21 := _m21;
Self.m22 := _m22;
Self.dx := _dx;
Self.dy := _dy;
end;
class function TAffineMatrix.CreateRotation(
const AAngle: Single): TAffineMatrix;
procedure SinCosSingle(const Theta: Single; var Sin, Cos: Single);
var
{$IF SizeOf(Extended) > SizeOf(Double)}
S, C: Extended;
{$ELSE}
S, C: Double;
{$IFEND}
begin
System.SineCosine(Theta, S, C);
Sin := S;
Cos := C;
end;
var
Sine, Cosine: Single;
begin
SinCosSingle(AAngle, Sine, Cosine);
Result := AffineMatrixIdentity;
Result.m11 := Cosine;
Result.m12 := Sine;
Result.m21 := -Sine;
Result.m22 := Cosine;
end;
class function TAffineMatrix.CreateScaling(const AScaleX,
AScaleY: Single): TAffineMatrix;
begin
Result := AffineMatrixIdentity;
Result.m11 := AScaleX;
Result.m22 := AScaleY;
end;
class function TAffineMatrix.CreateTranslation(const ADeltaX,
ADeltaY: Single): TAffineMatrix;
begin
Result := AffineMatrixIdentity;
Result.dx := ADeltaX;
Result.dy := ADeltaY;
end;
constructor TAffineMatrix.FromGPMatrix(GPMatrix: TGPMatrix);
Var
MA: Winapi.GDIPOBJ.TMatrixArray;
begin
GPMatrix.GetElements(MA);
Self.m11 := MA[0];
Self.m12 := MA[1];
Self.m21 := MA[2];
Self.m22 := MA[3];
Self.dx := MA[4];
Self.dy := MA[5];
end;
function TAffineMatrix.IsEmpty: Boolean;
begin
Result := CompareMem(@Self, @AffineMatrixEmpty, SizeOf(TAffineMatrix));
end;
function TAffineMatrix.IsIdentity: Boolean;
begin
Result := CompareMem(@Self, @AffineMatrixIdentity, SizeOf(TAffineMatrix));
end;
class operator TAffineMatrix.Multiply(const APoint: TPointF;
const AMatrix: TAffineMatrix): TPointF;
begin
Result.X := APoint.X * AMatrix.m11 + APoint.Y * AMatrix.m21 + AMatrix.dx;
Result.Y := APoint.X * AMatrix.m12 + APoint.Y * AMatrix.m22 + AMatrix.dy;
end;
function TAffineMatrix.ToGPMatrix: TGPMatrix;
begin
Result := TGPMatrix.Create(m11, m12, m21, m22, dx, dy);
end;
class operator TAffineMatrix.Multiply(const AMatrix1,
AMatrix2: TAffineMatrix): TAffineMatrix;
begin
Result.m11 := AMatrix1.m11 * AMatrix2.m11 + AMatrix1.m12 * AMatrix2.m21;
Result.m12 := AMatrix1.m11 * AMatrix2.m12 + AMatrix1.m12 * AMatrix2.m22;
Result.m21 := AMatrix1.m21 * AMatrix2.m11 + AMatrix1.m22 * AMatrix2.m21;
Result.m22 := AMatrix1.m21 * AMatrix2.m12 + AMatrix1.m22 * AMatrix2.m22;
Result.dx := AMatrix1.dx * AMatrix2.m11 + AMatrix1.dy * AMatrix2.m21 + AMatrix2.dx;
Result.dy := AMatrix1.dx * AMatrix2.m12 + AMatrix1.dy * AMatrix2.m22 + AMatrix2.dy;
end;
end.
|
Program ex21 ;
//Lucas Perussi
var n1, n2, n3:Integer;
aux, aux2, aux3, numero:integer;
Begin
Writeln ('Digite um número inteiro de três digitos: ');
read (numero);
while (numero < 100) or (numero > 999) do
begin
clrscr;
Writeln ('Número inválido!!');
Writeln ('Digite um número inteiro de três digitos: ');
read (numero);
end;
aux := (numero mod 10);
n1 := aux;
aux := numero div 10;
aux2 := (aux mod 10);
n2 := aux2;
aux2 := (aux div 10);
n3:= (aux2 mod 10);
writeln('O inverso do valor informado é: ',n1, n2, n3);
End.
Program ex22 ;
//Lucas Perussi
var dia, mes, ano:Integer;
Begin
Writeln ('Informe uma dia: ');
read(dia);
while (dia <1) or (dia > 31) do
begin
clrscr;
Writeln ('data Inválida! ');
Writeln ('Informe uma dia: ');
read(dia);
end;
Writeln ('Informe um mês : ');
read(mes);
Writeln ('Informe um ano : ');
read(ano);
if (mes > 12) then Writeln ('Data Inválida!');
if (ano < 1900) then Writeln ('Data Inválida!');
if (mes =4) or (mes =6) or (mes =9) or (mes =11) and (dia > 30) then
begin
Writeln ('Data Inválida!');
end;
if (mes =1) or (mes =3) or (mes =5) or (mes =7) or (mes =8)or (mes =10)or (mes =12) and (dia > 31) then
begin
Writeln ('Data Inválida!');
end;
if ((ano mod 4) = 0) then //bissexto
begin
if (mes =2) and (dia > 29) then Writeln ('Data Inválida!');
end;
if ((ano mod 4) <> 0) then //não bissexto
begin
if (mes =2) and (dia > 28) then Writeln ('Data Inválida!');
end
else
begin
Writeln ('A data ', dia, '/', mes, '/', ano, ' está correta!');
end;
End.
Program ex24 ;
//Lucas Perussi
var x, y, aux, i, valor:Integer;
begin
Writeln ('Informe um valor inteiro para X: ');
read (x);
Writeln ('Informe um valor inteiro para Y: ');
read (y);
aux := x;
for i := 1 to (y-1) do
begin
aux := aux * x;
end;
writeln('=============================================== ');
writeln;
writeln(x, ' elevado na ', y, ' tem o resultado de : ', aux);
readln;
End.
Program ex29 ;
//Lucas Perussi
var entrada, contador:integer;
Begin
entrada := -1;
//while(entrada <> 0) do
repeat
begin
contador := 1;
write('Digite seu numero para calcular, ou zero para sair: ');
readln(entrada);
if (entrada > 0) then
begin
writeln();
writeln('O numero ',entrada, ' pode ser divisivel por:');
while(contador <= entrada) do
begin
if(entrada mod contador = 0) then
writeln(contador);
contador := contador + 1;
end;
writeln();
end;
end;
until (entrada = 0);
End.
|
(*
Category: SWAG Title: SORTING ROUTINES
Original name: 0006.PAS
Description: COMB1.PAS
Author: SWAG SUPPORT TEAM
Date: 05-28-93 13:57
*)
{
>Has anyone successfully converted the Combsort algorithm (I think it was
>published in DDJ or Byte about two years ago) from C to Pascal? I've
>lost the original C source For this, but if anyone has any info, I would
>appreciate it.
}
Program TestCombSort; { Byte magazine, April '91 page 315ff }
Const
Size = 25;
Type
SortType = Integer;
Var
A: Array [1..size] of SortType;
i: Word;
Procedure CombSort (Var Ain);
Var
A: Array [1..Size] of SortType Absolute Ain;
Switch: Boolean;
i, j, Gap: Word;
Hold: SortType;
begin
Gap := Size;
Repeat
Gap := Trunc (Gap / 1.3);
if Gap < 1 then
Gap := 1;
Switch := False;
For i := 1 to Size - Gap do
begin
j := i + Gap;
if A [i] > A [j] then { swap }
begin
Hold := A [i];
A [i] := A [j];
A [j] := Hold;
Switch := True;;
end;
end;
Until (Gap = 1) and not Switch;
end;
begin
Randomize;
For i := 1 to Size do
A [i] := Random (32767);
WriteLn;
WriteLn ('Unsorted:');
For i := 1 to Size do
Write (A [i]:8);
WriteLn;
CombSort (A);
WriteLn ('Sorted:');
For i := 1 to Size do
Write (A [i]:8);
WriteLn;
end.
|
program lf;
{$mode objfpc}{$H+}{$J-}
{$ifdef windows}
{$APPTYPE CONSOLE}
{$endif}
{.$R *.res}
uses
SysUtils, {$ifdef unix}LCLIntf, crt, termio, BaseUnix,{$endif} {LCLIntf, LCLType, LMessages,} StrUtils{$ifdef windows}, Windows {$endif}{, fpjson, jsonparser, fpjsonrtti};
function MatchString(const AText: string; const AValues: array of string; var AIndex: Integer): Boolean;
begin
AIndex := AnsiIndexStr(AText, AValues);
Result := AIndex <> -1;
end;
{$ifdef windows}
function IsWow64: Boolean;
type
TIsWow64Process = function(Handle: THandle; var Res: BOOL): BOOL; stdcall;
var
IsWow64Result: BOOL;
IsWow64Process: TIsWow64Process = nil;
begin
// Try to load required function from kernel32
Pointer(IsWow64Process) := GetProcAddress(GetModuleHandle('kernel32.dll'), 'IsWow64Process');
if Assigned(IsWow64Process) then
begin
// Function is implemented: call it
IsWow64Result := False;
if not IsWow64Process(GetCurrentProcess, IsWow64Result) then
raise Exception.Create('IsWow64: bad process handle');
// Return result of function
Result := IsWow64Result;
end
else
// Function not implemented: can't be running on Wow64
Result := False;
end;
type
TWow64DisableWow64FsRedirection = function(var OldValue: Windows.PVOID): Windows.BOOL; stdcall;
TWow64RevertWow64FsRedirection = function(var OldValue: Windows.PVOID): Windows.BOOL; stdcall;
{$endif}
procedure ConsoleColor(var hConsole: THandle; color:Integer);
begin
{$ifdef windows}
SetConsoleTextAttribute(hConsole, color);
{$else}
// TODO: print using color codes on unix oses
TextColor(color); // Temporary workaround
{$endif}
end;
var
hConsole: THandle;
{$ifdef windows}
screen_info_t: TConsoleScreenBufferInfo;
{$else}
ws: winsize;
{$endif}
original_attributes: WORD;
console_width: Integer;//SHORT;
line_count: Integer = 3;//SHORT = 3;
console_height: integer = 24;
search_string: string;
wild_char: string = '*.*';
file_size: Real;
//total_size: Real = 0.0;
i: Integer;
pause: string = 'q'; //quick by default
{$ifdef windows}
Wow64DisableWow64FsRedirection: TWow64DisableWow64FsRedirection = nil;
Wow64RevertWow64FsRedirection: TWow64RevertWow64FsRedirection = nil;
OldValue: Pointer = nil;
{$endif}
sr: TSearchRec;
rs: Integer;
//devicons: TArray<string>;
filetype: Array [0..54] of string = (
'.exe', '.dll', '.json', '.js', '.php', '.ini', '.cmd', '.bat',
'.gif', '.png', '.jpeg', '.jpg', '.bmp', '.webp', '.flif', '.tga', '.tiff', '.psd',
'.ts', '.vue', '.sass', '.less', '.css', '.html', '.htm', '.xml', '.rb',
'.go', '.cs', '.py', '.styl', '.db', '.sql', '.md', '.markdown', '.java', '.class',
'.apk', '.pas', '.inc', '.lnk', '.sh', '.log', '.todo', '.csproj', '.sln',
'.rar', '.zip', '.7z', '.cab', '.tgz', '.env', '.pdf', '.doc', '.scss'
);
devicons: Array [0..54] of integer = (
//$e608 <- elefante php
$e70f, $e714, $e60b, $e74e, $e73d, $e615, $e795, $e795,
$e60d, $e60d, $e60d, $e60d, $e60d, $e60d, $e60d, $e60d, $e60d, $e60d,
$e628, $e62b, $e603, $e758, $e749, $e736, $e736, $e7a3, $e791,
$e627, $e72e, $e73c, $e759, $e706, $e704, $e73e, $e73e, $e738, $e738,
$e70e, $e72d, $e7aa, $e62a, $e7a2, $e705, $e714, $e77f, $e77f,
$e707, $e707, $e707, $e707, $e707, $e799, $e760, $e76f, $e603
);
colors: Array [0..54] of integer = (
$0F, $08, $0A, $0A, $0E, $0B, $0F, $0F,
$09, $09, $09, $09, $09, $09, $09, $09, $09, $09,
$0A, $02, $08, $08, $03, $03, $03, $03, $08,
$08, $08, $08, $08, $08, $08, $08, $08, $08, $08,
$0A, $08, $08, $08, $08, $08, $08, $08, $08,
$08, $08, $08, $08, $08, $0B, $08, $08, $08
);
idx: Integer;
begin
//try
// UTF-8
// SetConsoleOutputCP(CP_WINUNICODE);
{$ifdef windows}
SetConsoleOutputCP(CP_UTF8);
hConsole := GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(hConsole, screen_info_t);
original_attributes := screen_info_t.wAttributes;
console_width := screen_info_t.srWindow.Right;
console_height := screen_info_t.srWindow.Bottom - screen_info_t.srWindow.Top;
{$else}
//STDIN_FILENO = 0
//STDOUT_FILENO = 1
//STOERR_FILENO = 2
FpIOCtl(1, TIOCGWINSZ, @ws);
console_width := ws.ws_col;
console_height:= ws.ws_row;
{$endif}
search_string := GetCurrentDir;
//ConsoleColor(hConsole, $0F); // Bright white label
ConsoleColor(hConsole, 3);
//Writeln('Path: ' + search_string);
{$ifdef windows}
for i := 0 to console_width - 1 do
begin
if console_width / 2 = i then
Write('┬')
else
Write('─');
end;
if IsWow64 then
begin
Pointer(Wow64DisableWow64FsRedirection) := Windows.GetProcAddress(Windows.GetModuleHandle('kernel32.dll'), 'Wow64DisableWow64FsRedirection');
if Assigned(Wow64DisableWow64FsRedirection) then
Wow64DisableWow64FsRedirection(&OldValue);
//writeln(#13#10'WowRedirection Disabled');
end;
{$endif}
// parse params
if (ParamCount = 1) and (ParamStr(1) = '?') then
begin
WriteLn(#13#10'Help');
end
else if ParamCount > 0 then
begin
if (ParamCount = 1) and (ParamStr(1) = '/p') then
pause := 'n' // page it
else
wild_char := ParamStr(1);
if (ParamCount > 1) and (ParamStr(2) = '/p') then
begin
wild_char := ParamStr(1);
pause := 'n'; // page it
end;
end;
// devicons
//https://stackoverflow.com/questions/8409026/search-a-string-array-in-delphi
//https://stackoverflow.com/questions/3054517/delphi-search-files-and-directories-fastest-alghorithm
//devicons := TArray<string>.Create('.exe', '.dll');
Writeln('');
// search now
//rs := FindFirst('c:\windows\*.*', faAnyFile, sr);
{$ifdef windows}
rs := FindFirst(search_string + '\' + wild_char, faAnyFile, sr);
{$else}
rs := FindFirst(search_string + '/' + wild_char, faAnyFile, sr);
{$endif}
if rs = 0 then
try
while rs = 0 do
begin
if (sr.Name <> '.') and (sr.Name <> '..') then
begin
Write(' ');
if sr.Attr and faDirectory = faDirectory then
begin
ConsoleColor(hConsole, $0D);
if sr.Name = '.git' then
begin
ConsoleColor(hConsole, $04);
Write(WideChar($e5fb))
end
else if sr.Name = 'node_modules' then
Write(WideChar($e5fa))
else if sr.Name = '.vscode' then
Write(WideChar($e70c))
else
Write(WideChar($e5fe))
end
else if sr.Name = 'artisan' then
begin
ConsoleColor(hConsole, $0F);
Write(WideChar($e795))
end
else if (sr.Name = '.gitignore') or (sr.Name = '.gitattributes') then
Write(WideChar($e727))
else if pos('.blade.php', sr.Name) > 0 then
Write(WideChar($e73f))
else if MatchString(LowerCase(ExtractFileExt(sr.Name)), filetype, idx) then
begin
ConsoleColor(hConsole, colors[idx]);
Write(WideChar(devicons[idx]));
end
else
begin
ConsoleColor(hConsole, $08);
Write(WideChar($f016));
end;
Write(Format(' %-*s' ,[(console_width div 2 - 8), sr.Name]));
if sr.Attr and faDirectory <> faDirectory then
begin
write(' ');
file_size := sr.Size;
//total_size := total_size + file_size;
if file_size > 1023 then
begin
file_size := file_size / 1024.0;
if file_size > 1023 then
begin
file_size := file_size / 1024.0;
if file_size > 1023 then
begin
file_size := file_size / 1024.0;
if file_size > 1023 then
begin
write(Format('%5.1f TB', [file_size]));
end
else
write(Format('%5.1f GB', [file_size]));
end
else
write(Format('%5.1f MB', [file_size]));
end
else
write(Format('%5.1f KB', [file_size]));
end
else
write(Format('%5.1f B', [file_size]));
end
else
write(' <dir>');
writeln('');
end;
line_count := line_count + 1;
if (line_count = console_height) and (pause <> 'q') then
begin
{$ifdef windows}
ConsoleColor(hConsole, original_attributes);
{$else}
{$endif}
writeln('Press Enter to continue...');
readln(pause);
//Winexec('c:\windows\system32\cmd.exe /c pause', SW_SHOWNORMAL);
line_count := 3;
end;
rs := FindNext(sr);
end;
ConsoleColor(hConsole, original_attributes);
finally
SysUtils.FindClose(sr);
end;
{$ifdef windows}
if IsWow64 then
begin
Pointer(Wow64RevertWow64FsRedirection) := Windows.GetProcAddress(Windows.GetModuleHandle('kernel32.dll'), 'Wow64RevertWow64FsRedirection');
if Assigned(Wow64RevertWow64FsRedirection) then
Wow64RevertWow64FsRedirection(OldValue);
//writeln(#13#10'WowRedirection Reverted');
end;
{$endif}
//Readln;
//except
// on E: Exception do
// Writeln(E.ClassName, ': ', E.Message);
//end;
end.
|
// ************************************************************************
// ***************************** CEF4Delphi *******************************
// ************************************************************************
//
// CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based
// browser in Delphi applications.
//
// The original license of DCEF3 still applies to CEF4Delphi.
//
// For more information about CEF4Delphi visit :
// https://www.briskbard.com/index.php?lang=en&pageid=cef
//
// Copyright © 2017 Salvador Díaz Fau. All rights reserved.
//
// ************************************************************************
// ************ vvvv Original license and comments below vvvv *************
// ************************************************************************
(*
* Delphi Chromium Embedded 3
*
* Usage allowed under the restrictions of the Lesser GNU General Public License
* or alternatively the restrictions of the Mozilla Public License 1.1
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
*
* Unit owner : Henri Gourvest <hgourvest@gmail.com>
* Web site : http://www.progdigy.com
* Repository : http://code.google.com/p/delphichromiumembedded/
* Group : http://groups.google.com/group/delphichromiumembedded
*
* Embarcadero Technologies, Inc is not permitted to use or redistribute
* this source code without explicit permission.
*
*)
unit uCEFServer;
{$IFNDEF CPUX64}
{$ALIGN ON}
{$MINENUMSIZE 4}
{$ENDIF}
{$I cef.inc}
interface
uses
uCEFBaseRefCounted, uCEFInterfaces, uCEFTypes;
type
TCEFServerRef = class(TCefBaseRefCountedRef, ICefServer)
protected
function GetTaskRunner : ICefTaskRunner; virtual;
procedure Shutdown; virtual;
function IsRunning : boolean; virtual;
function GetAddress : ustring; virtual;
function HasConnection : boolean; virtual;
function IsValidConnection(connection_id: Integer) : boolean; virtual;
procedure SendHttp200response(connection_id: Integer; const content_type: ustring; const data: Pointer; data_size: NativeUInt); virtual;
procedure SendHttp404response(connection_id: Integer); virtual;
procedure SendHttp500response(connection_id: Integer; const error_message: ustring); virtual;
procedure SendHttpResponse(connection_id, response_code: Integer; const content_type: ustring; content_length: int64; const headerMap: ICefStringMultimap); virtual;
procedure SendRawData(connection_id: Integer; const data: Pointer; data_size: NativeUInt); virtual;
procedure CloseConnection(connection_id: Integer); virtual;
procedure SendWebSocketMessage(connection_id: Integer; const data: Pointer; data_size: NativeUInt); virtual;
public
class function UnWrap(data: Pointer): ICefServer;
end;
implementation
uses
uCEFMiscFunctions, uCEFTaskRunner;
// ******************************************************
// ****************** TCEFServerRef *********************
// ******************************************************
class function TCEFServerRef.UnWrap(data: Pointer): ICefServer;
begin
if (data <> nil) then
Result := Create(data) as ICefServer
else
Result := nil;
end;
function TCEFServerRef.GetTaskRunner : ICefTaskRunner;
begin
Result := TCefTaskRunnerRef.UnWrap(PCefServer(FData).get_task_runner(PCefServer(FData)));
end;
procedure TCEFServerRef.Shutdown;
begin
PCefServer(FData).shutdown(PCefServer(FData));
end;
function TCEFServerRef.IsRunning : boolean;
begin
Result := PCefServer(FData).is_running(PCefServer(FData)) <> 0;
end;
function TCEFServerRef.GetAddress : ustring;
begin
Result := CefStringFreeAndGet(PCefServer(FData).get_address(PCefServer(FData)));
end;
function TCEFServerRef.HasConnection : boolean;
begin
Result := PCefServer(FData).has_connection(PCefServer(FData)) <> 0;
end;
function TCEFServerRef.IsValidConnection(connection_id: Integer) : boolean;
begin
Result := PCefServer(FData).is_valid_connection(PCefServer(FData), connection_id) <> 0;
end;
procedure TCEFServerRef.SendHttp200response(connection_id: Integer; const content_type: ustring; const data: Pointer; data_size: NativeUInt);
var
TempContentType : TCefString;
begin
TempContentType := CefString(content_type);
PCefServer(FData).send_http200response(PCefServer(FData), connection_id, @TempContentType, data, data_size);
end;
procedure TCEFServerRef.SendHttp404response(connection_id: Integer);
begin
PCefServer(FData).send_http404response(PCefServer(FData), connection_id);
end;
procedure TCEFServerRef.SendHttp500response(connection_id: Integer; const error_message: ustring);
var
TempError : TCefString;
begin
TempError := CefString(error_message);
PCefServer(FData).send_http500response(PCefServer(FData), connection_id, @TempError);
end;
procedure TCEFServerRef.SendHttpResponse(connection_id, response_code: Integer; const content_type: ustring; content_length: int64; const headerMap: ICefStringMultimap);
var
TempContentType : TCefString;
begin
TempContentType := CefString(content_type);
PCefServer(FData).send_http_response(PCefServer(FData), connection_id, response_code, @TempContentType, content_length, headerMap.Handle);
end;
procedure TCEFServerRef.SendRawData(connection_id: Integer; const data: Pointer; data_size: NativeUInt);
begin
PCefServer(FData).send_raw_data(PCefServer(FData), connection_id, data, data_size);
end;
procedure TCEFServerRef.CloseConnection(connection_id: Integer);
begin
PCefServer(FData).close_connection(PCefServer(FData), connection_id);
end;
procedure TCEFServerRef.SendWebSocketMessage(connection_id: Integer; const data: Pointer; data_size: NativeUInt);
begin
PCefServer(FData).send_web_socket_message(PCefServer(FData), connection_id, data, data_size);
end;
end.
|
unit Camera;
interface
uses BasicMathsTypes, math3d, math, dglOpenGL;
type
PCamera = ^TCamera;
TCamera = class
private
// For the renderer
RequestUpdateWorld: boolean;
// Misc
function CleanAngle(Angle: single): single;
public
// List
Next : PCamera;
// Atributes
PositionAcceleration : TVector3f;
RotationAcceleration : TVector3f;
PositionSpeed : TVector3f; // Move for the next frame.
RotationSpeed : TVector3f;
Position : TVector3f;
Rotation : TVector3f;
// Constructors
constructor Create;
procedure Reset;
// Execution
procedure RotateCamera;
procedure MoveCamera;
procedure ProcessNextFrame;
// Gets
function GetRequestUpdateWorld: boolean;
// Sets
procedure SetPosition(_x, _y, _z: single); overload;
procedure SetPosition(_Vector: TVector3f); overload;
procedure SetRotation(_x, _y, _z: single); overload;
procedure SetRotation(_Vector: TVector3f); overload;
procedure SetPositionSpeed(_x, _y, _z: single); overload;
procedure SetPositionSpeed(_Vector: TVector3f); overload;
procedure SetRotationSpeed(_x, _y, _z: single); overload;
procedure SetRotationSpeed(_Vector: TVector3f); overload;
procedure SetPositionAcceleration(_x, _y, _z: single); overload;
procedure SetPositionAcceleration(_Vector: TVector3f); overload;
procedure SetRotationAcceleration(_x, _y, _z: single); overload;
procedure SetRotationAcceleration(_Vector: TVector3f); overload;
end;
implementation
constructor TCamera.Create;
begin
Next := nil;
Reset;
end;
procedure TCamera.Reset;
begin
Rotation.X := 0;
Rotation.Y := -5;
Rotation.Z := 0;
Position.X := 0;
Position.Y := 0;
Position.Z := -150;
PositionSpeed := SetVector(0,0,0);
RotationSpeed := SetVector(0,0,0);
PositionAcceleration := SetVector(0,0,0);
RotationAcceleration := SetVector(0,0,0);
RequestUpdateWorld := true;
end;
procedure TCamera.RotateCamera;
begin
glRotatef(Rotation.X, 1, 0, 0);
glRotatef(Rotation.Y, 0, 1, 0);
glRotatef(Rotation.Z, 0, 0, 1);
end;
procedure TCamera.MoveCamera;
begin
glTranslatef(Position.X, Position.Y, Position.Z);
end;
procedure TCamera.ProcessNextFrame;
var
Signal : integer;
begin
// Process acceleration.
Signal := Sign(PositionSpeed.X);
PositionSpeed.X := PositionSpeed.X + PositionAcceleration.X;
if Signal <> Sign(PositionSpeed.X) then
PositionSpeed.X := 0;
Signal := Sign(PositionSpeed.Y);
PositionSpeed.Y := PositionSpeed.Y + PositionAcceleration.Y;
if Signal <> Sign(PositionSpeed.Y) then
PositionSpeed.Y := 0;
Signal := Sign(PositionSpeed.Z);
PositionSpeed.Z := PositionSpeed.Z + PositionAcceleration.Z;
if Signal <> Sign(PositionSpeed.Z) then
PositionSpeed.Z := 0;
Signal := Sign(RotationSpeed.X);
RotationSpeed.X := RotationSpeed.X + RotationAcceleration.X;
if Signal <> Sign(RotationSpeed.X) then
RotationSpeed.X := 0;
Signal := Sign(RotationSpeed.Y);
RotationSpeed.Y := RotationSpeed.Y + RotationAcceleration.Y;
if Signal <> Sign(RotationSpeed.Y) then
RotationSpeed.Y := 0;
Signal := Sign(RotationSpeed.Z);
RotationSpeed.Z := RotationSpeed.Z + RotationAcceleration.Z;
if Signal <> Sign(RotationSpeed.Z) then
RotationSpeed.Z := 0;
// Process position and angle
Position.X := Position.X + PositionSpeed.X;
Position.Y := Position.Y + PositionSpeed.Y;
Position.Z := Position.Z + PositionSpeed.Z;
Rotation.X := CleanAngle(Rotation.X + RotationSpeed.X);
Rotation.Y := CleanAngle(Rotation.Y + RotationSpeed.Y);
Rotation.Z := CleanAngle(Rotation.Z + RotationSpeed.Z);
// update request world update.
RequestUpdateWorld := RequestUpdateWorld or (PositionSpeed.X <> 0) or (PositionSpeed.Y <> 0) or (PositionSpeed.Z <> 0) or (RotationSpeed.X <> 0) or (RotationSpeed.Y <> 0) or (RotationSpeed.Z <> 0);
end;
function TCamera.GetRequestUpdateWorld: boolean;
begin
Result := RequestUpdateWorld;
RequestUpdateWorld := false;
end;
// Sets
procedure TCamera.SetPosition(_x, _y, _z: single);
begin
Position.X := _x;
Position.Y := _y;
Position.Z := _z;
RequestUpdateWorld := true;
end;
procedure TCamera.SetPosition(_Vector: TVector3f);
begin
Position.X := _Vector.X;
Position.Y := _Vector.Y;
Position.Z := _Vector.Z;
RequestUpdateWorld := true;
end;
procedure TCamera.SetRotation(_x, _y, _z: single);
begin
Rotation.X := CleanAngle(_x);
Rotation.Y := CleanAngle(_y);
Rotation.Z := CleanAngle(_z);
RequestUpdateWorld := true;
end;
procedure TCamera.SetRotation(_Vector: TVector3f);
begin
Rotation.X := CleanAngle(_Vector.X);
Rotation.Y := CleanAngle(_Vector.Y);
Rotation.Z := CleanAngle(_Vector.Z);
RequestUpdateWorld := true;
end;
procedure TCamera.SetPositionSpeed(_x, _y, _z: single);
begin
PositionSpeed.X := _x;
PositionSpeed.Y := _y;
PositionSpeed.Z := _z;
RequestUpdateWorld := true;
end;
procedure TCamera.SetPositionSpeed(_Vector: TVector3f);
begin
PositionSpeed.X := _Vector.X;
PositionSpeed.Y := _Vector.Y;
PositionSpeed.Z := _Vector.Z;
RequestUpdateWorld := true;
end;
procedure TCamera.SetRotationSpeed(_x, _y, _z: single);
begin
RotationSpeed.X := _x;
RotationSpeed.Y := _y;
RotationSpeed.Z := _z;
RequestUpdateWorld := true;
end;
procedure TCamera.SetRotationSpeed(_Vector: TVector3f);
begin
RotationSpeed.X := _Vector.X;
RotationSpeed.Y := _Vector.Y;
RotationSpeed.Z := _Vector.Z;
RequestUpdateWorld := true;
end;
procedure TCamera.SetPositionAcceleration(_x, _y, _z: single);
begin
PositionAcceleration.X := _x;
PositionAcceleration.Y := _y;
PositionAcceleration.Z := _z;
RequestUpdateWorld := true;
end;
procedure TCamera.SetPositionAcceleration(_Vector: TVector3f);
begin
PositionAcceleration.X := _Vector.X;
PositionAcceleration.Y := _Vector.Y;
PositionAcceleration.Z := _Vector.Z;
RequestUpdateWorld := true;
end;
procedure TCamera.SetRotationAcceleration(_x, _y, _z: single);
begin
RotationAcceleration.X := _x;
RotationAcceleration.Y := _y;
RotationAcceleration.Z := _z;
RequestUpdateWorld := true;
end;
procedure TCamera.SetRotationAcceleration(_Vector: TVector3f);
begin
RotationAcceleration.X := _Vector.X;
RotationAcceleration.Y := _Vector.Y;
RotationAcceleration.Z := _Vector.Z;
RequestUpdateWorld := true;
end;
// Misc
function TCamera.CleanAngle(Angle: single): single;
begin
Result := Angle;
if Result < 0 then
Result := Result + 360;
if Result > 360 then
Result := Result - 360;
end;
end.
|
unit uPathUtils;
interface
uses
Classes,
uMemory,
SysUtils;
type
TPath = class
class function Combine(FirstPath: string; PathToCombine: string): string;
class function TrimPathDirectories(Path: string): string;
class function CleanUp(Path: string): string;
end;
implementation
{ TPath }
class function TPath.CleanUp(Path: string): string;
begin
Result := StringReplace(Path, '\', '', [rfReplaceAll]);
Result := StringReplace(Path, '/', '', [rfReplaceAll]);
Result := StringReplace(Path, ':', '', [rfReplaceAll]);
Result := StringReplace(Path, '*', '', [rfReplaceAll]);
Result := StringReplace(Path, '?', '', [rfReplaceAll]);
Result := StringReplace(Path, '"', '', [rfReplaceAll]);
Result := StringReplace(Path, '<', '', [rfReplaceAll]);
Result := StringReplace(Path, '>', '', [rfReplaceAll]);
Result := StringReplace(Path, '|', '', [rfReplaceAll]);
end;
class function TPath.Combine(FirstPath, PathToCombine: string): string;
begin
Result := FirstPath;
Result := IncludeTrailingPathDelimiter(Result);
if PathToCombine <> '' then
if IsDelimiter('\/', PathToCombine, 1) then
Delete(PathToCombine, 1, 1);
Result := Result + PathToCombine;
end;
class function TPath.TrimPathDirectories(Path: string): string;
procedure ClearPathParts(C: Char);
var
I: Integer;
SL: TStringList;
begin
SL := TStringList.Create;
try
SL.Delimiter := C;
SL.StrictDelimiter := True;
SL.DelimitedText := Result;
for I := 0 to SL.Count - 1 do
SL[I] := TPath.CleanUp(Trim(SL[I]));
Result := SL.DelimitedText;
finally
F(SL);
end;
end;
begin
Result := Path;
ClearPathParts('/');
ClearPathParts('\');
end;
end.
|
// uses System, Variants
function IsEmptyOrNull(const Value: Variant): Boolean;
begin
Result := VarIsClear(Value) or VarIsEmpty(Value) or VarIsNull(Value) or (VarCompareValue(Value, Unassigned) = vrEqual);
if (not Result) and VarIsStr(Value) then
Result := Value = '';
end; |
unit uPlugin;
interface
uses
Windows,
AIMPCustomPlugin,
//
apiCore,
apiGUI,
apiPlugin,
apiWrappers,
//
uDemoForm,
uDataProvider;
type
{ TAIMPMusicLibraryBrowserDemoPlugin }
TAIMPMusicLibraryBrowserDemoPlugin = class(TAIMPCustomPlugin, IAIMPExternalSettingsDialog)
strict private
FDataProvider: TMLDataProvider;
protected
function Initialize(Core: IAIMPCore): HRESULT; override; stdcall;
procedure Finalize; override; stdcall;
public
function InfoGet(Index: Integer): PWideChar; override;
function InfoGetCategories: DWORD; override;
// IAIMPExternalSettingsDialog
procedure Show(ParentWindow: HWND); stdcall;
end;
implementation
{ TAIMPMusicLibraryBrowserDemoPlugin }
procedure TAIMPMusicLibraryBrowserDemoPlugin.Finalize;
begin
inherited;
FDataProvider.Free;
FDataProvider := nil;
end;
function TAIMPMusicLibraryBrowserDemoPlugin.InfoGet(Index: Integer): PWideChar;
begin
case Index of
AIMP_PLUGIN_INFO_NAME:
Result := 'MusicLibraryBrowser Demo';
AIMP_PLUGIN_INFO_AUTHOR:
Result := 'Artem Izmaylov';
AIMP_PLUGIN_INFO_SHORT_DESCRIPTION:
Result := 'Demo shows how to implement custom music library browser';
else
Result := nil;
end;
end;
function TAIMPMusicLibraryBrowserDemoPlugin.InfoGetCategories: DWORD;
begin
Result := AIMP_PLUGIN_CATEGORY_ADDONS;
end;
function TAIMPMusicLibraryBrowserDemoPlugin.Initialize(Core: IAIMPCore): HRESULT;
begin
Result := inherited;
FDataProvider := TMLDataProvider.Create;
end;
procedure TAIMPMusicLibraryBrowserDemoPlugin.Show(ParentWindow: HWND);
var
AService: IAIMPServiceUI;
begin
if CoreGetService(IAIMPServiceUI, AService) then
TDemoForm.Create(AService, FDataProvider).ShowModal;
end;
end.
|
unit u_ast_blocks;
{$INTERFACES CORBA}
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
type
TMashASTBlockType = (
btExpression,
btImport, btRegAPI, btUses, btInline, btConst,
btMethod, btParam,
btIf, btForEach, btWhile, btWhilst,
btReturn,
btSwitch, btCase,
btLaunch, btAsync, btWait,
btBreak, btContinue,
btClass, btClassField, btPublic, btProtected, btPrivate,
btTry, btRaise,
btSafe,
btEnum, btEnumItem,
btEOperation,
btEOperationLR,
btPSimpleObject,
btPReference,
btPIndexedObject,
btPCall,
btPEnum,
btPOperator
);
IMashASTBlock = interface
function GetType: TMashASTBlockType;
procedure Free;
end;
IMashASTBlockWithNodes = interface(IMashASTBlock)
function GetNodes: TList;
end;
TMashASTBlock = class(IMashASTBlock)
public
BlockType: TMashASTBlockType;
constructor Create(_BlockType: TMashASTBlockType);
function GetType: TMashASTBlockType;
procedure Free;
end;
TMashASTBlockWithNodes = class(TMashASTBlock, IMashASTBlockWithNodes)
public
Nodes: TList;
function GetNodes: TList;
constructor Create(_BlockType: TMashASTBlockType);
destructor Destroy; override;
end;
var
MashASTBlocks: TList;
procedure CleanUpASTBlocks;
implementation
// AST Block Interface
constructor TMashASTBlock.Create(_BlockType: TMashASTBlockType);
begin
inherited Create;
self.BlockType := _BlockType;
MashASTBlocks.add(self);
end;
function TMashASTBlock.GetType: TMashASTBlockType;
begin
Result := self.BlockType;
end;
procedure TMashASTBlock.Free;
begin
if self <> nil then
self.Destroy;
end;
constructor TMashASTBlockWithNodes.Create(_BlockType: TMashASTBlockType);
begin
inherited Create(_BlockType);
self.Nodes := TList.Create;
end;
destructor TMashASTBlockWithNodes.Destroy;
begin
FreeAndNil(self.Nodes);
inherited;
end;
function TMashASTBlockWithNodes.GetNodes: TList;
begin
Result := self.Nodes;
end;
// Some methods
procedure CleanUpASTBlocks;
begin
while MashASTBlocks.count > 0 do
begin
TMashASTBlock(MashASTBlocks[0]).Free;
MashASTBlocks.Delete(0);
end;
end;
initialization
MashASTBlocks := TList.Create;
finalization
FreeAndNil(MashASTBlocks);
end.
|
unit RusDlg;
interface
implementation
uses Classes, Forms, Consts, Dialogs; //, RtpCtrls;
resourcestring
SMsgDlgRusWarning = 'Предупреждение';
SMsgDlgRusError = 'Ошибка';
SMsgDlgRusInformation = 'Информация';
SMsgDlgRusConfirm = 'Подтверждение';
SMsgDlgRusYes = '&Да';
SMsgDlgRusNo = '&Нет';
SMsgDlgRusOK = 'Ясно';
SMsgDlgRusCancel = 'Отмена';
SMsgDlgRusHelp = '&Помощь';
SMsgDlgRusHelpNone = 'Помощь недоступна';
SMsgDlgRusHelpHelp = 'Помощь';
SMsgDlgRusAbort = '&Прервать';
SMsgDlgRusRetry = 'По&вторить';
SMsgDlgRusIgnore = '&Игнорировать';
SMsgDlgRusAll = '&Все';
SMsgDlgRusNoToAll = 'H&ет для всех';
SMsgDlgRusYesToAll = 'Д&а для всех';
const
Captions: array[TMsgDlgType] of Pointer = (@SMsgDlgRusWarning,
@SMsgDlgRusError,
@SMsgDlgRusInformation, @SMsgDlgRusConfirm, nil);
ButtonCaptions: array[TMsgDlgBtn] of Pointer = (
@SMsgDlgRusYes, @SMsgDlgRusNo, @SMsgDlgRusOK, @SMsgDlgRusCancel,
@SMsgDlgRusAbort,
@SMsgDlgRusRetry, @SMsgDlgRusIgnore, @SMsgDlgRusAll, @SMsgDlgRusNoToAll,
@SMsgDlgRusYesToAll,
@SMsgDlgRusHelp);
procedure _ChangeCaptions(List: PPointerList;Last: Pointer);
var i, Max: Integer;
IsFind: Boolean;
begin
Max := (Integer(Last)-Integer(List)) div SizeOf(Pointer);
IsFind := False;
for i := 0 to Max - 2 do
if (List[i] = @SMsgDlgWarning) and (List[i+2] = @SMsgDlgInformation) then
begin
IsFind := True;
break;
end;
if IsFind then Move(Captions, List[i], SizeOf(Captions));
IsFind := False;
for i := i to Max - 2 do
if (List[i] = @SMsgDlgYes) and (List[i+2] = @SMsgDlgOK) then
begin
IsFind := True;
break;
end;
if IsFind then Move(ButtonCaptions, List[i], SizeOf(ButtonCaptions));
end;
initialization
_ChangeCaptions(@DebugHook, @Application);
end.
|
unit cnFormMargin;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, umcmIntE;
type
TFormPageMargin1 = class(TForm)
btnOK : TButton;
btnCancel : TButton;
gbMargin : TGroupBox;
lLeft : TLabel;
lTop : TLabel;
lRight : TLabel;
lBottom : TLabel;
rsLeft : TmcmRealSpin;
rsTop : TmcmRealSpin;
rsRight : TmcmRealSpin;
rsBottom : TmcmRealSpin;
cbForceMargin : TCheckBox;
procedure FormCreate(Sender: TObject);
procedure btnOKClick(Sender: TObject);
private
{ Private declarations }
function GetForceMargin : boolean;
function GetMarginBottom : double;
function GetMarginLeft : double;
function GetMarginRight : double;
function GetMarginTop : double;
procedure SetForceMargin(Value : boolean);
procedure SetMarginBottom(Value : double);
procedure SetMarginLeft(Value : double);
procedure SetMarginRight(Value : double);
procedure SetMarginTop(Value : double);
public
{ Public declarations }
property ForceMargin : boolean
read GetForceMargin
write SetForceMargin;
property MarginBottom : double
read GetMarginBottom
write SetMarginBottom;
property MarginLeft : double
read GetMarginLeft
write SetMarginLeft;
property MarginRight : double
read GetMarginRight
write SetMarginRight;
property MarginTop : double
read GetMarginTop
write SetMarginTop;
end;
var
FormPageMargin: TFormPageMargin;
implementation
{$R *.DFM}
procedure TFormPageMargin.FormCreate(Sender : TObject);
begin
;
end; // TFormPageMargin.FormCreate.
procedure TFormPageMargin.btnOKClick(Sender : TObject);
begin
;
end; // TFormPageMargin.btnOKClick.
function TFormPageMargin.GetForceMargin : boolean;
begin
Result := cbForceMargin.Checked;
end; // TFormPageMargin.GetForceMargin.
procedure TFormPageMargin.SetForceMargin(Value : boolean);
begin
cbForceMargin.Checked := Value;
end; // TFormPageMargin.SetForceMargin.
function TFormPageMargin.GetMarginBottom : double;
begin
Result := rsBottom.Value;
end; // TFormPageMargin.GetMarginBottom.
function TFormPageMargin.GetMarginLeft : double;
begin
Result := rsLeft.Value;
end; // TFormPageMargin.GetMarginLeft.
function TFormPageMargin.GetMarginRight : double;
begin
Result := rsRight.Value;
end; // TFormPageMargin.GetMarginRight.
function TFormPageMargin.GetMarginTop : double;
begin
Result := rsTop.Value;
end; // TFormPageMargin.GetMarginTop.
procedure TFormPageMargin.SetMarginBottom(Value : double);
begin
rsBottom.Value := Value;
end; // TFormPageMargin.SetMarginBottom.
procedure TFormPageMargin.SetMarginLeft(Value : double);
begin
rsLeft.Value := Value;
end; // TFormPageMargin.SetMarginLeft.
procedure TFormPageMargin.SetMarginRight(Value : double);
begin
rsRight.Value := Value;
end; // TFormPageMargin.SetMarginRight.
procedure TFormPageMargin.SetMarginTop(Value : double);
begin
rsTop.Value := Value;
end; // TFormPageMargin.SetMarginTop.
end.
|
{ ***************************************************** }
{ }
{ XML Data Binding }
{ }
{ Generated on: 22/08/2018 14:27:56 }
{ Generated from: Q:\dbscript\PG\dbChange.xml }
{ Settings stored in: Q:\dbscript\PG\dbChange.xdb }
{ }
{ ***************************************************** }
unit Validador.Data.dbChangeXML;
interface
uses
Xml.xmldom, Xml.XMLDoc, Xml.XMLIntf;
type
{ Forward Decls }
IXMLHavillanType = interface;
IXMLScriptType = interface;
{ IXMLHavillanType }
IXMLHavillanType = interface(IXMLNodeCollection)
['{33100F16-3FD3-4EAD-AE85-8AC002FC2122}']
{ Property Accessors }
function Get_Script(Index: Integer): IXMLScriptType;
{ Methods & Properties }
function Add: IXMLScriptType;
function Insert(const Index: Integer): IXMLScriptType;
property Script[Index: Integer]: IXMLScriptType read Get_Script; default;
end;
{ IXMLScriptType }
IXMLScriptType = interface(IXMLNode)
['{6C569648-F9BA-409D-ACDB-A329F0269F09}']
{ Property Accessors }
function Get_A_name: UnicodeString;
function Get_Version: UnicodeString;
function Get_Z_description: UnicodeString;
function Get_Description: UnicodeString;
function Get_X_has_pos: UnicodeString;
procedure Set_A_name(Value: UnicodeString);
procedure Set_Version(Value: UnicodeString);
procedure Set_Z_description(Value: UnicodeString);
procedure Set_Description(Value: UnicodeString);
procedure Set_X_has_pos(Value: UnicodeString);
{ Methods & Properties }
property A_name: UnicodeString read Get_A_name write Set_A_name;
property Version: UnicodeString read Get_Version write Set_Version;
property Z_description: UnicodeString read Get_Z_description write Set_Z_description;
property Description: UnicodeString read Get_Description write Set_Description;
property X_has_pos: UnicodeString read Get_X_has_pos write Set_X_has_pos;
end;
{ Forward Decls }
TXMLHavillanType = class;
TXMLScriptType = class;
{ TXMLHavillanType }
TXMLHavillanType = class(TXMLNodeCollection, IXMLHavillanType)
protected
{ IXMLHavillanType }
function Get_Script(Index: Integer): IXMLScriptType;
function Add: IXMLScriptType;
function Insert(const Index: Integer): IXMLScriptType;
public
procedure AfterConstruction; override;
end;
{ TXMLScriptType }
TXMLScriptType = class(TXMLNode, IXMLScriptType)
protected
{ IXMLScriptType }
function Get_A_name: UnicodeString;
function Get_Version: UnicodeString;
function Get_Z_description: UnicodeString;
function Get_Description: UnicodeString;
function Get_X_has_pos: UnicodeString;
procedure Set_A_name(Value: UnicodeString);
procedure Set_Version(Value: UnicodeString);
procedure Set_Z_description(Value: UnicodeString);
procedure Set_Description(Value: UnicodeString);
procedure Set_X_has_pos(Value: UnicodeString);
end;
{ Global Functions }
function Gethavillan(Doc: IXMLDocument): IXMLHavillanType;
function Loadhavillan(const FileName: string): IXMLHavillanType;
function Newhavillan: IXMLHavillanType;
procedure AtribuirNome(const AXMLScriptType: IXMLScriptType; const AValue, ANome: string);
const
TargetNamespace = '';
implementation
uses
System.SysUtils, Xml.xmlutil;
{ Global Functions }
function Gethavillan(Doc: IXMLDocument): IXMLHavillanType;
begin
Result := Doc.GetDocBinding('havillan', TXMLHavillanType, TargetNamespace) as IXMLHavillanType;
end;
function Loadhavillan(const FileName: string): IXMLHavillanType;
begin
Result := LoadXMLDocument(FileName).GetDocBinding('havillan', TXMLHavillanType, TargetNamespace)
as IXMLHavillanType;
end;
function Newhavillan: IXMLHavillanType;
begin
Result := NewXMLDocument.GetDocBinding('havillan', TXMLHavillanType, TargetNamespace)
as IXMLHavillanType;
end;
procedure AtribuirNome(const AXMLScriptType: IXMLScriptType; const AValue, ANome: string);
begin
if Not AValue.Trim.IsEmpty then
Exit;
if not ANome.Trim.IsEmpty then
AXMLScriptType.A_name := ANome;
end;
{ TXMLHavillanType }
procedure TXMLHavillanType.AfterConstruction;
begin
RegisterChildNode('script', TXMLScriptType);
ItemTag := 'script';
ItemInterface := IXMLScriptType;
inherited;
end;
function TXMLHavillanType.Get_Script(Index: Integer): IXMLScriptType;
begin
Result := List[Index] as IXMLScriptType;
end;
function TXMLHavillanType.Add: IXMLScriptType;
begin
Result := AddItem(-1) as IXMLScriptType;
end;
function TXMLHavillanType.Insert(const Index: Integer): IXMLScriptType;
begin
Result := AddItem(Index) as IXMLScriptType;
end;
{ TXMLScriptType }
function TXMLScriptType.Get_A_name: UnicodeString;
begin
Result := AttributeNodes['a_name'].Text;
end;
procedure TXMLScriptType.Set_A_name(Value: UnicodeString);
begin
SetAttribute('a_name', Value);
end;
function TXMLScriptType.Get_Version: UnicodeString;
begin
Result := AttributeNodes['version'].Text;
end;
procedure TXMLScriptType.Set_Version(Value: UnicodeString);
begin
SetAttribute('version', Value);
end;
function TXMLScriptType.Get_Z_description: UnicodeString;
begin
Result := AttributeNodes['z_description'].Text;
end;
procedure TXMLScriptType.Set_Z_description(Value: UnicodeString);
begin
SetAttribute('z_description', Value);
end;
function TXMLScriptType.Get_Description: UnicodeString;
begin
Result := AttributeNodes['description'].Text;
end;
procedure TXMLScriptType.Set_Description(Value: UnicodeString);
begin
SetAttribute('description', Value);
end;
function TXMLScriptType.Get_X_has_pos: UnicodeString;
begin
Result := AttributeNodes['x_has_pos'].Text;
end;
procedure TXMLScriptType.Set_X_has_pos(Value: UnicodeString);
begin
SetAttribute('x_has_pos', Value);
end;
end.
|
unit PureMVC.Patterns.Proxy;
interface
uses
RTTI,
PureMVC.Interfaces.INotifier,
PureMVC.Interfaces.IProxy,
PureMVC.Patterns.Notifier;
type
/// <summary>
/// A base <c>IProxy</c> implementation
/// </summary>
/// <remarks>
/// <para>In PureMVC, <c>Proxy</c> classes are used to manage parts of the application's data model</para>
/// <para>A <c>Proxy</c> might simply manage a reference to a local data object, in which case interacting with it might involve setting and getting of its data in synchronous fashion</para>
/// <para><c>Proxy</c> classes are also used to encapsulate the application's interaction with remote services to save or retrieve data, in which case, we adopt an asyncronous idiom; setting data (or calling a method) on the <c>Proxy</c> and listening for a <c>Notification</c> to be sent when the <c>Proxy</c> has retrieved the data from the service</para>
/// </remarks>
/// <see cref="PureMVC.Core.Model"/>
TProxy = class(TNotifier, IProxy, INotifier)
{$REGION 'Members'}
protected
/// <summary>
/// The name of the proxy
/// </summary>
FProxyName: string;
/// <summary>
/// The data object to be managed
/// </summary>
FData: TValue;
{$ENDREGION}
{$REGION 'Constants'}
public
/// <summary>
/// The default proxy name
/// </summary>
const
NAME = 'Proxy';
{$ENDREGION}
{$REGION 'Constructors'}
/// <summary>
/// Constructs a new proxy with the specified name and data
/// </summary>
/// <param name="ProxyName">The name of the proxy</param>
/// <param name="Data">The data to be managed</param>
constructor Create(ProxyName: string; Data: TValue); overload;
constructor Create(ProxyName: string = NAME); overload;
{$ENDREGION}
{$REGION 'Methods'}
{$REGION 'IProxy Members'}
public
/// <summary>
/// Called by the Model when the Proxy is registered
/// </summary>
procedure OnRegister; virtual;
/// <summary>
/// Called by the Model when the Proxy is removed
/// </summary>
procedure OnRemove; virtual;
function GetProxyName: string;
function GetData: TValue;virtual;
procedure SetData(Value: TValue);virtual;
property Data: TValue read GetData write SetData;
{$ENDREGION}
{$ENDREGION}
end;
implementation
{ TProxy }
constructor TProxy.Create(ProxyName: string; Data: TValue);
begin
inherited Create;
FProxyName := ProxyName;
if FProxyName = '' then
FProxyName := NAME;
FData := Data;
end;
constructor TProxy.Create(ProxyName: string);
begin
Create(ProxyName, nil);
end;
procedure TProxy.SetData(Value: TValue);
begin
FData := Value;
end;
function TProxy.GetData: TValue;
begin
Result := FData;
end;
function TProxy.GetProxyName: string;
begin
Result := FProxyName;
end;
procedure TProxy.OnRegister;
begin
end;
procedure TProxy.OnRemove;
begin
end;
end.
|
unit ExternProgsAddUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons;
type
TExternProgsAddForm = class(TForm)
NameEdit: TEdit;
FileEdit: TEdit;
ParamsEdit: TEdit;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
OkButton: TBitBtn;
CancelButton: TBitBtn;
Button2: TButton;
OpenDialog: TOpenDialog;
procedure OkButtonClick(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
ExternProgsAddForm: TExternProgsAddForm;
implementation
{$R *.dfm}
procedure TExternProgsAddForm.OkButtonClick(Sender: TObject);
begin
if (NameEdit.Text = '')
then
MessageDlg('Потрібно ввести назву!', mtError, [mbOk], 0)
else
if (FileEdit.Text = '')
then
MessageDlg('Потрібно вибрати файл!', mtError, [mbOk], 0)
else
ModalResult := mrOk;
end;
procedure TExternProgsAddForm.Button2Click(Sender: TObject);
begin
OpenDialog.Filter := 'Исполняемые файлы|*.exe';
if OpenDialog.Execute then FileEdit.Text := OpenDialog.FileName;
end;
end.
|
{*******************************************************}
{*
{* uMatchAccuracy.pas
{* Delphi Implementation of the Class MatchAccuracy
{* Generated by Enterprise Architect
{* Created on: 09-févr.-2015 11:41:48
{* Original author: Brady Vidovic OK
{*
{*******************************************************}
unit xmltvdb.MatchAccuracy;
interface
type
TMatchAccuracy= (
//ordered from best to worst
ORIGINAL_AIR_DATE_AND_EXACT_TITLE,
ORIGINAL_AIR_DATE_AND_FUZZY_TITLE,
ORIGINAL_AIR_DATE_AND_CONTAINS_TITLE,
EXACT_TITLE,
ORIGINAL_AIR_DATE,
FUZZY_TITLE,
CONTAINS_TITLE
);
type TMatchAccuracyHelper = record helper for TMatchAccuracy
public
function ToString() : string;
end;
implementation
uses TypInfo;
{ TStringsHelper }
function TMatchAccuracyHelper.ToString: string;
begin
Result := GetEnumName(TypeInfo(TMatchAccuracy), integer(Self)) ;
end;
end. |
unit ProjectDocument;
interface
uses
SysUtils, Classes, Contnrs,
LrDocument,
Servers, ServerDatabases, TurboPhpDocument;
type
TProjectItem = class(TComponent)
private
FSource: string;
FDestination: string;
FDisplayName: string;
protected
function GetDestination: string; virtual;
function GetDisplayName: string; virtual;
function GetSource: string; virtual;
procedure SetDestination(const Value: string); virtual;
procedure SetDisplayName(const Value: string);
procedure SetSource(const Value: string); virtual;
public
constructor Create; reintroduce; virtual;
published
property Destination: string read GetDestination write SetDestination;
property DisplayName: string read GetDisplayName write SetDisplayName;
property Source: string read GetSource write SetSource;
end;
//
TProjectItems = class(TComponent)
protected
function GetCount: Integer;
function GetItems(inIndex: Integer): TProjectItem;
procedure Clear;
procedure DefineProperties(Filer: TFiler); override;
procedure LoadFromStream(inStream: TStream);
procedure ReadItems(Stream: TStream);
procedure SaveToStream(inStream: TStream);
procedure WriteItems(Stream: TStream);
public
constructor Create(inOwner: TComponent); reintroduce;
destructor Destroy; override;
procedure Add(inItem: TProjectItem);
property Count: Integer read GetCount;
property Items[inIndex: Integer]: TProjectItem read GetItems; default;
end;
//
TSubitemsItem = class(TProjectItem)
private
FItems: TProjectItems;
protected
procedure SetItems(const Value: TProjectItems);
public
constructor Create; override;
destructor Destroy; override;
published
property Items: TProjectItems read FItems write SetItems;
end;
//
TDocumentItem = class(TProjectItem)
private
FDocument: TLrDocument;
protected
function GetSource: string; override;
procedure SetDocument(const Value: TLrDocument);
public
property Document: TLrDocument read FDocument write SetDocument;
end;
//
TTurboPhpDocumentItem = class(TDocumentItem)
end;
//
TProjectDocument = class(TLrDocument)
private
FServers: TServerProfileMgr;
FDatabases: TServerDatabaseProfileMgr;
FItems: TProjectItems;
protected
function GetDatabasesFilename: string;
function GetServersFilename: string;
function GetUntitledName: string; override;
public
constructor Create; override;
destructor Destroy; override;
function Find(const inSource: string;
inItems: TProjectItems = nil): TProjectItem;
function GetUniqueName(const inName: string): string;
function NewTurboPhpDocument: TTurboPhpDocument;
procedure AddFile(const inFilename: string);
procedure AddItem(inItem: TProjectItem);
procedure AddTurboPhpDocumentItem(const inFilename: string);
procedure DocumentOpened(inDocument: TLrDocument);
procedure DocumentClosed(inDocument: TLrDocument);
procedure DocumentChange(Sender: TObject);
procedure Open(const inFilename: string); override;
procedure Save; override;
property Databases: TServerDatabaseProfileMgr read FDatabases;
property Items: TProjectItems read FItems;
property Servers: TServerProfileMgr read FServers;
end;
implementation
uses
LrVclUtils,
Controller;
{ TProjectItem }
constructor TProjectItem.Create;
begin
inherited Create(nil);
end;
function TProjectItem.GetDestination: string;
begin
Result := FDestination;
end;
function TProjectItem.GetDisplayName: string;
begin
if FDisplayName <> '' then
Result := FDisplayName
else begin
Result := ExtractFileName(Source);
if Result = '' then
Result := '(untitled)';
end;
end;
function TProjectItem.GetSource: string;
begin
Result := FSource;
end;
procedure TProjectItem.SetDestination(const Value: string);
begin
FDestination := Value;
end;
procedure TProjectItem.SetDisplayName(const Value: string);
begin
FDisplayName := Value;
end;
procedure TProjectItem.SetSource(const Value: string);
begin
FSource := Value;
end;
{ TProjectItems }
constructor TProjectItems.Create(inOwner: TComponent);
begin
inherited Create(inOwner);
end;
destructor TProjectItems.Destroy;
begin
inherited;
end;
procedure TProjectItems.Clear;
begin
DestroyComponents;
end;
procedure TProjectItems.ReadItems(Stream: TStream);
var
c, i: Integer;
begin
Stream.Read(c, 4);
for i := 0 to Pred(c) do
Add(TProjectItem(Stream.ReadComponent(nil)));
end;
procedure TProjectItems.WriteItems(Stream: TStream);
var
c, i: Integer;
begin
c := Count;
Stream.Write(c, 4);
for i := 0 to Pred(Count) do
Stream.WriteComponent(Items[i]);
end;
procedure TProjectItems.DefineProperties(Filer: TFiler);
begin
Filer.DefineBinaryProperty('Items', ReadItems, WriteItems, true);
end;
procedure TProjectItems.SaveToStream(inStream: TStream);
begin
LrSaveComponentToStream(Self, inStream);
end;
procedure TProjectItems.LoadFromStream(inStream: TStream);
begin
Clear;
LrLoadComponentFromStream(Self, inStream);
end;
function TProjectItems.GetCount: Integer;
begin
Result := ComponentCount;
end;
function TProjectItems.GetItems(inIndex: Integer): TProjectItem;
begin
Result := TProjectItem(Components[inIndex]);
end;
procedure TProjectItems.Add(inItem: TProjectItem);
begin
InsertComponent(inItem);
end;
{ TSubitemsItem }
constructor TSubitemsItem.Create;
begin
inherited;
FItems := TProjectItems.Create(Self);
end;
destructor TSubitemsItem.Destroy;
begin
inherited;
end;
procedure TSubitemsItem.SetItems(const Value: TProjectItems);
begin
FItems.Assign(Value);
end;
{ TProjectDocument }
constructor TProjectDocument.Create;
begin
inherited;
EnableSaveAs('TurboPhp Projects', '.trboprj');
FDatabases := TServerDatabaseProfileMgr.Create;
FItems := TProjectItems.Create(nil);
FServers := TServerProfileMgr.Create;
end;
destructor TProjectDocument.Destroy;
begin
Servers.Free;
Items.Free;
Databases.Free;
inherited;
end;
function TProjectDocument.GetUntitledName: string;
begin
Result := 'Untitled Project';
end;
function TProjectDocument.GetDatabasesFilename: string;
begin
Result := Filename + '.dbs';
end;
function TProjectDocument.GetServersFilename: string;
begin
Result := Filename + '.servers';
end;
procedure TProjectDocument.Open(const inFilename: string);
var
s: TStream;
begin
Filename := inFilename;
s := TFileStream.Create(Filename, fmOpenRead);
try
Items.LoadFromStream(s);
finally
s.Free;
end;
Servers.LoadFromFile(GetServersFilename);
Databases.LoadFromFile(GetDatabasesFilename);
inherited;
end;
procedure TProjectDocument.Save;
var
s: TStream;
begin
s := TFileStream.Create(Filename, fmCreate);
try
Items.SaveToStream(s);
finally
s.Free;
end;
Servers.SaveToFile(GetServersFilename);
Databases.SaveToFile(GetDatabasesFilename);
inherited;
end;
function TProjectDocument.Find(const inSource: string;
inItems: TProjectItems): TProjectItem;
var
i: Integer;
begin
if inItems = nil then
inItems := Items;
Result := nil;
for i := 0 to Pred(inItems.Count) do
begin
if (inItems[i].Source = inSource) then
Result := inItems[i]
else if (inItems[i] is TSubitemsItem) then
Result := Find(inSource, TSubitemsItem(inItems[i]).Items);
if Result <> nil then
break;
end;
end;
function TProjectDocument.GetUniqueName(const inName: string): string;
var
i: Integer;
begin
if Find(inName) = nil then
Result := inName
else begin
i := 0;
repeat
Inc(i);
Result := inName + IntToStr(i);
until Find(Result) = nil;
end;
end;
procedure TProjectDocument.AddItem(inItem: TProjectItem);
begin
Items.Add(inItem);
Change;
end;
procedure TProjectDocument.AddTurboPhpDocumentItem(const inFilename: string);
var
item: TProjectItem;
begin
item := TTurboPhpDocumentItem.Create;
item.Source := inFilename;
AddItem(item);
end;
function TProjectDocument.NewTurboPhpDocument: TTurboPhpDocument;
begin
Result := TTurboPhpDocument.Create;
Result.Filename := GetUniqueName(Result.DisplayName);
AddTurboPhpDocumentItem(Result.Filename);
end;
procedure TProjectDocument.AddFile(const inFilename: string);
var
e: string;
begin
e := LowerCase(ExtractFileExt(inFilename));
if (e = cPageExt) then
AddTurboPhpDocumentItem(inFilename);
end;
procedure TProjectDocument.DocumentOpened(inDocument: TLrDocument);
var
item: TProjectItem;
begin
item := Find(inDocument.Filename);
if item is TDocumentItem then
TDocumentItem(item).Document := inDocument;
end;
procedure TProjectDocument.DocumentClosed(inDocument: TLrDocument);
var
item: TProjectItem;
begin
item := Find(inDocument.Filename);
if item is TDocumentItem then
TDocumentItem(item).Document := nil;
end;
{
function TProjectDocument.FindDocumentItem(const inDocument: TLrDocument;
inItems: TProjectItems): TDocumentItem;
var
i: Integer;
begin
if inItems = nil then
inItems := Items;
Result := nil;
for i := 0 to Pred(inItems.Count) do
begin
if (inItems[i] is TDocumentItem) then
begin
Result := TDocumentItem(inItems[i]);
if Result.Document <> inDocument then
Result := nil;
end
if (Result = nil) and (inItems[i] is TSubitemsItem) then
Result := FindDocumentItem(inDocument, TSubitemsItem(inItems[i]).Items);
if Result <> nil then
break;
end;
end;
}
procedure TProjectDocument.DocumentChange(Sender: TObject);
begin
Change;
end;
{ TDocumentItem }
function TDocumentItem.GetSource: string;
begin
if FDocument <> nil then
Source := FDocument.Filename;
Result := inherited GetSource;
end;
procedure TDocumentItem.SetDocument(const Value: TLrDocument);
begin
FDocument := Value;
end;
initialization
RegisterClass(TTurboPhpDocumentItem);
end.
|
unit Unit1;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.ListBox,
FMX.Layouts, FMX.Objects, FMX.MultiView, FMX.Controls.Presentation,
FMX.StdCtrls, FMX.TabControl, FMX.Ani;
type
TForm1 = class(TForm)
MultiView1: TMultiView;
Rect_menu_top: TRectangle;
Circ_image: TCircle;
Lab_name: TLabel;
Lab_email: TLabel;
Rect_bottom_all: TRectangle;
Rect_item1: TRectangle;
Lab_itm_corbeill: TLabel;
Rect_item2: TRectangle;
Lab_itm_spam: TLabel;
Recta_item3: TRectangle;
Lab_itm_favori: TLabel;
Rect_item4: TRectangle;
Lab_itm_sms: TLabel;
Rect_itm_5: TRectangle;
Lab_itm_import: TLabel;
Rect_img_favori: TRectangle;
Rect_img_spam: TRectangle;
Rect_img_import: TRectangle;
Rec_img_sms: TRectangle;
Rect_img_corbeil: TRectangle;
ToolBa_top: TToolBar;
btn_menu: TSpeedButton;
Layout1: TLayout;
Rectangle3: TRectangle;
Circ_photo: TCircle;
Labe_zekiri_nom: TLabel;
Labe_email_zekiri: TLabel;
private
{ Déclarations privées }
public
{ Déclarations publiques }
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
{$R *.NmXhdpiPh.fmx ANDROID}
{$R *.iPhone.fmx IOS}
{$R *.LgXhdpiTb.fmx ANDROID}
{$R *.iPhone55in.fmx IOS}
{$R *.XLgXhdpiTb.fmx ANDROID}
{$R *.SmXhdpiPh.fmx ANDROID}
{$R *.iPhone4in.fmx IOS}
{$R *.iPhone47in.fmx IOS}
end.
|
//Read more: http://www.linhadecodigo.com.br/artigo/2237/implementando-algoritmo-buscabr.aspx#ixzz4kmJj5J00
unit Myloo.Phonetic.BuscaBR;
interface
uses
System.SysUtils,
System.StrUtils,
System.classes,
Myloo.Phonetic.Interfaces,
Myloo.Patterns.Singleton,
Myloo.Strings.Utils;
type
TBuscaBR = class(TInterfacedObject, IPhoneticMatching)
public
class function PhoneticMatching(AText:string):string;overload;
function Phonetic(AText:string):string;overload;
function Similar(const AText, AOther: string): Boolean;
function Compare(const AText, AOther: string): Integer;
function Proc(const AText, AOther: string): Boolean;
end;
TSBuscaBR = TSingleton<TBuscaBR>;
implementation
{ TBuscaBR }
class function TBuscaBR.PhoneticMatching(AText: string): string;
var
NewStr:string;
begin
Result := EmptyStr;
NewStr := RemoveAccents(AText);
NewStr := StrReplace(NewStr,['BL','BR'],'B');
NewStr := StrReplace(NewStr,['PH'],'F');
NewStr := StrReplace(NewStr,['GL','GR','MG','NG','RG'],'G');
NewStr := StrReplace(NewStr,['Y'],'I');
NewStr := StrReplace(NewStr,['GE','GI','RJ','MJ'],'J');
NewStr := StrReplace(NewStr,['CA','CO','CU','CK','Q'],'K');
NewStr := StrReplace(NewStr,['N','AO','AUM','GM','MD','OM','ON'],'M');
NewStr := StrReplace(NewStr,['PR'],'P');
NewStr := StrReplace(NewStr,['L'],'R');
NewStr := StrReplace(NewStr,['Ç','CE','CI','CH','CS','RS','TS','X','Z'],'S');
NewStr := StrReplace(NewStr,['TR','TL','CT','RT','ST','PT'],'T');
NewStr := ReplaceInitialChar(NewStr,['U','W'],'V');
NewStr := StrReplace(NewStr,['RM'],'SM');
NewStr := ReplaceFinalChar(NewStr,['M','R','S'],#0);
NewStr := StrReplace(NewStr,['H','A','E','I','O','U'],EmptyStr);
NewStr := RemoveSpecialCharacters(NewStr);
Result := NewStr;
end;
function TBuscaBR.Phonetic(AText: string): string;
var
NewStr:string;
begin
Result := EmptyStr;
NewStr := RemoveAccents(AText);
NewStr := StrReplace(NewStr,['BL','BR'],'B');
NewStr := StrReplace(NewStr,['PH'],'F');
NewStr := StrReplace(NewStr,['GL','GR','MG','NG','RG'],'G');
NewStr := StrReplace(NewStr,['Y'],'I');
NewStr := StrReplace(NewStr,['GE','GI','RJ','MJ'],'J');
NewStr := StrReplace(NewStr,['CA','CO','CU','CK','Q'],'K');
NewStr := StrReplace(NewStr,['N','AO','AUM','GM','MD','OM','ON'],'M');
NewStr := StrReplace(NewStr,['PR'],'P');
NewStr := StrReplace(NewStr,['L'],'R');
NewStr := StrReplace(NewStr,['Ç','CE','CI','CH','CS','RS','TS','X','Z'],'S');
NewStr := StrReplace(NewStr,['TR','TL','CT','RT','ST','PT'],'T');
NewStr := ReplaceInitialChar(NewStr,['U','W'],'V');
NewStr := StrReplace(NewStr,['RM'],'SM');
NewStr := ReplaceFinalChar(NewStr,['M','R','S'],#0);
NewStr := StrReplace(NewStr,['H','A','E','I','O','U'],EmptyStr);
NewStr := RemoveSpecialCharacters(NewStr);
Result := NewStr;
end;
function TBuscaBR.Similar(const AText, AOther: string): Boolean;
begin
Result := Phonetic(AText) = Phonetic(AOther); // compara se as 2 strings são iguais e retorna boolean
end;
function TBuscaBR.Compare(const AText, AOther: string): Integer; // Compara se as 2 strings são iguais e retorna inteiro
begin
Result := AnsiCompareStr(Phonetic(AText), Phonetic(AOther));
end;
function TBuscaBR.Proc(const AText, AOther: string): Boolean; // compara se os 4 primeiros caracteres são iguais e retorna boolean
begin
Result := Similar(LeftStr(AText,4), LeftStr(AOther,4));
end;
end.
|
{@abstract(@name defines a series of cursor constants.
It creates the associated cursors in the initialization section and
destroys them in the finalization section.)
The bitmaps for the cursors are stored in ModelMuseCursors.res.}
unit CursorsFoiledAgain;
interface
uses Windows;
{User defined cursors are assigned unique, arbitrary, positive values.}
const
// @name represents a cursor shaped like a hand.
// See @link(crHandGrab).
crHandFlat = 34;
// @name represents a cursor shaped like a magnifying glass with
// a "+" symbol in the middle.
// See @link(crZoomOut) and @link(crZoom).
crZoomIn = 2;
// @name represents a cursor shaped like a magnifying glass with
// a "-" symbol in the middle.
// See @link(crZoomIn) and @link(crZoom).
crZoomOut = 3;
// @name represents a cursor shaped like a magnifying glass.
// See @link(crZoomIn) and @link(crZoomOut).
crZoom = 4;
// @name represents a cursor shaped like an "X".
crDelete = 5;
// @name represents a cursor shaped like a horizontal line.
crHorizontal = 6;
// @name represents a cursor shaped like a vertical line.
crVertical = 7;
// @name represents a cursor shaped like two vertical lines close together
// with arrows point away from them horizontally.
crMoveColumn = 8;
// @name represents a cursor shaped like two horizontal lines close together
// with arrows point away from them vertically.
crMoveRow = 9;
// @name represents a cursor shaped like three vertical
// lines close together crossed by three horizontal lines.
crSubdivide = 10;
// @name represents a cursor shaped like a large arrowhead.
crSelectPoint = 11;
// @name represents a cursor shaped like a hand
// with bent fingers as if holding something.
// See @link(crHandGrab).
crHandGrab = 12;
// @name represents a cursor shaped like
// A large "+" with a dot in the middle
// with a smaller dot and line in the upper left.
crInsertPoint = 13;
// @name represents a cursor shaped like
// A large "X" with a smaller broken line in the upper left.
crDeleteSegment = 14;
// @name represents a cursor shaped like
// A large "+" with a dot in the middle
// with a smaller dot and line in the upper left.
// the "+" is drawn with a dotted line.
crDisabledInsertPoint = 15;
// @name represents a cursor shaped like
// A large "X" with a smaller broken line in the upper left.
// the "X" is drawn with a dotted line.
crDisabledDeleteSegment = 16;
// @name represents a cursor shaped like two widely spaced vertical
// lines close together crossed by two widely spaced horizontal lines.
crSetWidth = 17;
// @name represents a cursor shaped like a curved, double-headed
// arrow with a dot at the center of the circle defined by the curve.
crRotate = 18;
// @name represents a cursor shaped like an arrow with a large point
// in the upper right.
crPointArrow = 19;
// @name represents a cursor shaped like an arrow with a poly line
// on the right.
crLineArrow = 20;
// @name represents a cursor shaped like an arrow with a polygon
// on the right.
crPolygonArrow = 21;
// @name represents a cursor shaped like an arrow with a stair-step pattern
// on the right.
crStraightLineArrow = 22;
// @name represents a cursor shaped like an arrow with a rectangle
// on the right.
crRectangleArrow = 23;
// @name represents a cursor with multiple polygons. The cursor is
// used when drawing @link(TScreenObject)s with multiple polygons.
crMultiPartPolygon = 24;
// @name represents a cursor with multiple lines. The cursor is
// used when drawing @link(TScreenObject)s with multiple lines.
crMultiPartLine = 25;
// @name represents a cursor with multiple points. The cursor is
// used when drawing @link(TScreenObject)s with multiple points.
crMultiPartPoint = 26;
crSnapPointArrow = 27;
crSnapLineArrow = 28;
crSnapPolygonArrow = 29;
crSnapStraightLineArrow = 30;
crSnapRectangleArrow = 31;
crSnapMultiPartPolygon = 32;
crSnapMultiPartPoint = 35;
crSnapMultiPartLine = 36;
// @name represents a cursor shaped like a magnifying glass with
// a plus sign above it and a minus sign below it.
crZoomByY = 33;
// @name represents a cursor shaped like a large arrowhead.
crSnapSelectPoint = 37;
crVertexValue = 38;
crMeasure = 39;
crMoveCrossSection = 40;
crFishnet = 50;
crMoveNode = 51;
// cursor numbers 41-46 are defined dynamically in frmGoPhast.
implementation
// Force GExperts' "Backup Project" to backup ModelMuseCursors.res.
{#BACKUP ModelMuseCursors.res}
// ModelMuseCursors.res contains the monochrome bitmaps that will define
// the new cursors. The bitmaps are 32 x 32 pixels in size.
{$R ModelMuseCursors.res}
uses Forms, Graphics;
var
LastCursor: integer = 0;
MyCursors: array of integer;
(*procedure CreateMaskedCursor(const BitmapName, MaskName: string;
const CursorNumber, HotPointX, HotPointY: integer);
var
QBitmap, QMask: QBitmapH;
QCursor: QCursorH;
bmCursor, bmMask: TBitmap;
Index: integer;
begin
// ReferenceS:
// p. 588 of
// Teixeira, Steve and Pacheco, Xavier. 2002. Borland®
// Delphi TM 6 Developer's Guide. Sams Publishing,
// 201 West 103rd St., Indianapolis, Indiana, 46290 USA, 1169 p.
//
// P. 442 of
// Shemitz, Jon, 2002. Kylix: The Prefessional Developer's Guide
// and Reference. Apress, 901 Grayson Street, Suite 204,
// Berkeley, CA 94710, 943 p.
// Make sure the cursor number is not duplicated.
for Index := 0 to LastCursor - 1 do
begin
Assert(MyCursors[Index] <> CursorNumber);
end;
// store the cursor number in MyCursors for use in DestroyCursors.
Inc(LastCursor);
SetLength(MyCursors, LastCursor);
MyCursors[LastCursor - 1] := CursorNumber;
{
from http://doc.trolltech.com/3.0/qcursor.html#QCursor-3
The cursor bitmap (B) and mask (M) bits are combined like this:
B=1 and M=1 gives black.
B=0 and M=1 gives white.
B=0 and M=0 gives transparent.
B=1 and M=0 gives an undefined result.
}
// Now create the cursor.
// First create two bitmaps.
// The first represents the cursor;
// the second represents the mask.
bmCursor := TBitmap.Create;
bmMask := TBitmap.Create;
try
// load the appropriate contents into the two bitmaps.
bmCursor.LoadFromResourceName(HInstance, BitmapName);
bmMask.LoadFromResourceName(HInstance, MaskName);
// Create two QBitmapH.
// The first represents the cursor;
// the second represents the mask.
QBitmap := QBitmap_create;
QMask := QBitmap_create;
try
// load the appropriate contents into the two QBitmapHs.
QBitmap_from_QPixmap(QBitmap, bmCursor.Handle);
QBitmap_from_QPixmap(QMask, bmMask.Handle);
// make a cursor.
QCursor := QCursor_create(QBitmap, QMask, HotPointX, HotPointY);
finally
// clean up.
QBitmap_destroy(QBitmap);
QBitmap_destroy(QMask);
end;
finally
// clean up.
bmCursor.Free;
bmMask.Free;
end;
// store the cursor in Screen.Cursors.
Screen.Cursors[CursorNumber] := QCursor;
end;
*)
Procedure LoadACursor(const CursorName: string; CursorNumber: integer);
var
Index: integer;
begin
// Make sure the cursor number is not duplicated.
for Index := 0 to LastCursor - 1 do
begin
Assert(MyCursors[Index] <> CursorNumber);
end;
// store the cursor number in MyCursors for use in DestroyCursors.
Inc(LastCursor);
SetLength(MyCursors, LastCursor);
MyCursors[LastCursor - 1] := CursorNumber;
Screen.Cursors[CursorNumber] := LoadCursor(HInstance, PChar(CursorName));
end;
{procedure DestroyCursors;
var
Index: integer;
begin
// Screen destroys the cursors by calling QCursor_destroy.
for Index := 0 to LastCursor - 1 do
begin
Screen.Cursors[MyCursors[Index]] := nil;
end;
end; }
initialization
LoadACursor('CRHANDFLAT', crHandFlat);
LoadACursor('CRZOOMIN', crZoomIn);
LoadACursor('CRZOOMOUT', crZoomOut);
LoadACursor('CRZOOM', crZoom);
LoadACursor('CRDELETE', crDelete);
LoadACursor('CRHORIZONTALLINE', crHorizontal);
LoadACursor('CRVERTICALLINE', crVertical);
LoadACursor('CRMOVECOLUMN', crMoveColumn);
LoadACursor('CRMOVEROW', crMoveRow);
LoadACursor('CRSUBDIVIDE', crSubdivide);
LoadACursor('CRSELECTPOINT', crSelectPoint);
LoadACursor('CRHANDGRAB', crHandGrab);
LoadACursor('CRINSERTPOINT', crInsertPoint);
LoadACursor('CRDELETESEGMENT', crDeleteSegment);
LoadACursor('CRDISABLEDINSERTPOINT', crDisabledInsertPoint);
LoadACursor('CRDISABLEDDELETESEGMENT', crDisabledDeleteSegment);
LoadACursor('CRSETWIDTH', crSetWidth);
LoadACursor('CRROTATE', crRotate);
LoadACursor('CRPOINTARROW', crPointArrow);
LoadACursor('CRLINEARROW', crLineArrow);
LoadACursor('CRPOLYGONARROW', crPolygonArrow);
LoadACursor('CRSTRAIGHTLINEARROW', crStraightLineArrow);
LoadACursor('CRRECTANGLEARROW', crRectangleArrow);
LoadACursor('CRMULTIPARTPOLYGON', crMultiPartPolygon);
LoadACursor('CRMULTIPARTLINE', crMultiPartLine);
LoadACursor('CRMULTIPARTPOINT', crMultiPartPoint);
LoadACursor('CRSNAPPOINTARROW', crSnapPointArrow);
LoadACursor('CRSNAPLINEARROW', crSnapLineArrow);
LoadACursor('CRSNAPPOLYGONARROW', crSnapPolygonArrow);
LoadACursor('CRSNAPSTRAIGHTLINEARROW', crSnapStraightLineArrow);
LoadACursor('CRSNAPRECTANGLEARROW', crSnapRectangleArrow);
LoadACursor('CRSNAPMULTIPARTPOINT', crSnapMultiPartPoint);
LoadACursor('CRSNAPMULTIPARTLINE', crSnapMultiPartLine);
LoadACursor('CRSNAPMULTIPARTPOLYGON', crSnapMultiPartPolygon);
LoadACursor('CRZOOMBYY', crZoomByY);
LoadACursor('CRSNAPSELECTPOINT', crSnapSelectPoint);
LoadACursor('CRVERTEXVALUE', crVertexValue);
LoadACursor('CRMEASURE', crMeasure);
LoadACursor('CRMOVECROSSSECTION', crMoveCrossSection);
LoadACursor('CRFISHNET', crFishnet);
LoadACursor('CRMOVENODE', crMoveNode);
{
CreateMaskedCursor('CRHANDFLAT', 'MASKHANDFLAT', crHandFlat, 14, 11);
CreateMaskedCursor('CRZOOMIN', 'MASKZOOMIN', crZoomIn, 11, 11);
CreateMaskedCursor('CRZOOMOUT', 'MASKZOOMOUT', crZoomOut, 11, 11);
CreateMaskedCursor('CRZOOM', 'MASKZOOM', crZoom, 11, 11);
CreateMaskedCursor('CRZOOMNODOT', 'MASKZOOM', crZoomNoDot, 11, 11);
CreateMaskedCursor('CRDELETE', 'MASKDELETE', crDelete, 15, 15);
CreateMaskedCursor('CRHORIZONTALLINE', 'MASKHORIZONTALLINE',
crHorizontal, 16, 16);
CreateMaskedCursor('CRVERTICALLINE', 'MASKVERTICALLINE', crVertical, 16, 16);
CreateMaskedCursor('CRMOVECOLUMN', 'MASKMOVECOLUMN', crMoveColumn, 16, 16);
CreateMaskedCursor('CRMOVEROW', 'MASKMOVEROW', crMoveRow, 16, 16);
CreateMaskedCursor('CRSUBDIVIDE', 'MASKSUBDIVIDE', crSubdivide, 16, 16);
CreateMaskedCursor('CRSELECTPOINT', 'MASKSELECTPOINT', crSelectPoint, 7, 7);
CreateMaskedCursor('CRHANDGRAB', 'MASKHANDGRAB', crHandGrab, 16, 11);
CreateMaskedCursor('CRINSERTPOINT', 'MASKINSERTPOINT', crInsertPoint, 15, 15);
CreateMaskedCursor('CRDELETESEGMENT', 'MASKDELETESEGMENT',
crDeleteSegment, 21, 21);
CreateMaskedCursor('CRDISABLEDINSERTPOINT', 'MASKINSERTPOINT',
crDisabledInsertPoint, 15, 15);
CreateMaskedCursor('CRDISABLEDDELETESEGMENT', 'MASKDELETESEGMENT',
crDisabledDeleteSegment, 21, 21);
CreateMaskedCursor('CRSETWIDTH', 'MASKSETWIDTH', crSetWidth, 16, 16);
CreateMaskedCursor('CRROTATE', 'MASKROTATE', crRotate, 16, 16);
CreateMaskedCursor('CRPOINTARROW', 'MASKPOINTARROW', crPointArrow, 2, 2);
CreateMaskedCursor('CRLINEARROW', 'MASKLINEARROW', crLineArrow, 2, 2);
CreateMaskedCursor('CRPOLYGONARROW', 'MASKPOLYGONARROW',
crPolygonArrow, 2, 2);
CreateMaskedCursor('CRSTRAIGHTLINEARROW', 'MASKSTRAIGHTLINEARROW',
crStraightLineArrow, 2, 2);
CreateMaskedCursor('CRRECTANGLEARROW', 'MASKRECTANGLEARROW',
crRectangleArrow, 2, 2);
CreateMaskedCursor('CR3DPOINTARROW', 'MASK3DPOINTARROW',
cr3dPointArrow, 2, 2);
CreateMaskedCursor('CR3DLINEARROW', 'MASK3DLINEARROW', cr3dLineArrow, 2, 2);
CreateMaskedCursor('CR3DSHEETARROW', 'MASK3DSHEETARROW',
cr3dSheetArrow, 2, 2);
CreateMaskedCursor('CR3DSOLIDARROW', 'MASK3DSOLIDARROW',
cr3dSolidArrow, 2, 2);
CreateMaskedCursor('CR3DSTRAIGHTLINEARROW', 'MASK3DSTRAIGHTLINEARROW',
cr3dStraightLineArrow, 2, 2);
CreateMaskedCursor('CR3DCUBEARROW', 'MASK3DCUBEARROW', crCubeArrow, 2, 2);
CreateMaskedCursor('CRDOMAINLINE', 'MASKDOMAINLINE', crDomainLine, 2, 2);
CreateMaskedCursor('CRDOMAINPOLYGON', 'MASKDOMAINPOLYGON',
crDomainPolygon, 2, 2);
// CreateMaskedCursor('CRZOOMBYY', 'MASKZOOMBYY',
// crZoomByY, 15, 15);
CreateMaskedCursor('3DZOOM', '3DZOOMMASK',
crZoomByY, 15, 32); }
//finalization
// DestroyCursors;
end.
|
unit Odontologia.Vistas.Usuarios;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.Variants,
System.Classes,
System.ImageList,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Data.DB,
Vcl.ImgList,
Vcl.StdCtrls,
Vcl.Buttons,
Vcl.Grids,
Vcl.DBGrids,
Vcl.WinXPanels,
Vcl.ExtCtrls,
Vcl.DBCtrls,
Vcl.ExtDlgs,
Vcl.Imaging.jpeg,
Odontologia.Controlador,
Odontologia.Controlador.Interfaces,
Odontologia.Controlador.Empresa.Interfaces,
Odontologia.Controlador.Estado.Interfaces,
Odontologia.Controlador.Usuario.Interfaces,
Odontologia.Vistas.Template;
type
TPagUsuario = class(TPagTemplate)
DataSource2: TDataSource;
cmbEmpresa: TDBLookupComboBox;
edtCodigo: TEdit;
edtClave: TEdit;
edtNivel: TEdit;
edtLogin: TEdit;
Label1: TLabel;
Label11: TLabel;
Label2: TLabel;
Label3: TLabel;
Label5: TLabel;
Label8: TLabel;
Image1: TImage;
Panel1: TPanel;
btnGuardarImagen: TSpeedButton;
OpenPictureDialog1: TOpenPictureDialog;
cmbEstado: TDBLookupComboBox;
DataSource3: TDataSource;
procedure FormCreate(Sender: TObject);
procedure btnBorrarClick(Sender: TObject);
procedure btnGuardarClick(Sender: TObject);
procedure btnCancelarClick(Sender: TObject);
procedure btnNuevoClick(Sender: TObject);
procedure btnActualizarClick(Sender: TObject);
procedure DBGrid1DblClick(Sender: TObject);
procedure DataSource1DataChange(Sender: TObject; Field: TField);
procedure Image1DblClick(Sender: TObject);
procedure btnGuardarImagenClick(Sender: TObject);
procedure edtSearchKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
{ Private declarations }
FController : iController;
FEmpresa : iControllerEmpresa;
FEstado : iControllerEstado;
FUsuario : iControllerUsuario;
procedure prc_estado_inicial;
procedure prc_copiar_img_directorio(origen : String);
public
{ Public declarations }
end;
var
PagUsuario : TPagUsuario;
Insercion : Boolean;
imagenURL : String;
imagenModif : Boolean;
path : string;
implementation
uses
System.SysUtils;
{$R *.dfm}
procedure TPagUsuario.btnActualizarClick(Sender: TObject);
begin
inherited;
FUsuario.Buscar;
prc_estado_inicial;
end;
procedure TPagUsuario.btnBorrarClick(Sender: TObject);
var
ShouldClose: Boolean;
begin
inherited;
if MessageDlg('Realmente desea eliminar este registro?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then
begin
FUsuario.Entidad.USU_CODIGO := StrToInt(edtCodigo.Text);
FUsuario.Eliminar;
FUsuario.Buscar;
prc_estado_inicial;
end else
begin
edtLogin.SetFocus;
end;
end;
procedure TPagUsuario.btnCancelarClick(Sender: TObject);
begin
inherited;
prc_estado_inicial;
end;
procedure TPagUsuario.btnGuardarClick(Sender: TObject);
begin
inherited;
if Insercion then
begin
FUsuario.Entidad.USU_LOGIN := edtLogin.Text;
FUsuario.Entidad.USU_COD_ESTADO := DataSource3.DataSet.FieldByName('SIT_CODIGO').AsInteger;
FUsuario.Entidad.USU_NIVEL := StrToInt(edtNivel.Text);
FUsuario.Entidad.USU_CLAVE := edtClave.Text;
FUsuario.Entidad.USU_COD_EMPRESA := DataSource2.DataSet.FieldByName('CODIGO').AsInteger;
if imagenModif then
begin
FUsuario.Entidad.USU_FOTO := imagenURL;
end else
begin
FUsuario.Entidad.USU_FOTO := '';
end;
FUsuario.Insertar;
end
else
begin
FUsuario.Entidad.USU_CODIGO := StrToInt(edtCodigo.Text);
FUsuario.Entidad.USU_LOGIN := edtLogin.Text;
FUsuario.Entidad.USU_COD_ESTADO := DataSource3.DataSet.FieldByName('SIT_CODIGO').AsInteger;
FUsuario.Entidad.USU_NIVEL := StrToInt(edtNivel.Text);
FUsuario.Entidad.USU_CLAVE := edtClave.Text;
FUsuario.Entidad.USU_COD_EMPRESA := DataSource2.DataSet.FieldByName('CODIGO').AsInteger;
FUsuario.Entidad.USU_FOTO := imagenURL;
FUsuario.Modificar;
end;
prc_estado_inicial;
end;
procedure TPagUsuario.btnGuardarImagenClick(Sender: TObject);
begin
inherited;
if edtLogin.Text = '' then
begin
ShowMessage('Primero debe ingresar un dato');
edtlogin.SetFocus;
end else
begin
prc_copiar_img_directorio(OpenPictureDialog1.FileName);
imagenModif := true;
btnGuardarImagen.Enabled := false;
end;
ShowMessage('La imagen ha sido guardada');
end;
procedure TPagUsuario.btnNuevoClick(Sender: TObject);
begin
inherited;
CardPanel1.ActiveCard := Card2;
lblTitulo2.Caption := 'Agregar nuevo registro';
edtCodigo.Enabled := False;
cmbEstado.KeyValue := 1;
cmbEmpresa.KeyValue := 1;
edtLogin.SetFocus;
end;
procedure TPagUsuario.DataSource1DataChange(Sender: TObject; Field: TField);
begin
inherited;
edtCodigo.Text := DataSource1.DataSet.FieldByName('EMP_CODIGO').AsString;
edtLogin.Text := DataSource1.DataSet.FieldByName('EMP_NOMBRE').AsString;
end;
procedure TPagUsuario.DBGrid1DblClick(Sender: TObject);
begin
inherited;
Insercion := False;
CardPanel1.ActiveCard := Card2;
lblTitulo2.Caption := 'Modificar registro';
edtCodigo.Text := DataSource1.DataSet.FieldByName('CODIGO').AsString;
edtLogin.Text := DataSource1.DataSet.FieldByName('LOGIN').AsString;
cmbEstado.KeyValue := DataSource1.DataSet.FieldByName('CODESTADO').AsInteger;
edtnivel.Text := DataSource1.DataSet.FieldByName('NIVEL').AsString;
edtClave.Text := DataSource1.DataSet.FieldByName('CLAVE').AsString;
edtClave.Enabled := false;
cmbEmpresa.KeyValue := DataSource1.DataSet.FieldByName('CODEMPRESA').AsString;
imagenURL := DataSource1.DataSet.FieldByName('FOTO').AsString;
if not (VarIsNull(imagenURL) or imagenurl.IsEmpty) then
begin
Image1.Picture.LoadFromFile(imagenURL);
end;
end;
procedure TPagUsuario.edtSearchKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
inherited;
FUsuario.Buscar('%' + edtSearch.Text + '%');
end;
procedure TPagUsuario.FormCreate(Sender: TObject);
begin
inherited;
path := ExtractFilePath(ParamStr(0));
lblTitulo.Caption := 'Registro de usuarios';
edtCodigo.Enabled := False;
FController := TController.New;
FUsuario := FController.Usuario.DataSource(DataSource1);
FEmpresa := FController.Empresa.DataSource(DataSource2);
FEstado := FController.Estado.DataSource(DataSource3);
prc_estado_inicial;
end;
procedure TPagUsuario.Image1DblClick(Sender: TObject);
begin
inherited;
if OpenPictureDialog1.Execute then
if FileExists(OpenPictureDialog1.FileName) then
begin
Image1.Picture.LoadFromFile(OpenPictureDialog1.FileName);
btnGuardarImagen.Enabled := true;
end else
begin
raise Exception.Create('File does not exist.');
end;
end;
procedure TPagUsuario.prc_copiar_img_directorio(origen : String);
begin
imagenURL := path + 'fotos\usuario_' + edtLogin.text + '.jpg';
CopyFile(PChar(origen),PChar(imagenURL),False);
end;
procedure TPagUsuario.prc_estado_inicial;
begin
imagenModif := false;
imagenURL := path + 'fotos\noimage.jpg';
if FileExists(imagenURL) then
begin
Image1.Picture.LoadFromFile(imagenURL);
end else
begin
Image1.Picture.Assign(nil);
end;
Insercion := True;
CardPanel1.ActiveCard := Card1;
edtSearch.Text := '';
edtCodigo.Text := '';
edtlogin.Text := '';
cmbEstado.KeyValue := 1;
edtNivel.Text := '';
edtClave.Text := '';
cmbEmpresa.KeyValue := 1;
FEmpresa.Buscar;
FEstado.Buscar;
FUsuario.Buscar;
end;
end.
|
unit CatTasks;
{
Catarinka - Task Management library
Copyright (c) 2003-2020 Felipe Daragon
License: 3-clause BSD
See https://github.com/felipedaragon/catarinka/ for details
}
interface
{$I Catarinka.inc}
uses
{$IFDEF DXE2_OR_UP}
Winapi.Windows, Vcl.Forms, System.SysUtils, System.Classes, Winapi.TlHelp32, Winapi.PSAPI;
{$ELSE}
Windows, Forms, SysUtils, Classes, TlHelp32, PSAPI;
{$ENDIF}
function KillTask(const ExeFileName: string;FullName:boolean=false): Integer;
function KillChildTasks: boolean;
function MatchProcessFilename(pe:TProcessEntry32; const ExeFileName: string; FullName:boolean=false):boolean;
function RunTask(const ExeFileName: string; const Wait: boolean = false;
const WindowState: Integer = SW_SHOW): Cardinal;
function TaskRunning(const ExeFileName: WideString;const FullName:boolean): boolean;
function TaskRunningCount(const ExeFileName: WideString;const FullName:boolean): integer;
function TaskRunningSingleInstance(const ExeFileName: WideString;const FullName:boolean): boolean;
function TaskRunningWithPID(const ExeFileName: WideString; const PID: Cardinal;const FullName:boolean): boolean;
procedure GetTaskList(ProcList: TStrings;FileMask:string='');
procedure GetTaskListEx(ProcList: TStrings;FileMask:string;FullName:boolean);
procedure KillTaskByMask(FileMask:string);
procedure KillTaskbyPID(const PID: Cardinal);
procedure KillTaskList(ProcList: TStringList);
procedure ResumeProcess(const ProcessID: DWORD);
procedure SuspendProcess(const ProcessID: DWORD);
implementation
uses CatStrings, CatMatch;
const
THREAD_SUSPEND_RESUME = $00000002;
cProcSep = '|pid=';
function OpenThread(dwDesiredAccess: DWORD; bInheritHandle: BOOL;
dwThreadId: DWORD): DWORD; stdcall; external 'kernel32.dll';
// Gets the full filename of a process ID
function GetFilenameByPID(const PID: THandle): WideString;
const
PROCESS_QUERY_LIMITED_INFORMATION = $1000;
type
TQueryFullProcessImageNameW = function(hProcess: THandle; dwFlags: DWORD; lpExeName: PWideChar; nSize: PDWORD): BOOL; stdcall;
var
hProcess: THandle;
TargetName: WideString;
QueryFullProcessImageNameW: TQueryFullProcessImageNameW;
nSize: cardinal;
begin
Result := '';
nSize := MAX_PATH;
SetLength(TargetName, nSize);
if Win32MajorVersion >= 6 then begin
hProcess := OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, PID);
if hProcess <> 0 then begin
try
@QueryFullProcessImageNameW := GetProcAddress(GetModuleHandle('kernel32'), 'QueryFullProcessImageNameW');
if Assigned(QueryFullProcessImageNameW) then
if QueryFullProcessImageNameW(hProcess, 0, PWideChar(TargetName), @nSize) then
Result := PWideChar(TargetName);
finally
CloseHandle(hProcess);
end;
end;
end else begin
hProcess := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, false, PID);
if hProcess <> 0 then
try
if GetModuleFileNameExW(hProcess, 0, PWideChar(TargetName), nSize) <> 0 then
Result := PWideChar(TargetName);
finally
CloseHandle(hProcess);
end;
end;
end;
// Gets a list of tasks, optionally based on a mask
procedure GetTaskList(ProcList: TStrings;FileMask:string='');
begin
GetTaskListEx(ProcList, FileMask, false);
end;
// Gets a list of tasks, optionally based on a mask and with full filename
procedure GetTaskListEx(ProcList: TStrings;FileMask:string;FullName:boolean);
var
ContinueLoop: BOOL;
FSnapshotHandle: THandle;
FProcessEntry32: TProcessEntry32;
fn: string;
canadd: boolean;
begin
FSnapshotHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
FProcessEntry32.dwSize := sizeof(FProcessEntry32);
ContinueLoop := Process32First(FSnapshotHandle, FProcessEntry32);
while Integer(ContinueLoop) <> 0 do
begin
canadd := true;
fn := string(FProcessEntry32.szExeFile);
if fullname = true then
fn := GetFileNameByPID(FProcessEntry32.th32ProcessID);
if (FileMask <> emptystr) and (MatchWildcard(ExtractFilename(fn),FileMask, true) = false) then
canadd := false;
if canadd = true then
ProcList.Add(fn + cProcSep + IntToStr(FProcessEntry32.th32ProcessID));
ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32);
end;
CloseHandle(FSnapshotHandle);
end;
// Note: full name may require admin privileges to work for certain processes
function MatchProcessFilename(pe:TProcessEntry32; const ExeFileName: string; FullName:boolean=false):boolean;
var
fn, targetfn:string;
begin
result := false;
if FullName = true then begin
fn := GetFileNameByPID(pe.th32ProcessID);
targetfn := exefilename;
end else begin
fn := pe.szExeFile;
targetfn := extractfilename(exefilename);
end;
if Uppercase(fn) = Uppercase(targetfn) = true then
result := true;
end;
// Kills all child tasks from current process ID
function KillChildTasks: boolean;
var
h: THandle;
pe: TProcessEntry32;
curpid: {$IFDEF UNICODE}Cardinal{$ELSE}DWORD{$ENDIF};
begin
result := false;
curpid := GetCurrentProcessId;
h := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
pe.dwSize := SizeOf(pe);
if Process32First(h, pe) then
begin
while Process32Next(h, pe) do
begin
if pe.th32ParentProcessID = curpid then begin
//if lowercase(exename) = lowercase(string(pe.szExeFile)) then
KillTaskbyPID(pe.th32ProcessID);
result := true;
end;
end;
end;
end;
// Kills a process by its process ID
procedure KillTaskbyPID(const PID: Cardinal);
var
h: THandle;
lpExitCode: {$IFDEF UNICODE}Cardinal{$ELSE}DWORD{$ENDIF};
begin
h := OpenProcess(PROCESS_TERMINATE or PROCESS_QUERY_INFORMATION, false, PID);
if h = 0 then
exit;
if GetExitCodeProcess(h, lpExitCode) then
TerminateProcess(h, lpExitCode)
else
CloseHandle(h);
end;
// Runs a coomand and optionally waits for the execution to end
function RunTask(const ExeFileName: string; const Wait: boolean = false;
const WindowState: Integer = SW_SHOW): Cardinal;
var
Prog: array [0 .. 512] of char;
CurDir: array [0 .. 255] of char;
WorkDir: string;
StartupInfo: TStartupInfo;
ProcessInfo: TProcessInformation;
ExitCode: Cardinal;
begin
StrPCopy(Prog, ExeFileName);
GetDir(0, WorkDir);
StrPCopy(CurDir, WorkDir);
FillChar(StartupInfo, sizeof(StartupInfo), #0);
StartupInfo.cb := sizeof(StartupInfo);
StartupInfo.dwFlags := STARTF_USESHOWWINDOW;
StartupInfo.wShowWindow := WindowState;
if CreateProcess(nil, Prog, nil, nil, false, CREATE_NEW_CONSOLE or
NORMAL_PRIORITY_CLASS, nil, nil, StartupInfo, ProcessInfo) then
begin
Result := ProcessInfo.dwProcessId;
if Wait = true then
begin
repeat
application.ProcessMessages;
GetExitCodeProcess(ProcessInfo.hProcess, ExitCode);
WaitForSingleObject(ProcessInfo.hProcess, 10);
until (ExitCode <> STILL_ACTIVE) or application.Terminated;
end;
end
else
Result := $FFFFFFFF; // -1
end;
// Returns the number of running tasks
function TaskRunningCount(const ExeFileName: WideString;const FullName:boolean): integer;
var
ContinueLoop: BOOL;
FSnapshotHandle: THandle;
FProcessEntry32: TProcessEntry32;
begin
Result := 0;
FSnapshotHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
FProcessEntry32.dwSize := sizeof(FProcessEntry32);
ContinueLoop := Process32First(FSnapshotHandle, FProcessEntry32);
while Integer(ContinueLoop) <> 0 do
begin
if MatchProcessFilename(FProcessEntry32, ExeFilename, FullName) then
Inc(Result);
ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32);
end;
CloseHandle(FSnapshotHandle);
end;
// Returns true if a task is running, false otherwise
function TaskRunning(const ExeFileName: WideString;const FullName:boolean): boolean;
begin
Result := TaskRunningCount(ExeFileName, FullName) <> 0;
end;
// Returns true if a task is running with a specific PID, false otherwise
function TaskRunningWithPID(const ExeFileName: WideString;const PID: Cardinal;const FullName:boolean): boolean;
var
ContinueLoop: BOOL;
FSnapshotHandle: THandle;
FProcessEntry32: TProcessEntry32;
begin
Result := false;
FSnapshotHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
FProcessEntry32.dwSize := sizeof(FProcessEntry32);
ContinueLoop := Process32First(FSnapshotHandle, FProcessEntry32);
while Integer(ContinueLoop) <> 0 do
begin
if (MatchProcessFilename(FProcessEntry32, ExeFilename, FullName) = true)
and (FProcessEntry32.th32ProcessID = PID) then
result := true;
ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32);
end;
CloseHandle(FSnapshotHandle);
end;
// Returns true if a single instance of a task is running, false otherwise
function TaskRunningSingleInstance(const ExeFileName: WideString;const FullName:boolean): boolean;
begin
Result := not (TaskRunningCount(ExeFileName, FullName) >= 2);
end;
// Kills a process by its executable filename
// Note: full name may require admin privileges to work for certain processes
function KillTask(const ExeFileName: string; FullName:boolean=false): Integer;
const
PROCESS_TERMINATE = $0001;
var
ContinueLoop: BOOL;
FSnapshotHandle: THandle;
FProcessEntry32: TProcessEntry32;
begin
Result := 0;
FSnapshotHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
FProcessEntry32.dwSize := sizeof(FProcessEntry32);
ContinueLoop := Process32First(FSnapshotHandle, FProcessEntry32);
while Integer(ContinueLoop) <> 0 do
begin
if MatchProcessFilename(FProcessEntry32, exefilename, fullname) = true then
Result := Integer(TerminateProcess(OpenProcess(PROCESS_TERMINATE, BOOL(0),
FProcessEntry32.th32ProcessID), 0));
ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32);
end;
CloseHandle(FSnapshotHandle);
end;
// Kills a task or multiple tasks by a wildcard filename, such as notep*.exe
procedure KillTaskByMask(FileMask:string);
var sl:TStringList;
begin
if filemask = emptystr then
Exit;
sl := TStringList.Create;
GetTaskList(sl, FileMask);
KillTaskList(sl);
sl.Free;
end;
// Kills a list of processes by their process IDs
// Expects a list of PIDs in the following format:
// process.exe|pid=111
procedure KillTaskList(ProcList: TStringList);
var
i, c, pid: Integer;
//fn: string;
begin
c := ProcList.Count;
for i := 0 to c do
begin
If i < c then
begin
//fn := before(ProcList.strings[i], cProcSep);
pid := strtoint(after(ProcList.strings[i], cProcSep));
KillTaskbyPID(pid);
end;
end;
end;
// Suspends a process
procedure SuspendProcess(const ProcessID: DWORD);
var
ThreadsSnapshot, ThreadHandle: THandle;
ThreadRecord: TThreadEntry32;
begin
ThreadsSnapshot := CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
ThreadRecord.dwSize := sizeof(ThreadRecord);
if Thread32First(ThreadsSnapshot, ThreadRecord) then
begin
repeat
if ThreadRecord.th32OwnerProcessID = ProcessID then
begin
ThreadHandle := OpenThread(THREAD_SUSPEND_RESUME, false,
ThreadRecord.th32ThreadID);
if ThreadHandle = 0 then
exit;
SuspendThread(ThreadHandle);
CloseHandle(ThreadHandle);
end;
until not Thread32Next(ThreadsSnapshot, ThreadRecord);
end;
CloseHandle(ThreadsSnapshot);
end;
// Resumes a process
procedure ResumeProcess(const ProcessID: DWORD);
var
ThreadsSnapshot: THandle;
ThreadRecord: TThreadEntry32;
ThreadHandle: THandle;
begin
ThreadsSnapshot := CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
ThreadRecord.dwSize := sizeof(ThreadRecord);
if Thread32First(ThreadsSnapshot, ThreadRecord) then
begin
repeat
if ThreadRecord.th32OwnerProcessID = ProcessID then
begin
ThreadHandle := OpenThread(THREAD_SUSPEND_RESUME, false,
ThreadRecord.th32ThreadID);
if ThreadHandle = 0 then
exit;
ResumeThread(ThreadHandle);
CloseHandle(ThreadHandle);
end;
until not Thread32Next(ThreadsSnapshot, ThreadRecord);
end;
CloseHandle(ThreadsSnapshot);
end;
// ------------------------------------------------------------------------//
end.
|
unit uFrmFTPConfig;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, ExtCtrls, Registry, uDMGlobal, siComp;
type
TFrmFTPConfig = class(TForm)
pnlConfig: TPanel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
sbReset: TSpeedButton;
sbSave: TSpeedButton;
sbCancel: TSpeedButton;
edtFTP: TEdit;
edtPort: TEdit;
edtUser: TEdit;
edtPW: TEdit;
siLang1: TsiLang;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure sbCancelClick(Sender: TObject);
procedure sbResetClick(Sender: TObject);
procedure sbSaveClick(Sender: TObject);
private
{ Private declarations }
myReg : TRegistry;
sFTP, sPort, sUser, sPW, sResult : String;
public
function start:String;
end;
implementation
uses uMsgBox, uEncryptFunctions;
{$R *.dfm}
{ TFrmFTPConfig }
function TFrmFTPConfig.start: String;
begin
try
myReg := TRegistry.Create;
myReg.RootKey := HKEY_LOCAL_MACHINE;
myReg.OpenKey('SOFTWARE\AppleNet\CurrentVersions', True);
ShowModal;
Result := '';
finally
myReg.CloseKey;
FreeAndNil(myReg);
end;
end;
procedure TFrmFTPConfig.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TFrmFTPConfig.sbCancelClick(Sender: TObject);
begin
Close;
end;
procedure TFrmFTPConfig.sbResetClick(Sender: TObject);
begin
myReg.WriteString('FTPInfo', '0');
Close;
end;
procedure TFrmFTPConfig.sbSaveClick(Sender: TObject);
begin
//Save Date
sFTP := '#SRV#='+edtFTP.Text+';';
sPort := '#PRT#='+edtPort.Text+';';
sUser := '#USR#='+edtUser.Text+';';
sPW := '#PW#='+edtPW.Text+';';
sResult := sFTP + sPort + sUser + sPW;
myReg.WriteString('FTPInfo', EncodeServerInfo(sResult, 'FTPServer', CIPHER_TEXT_STEALING, FMT_UU));
MsgBox('Please restart again!', vbOKOnly + vbInformation);
Close;
end;
end.
|
unit DateAcc_Filter;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, cxCheckBox, StdCtrls, cxButtons,
cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxButtonEdit, cxControls,
cxGroupBox, cxSpinEdit, cxDropDownEdit, Unit_ZGlobal_Consts, GlobalSpr,
IBase, PackageLoad, ZTypes, Dates, FIBDatabase, pFIBDatabase, DB,
FIBDataSet, pFIBDataSet, ZMessages, cxRadioGroup, cxLabel, ZProc,
ActnList, uCommonSp;
type TZTypeDataFilter = (tztdfPeople,tztdfDepartment,tztdfVidOpl,tztdfNULL);
function TypeDataFilterToByte(AParameter:TZTypeDataFilter):Byte;
type TZDataFilter = record
KodSetup1:integer;
KodSetup2:integer;
TypeId:TZTypeDataFilter;
Id:integer;
TextId:string;
ModalResult:TModalResult;
end;
type
TZDatesAccFilter = class(TForm)
YesBtn: TcxButton;
CancelBtn: TcxButton;
BoxKodSetup: TcxGroupBox;
MonthesList1: TcxComboBox;
YearSpinEdit1: TcxSpinEdit;
DB: TpFIBDatabase;
DSet: TpFIBDataSet;
ReadTransaction: TpFIBTransaction;
BoxDataFilter: TcxGroupBox;
EditDataFilter: TcxButtonEdit;
FilterType: TcxRadioGroup;
MonthesList2: TcxComboBox;
YearSpinEdit2: TcxSpinEdit;
LabelFrom: TcxLabel;
LabelTo: TcxLabel;
ActionList: TActionList;
ActionYes: TAction;
ActionCancel: TAction;
EdCodeDataFilter: TcxTextEdit;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure EditDataFilterPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure FilterTypePropertiesChange(Sender: TObject);
procedure ActionYesExecute(Sender: TObject);
procedure ActionCancelExecute(Sender: TObject);
procedure EdCodeDataFilterExit(Sender: TObject);
private
PParameter:TZDataFilter;
PLanguageIndex:byte;
procedure GetDepartment;
procedure GetMan;
public
constructor Create(AOwner:TComponent;ADB_Handle:TISC_DB_HANDLE;AParameter:TZDataFilter);reintroduce;
property Parameter:TZDataFilter read PParameter;
end;
function ViewFilter(AOwner:TComponent;ADB_Handle:TISC_DB_HANDLE;AParameter:TZDataFilter):TZDataFilter;
implementation
uses StrUtils;
{$R *.dfm}
function TypeDataFilterToByte(AParameter:TZTypeDataFilter):Byte;
begin
Result:=0;
case AParameter of
tztdfPeople: Result:=1;
tztdfDepartment: Result:=2;
tztdfNULL: Result:=3;
tztdfVidOpl: Result:=4;
end;
end;
function ViewFilter(AOwner:TComponent;ADB_Handle:TISC_DB_HANDLE;AParameter:TZDataFilter):TZDataFilter;
var Filter:TZDatesAccFilter;
Res:TZDataFilter;
begin
Filter := TZDatesAccFilter.Create(AOwner,ADB_Handle,AParameter);
Res:=AParameter;
if Filter.ShowModal=mrYes then
Res:=Filter.Parameter;
Res.ModalResult:=Filter.ModalResult;
Filter.Free;
ViewFilter:=Res;
end;
procedure TZDatesAccFilter.GetMan;
var Man:Variant;
begin
if (Trim(EdCodeDataFilter.Text)<>'')
then begin
Man:=ManByTn(StrToInt(EdCodeDataFilter.Text),DB.Handle);
if VarArrayDimCount(Man)>0
then begin
PParameter.TypeId := tztdfPeople;
PParameter.Id :=Man[0];
EdCodeDataFilter.Text :=Man[1];
EditDataFilter.Text:=Man[2];
end;
end
else begin
PParameter.Id :=-1;
EdCodeDataFilter.Text :='';
EditDataFilter.Text :='';
end;
end;
procedure TZDatesAccFilter.GetDepartment;
var Dep:Variant;
begin
if (Trim(EdCodeDataFilter.Text)<>'')
then begin
Dep:=DepartmentByKod(EdCodeDataFilter.Text,DB.Handle);
if VarArrayDimCount(Dep)>0
then begin
PParameter.TypeId := tztdfDepartment;
EdCodeDataFilter.Text:= Dep[1];
EditDataFilter.Text := Dep[2];
PParameter.Id := Dep[0];
PParameter.TextId := Dep[2];
end;
end
else begin
if (Trim(EditDataFilter.Text)='')
then begin
EdCodeDataFilter.Text:= '';
EditDataFilter.Text := '';
PParameter.Id := -1;
PParameter.TextId := '';
end;
end;
end;
constructor TZDatesAccFilter.Create(AOwner:TComponent;ADB_Handle:TISC_DB_HANDLE;AParameter:TZDataFilter);
begin
inherited Create(AOwner);
PParameter:=AParameter;
PLanguageIndex:=LanguageIndex;
//******************************************************************************
Caption := FilterBtn_Caption[PLanguageIndex];
YesBtn.Caption := YesBtn_Caption[PLanguageIndex];
CancelBtn.Caption := CancelBtn_Caption[PLanguageIndex];
YesBtn.Hint := YesBtn.Caption;
CancelBtn.Hint := CancelBtn.Caption;
FilterType.Properties.Items[0].Caption := LabelMan_Caption[PLanguageIndex];
FilterType.Properties.Items[1].Caption := LabelDepartment_Caption[PLanguageIndex];
FilterType.Properties.Items[2].Caption := LabelVidOpl_Caption[PLanguageIndex];
FilterType.Properties.Items[3].Caption := LabelNotFilter_Caption[PLanguageIndex];
LabelFrom.Caption := LabelDateBeg_Caption[PLanguageIndex];
LabelTo.Caption := AnsiLowerCase(LabelDateEnd_Caption[PLanguageIndex]);
MonthesList1.Properties.Items.Text := MonthesList_Text[PlanguageIndex];
MonthesList2.Properties.Items.Text := MonthesList_Text[PlanguageIndex];
//******************************************************************************
DB.Handle := ADB_Handle;
ReadTransaction.StartTransaction;
if PParameter.KodSetup1=0 then
begin
DSet.SQLs.SelectSQL.Text := 'SELECT * FROM Z_KOD_SETUP_RETURN';
DSet.Open;
YearSpinEdit1.Value:=YearMonthFromKodSetup(DSet.FieldValues['KOD_SETUP']);
MonthesList1.ItemIndex:= YearMonthFromKodSetup(DSet.FieldValues['KOD_SETUP'],false)-1;
end
else
begin
YearSpinEdit1.Value:=YearMonthFromKodSetup(PParameter.KodSetup1);
MonthesList1.ItemIndex:= YearMonthFromKodSetup(PParameter.KodSetup1,false)-1;
end;
if PParameter.KodSetup2=0 then
begin
if not DSet.Active then
begin
DSet.SQLs.SelectSQL.Text := 'SELECT * FROM Z_KOD_SETUP_RETURN';
DSet.Open;
end;
YearSpinEdit2.Value:=YearMonthFromKodSetup(DSet.FieldValues['KOD_SETUP']);
MonthesList2.ItemIndex:= YearMonthFromKodSetup(DSet.FieldValues['KOD_SETUP'],false)-1;
end
else
begin
YearSpinEdit2.Value:=YearMonthFromKodSetup(PParameter.KodSetup2);
MonthesList2.ItemIndex:= YearMonthFromKodSetup(PParameter.KodSetup2,false)-1;
end;
case PParameter.TypeId of
tztdfPeople:
begin
FilterType.ItemIndex:=0;
BoxDataFilter.Enabled:=True;
EditDataFilter.Text := PParameter.TextId;
end;
tztdfDepartment:
begin
FilterType.ItemIndex:=1;
BoxDataFilter.Enabled:=True;
EditDataFilter.Text := PParameter.TextId;
end;
tztdfVidOpl:
begin
FilterType.ItemIndex:=2;
BoxDataFilter.Enabled:=True;
EditDataFilter.Text := PParameter.TextId;
end;
tztdfNULL:
begin
FilterType.ItemIndex:=3;
BoxDataFilter.Enabled:=False;
EditDataFilter.Text := '';
end;
end;
//******************************************************************************
end;
procedure TZDatesAccFilter.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if ReadTransaction.InTransaction then ReadTransaction.Commit;
end;
procedure TZDatesAccFilter.EditDataFilterPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var ResultView:Variant;
sp: TSprav;
begin
case FilterType.ItemIndex of
0:
begin
ResultView:=LoadPeopleModal(Self,DB.Handle);
if VarArrayDimCount(ResultView)> 0 then
If ResultView[0]<>NULL then
begin
PParameter.TypeId := tztdfPeople;
EditDataFilter.Text := VarToStr(ResultView[4])+' - '+
VarToStr(ResultView[1])+' '+
VarToStr(ResultView[2])+' '+
VarToStr(ResultView[3]);
PParameter.Id := ResultView[0];
PParameter.TextId := EditDataFilter.Text;
end;
end;
1:
begin
sp := GetSprav('SpDepartment');
if sp <> nil
then begin
// заполнить входные параметры
with sp.Input do
begin
Append;
FieldValues['DBHandle'] := Integer(DB.Handle);
FieldValues['ShowStyle'] := 0;
FieldValues['Select'] := 1;
FieldValues['Actual_Date'] := Date;
Post;
end;
end;
sp.Show;
if sp.Output = nil
then ShowMessage('BUG: Output is NIL!!!')
else
if not sp.Output.IsEmpty
then begin
PParameter.TypeId := tztdfDepartment;
EdCodeDataFilter.Text:= varToStrDef(sp.Output['DEPARTMENT_CODE'],'');
EditDataFilter.Text := varToStrDef(sp.Output['NAME_FULL'],'');
PParameter.Id := sp.Output['ID_DEPARTMENT'];
PParameter.TextId := varToStrDef(sp.Output['NAME_FULL'],'');
end;
sp.Free;
end;
2:
begin
ResultView:=LoadVidOpl(Self,DB.Handle,zfsModal,0);
if VarArrayDimCount(ResultView)> 0 then
If ResultView[0]<>NULL then
begin
PParameter.TypeId := tztdfVidOpl;
EditDataFilter.Text := VarToStr(ResultView[2])+' - '+
VarToStr(ResultView[1]);
EdCodeDataFilter.Text:=VarToStr(ResultView[2]);
PParameter.Id := ResultView[0];
PParameter.TextId := EditDataFilter.Text;
end;
end;
end;
end;
procedure TZDatesAccFilter.FilterTypePropertiesChange(Sender: TObject);
var CurrentSelect:byte;
begin
CurrentSelect:=0;
case PParameter.TypeId of
tztdfPeople: CurrentSelect:=0;
tztdfDepartment: CurrentSelect:=1;
tztdfNULL: CurrentSelect:=2;
tztdfVidOpl: CurrentSelect:=3;
end;
BoxDataFilter.Enabled := (FilterType.ItemIndex<>FilterType.Properties.Items.Count-1);
EditDataFilter.Text := IfThen(FilterType.ItemIndex=CurrentSelect,PParameter.TextId,'');
end;
procedure TZDatesAccFilter.ActionYesExecute(Sender: TObject);
begin
if FilterType.ItemIndex = FilterType.Properties.Items.Count-1 then
begin
PParameter.TypeId := tztdfNULL;
PParameter.Id := 0;
PParameter.TextId := '';
end;
if PeriodToKodSetup(YearSpinEdit1.Value,MonthesList1.ItemIndex+1)>PeriodToKodSetup(YearSpinEdit2.Value,MonthesList2.ItemIndex+1) then
begin
ZShowMessage(Error_Caption[PLanguageIndex],ZeInputKodSetups_ErrorText[PLanguageIndex],mtWarning,[mbOK]);
MonthesList1.SetFocus;
end
else
begin
PParameter.KodSetup1:=PeriodToKodSetup(YearSpinEdit1.Value,MonthesList1.ItemIndex+1);
PParameter.KodSetup2:=PeriodToKodSetup(YearSpinEdit2.Value,MonthesList2.ItemIndex+1);
ModalResult:=mrYes;
end;
end;
procedure TZDatesAccFilter.ActionCancelExecute(Sender: TObject);
begin
ModalResult:=mrCancel;
end;
procedure TZDatesAccFilter.EdCodeDataFilterExit(Sender: TObject);
begin
case FilterType.ItemIndex of
0:
begin
GetMan;
end;
1:
begin
GetDepartment;
end;
2:
begin
end;
end;
end;
end.
|
unit ActorActionCommandBase;
interface
uses ControllerDataTypes, CommandBase, Actor, Classes;
type
TActorActionCommandBase = class (TCommandBase)
protected
FActor: TActor; // do not free it in the destroy!
FCommandName: string;
public
constructor Create(var _Actor: TActor; var _Params: TCommandParams); virtual;
end;
implementation
uses GlobalVars;
constructor TActorActionCommandBase.Create(var _Actor: TActor; var _Params: TCommandParams);
begin
FActor := _Actor;
GlobalVars.ModelUndoEngine.Add(FActor.Models[0]^,FCommandName);
end;
end.
|
unit htImage;
interface
uses
SysUtils, Types, Classes, Controls, Graphics,
LrGraphics,
htPicture, htControls, htMarkup;
type
ThtImage = class(ThtGraphicControl)
private
FAltText: string;
FHAlign: TLrHAlign;
FPicture: ThtPicture;
FAutoAspect: Boolean;
protected
function CalcSize: TPoint;
function GetAltText: string;
function GetHAlign: TLrHAlign;
procedure Generate(const inContainer: string;
inMarkup: ThtMarkup); override;
procedure PerformAutoSize; override;
procedure PictureChange(inSender: TObject);
procedure SetAltText(const Value: string);
procedure SetAutoAspect(const Value: Boolean);
procedure SetHAlign(const Value: TLrHAlign);
procedure SetPicture(const Value: ThtPicture);
procedure StylePaint; override;
public
constructor Create(inOwner: TComponent); override;
destructor Destroy; override;
published
property Align;
property AltText: string read GetAltText write SetAltText;
property AutoAspect: Boolean read FAutoAspect write SetAutoAspect;
property AutoSize;
property HAlign: TLrHAlign read GetHAlign write SetHAlign;
property Caption;
property Outline;
property Picture: ThtPicture read FPicture write SetPicture;
property Style;
end;
implementation
{ ThtImage }
constructor ThtImage.Create(inOwner: TComponent);
begin
inherited;
FPicture := ThtPicture.Create;
FPicture.OnChange := PictureChange;
ShowHint := true;
end;
destructor ThtImage.Destroy;
begin
FPicture.Free;
inherited;
end;
procedure ThtImage.PictureChange(inSender: TObject);
begin
AdjustSize;
Invalidate;
end;
function ThtImage.GetHAlign: TLrHAlign;
begin
Result := FHAlign;
end;
function ThtImage.GetAltText: string;
begin
if FAltText <> '' then
Result := FAltText
else
Result := Name;
end;
procedure ThtImage.SetAltText(const Value: string);
begin
FAltText := Value;
Hint := AltText;
end;
procedure ThtImage.SetAutoAspect(const Value: Boolean);
begin
FAutoAspect := Value;
Invalidate;
end;
procedure ThtImage.SetHAlign(const Value: TLrHAlign);
begin
FHAlign := Value;
Invalidate;
end;
procedure ThtImage.SetPicture(const Value: ThtPicture);
begin
FPicture.Assign(Value);
Invalidate;
end;
function ThtImage.CalcSize: TPoint;
begin
with Result do
if not Picture.HasGraphic then
begin
X := 0;
Y := 0;
end
else begin
X := Picture.Picture.Width;
Y := Picture.Picture.Height;
if AutoAspect then
Result := LrCalcAspectSize(ClientWidth, ClientHeight, X, Y);
end;
end;
procedure ThtImage.PerformAutoSize;
begin
with CalcSize do
SetBounds(Left, Top, X, Y)
end;
procedure ThtImage.StylePaint;
begin
inherited;
if Picture.HasGraphic then
if AutoAspect then
LrAspectPaintPicture(Canvas, Picture.Picture, ClientRect, HAlign, vaTop)
else
LrPaintPicture(Canvas, Picture.Picture, ClientRect, HAlign, vaTop);
//Canvas.Draw(0, 0, Picture.Graphic);
end;
procedure ThtImage.Generate(const inContainer: string;
inMarkup: ThtMarkup);
var
s: string;
begin
s := CtrlStyle.InlineAttribute;
if (s <> '') then
inMarkup.Styles.Add(Format('#%s {%s }', [ inContainer, s ]));
if AutoAspect then
begin
with CalcSize do
if X = ClientWidth then
s := Format(' width: %dpx', [ X ])
else
s := Format(' height: %dpx', [ Y ]);
inMarkup.Styles.Add(Format('#%s {%s }', [ Name, s ]));
end;
inMarkup.Add(
Format('<img id="%s" src="file:///%s" alt="%s"/>',
[ Name, Picture.Filename, AltText ])
);
end;
end.
|
unit BuscaCEP;
interface
uses
System.Classes,
System.SysUtils,
System.NetConsts,
System.Net.URLClient,
System.Net.HttpClient,
System.Net.HttpClientComponent;
const
URL_VIA_CEP = 'https://viacep.com.br/ws/%s/json/unicode/';
URL_WEB_MANIA = 'https://webmaniabr.com/api/1/cep/%s/?app_key=%s&app_secret=%s';
URL_WSCEP = 'http://127.0.0.1/cep/index.php?secret_key=%s&CEP=%s';
type
TServidor = (ViaCEP, WebMania, WSCEP);
TViaCEPResult = class
private
FLogradouro : string;
FIBGE : string;
FBairro : string;
FUF : string;
FCEP : string;
FLocalidade : string;
FUnidade : string;
FComplemento: string;
FGIA : string;
public
property CEP : string read FCEP write FCEP;
property Logradouro : string read FLogradouro write FLogradouro;
property Complemento: string read FComplemento write FComplemento;
property Bairro : string read FBairro write FBairro;
property Localidade : string read FLocalidade write FLocalidade;
property UF : string read FUF write FUF;
property Unidade : string read FUnidade write FUnidade;
property IBGE : string read FIBGE write FIBGE;
property GIA : string read FGIA write FGIA;
end;
TWebManiaCEPResult = class
private
FEndereco : string;
FBairro : string;
FCidade : string;
FUF : string;
FCEP : string;
FIBGE : string;
public
property Endereco : string read FEndereco write FEndereco;
property Bairro : string read FBairro write FBairro;
property Cidade : string read FCidade write FCidade;
property UF : string read FUF write FUF;
property CEP : string read FCEP write FCEP;
property IBGE : string read FIBGE write FIBGE;
end;
TWSCEPResult = class
private
FLogradouro : string;
FIBGE : string;
FBairro : string;
FUF : string;
FCidade : string;
FComplemento: string;
FCEP : string;
public
property Logradouro : string read FLogradouro write FLogradouro;
property IBGE : string read FIBGE write FIBGE;
property Bairro : string read FBairro write FBairro;
property UF : string read FUF write FUF;
property Cidade : string read FCidade write FCidade;
property Complemento: string read FComplemento write FComplemento;
property CEP : string read FCEP write FCEP;
end;
TBuscaCEP = class(TComponent)
private
FLogradouro : string;
FIBGE : string;
FBairro : string;
FUF : string;
FCEP : string;
FLocalidade : string;
FUnidade : string;
FComplemento : string;
FGIA : string;
FServidor : TServidor;
FWebManiaAppkey : string;
FWebManiaAppSecret: string;
FWSCEPSecretKey : string;
FURLWebMania: string;
FURLViaCEP : string;
FURLWSCEP : string;
FViaCEP : TViaCEPResult;
FWebMania : TWebManiaCEPResult;
FWSCEP : TWSCEPResult;
procedure LimparDadosCEP;
procedure LiberarObjetosPesquisa;
function CEPLocalizado(const AResultado: string): Boolean;
public
constructor Create(AOwner: TComponent); override;
property CEP : string read FCEP write FCEP;
property Logradouro : string read FLogradouro write FLogradouro;
property Complemento: string read FComplemento write FComplemento;
property Bairro : string read FBairro write FBairro;
property Localidade : string read FLocalidade write FLocalidade;
property UF : string read FUF write FUF;
property Unidade : string read FUnidade write FUnidade;
property IBGE : string read FIBGE write FIBGE;
property GIA : string read FGIA write FGIA;
function Buscar(const ACEP: string): boolean;
published
property Servidor : TServidor read FServidor write FServidor;
property WebManiaAppkey : string read FWebManiaAppkey write FWebManiaAppkey;
property WebManiaAppSecret: string read FWebManiaAppSecret write FWebManiaAppSecret;
property WSCEPSecretKey : string read FWSCEPSecretKey write FWSCEPSecretKey;
property URLViaCEP : string read FURLViaCEP write FURLViaCEP;
property URLWebMania : string read FURLWebMania write FURLWebMania;
property URLWSCEP : string read FURLWSCEP write FURLWSCEP;
end;
procedure Register;
implementation
uses
REST.Json;
procedure Register;
begin
RegisterComponents('iNoveFast', [TBuscaCEP]);
end;
function TBuscaCEP.Buscar(const ACEP: string): boolean;
var
HttpClient: THttpClient;
Response : IHttpResponse;
begin
try
LimparDadosCEP;
LiberarObjetosPesquisa;
Self.CEP := ACEP;
try
HttpClient := THttpClient.Create;
HttpClient.ContentType := 'application/json';
HttpClient.Accept := 'text/javascript';
case Servidor of
ViaCEP : Response := HttpClient.Get(Format(URL_VIA_CEP, [ACEP]), nil, nil);
WebMania: Response := HttpClient.Get(Format(URL_WEB_MANIA, [ACEP, Self.WebManiaAppkey, Self.WebManiaAppSecret]), nil, nil);
WSCEP : Response := HttpClient.Get(Format(URL_WSCEP, [Self.FWSCEPSecretKey, ACEP]), nil, nil);
end;
Result := CEPLocalizado(Response.ContentAsString);
except
on E:Exception do
raise Exception.Create(E.Message);
end;
finally
if Assigned(HttpClient) then
FreeAndNil(HttpClient);
end;
end;
procedure TBuscaCEP.LiberarObjetosPesquisa;
begin
if Assigned(FViaCEP) then
FreeAndNil(FViaCEP);
if Assigned(FWebMania) then
FreeAndNil(FWebMania);
if Assigned(FWSCEP) then
FreeAndNil(FWSCEP);
end;
procedure TBuscaCEP.LimparDadosCEP;
begin
Self.CEP := '';
Self.Logradouro := '';
Self.IBGE := '';
Self.Bairro := '';
Self.Localidade := '';
Self.UF := '';
Self.Unidade := '';
Self.Complemento:= '';
Self.GIA := '';
end;
function TBuscaCEP.CEPLocalizado(const AResultado: string): Boolean;
begin
if AResultado.Contains('"erro"') then
begin
Self.Logradouro := 'NÃO LOCALIZADO';
Exit(False);
end;
try
try
case Servidor of
ViaCEP:
begin
FViaCEP := TJson.JsonToObject<TViaCEPResult>(AResultado);
Self.CEP := FViaCEP.CEP;
Self.Logradouro := FViaCEP.Logradouro;
Self.IBGE := FViaCEP.IBGE;
Self.Bairro := FViaCEP.Bairro;
Self.Localidade := FViaCEP.Localidade;
Self.UF := FViaCEP.UF;
Self.Unidade := FViaCEP.Unidade;
Self.Complemento:= FViaCEP.Complemento;
Self.GIA := FViaCEP.GIA;
end;
WebMania:
begin
FWebMania := TJson.JsonToObject<TWebManiaCEPResult>(AResultado);
Self.CEP := FWebMania.CEP;
Self.Logradouro := FWebMania.Endereco;
Self.IBGE := FWebMania.IBGE;
Self.Bairro := FWebMania.Bairro;
Self.Localidade := FWebMania.Cidade;
Self.UF := FWebMania.UF;
end;
WSCEP:
begin
FWSCEP := TJson.JsonToObject<TWSCEPResult>(Copy(AResultado, 2, Length(AResultado)-2));
Self.CEP := FWSCEP.CEP;
Self.Logradouro := FWSCEP.Logradouro;
Self.IBGE := FWSCEP.IBGE;
Self.Bairro := FWSCEP.Bairro;
Self.Localidade := FWSCEP.Cidade;
Self.UF := FWSCEP.UF;
end;
end;
Result := True;
except
Result := False;
end;
finally
LiberarObjetosPesquisa;
end;
end;
constructor TBuscaCEP.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Self.URLViaCEP := URL_VIA_CEP;
Self.URLWebMania := URL_WEB_MANIA;
Self.URLWSCEP := URL_WSCEP;
end;
end.
|
unit Allgemein.SysFolderlocation;
interface
uses
Windows,
SysUtils,
shlobj,
ActiveX;
type
TSysFolderLocation = class(TObject)
private
_CSIDL: Integer;
function PathFromIDList(Pidl: PItemIdList): WideString;
public
property CSIDL: Integer read _CSIDL write _CSIDL;
constructor Create(CSIDL: Integer);
function GetShellFolder: WideString;
class function GetFolder(aCSIDL: Integer): string;
end;
implementation
{ SysFolderLocation }
function SHGetFolderLocation(hwndOwnder: THandle; nFolder: Integer; hToken: THandle; dwReserved: DWORD; ppidl:
PItemIdList): HRESULT; stdcall; external 'shell32.dll' name 'SHGetFolderLocation';
function SHGetPathFromIDListW(Pidl: PItemIDList; pszPath: PWideChar): BOOL; stdcall; external 'shell32.dll' name 'SHGetPathFromIDListW';
resourcestring
rsE_GetPathFromIDList = 'Ordner kann nicht ermittelt werden';
rsE_S_FALSE = 'Ordner existiert nicht';
rsE_InvalidArgument = 'Argument ungültig';
constructor TSysFolderLocation.Create(CSIDL: Integer);
begin
_CSIDL := CSIDL;
end;
class function TSysFolderLocation.GetFolder(aCSIDL: Integer): string;
var
Folder : TSysFolderLocation;
begin
Folder := TSysFolderLocation.Create(aCSIDL);
try
try
Result := Folder.GetShellFolder;
except
Result := 'Invalid';
raise;
end;
finally
FreeAndNil(Folder);
end;
end;
function TSysFolderLocation.GetShellFolder: WideString;
var
ppidl: PItemIdList;
begin
try
case SHGetFolderLocation(0, _CSIDL, 0, 0, @ppidl) of
S_OK: Result := trim(PathFromIDList(ppidl));
S_FALSE: raise Exception.Create(rsE_S_FALSE);
E_INVALIDARG: raise Exception.Create(rsE_InvalidArgument);
end;
finally
CoTaskMemFree(ppidl);
end;
end;
function TSysFolderLocation.PathFromIDList(Pidl: PItemIdList): WideString;
const
NTFS_MAX_PATH = 32767;
var
Path: PWideChar;
begin
GetMem(Path, (NTFS_MAX_PATH + 1) * 2);
try
if not SHGetPathFromIDListW(Pidl, Path) then
begin
FreeMem(Path);
raise Exception.Create(rsE_GetPathFromIDList);
end;
Result := WideString(Path);
finally
FreeMem(Path);
end;
end;
end.
|
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
BrookAction , sysutils , Classes, fpmimetypes;
type
TMyAction = class(TBrookAction)
public
procedure Get; override;
end;
implementation
procedure TMyAction.Get;
const f = 'D:\Projeto Lazarus\AulaBrook\CursoBrookEAD30\Aula2\Exercicio\Exer2renderImage\images.jpg';
begin
TheResponse.ContentStream := TFileStream.Create( f, fmOpenRead or fmShareDenyWrite);
try
{ TheResponse.ContentType := BrookMimeTypeFromFileName(f);// assim da bug com foto jpeg}
TheResponse.ContentType :=MimeTypes.GetMimeType(f);// funciona normalmente
TheResponse.SetCustomHeader('Content-Disposition', 'inline; filename="' + ExtractFileName(f) + '"');
TheResponse.SendContent;
finally
TheResponse.ContentStream.Free;
TheResponse.ContentStream := nil;
end;
end;
initialization
TMyAction.Register('*');
// Caso não possua o arquivo de MIMEs, baixe aqui:
// https://raw.githubusercontent.com/leledumbo/QTemplate/master/examples/brook/mime.types
//utilizado somente com metodo mimetypes
MimeTypes.LoadFromFile({$IFDEF UNIX}'/etc/mime.types'{$ELSE}'D:\Projeto Lazarus\AulaBrook\CursoBrookEAD30\Aula2\Exercicio\Exer2renderImage\Met2\mime.types'{$ENDIF});
end.
|
unit uSendScreen;
interface
// IdGlobal => 用到 TIdBytes, RawToBytes
//
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdContext,
IdCustomTCPServer, IdTCPServer, IdGlobal, IdException, Vcl.ExtCtrls,
UnitGlobal, uThread, jpeg;
type
TFormSendScreen = class(TForm)
IdTCPClient1: TIdTCPClient;
Memo1: TMemo;
tmrAutoConnect: TTimer;
BtnStart: TButton;
BtnStop: TButton;
edtHost: TLabeledEdit;
edtPort: TLabeledEdit;
BtnClearMemo: TButton;
btnDiscon: TButton;
tmrShot: TTimer;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure tmrAutoConnectTimer(Sender: TObject);
procedure IdTCPClient1Connected(Sender: TObject);
procedure BtnStopClick(Sender: TObject);
procedure BtnStartClick(Sender: TObject);
procedure IdTCPClient1AfterBind(Sender: TObject);
procedure IdTCPClient1BeforeBind(Sender: TObject);
procedure IdTCPClient1Disconnected(Sender: TObject);
procedure IdTCPClient1SocketAllocated(Sender: TObject);
procedure IdTCPClient1Status(ASender: TObject; const AStatus: TIdStatus;
const AStatusText: string);
procedure IdTCPClient1Work(ASender: TObject; AWorkMode: TWorkMode;
AWorkCount: Int64);
procedure IdTCPClient1WorkBegin(ASender: TObject; AWorkMode: TWorkMode;
AWorkCountMax: Int64);
procedure IdTCPClient1WorkEnd(ASender: TObject; AWorkMode: TWorkMode);
procedure BtnClearMemoClick(Sender: TObject);
procedure btnDisconClick(Sender: TObject);
procedure tmrShotTimer(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
thread: TReadThread;
procedure InitConnectGUI(init: Boolean);
procedure MyScreenShot(x: integer; y: integer; Width: integer;
Height: integer; bm: TBitmap);
public
{ Public declarations }
procedure ParseCmd(cmd: String);
end;
var
FormSendScreen: TFormSendScreen;
procedure BMPtoJPGStream(const Bitmap: TBitmap; var AStream: TMemoryStream);
implementation
{$R *.dfm}
procedure TFormSendScreen.FormCreate(Sender: TObject);
var
x: integer;
begin
edtHost.text := IdTCPClient1.Host;
edtPort.text := IntToStr(IdTCPClient1.Port);
InitConnectGUI(True);
end;
procedure TFormSendScreen.FormShow(Sender: TObject);
begin
BtnStartClick(Sender);
end;
procedure TFormSendScreen.IdTCPClient1AfterBind(Sender: TObject);
begin
Memo1.Lines.Add('C-AfterBind');
end;
procedure TFormSendScreen.IdTCPClient1BeforeBind(Sender: TObject);
begin
Memo1.Lines.Add('C-BeforeBind');
end;
procedure TFormSendScreen.IdTCPClient1Connected(Sender: TObject);
begin
Memo1.Lines.Add(DateTimeToStr(Now));
Memo1.Lines.Add('C-Connected');
BtnStop.Enabled := False;
// 用 thread 的方法
thread := TReadThread.Create;
thread.IdTCPClient := IdTCPClient1;
thread.FreeOnTerminate := true;
// 用 timer 的方法
// tmReadLn.Enabled := True;
end;
procedure TFormSendScreen.IdTCPClient1Disconnected(Sender: TObject);
begin
thread.Terminate;
Memo1.Lines.Add(DateTimeToStr(Now));
Memo1.Lines.Add('C-Disconnected');
end;
procedure TFormSendScreen.IdTCPClient1SocketAllocated(Sender: TObject);
begin
Memo1.Lines.Add('C-SocketAllocated');
end;
procedure TFormSendScreen.IdTCPClient1Status(ASender: TObject;
const AStatus: TIdStatus; const AStatusText: string);
begin
Memo1.Lines.Add(DateTimeToStr(Now));
Memo1.Lines.Add('C-Status: ' + AStatusText);
end;
procedure TFormSendScreen.IdTCPClient1Work(ASender: TObject;
AWorkMode: TWorkMode; AWorkCount: Int64);
begin
// Memo1.Lines.Add('C-Client1Work');
end;
procedure TFormSendScreen.IdTCPClient1WorkBegin(ASender: TObject;
AWorkMode: TWorkMode; AWorkCountMax: Int64);
begin
// Memo1.Lines.Add('C-WorkBegin');
end;
procedure TFormSendScreen.IdTCPClient1WorkEnd(ASender: TObject;
AWorkMode: TWorkMode);
begin
// Memo1.Lines.Add('C-WorkEnd');
end;
procedure TFormSendScreen.tmrAutoConnectTimer(Sender: TObject);
begin
if not IdTCPClient1.Connected then
begin
Memo1.Lines.Add('Timer1每5秒自動連線中…');
try
IdTCPClient1.Connect;
except
on E: EIdException do
Memo1.Lines.Add('== EIdException: ' + E.Message);
end;
end
else
begin
tmrAutoConnect.Enabled := False;
Memo1.Lines.Add('自動連線已連上,關閉tmrAutoConnect');
end;
end;
procedure TFormSendScreen.tmrShotTimer(Sender: TObject);
var
JpegStream: TMemoryStream;
pic: TBitmap;
begin
if not IdTCPClient1.Connected then
Exit;
// Memo1.Lines.Insert(0, 'Sending screen shot: ' + DateTimeToStr(Now));
pic := TBitmap.Create;
JpegStream := TMemoryStream.Create;
MyScreenShot(0, 0, screen.Width, screen.Height, pic);
BMPtoJPGStream(pic, JpegStream);
pic.FreeImage;
pic.DisposeOf;
// copy file stream to write stream
IdTCPClient1.IOHandler.Write(JpegStream.Size);
IdTCPClient1.IOHandler.WriteBufferOpen;
IdTCPClient1.IOHandler.Write(JpegStream);
IdTCPClient1.IOHandler.WriteBufferClose;
JpegStream.DisposeOf;
end;
procedure TFormSendScreen.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if IdTCPClient1.Connected then
begin
// Sleep(500);
try
IdTCPClient1.Disconnect;
except
on E: EIdException do
ShowMessage('EIdException: ' + E.Message);
end;
end;
end;
procedure TFormSendScreen.BtnClearMemoClick(Sender: TObject);
begin
Memo1.Clear;
end;
procedure TFormSendScreen.btnDisconClick(Sender: TObject);
begin
IdTCPClient1.Disconnect;
InitConnectGUI(False);
end;
procedure TFormSendScreen.BtnStartClick(Sender: TObject);
begin
IdTCPClient1.Host := edtHost.text;
IdTCPClient1.Port := StrToInt(edtPort.text);
Memo1.Lines.Add('tmrAutoConnect已啟動,稍待 ' + FloatToStr(tmrAutoConnect.Interval /
1000) + ' 秒');
InitConnectGUI(true);
end;
procedure TFormSendScreen.InitConnectGUI(init: Boolean);
begin
tmrAutoConnect.Enabled := init;
BtnStart.Enabled := not init;
BtnStop.Enabled := init;
btnDiscon.Enabled := init;
end;
procedure TFormSendScreen.BtnStopClick(Sender: TObject);
begin
InitConnectGUI(False);
end;
procedure TFormSendScreen.ParseCmd(cmd: String);
begin
Memo1.Lines.Add(cmd);
if cmd = 'TakeShot' then
begin
tmrShot.Enabled := true;
end;
end;
procedure TFormSendScreen.MyScreenShot(x: integer; y: integer; Width: integer;
Height: integer; bm: TBitmap);
var
dc: HDC;
lpPal: PLOGPALETTE;
begin
{ test width and height }
if ((Width = 0) OR (Height = 0)) then
Exit;
bm.Width := Width;
bm.Height := Height;
{ get the screen dc }
dc := GetDc(0);
if (dc = 0) then
Exit;
{ do we have a palette device? }
if (GetDeviceCaps(dc, RASTERCAPS) AND RC_PALETTE = RC_PALETTE) then
begin
{ allocate memory for a logical palette }
GetMem(lpPal, SizeOf(TLOGPALETTE) + (255 * SizeOf(TPALETTEENTRY)));
{ zero it out to be neat }
FillChar(lpPal^, SizeOf(TLOGPALETTE) + (255 * SizeOf(TPALETTEENTRY)), #0);
{ fill in the palette version }
lpPal^.palVersion := $300;
{ grab the system palette entries }
lpPal^.palNumEntries := GetSystemPaletteEntries(dc, 0, 256,
lpPal^.palPalEntry);
if (lpPal^.palNumEntries <> 0) then
begin
{ create the palette }
bm.Palette := CreatePalette(lpPal^);
end;
FreeMem(lpPal, SizeOf(TLOGPALETTE) + (255 * SizeOf(TPALETTEENTRY)));
end;
{ copy from the screen to the bitmap }
BitBlt(bm.Canvas.Handle, 0, 0, Width, Height, dc, x, y, SRCCOPY);
{ release the screen dc }
ReleaseDc(0, dc);
end; (* ScreenShot *)
// convert BMP to JPEG
procedure BMPtoJPGStream(const Bitmap: TBitmap; var AStream: TMemoryStream);
var
JpegImg: TJpegImage;
begin
JpegImg := TJpegImage.Create;
try
// JpegImg.CompressionQuality := 50;
JpegImg.PixelFormat := jf8Bit;
JpegImg.Assign(Bitmap);
JpegImg.SaveToStream(AStream);
finally
JpegImg.Free
end;
end; (* BMPtoJPG *)
end.
|
unit uFrmProgress;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.ExtCtrls,
Vcl.AppEvnts,
Vcl.Imaging.pngimage,
Dmitry.Graphics.Types,
uFormUtils,
uMemory,
uInstallUtils,
uDBForm,
uInstallScope;
type
TFrmProgress = class(TDBForm)
AeMain: TApplicationEvents;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure AeMainMessage(var Msg: tagMSG; var Handled: Boolean);
private
{ Private declarations }
FProgress: Byte;
FBackgroundImage : TBitmap;
FProgressMessage: Cardinal;
procedure RenderFormImage;
procedure LoadLanguage;
procedure SetProgress(const Value: Byte);
procedure WMMouseDown(var s : Tmessage); message WM_LBUTTONDOWN;
protected
procedure CreateParams(var Params: TCreateParams); override;
function GetFormID: string; override;
public
{ Public declarations }
property Progress : Byte read FProgress write SetProgress;
end;
implementation
{$R *.dfm}
procedure TFrmProgress.AeMainMessage(var Msg: tagMSG; var Handled: Boolean);
begin
if Msg.message = FProgressMessage then
RenderFormImage;
end;
procedure TFrmProgress.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
Params.WndParent := GetDesktopWindow;
with params do
ExStyle := ExStyle or WS_EX_APPWINDOW;
end;
procedure TFrmProgress.FormCreate(Sender: TObject);
var
MS: TMemoryStream;
Png: TPngImage;
begin
SetWindowLong(Handle, GWL_EXSTYLE, GetWindowLong(Handle, GWL_EXSTYLE) or WS_EX_LAYERED);
LoadLanguage;
FProgress := 0;
FBackgroundImage := TBitmap.Create;
FBackgroundImage.PixelFormat := pf32bit;
MS := TMemoryStream.Create;
try
GetRCDATAResourceStream('PROGRESS', MS);
Png := TPngImage.Create;
try
MS.Seek(0, soFromBeginning);
Png.LoadFromStream(MS);
FBackgroundImage.Assign(Png);
finally
F(Png);
end;
finally
F(MS);
end;
RenderFormImage;
FProgressMessage := RegisterWindowMessage('UPDATE_PROGRESS');
end;
procedure TFrmProgress.RenderFormImage;
var
FCurrentImage: TBitmap;
I, J, L, C: Integer;
P: PARGB32;
begin
FCurrentImage := TBitmap.Create;
try
FBackgroundImage.PixelFormat := pf32bit;
FCurrentImage.Assign(FBackgroundImage);
L := FCurrentImage.Width * Progress div 255;
if not CurrentInstall.IsUninstall then
begin
for I := 0 to FCurrentImage.Height - 1 do
begin
P := FCurrentImage.ScanLine[I];
for J := L to FCurrentImage.Width - 1 do
begin
C := (P[J].R * 77 + P[J].G * 151 + P[J].B * 28) shr 8;
P[J].R := C;
P[J].G := C;
P[J].B := C;
end;
end;
end else
begin
for I := 0 to FCurrentImage.Height - 1 do
begin
P := FCurrentImage.ScanLine[I];
for J := 0 to L - 1 do
begin
C := (P[J].R * 77 + P[J].G * 151 + P[J].B * 28) shr 8;
P[J].R := C;
P[J].G := C;
P[J].B := C;
end;
end;
end;
RenderForm(Handle, FCurrentImage, 255, False);
finally
F(FCurrentImage);
end;
end;
procedure TFrmProgress.FormDestroy(Sender: TObject);
begin
F(FBackgroundImage);
end;
function TFrmProgress.GetFormID: string;
begin
Result := 'Setup';
end;
procedure TFrmProgress.LoadLanguage;
begin
BeginTranslate;
try
Caption := L('Photo Database 4.6 Setup');
finally
EndTranslate;
end;
end;
procedure TFrmProgress.SetProgress(const Value: Byte);
var
OldProgress: Byte;
begin
OldProgress := FProgress;
FProgress := Value;
if OldProgress <> FProgress then
PostMessage(Handle, FProgressMessage, 0, 0);
end;
procedure TFrmProgress.WMMouseDown(var s: Tmessage);
begin
Perform(WM_NCLBUTTONDOWN, HTCaption, s.lparam);
end;
end.
|
unit Pospolite.View.CSS.Binder;
{
+-------------------------+
| Package: Pospolite View |
| Author: Matek0611 |
| Email: matiowo@wp.pl |
| Version: 1.0p |
+-------------------------+
Comments:
- https://www.tutorialrepublic.com/css-reference/css3-properties.php
- time is in ms
}
{$mode objfpc}{$H+}
{$modeswitch advancedrecords}
interface
uses
Classes, SysUtils, Controls, Pospolite.View.Basics, Pospolite.View.Drawing.Basics,
Pospolite.View.Drawing.Drawer;
type
TPLCSSSimpleUnitValue = specialize TPLParameter<TPLFloat, TPLString>;
operator := (const AValue: TPLFloat) r: TPLCSSSimpleUnitValue;
type
{ TPLCSSSimpleUnit }
TPLCSSSimpleUnit = packed record
public
Value: TPLCSSSimpleUnitValue;
Calculated: TPLFloat;
public
constructor Create(AValue: TPLCSSSimpleUnitValue; ACalculated: TPLFloat = 0);
class operator =(a, b: TPLCSSSimpleUnit) r: TPLBool;
class operator :=(a: TPLCSSSimpleUnit) r: Variant;
function IsAuto: TPLBool; inline;
class function Auto: TPLCSSSimpleUnit; static;
end;
TPLCSSSimpleUnitPoint = array[0..1] of TPLCSSSimpleUnit;
TPLCSSSimpleUnitFuncs = specialize TPLFuncs<TPLCSSSimpleUnit>;
{ TPLCSSSimpleUnitRect }
TPLCSSSimpleUnitRect = record
public
Left, Right, Top, Bottom: TPLCSSSimpleUnit;
public
constructor Create(const ALeft, ARight, ATop, ABottom: TPLCSSSimpleUnit);
constructor Create(const AWhole: TPLCSSSimpleUnit);
end;
{ TPLCSSBindingProperties }
TPLCSSBindingProperties = packed record
public type
TAlignContentType = (actCenter, actFlexStart, actFlexEnd, actSpaceBetween,
actSpaceAround, actStretch);
TAlignItemsType = (aitBaseline, aitCenter, aitFlexStart, aitFlexEnd, aitStretch);
TAlignSelfType = (astAuto, astBaseline, astCenter, astFlexStart, astFlexEnd,
astStretch);
TAnimationDirectionType = (adtNormal, adtReverse, adtAlternate, adtAlternateReverse);
TAnimationFillModeType = (afmtNone, afmtForwards, afmtBackwards, afmtBoth);
TAnimationPlayStateType = (pstPaused, pstRunning);
TTimingFunctionType = record
public
Name: TPLString;
Args: array[0..3] of TPLFloat;
end;
TBackgroundAttachmentType = (batScroll, batFixed);
TBoxModelType = (bmtBorderBox, bmtPaddingBox, bmtContentBox);
TBackgroundRepeatType = (brtRepeat, brtRepeatX, brtRepeatY, brtNoRepeat);
TClearType = (ctLeft, ctRight, ctAuto, ctBoth, ctNone);
TCaptionSideType = (cstTop, cstBottom);
TColumnFillType = (cftAuto, cftBalance);
TFlexDirectionType = (fdtRow, fdtRowReverse, fdtColumn, fdtColumnReverse);
TFlexWrapType = (fwtNowrap, fwtWrap, fwtWrapReverse);
TFloatType = (ftLeft, ftRight, ftNone);
TJustifyContentType = (jctFlexStart, jctFlexEnd, jctCenter, jctSpaceBetween,
jctSpaceAround);
TListStylePositionType = (lsptInside, lsptOutside);
TListStyleType = (lstDisc, lstCircle, lstSquare, lstDecimal, lstDecimalLeadingZero,
lstLowerRoman, lstUpperRoman, lstLowerGreek, lstLowerLatin, lstUpperLatin,
lstArmenian, lstGeorgian, lstLowerAlpha, lstUpperAlpha, lstNone);
TPageBreakType = (pbtAuto, pbtAlways, pbtAvoid, pbtLeft, pbtRight);
TTextDecorationStyleType = (tdstSolid, tdstDouble, tdstDotted, tdstDashed, tdstWavy);
TTextTransformType = (tttCapitalize, tttLowercase, tttNone, tttUppercase);
TTransformFunctionType = record
Name: TPLString;
Args: array of TPLFloat;
end;
TSimpleSizeType = record
Width, Height: TPLCSSSimpleUnit;
end;
public
Align: record
Content: TAlignContentType;
Items: TAlignItemsType;
Self: TAlignSelfType;
end;
Animation: record
Delay: TPLInt;
Direction: TAnimationDirectionType;
Duration: TPLInt;
FillMode: TAnimationFillModeType;
IterationCount: TPLFloat; // infinity = TPLFloat.PositiveInfinity
Name: TPLString;
PlayState: TAnimationPlayStateType;
TimingFunction: TTimingFunctionType;
end;
AspectRatio: TPLFloat;
BackfaceVisibility: TPLBool;
Background: record
Attachment: TBackgroundAttachmentType;
Clip: TBoxModelType;
Color: TPLColor;
Image: IPLDrawingBitmap;
Origin: TBoxModelType;
Position: TPLCSSSimpleUnitPoint;
&Repeat: TBackgroundRepeatType;
Size: TPLCSSSimpleUnitPoint;
end;
Border: record
Calculated: TPLDrawingBorders;
Units: array[0..1] of array[0..3] of TPLCSSSimpleUnit; // 0 - width, 1 - radius
Spacing: TPLCSSSimpleUnit;
end;
Bottom: TPLCSSSimpleUnit;
BoxShadow: Variant;
BoxSizing: TBoxModelType;
CaptionSide: TCaptionSideType;
Clear: TClearType;
Color: TPLColor;
Column: record
Count: TPLInt; // auto = -1
Fill: TColumnFillType;
Gap: TPLCSSSimpleUnit; // normal = 1em
Rule: record
Color: TPLColor;
Style: TPLDrawingBorderStyle;
Width: TPLCSSSimpleUnit;
end;
Span: TPLBool;
Width: TPLCSSSimpleUnit;
end;
Content: TPLString;
Counter: record
Increment: array of Variant;
Reset: Variant;
end;
Cursor: TCursor;
Direction: TPLReadingDirection;
EmptyCells: TPLBool;
Flex: record
Basis: TPLCSSSimpleUnit;
Direction: TFlexDirectionType;
Grow: TPLInt;
Shrink: TPLInt;
Wrap: TFlexWrapType;
end;
Float: TFloatType;
Font: record
Family: array of TPLString;
Size: TPLCSSSimpleUnit;
Adjust: TPLCSSSimpleUnit; // Firefox supports it only, so no need for supporting it here
Stretch: TPLDrawingFontStretch;
Style: TPLDrawingFontStyle;
VariantTags: TPLDrawingFontVariantTags; // = font-variant
Weight: TPLDrawingFontWeight;
end;
Height: TPLCSSSimpleUnit;
JustifyContent: TJustifyContentType;
Left: TPLCSSSimpleUnit;
LetterSpacing: TPLCSSSimpleUnit; // auto = normal
LineHeight: TPLCSSSimpleUnit;
ListStyle: record
Image: IPLDrawingBitmap;
Position: TListStylePositionType;
Kind: TListStyleType; // = list-style-type
end;
Margin: TPLCSSSimpleUnitRect;
Max: TSimpleSizeType; // max-width/height none = auto
Min: TSimpleSizeType; // min-width/height -//-
Opacity: TPLFloat;
Order: TPLInt;
Outline: record
Color: TPLString; // TPLColor or 'invert'
Offset: TPLCSSSimpleUnit;
Style: TPLDrawingBorderStyle;
Width: TPLCSSSimpleUnit;
end;
Overflow: array[0..1] of TPLString; // x, y
Padding: TPLCSSSimpleUnitRect;
PageBreak: record
After: TPageBreakType;
Before: TPageBreakType;
Inside: TPageBreakType; // 'auto' and 'avoid' only
end;
Perspective: record
Main: TPLCSSSimpleUnit;
Origin: array[0..1] of Variant;
end;
Quotes: array of array[0..1] of TPLString;
Resize: TPLString;
Right: TPLCSSSimpleUnit;
TabSize: TPLCSSSimpleUnit;
TableLayout: TPLUInt;
Text: record
Align: TPLTextDirection; // left = tdLeft, right = tdRight, center = tdCenter, justify = tdFill
AlignLast: TPLTextDirection;
Decoration: record
Color: TPLColor;
Line: TPLDrawingFontDecorations;
Style: TTextDecorationStyleType;
end;
Indent: TPLCSSSimpleUnit;
Overflow: Variant;
Shadow: Variant;
Transform: TTextTransformType;
end;
Top: TPLCSSSimpleUnit;
Transform: record
Main: TTransformFunctionType;
Origin: array[0..2] of TPLCSSSimpleUnit;
Style: TPLUInt;
end;
Transition: record
Delay: TPLInt;
Duration: TPLInt;
&Property: array of TPLString; // if empty = all
TimingFunction: TTimingFunctionType;
end;
UnicodeBidi: TPLUInt; // no support
VerticalAlign: Variant;
WhiteSpace: TPLUInt; // no support
Width: TPLCSSSimpleUnit;
Word: record
&Break: TPLUInt; // no support
Spacing: TPLCSSSimpleUnit; // auto = normal
Wrap: TPLBool;
end;
WritingMode: TPLWritingMode;
public
class function GetDefault: TPLCSSBindingProperties; static;
function GetProperty(const AName: TPLString): Pointer;
procedure SetProperty(const AName: TPLString; const AValue: Pointer);
end;
//generic TPLCSSBindingPropertiesManager
{ TPLCSSStyleBind }
TPLCSSStyleBind = packed record
public
Properties: array[TPLCSSElementState] of TPLCSSBindingProperties;
public
procedure RestoreDefault;
end;
TPLCSSStyleBinder = class;
{ TPLCSSStyleBinderThread }
TPLCSSStyleBinderThread = class(TThread)
private
FEnabled: TPLBool;
FBinder: TPLCSSStyleBinder;
procedure SetEnabled(AValue: TPLBool);
public
constructor Create(ABinder: TPLCSSStyleBinder);
procedure Execute; override;
property Enabled: TPLBool read FEnabled write SetEnabled;
end;
{ TPLCSSStyleBinder }
TPLCSSStyleBinder = class sealed
private
FThread: TPLCSSStyleBinderThread;
FDocument: Pointer;
procedure InternalUpdate;
procedure SetDocument(AValue: Pointer);
public
constructor Create(ADocument: Pointer);
destructor Destroy; override;
procedure UpdateBindings;
procedure Annihilate;
property Document: Pointer read FDocument write SetDocument;
end;
operator :=(s: TPLString) r: TPLCSSBindingProperties.TAlignContentType;
implementation
uses Pospolite.View.HTML.Document, Pospolite.View.HTML.Basics;
operator :=(const AValue: TPLFloat) r: TPLCSSSimpleUnitValue;
begin
r := TPLCSSSimpleUnitValue.Create(AValue, '');
end;
operator :=(s: TPLString) r: TPLCSSBindingProperties.TAlignContentType;
begin
case s.ToLower.Trim of
'center': r := actCenter;
'flex-start': r := actFlexStart;
'flex-end': r := actFlexEnd;
'space-between': r := actSpaceBetween;
'space-around': r := actSpaceAround;
'stretch': r := actStretch;
else r := actStretch;
end;
end;
{ TPLCSSSimpleUnit }
constructor TPLCSSSimpleUnit.Create(AValue: TPLCSSSimpleUnitValue;
ACalculated: TPLFloat);
begin
Value := AValue;
Calculated := ACalculated;
end;
class operator TPLCSSSimpleUnit.=(a, b: TPLCSSSimpleUnit) r: TPLBool;
begin
r := a.Calculated = b.Calculated;
end;
class operator TPLCSSSimpleUnit.:=(a: TPLCSSSimpleUnit) r: Variant;
begin
r := TPLString(a.Value.Key) + a.Value.Value;
end;
function TPLCSSSimpleUnit.IsAuto: TPLBool;
begin
Result := Value.Value = 'auto';
end;
class function TPLCSSSimpleUnit.Auto: TPLCSSSimpleUnit;
begin
Result := TPLCSSSimpleUnit.Create(TPLCSSSimpleUnitValue.Create(0, 'auto'));
end;
{ TPLCSSSimpleUnitRect }
constructor TPLCSSSimpleUnitRect.Create(const ALeft, ARight, ATop,
ABottom: TPLCSSSimpleUnit);
begin
Left := ALeft;
Right := ARight;
Top := ATop;
Bottom := ABottom;
end;
constructor TPLCSSSimpleUnitRect.Create(const AWhole: TPLCSSSimpleUnit);
begin
Create(AWhole, AWhole, AWhole, AWhole);
end;
{ TPLCSSBindingProperties }
class function TPLCSSBindingProperties.GetDefault: TPLCSSBindingProperties;
begin
Result := Default(TPLCSSBindingProperties);
with Result do begin
with Align do begin
Content := actStretch;
Items := aitStretch;
Self := astAuto;
end;
with Animation do begin
Delay := 0;
Direction := adtNormal;
Duration := 0;
FillMode := afmtNone;
IterationCount := 1;
Name := '';
PlayState := pstRunning;
TimingFunction.Name := 'ease';
TPLFloatFuncs.FillArray(TimingFunction.Args, 0);
end;
AspectRatio := 1;
BackfaceVisibility := true;
with Background do begin
Attachment := batScroll;
Clip := bmtBorderBox;
Color := TPLColor.Transparent;
Image := nil;
Origin := bmtPaddingBox;
TPLCSSSimpleUnitFuncs.FillArray(Position, TPLCSSSimpleUnit.Create(TPLCSSSimpleUnitValue.Create(0, '%')));
&Repeat := brtRepeat;
TPLCSSSimpleUnitFuncs.FillArray(Size, TPLCSSSimpleUnit.Auto);
end;
with Border do begin
Calculated := PLDrawingBordersDef;
TPLCSSSimpleUnitFuncs.FillArray(Units[0], TPLCSSSimpleUnit.Create(TPLCSSSimpleUnitValue.Create(0, 'px')));
TPLCSSSimpleUnitFuncs.FillArray(Units[1], TPLCSSSimpleUnit.Create(TPLCSSSimpleUnitValue.Create(0, 'px')));
Spacing := TPLCSSSimpleUnit.Create(TPLCSSSimpleUnitValue.Create(0, 'px'));
end;
Bottom := TPLCSSSimpleUnit.Auto;
BoxShadow := Null;
BoxSizing := bmtContentBox;
CaptionSide := cstTop;
Clear := ctNone;
Color := TPLColor.Black;
with Column do begin
Count := -1;
Fill := cftBalance;
Gap := TPLCSSSimpleUnit.Create(TPLCSSSimpleUnitValue.Create(1, 'em'));
with Rule do begin
Color := TPLColor.Black;
Style := dbsNone;
Width := TPLCSSSimpleUnit.Create(TPLCSSSimpleUnitValue.Create(3, 'px')); // medium
end;
Span := false;
Width := TPLCSSSimpleUnit.Auto;
end;
Content := 'normal';
with Counter do begin
SetLength(Increment, 0);
Reset := 'none';
end;
Cursor := crDefault;
Direction := rdLTR;
EmptyCells := true;
with Flex do begin
Basis := TPLCSSSimpleUnit.Auto;
Direction := fdtRow;
Grow := 0;
Shrink := 1;
Wrap := fwtNowrap;
end;
Float := ftNone;
with Font do begin
SetLength(Family, 1);
Family[0] := 'sans-serif';
Size := TPLCSSSimpleUnit.Create(TPLCSSSimpleUnitValue.Create(16, 'px'));
Adjust := TPLCSSSimpleUnit.Auto;
Stretch := dfstNormal;
Style := dfsNormal;
VariantTags := [];
Weight := dfwNormal;
end;
Height := TPLCSSSimpleUnit.Auto;
JustifyContent := jctFlexStart;
Left := TPLCSSSimpleUnit.Auto;
LetterSpacing := TPLCSSSimpleUnit.Auto;
LineHeight := TPLCSSSimpleUnit.Auto;
with ListStyle do begin
Image := nil;
Position := lsptOutside;
Kind := lstDisc;
end;
Margin := TPLCSSSimpleUnitRect.Create(TPLCSSSimpleUnit.Create(0));
with Max do begin
Width := TPLCSSSimpleUnit.Auto;
Height := TPLCSSSimpleUnit.Auto;
end;
with Min do begin
Width := TPLCSSSimpleUnit.Auto;
Height := TPLCSSSimpleUnit.Auto;
end;
Opacity := 1;
Order := 0;
with Outline do begin
Color := 'invert';
Offset := TPLCSSSimpleUnit.Create(0);
Style := dbsNone;
Width := TPLCSSSimpleUnit.Create(TPLCSSSimpleUnitValue.Create(3, 'px'));
end;
TPLStringFuncs.FillArray(Overflow, 'auto');
Padding := TPLCSSSimpleUnitRect.Create(TPLCSSSimpleUnit.Create(0));
with PageBreak do begin
After := pbtAuto;
Before := pbtAuto;
Inside := pbtAuto;
end;
with Perspective do begin
Main := TPLCSSSimpleUnit.Auto;
TPLVariantFuncs.FillArray(Origin, '0%');
end;
SetLength(Quotes, 0);
Resize := 'none';
Right := TPLCSSSimpleUnit.Auto;
TableLayout := 0;
TabSize := TPLCSSSimpleUnit.Create(8);
with Text do begin
Align := tdLeft;
AlignLast := tdLeft;
with Decoration do begin
Color := TPLColor.Black;
Line := [dfdUnderline];
Style := tdstSolid;
end;
Indent := TPLCSSSimpleUnit.Create(0);
Overflow := 'clip';
Shadow := Null;
Transform := tttNone;
end;
Top := TPLCSSSimpleUnit.Auto;
with Transform do begin
Main.Name := '';
SetLength(Main.Args, 0);
TPLCSSSimpleUnitFuncs.FillArray(Origin, TPLCSSSimpleUnit.Create(TPLCSSSimpleUnitValue.Create(0, '%')));
Style := 0;
end;
with Transition do begin
Delay := 0;
Duration := 0;
SetLength(&Property, 0);
TimingFunction.Name := 'ease';
TPLFloatFuncs.FillArray(TimingFunction.Args, 0);
end;
UnicodeBidi := 0;
VerticalAlign := 'baseline';
WhiteSpace := 0;
Width := TPLCSSSimpleUnit.Auto;
with Word do begin
&Break := 0;
Spacing := TPLCSSSimpleUnit.Auto;
Wrap := true;
end;
end;
end;
function TPLCSSBindingProperties.GetProperty(const AName: TPLString): Pointer;
begin
case AName.ToLower of
'align-content': Result := @Align.Content;
'align-items': Result := @Align.Items;
'align-self': Result := @Align.Self;
'margin': Result := @Margin;
'margin-left': Result := @Margin.Left;
'margin-right': Result := @Margin.Right;
'margin-top': Result := @Margin.Top;
'margin-bottom': Result := @Margin.Bottom;
'padding': Result := @Padding;
'padding-left': Result := @Padding.Left;
'padding-right': Result := @Padding.Right;
'padding-top': Result := @Padding.Top;
'padding-bottom': Result := @Padding.Bottom;
else Result := nil;
end;
end;
procedure TPLCSSBindingProperties.SetProperty(const AName: TPLString;
const AValue: Pointer);
begin
case AName.ToLower of
'align-content': Align.Content := TAlignContentType(AValue^);
'align-items': Align.Items := TAlignItemsType(AValue^);
'align-self': Align.Self := TAlignSelfType(AValue^);
'animation-delay': Animation.Delay := TPLInt(AValue^);
'animation-direction': Animation.Direction := TAnimationDirectionType(AValue^);
'animation-duration': Animation.Duration := TPLInt(AValue^);
'animation-fill-mode': Animation.FillMode := TAnimationFillModeType(AValue^);
'animation-interation-count': Animation.IterationCount := TPLFloat(AValue^);
'animation-name': Animation.Name := TPLString(AValue^);
'animation-play-state': Animation.PlayState := TAnimationPlayStateType(AValue^);
'animation-timing-function': Animation.TimingFunction := TTimingFunctionType(AValue^);
'aspect-ratio': AspectRatio := TPLFloat(AValue^);
'backface-visibility': BackfaceVisibility := TPLBool(AValue^);
'background-attachment': Background.Attachment := TBackgroundAttachmentType(AValue^);
'background-clip': Background.Clip := TBoxModelType(AValue^);
'background-color': Background.Color := TPLColor(AValue^);
'background-image': Background.Image := IPLDrawingBitmap(AValue^);
'background-origin': Background.Origin := TBoxModelType(AValue^);
'background-position': Background.Position := TPLCSSSimpleUnitPoint(AValue^);
'background-position-x': Background.Position[0] := TPLCSSSimpleUnit(AValue^);
'background-position-y': Background.Position[1] := TPLCSSSimpleUnit(AValue^);
'background-repeat': Background.&Repeat := TBackgroundRepeatType(AValue^);
'background-size': Background.Size := TPLCSSSimpleUnitPoint(AValue^);
'border': Border.Calculated := TPLDrawingBorders(AValue^);
'border-left': ;
end;
end;
{ TPLCSSStyleBind }
procedure TPLCSSStyleBind.RestoreDefault;
var
st: TPLCSSElementState;
begin
for st in TPLCSSElementState do
Properties[st] := TPLCSSBindingProperties.GetDefault;
end;
{ TPLCSSStyleBinderThread }
procedure TPLCSSStyleBinderThread.SetEnabled(AValue: TPLBool);
begin
if FEnabled = AValue then exit;
FEnabled := AValue;
if FEnabled then Start
else Suspended := true;
end;
constructor TPLCSSStyleBinderThread.Create(ABinder: TPLCSSStyleBinder);
begin
inherited Create(true);
FEnabled := false;
FBinder := ABinder;
end;
procedure TPLCSSStyleBinderThread.Execute;
begin
Synchronize(@FBinder.InternalUpdate);
FEnabled := false;
end;
{ TPLCSSStyleBinder }
procedure TPLCSSStyleBinder.InternalUpdate;
var
b: TPLHTMLBasicObject;
defs: TPLCSSStyleBind;
begin
if not Assigned(FDocument) then exit;
b := TPLHTMLDocument(FDocument).Body as TPLHTMLBasicObject;
if not Assigned(b) then exit;
defs.RestoreDefault;
b.RefreshStyles(defs);
end;
procedure TPLCSSStyleBinder.SetDocument(AValue: Pointer);
begin
if (FDocument = AValue) or (FThread.Enabled) then exit;
FDocument := AValue;
end;
constructor TPLCSSStyleBinder.Create(ADocument: Pointer);
begin
inherited Create;
FThread := TPLCSSStyleBinderThread.Create(self);
FDocument := ADocument;
end;
destructor TPLCSSStyleBinder.Destroy;
begin
FThread.Enabled := false;
FThread.Suspended := true;
FThread.Free;
inherited Destroy;
end;
procedure TPLCSSStyleBinder.UpdateBindings;
begin
FThread.Enabled := true;
end;
procedure TPLCSSStyleBinder.Annihilate;
begin
Free;
end;
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: VO relacionado à tabela [NFE_DETALHE]
The MIT License
Copyright: Copyright (C) 2014 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
*******************************************************************************}
unit NfeDetalheVO;
{$mode objfpc}{$H+}
interface
uses
VO, Classes, SysUtils, FGL,
NfeDetEspecificoVeiculoVO, NfeDetEspecificoCombustivelVO,
NfeDetalheImpostoIcmsVO, NfeDetalheImpostoIpiVO, NfeDetalheImpostoIiVO,
NfeDetalheImpostoPisVO, NfeDetalheImpostoCofinsVO, NfeDetalheImpostoIssqnVO,
NfeDeclaracaoImportacaoVO, NfeExportacaoVO, NfeDetEspecificoMedicamentoVO,
NfeDetEspecificoArmamentoVO;
type
TNfeDetalheVO = class(TVO)
private
FID: Integer;
FID_PRODUTO: Integer;
FID_NFE_CABECALHO: Integer;
FNUMERO_ITEM: Integer;
FCODIGO_PRODUTO: String;
FGTIN: String;
FNOME_PRODUTO: String;
FNCM: String;
FNVE: String;
FEX_TIPI: Integer;
FCFOP: Integer;
FUNIDADE_COMERCIAL: String;
FQUANTIDADE_COMERCIAL: Extended;
FVALOR_UNITARIO_COMERCIAL: Extended;
FVALOR_BRUTO_PRODUTO: Extended;
FGTIN_UNIDADE_TRIBUTAVEL: String;
FUNIDADE_TRIBUTAVEL: String;
FQUANTIDADE_TRIBUTAVEL: Extended;
FVALOR_UNITARIO_TRIBUTAVEL: Extended;
FVALOR_FRETE: Extended;
FVALOR_SEGURO: Extended;
FVALOR_DESCONTO: Extended;
FVALOR_OUTRAS_DESPESAS: Extended;
FENTRA_TOTAL: Integer;
FVALOR_SUBTOTAL: Extended;
FVALOR_TOTAL: Extended;
FNUMERO_PEDIDO_COMPRA: String;
FITEM_PEDIDO_COMPRA: Integer;
FINFORMACOES_ADICIONAIS: String;
FNUMERO_FCI: String;
FNUMERO_RECOPI: String;
FVALOR_TOTAL_TRIBUTOS: Extended;
FPERCENTUAL_DEVOLVIDO: Extended;
FVALOR_IPI_DEVOLVIDO: Extended;
// Grupo JA
FNfeDetEspecificoVeiculoVO: TNfeDetEspecificoVeiculoVO; //0:1
// Grupo LA
FNfeDetEspecificoCombustivelVO: TNfeDetEspecificoCombustivelVO; //0:1
// Grupo N
FNfeDetalheImpostoIcmsVO: TNfeDetalheImpostoIcmsVO; //1:1
// Grupo O
FNfeDetalheImpostoIpiVO: TNfeDetalheImpostoIpiVO; //0:1
// Grupo P
FNfeDetalheImpostoIiVO: TNfeDetalheImpostoIiVO; //0:1
// Grupo Q
FNfeDetalheImpostoPisVO: TNfeDetalheImpostoPisVO; //0:1
// Grupo S
FNfeDetalheImpostoCofinsVO: TNfeDetalheImpostoCofinsVO; //0:1
// Grupo U
FNfeDetalheImpostoIssqnVO: TNfeDetalheImpostoIssqnVO; //0:1
// Grupo I01
FListaNfeDeclaracaoImportacaoVO: TListaNfeDeclaracaoImportacaoVO; //0:100
// Grupo I03
FListaNfeExportacaoVO: TListaNfeExportacaoVO; //0:500
// Grupo K
FListaNfeDetEspecificoMedicamentoVO: TListaNfeDetEspecificoMedicamentoVO; //0:500
// Grupo L
FListaNfeDetEspecificoArmamentoVO: TListaNfeDetEspecificoArmamentoVO; //0:500
published
constructor Create; override;
destructor Destroy; override;
property Id: Integer read FID write FID;
property IdProduto: Integer read FID_PRODUTO write FID_PRODUTO;
property IdNfeCabecalho: Integer read FID_NFE_CABECALHO write FID_NFE_CABECALHO;
property NumeroItem: Integer read FNUMERO_ITEM write FNUMERO_ITEM;
property CodigoProduto: String read FCODIGO_PRODUTO write FCODIGO_PRODUTO;
property Gtin: String read FGTIN write FGTIN;
property NomeProduto: String read FNOME_PRODUTO write FNOME_PRODUTO;
property Ncm: String read FNCM write FNCM;
property Nve: String read FNVE write FNVE;
property ExTipi: Integer read FEX_TIPI write FEX_TIPI;
property Cfop: Integer read FCFOP write FCFOP;
property UnidadeComercial: String read FUNIDADE_COMERCIAL write FUNIDADE_COMERCIAL;
property QuantidadeComercial: Extended read FQUANTIDADE_COMERCIAL write FQUANTIDADE_COMERCIAL;
property ValorUnitarioComercial: Extended read FVALOR_UNITARIO_COMERCIAL write FVALOR_UNITARIO_COMERCIAL;
property ValorBrutoProduto: Extended read FVALOR_BRUTO_PRODUTO write FVALOR_BRUTO_PRODUTO;
property GtinUnidadeTributavel: String read FGTIN_UNIDADE_TRIBUTAVEL write FGTIN_UNIDADE_TRIBUTAVEL;
property UnidadeTributavel: String read FUNIDADE_TRIBUTAVEL write FUNIDADE_TRIBUTAVEL;
property QuantidadeTributavel: Extended read FQUANTIDADE_TRIBUTAVEL write FQUANTIDADE_TRIBUTAVEL;
property ValorUnitarioTributavel: Extended read FVALOR_UNITARIO_TRIBUTAVEL write FVALOR_UNITARIO_TRIBUTAVEL;
property ValorFrete: Extended read FVALOR_FRETE write FVALOR_FRETE;
property ValorSeguro: Extended read FVALOR_SEGURO write FVALOR_SEGURO;
property ValorDesconto: Extended read FVALOR_DESCONTO write FVALOR_DESCONTO;
property ValorOutrasDespesas: Extended read FVALOR_OUTRAS_DESPESAS write FVALOR_OUTRAS_DESPESAS;
property EntraTotal: Integer read FENTRA_TOTAL write FENTRA_TOTAL;
property ValorSubtotal: Extended read FVALOR_SUBTOTAL write FVALOR_SUBTOTAL;
property ValorTotal: Extended read FVALOR_TOTAL write FVALOR_TOTAL;
property NumeroPedidoCompra: String read FNUMERO_PEDIDO_COMPRA write FNUMERO_PEDIDO_COMPRA;
property ItemPedidoCompra: Integer read FITEM_PEDIDO_COMPRA write FITEM_PEDIDO_COMPRA;
property InformacoesAdicionais: String read FINFORMACOES_ADICIONAIS write FINFORMACOES_ADICIONAIS;
property NumeroFci: String read FNUMERO_FCI write FNUMERO_FCI;
property NumeroRecopi: String read FNUMERO_RECOPI write FNUMERO_RECOPI;
property ValorTotalTributos: Extended read FVALOR_TOTAL_TRIBUTOS write FVALOR_TOTAL_TRIBUTOS;
property PercentualDevolvido: Extended read FPERCENTUAL_DEVOLVIDO write FPERCENTUAL_DEVOLVIDO;
property ValorIpiDevolvido: Extended read FVALOR_IPI_DEVOLVIDO write FVALOR_IPI_DEVOLVIDO;
property NfeDetEspecificoVeiculoVO: TNfeDetEspecificoVeiculoVO read FNfeDetEspecificoVeiculoVO write FNfeDetEspecificoVeiculoVO;
property NfeDetEspecificoCombustivelVO: TNfeDetEspecificoCombustivelVO read FNfeDetEspecificoCombustivelVO write FNfeDetEspecificoCombustivelVO;
property NfeDetalheImpostoIcmsVO: TNfeDetalheImpostoIcmsVO read FNfeDetalheImpostoIcmsVO write FNfeDetalheImpostoIcmsVO;
property NfeDetalheImpostoIpiVO: TNfeDetalheImpostoIpiVO read FNfeDetalheImpostoIpiVO write FNfeDetalheImpostoIpiVO;
property NfeDetalheImpostoIiVO: TNfeDetalheImpostoIiVO read FNfeDetalheImpostoIiVO write FNfeDetalheImpostoIiVO;
property NfeDetalheImpostoPisVO: TNfeDetalheImpostoPisVO read FNfeDetalheImpostoPisVO write FNfeDetalheImpostoPisVO;
property NfeDetalheImpostoCofinsVO: TNfeDetalheImpostoCofinsVO read FNfeDetalheImpostoCofinsVO write FNfeDetalheImpostoCofinsVO;
property NfeDetalheImpostoIssqnVO: TNfeDetalheImpostoIssqnVO read FNfeDetalheImpostoIssqnVO write FNfeDetalheImpostoIssqnVO;
property ListaNfeDeclaracaoImportacaoVO: TListaNfeDeclaracaoImportacaoVO read FListaNfeDeclaracaoImportacaoVO write FListaNfeDeclaracaoImportacaoVO;
property ListaNfeExportacaoVO: TListaNfeExportacaoVO read FListaNfeExportacaoVO write FListaNfeExportacaoVO;
property ListaNfeDetEspecificoMedicamentoVO: TListaNfeDetEspecificoMedicamentoVO read FListaNfeDetEspecificoMedicamentoVO write FListaNfeDetEspecificoMedicamentoVO;
property ListaNfeDetEspecificoArmamentoVO: TListaNfeDetEspecificoArmamentoVO read FListaNfeDetEspecificoArmamentoVO write FListaNfeDetEspecificoArmamentoVO;
end;
TListaNfeDetalheVO = specialize TFPGObjectList<TNfeDetalheVO>;
implementation
constructor TNfeDetalheVO.Create;
begin
inherited;
FNfeDetEspecificoVeiculoVO := TNfeDetEspecificoVeiculoVO.Create;
FNfeDetEspecificoCombustivelVO := TNfeDetEspecificoCombustivelVO.Create;
FNfeDetalheImpostoIcmsVO := TNfeDetalheImpostoIcmsVO.Create;
FNfeDetalheImpostoIpiVO := TNfeDetalheImpostoIpiVO.Create;
FNfeDetalheImpostoIiVO := TNfeDetalheImpostoIiVO.Create;
FNfeDetalheImpostoPisVO := TNfeDetalheImpostoPisVO.Create;
FNfeDetalheImpostoCofinsVO := TNfeDetalheImpostoCofinsVO.Create;
FNfeDetalheImpostoIssqnVO := TNfeDetalheImpostoIssqnVO.Create;
FListaNfeDeclaracaoImportacaoVO := TListaNfeDeclaracaoImportacaoVO.Create;
FListaNfeExportacaoVO := TListaNfeExportacaoVO.Create;
FListaNfeDetEspecificoMedicamentoVO := TListaNfeDetEspecificoMedicamentoVO.Create;
FListaNfeDetEspecificoArmamentoVO := TListaNfeDetEspecificoArmamentoVO.Create;
end;
destructor TNfeDetalheVO.Destroy;
begin
FreeAndNil(FNfeDetEspecificoVeiculoVO);
FreeAndNil(FNfeDetEspecificoCombustivelVO);
FreeAndNil(FNfeDetalheImpostoIcmsVO);
FreeAndNil(FNfeDetalheImpostoIpiVO);
FreeAndNil(FNfeDetalheImpostoIiVO);
FreeAndNil(FNfeDetalheImpostoPisVO);
FreeAndNil(FNfeDetalheImpostoCofinsVO);
FreeAndNil(FNfeDetalheImpostoIssqnVO);
FreeAndNil(FListaNfeDeclaracaoImportacaoVO);
FreeAndNil(FListaNfeExportacaoVO);
FreeAndNil(FListaNfeDetEspecificoMedicamentoVO);
FreeAndNil(FListaNfeDetEspecificoArmamentoVO);
inherited;
end;
initialization
Classes.RegisterClass(TNfeDetalheVO);
finalization
Classes.UnRegisterClass(TNfeDetalheVO);
end.
|
unit CFToolButton;
interface
uses
Windows, Classes, Controls, Messages, Graphics, CFControl;
type
TCFButtonStates = set of (cfmsIn, cfmsDown, cfmsChecked);
TOnPaintIconEvent = procedure(const AImageIndex: Integer; const ACanvas: TCanvas; const ARect: TRect) of object;
TCFToolButton = class(TGraphicControl)
private
FImageIndex: Integer;
FOnPaintIcon: TOnPaintIconEvent;
function GetChecked: Boolean;
procedure SetChecked(const Value: Boolean);
procedure SetImageIndex(const Value: Integer);
procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
/// <summary> 鼠标移入 </summary>
procedure CMMouseEnter(var Msg: TMessage ); message CM_MOUSEENTER;
/// <summary> 鼠标移出 </summary>
procedure CMMouseLeave(var Msg: TMessage ); message CM_MOUSELEAVE;
protected
FStates: TCFButtonStates;
/// <summary> 绘制 </summary>
/// <param name="ACanvas">呈现画布</param>
procedure Paint; override;
function GetImageRect: TRect; virtual;
function GetTextRect: TRect; virtual;
procedure UpdateView;
public
constructor Create(AOwner: TComponent); override;
procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override;
property OnPaintIcon: TOnPaintIconEvent read FOnPaintIcon write FOnPaintIcon;
published
property ImageIndex: Integer read FImageIndex write SetImageIndex;
property Checked: Boolean read GetChecked write SetChecked;
property Caption;
property Align;
property OnClick;
end;
TCFMenuButton = class(TCFToolButton)
protected
/// <summary> 绘制 </summary>
/// <param name="ACanvas">呈现画布</param>
procedure Paint; override;
/// <summary> 单击事件 </summary>
procedure Click; override;
function GetTextRect: TRect; override;
published
property PopupMenu;
end;
implementation
uses
CFColorUtils;
{ TCFToolButton }
procedure TCFToolButton.CMMouseEnter(var Msg: TMessage);
begin
inherited;
Include(FStates, cfmsIn);
UpdateView;
end;
procedure TCFToolButton.CMMouseLeave(var Msg: TMessage);
begin
inherited;
Exclude(FStates, cfmsIn);
UpdateView;
end;
constructor TCFToolButton.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FImageIndex := -1;
Width := 75;
Height := 25;
end;
function TCFToolButton.GetChecked: Boolean;
begin
Result := cfmsChecked in FStates;
end;
function TCFToolButton.GetImageRect: TRect;
begin
if FImageIndex >= 0 then
Result := Rect(0, 0, 24, Height)
else
Result := Rect(0, 0, 0, 0);
end;
function TCFToolButton.GetTextRect: TRect;
begin
if FImageIndex >= 0 then
Result := Rect(24, 0, Width, Height)
else
Result := Rect(0, 0, Width, Height);
end;
procedure TCFToolButton.MouseDown(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
begin
inherited;
Include(FStates, cfmsDown);
UpdateView;
end;
procedure TCFToolButton.MouseUp(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
begin
inherited;
Exclude(FStates, cfmsDown);
UpdateView;
end;
procedure TCFToolButton.Paint;
var
vRect: TRect;
vText: string;
vBackColor: TColor;
vImage: TGraphic;
begin
vRect := Rect(0, 0, Width, Height);
if cfmsIn in FStates then // 鼠标在控件内
begin
vBackColor := GAreaBackColor;
//Canvas.Pen.Width := 1;
//Canvas.Pen.Color := GetBorderColor(vBackColor);
if cfmsDown in FStates then // 鼠标按下
Canvas.Brush.Color := GetDownColor(vBackColor)
else
Canvas.Brush.Color := GetHotColor(vBackColor);
Canvas.FillRect(vRect);
end
else // 普通状态
Canvas.Brush.Style := bsClear;
if (FImageIndex >= 0) and (Assigned(FOnPaintIcon)) then
begin
vRect := GetImageRect;
FOnPaintIcon(FImageIndex, Canvas, vRect);
end;
vRect := GetTextRect;
vText := Caption;
Canvas.TextRect(vRect, vText, [tfSingleLine, tfCenter,tfVerticalCenter]);
if cfmsChecked in FStates then
begin
vBackColor := GAreaBackColor;
Canvas.Pen.Width := 1;
Canvas.Pen.Color := GetBorderColor(vBackColor);
vRect := Rect(0, 0, Width, Height);
Canvas.Brush.Style := bsClear;
Canvas.Rectangle(vRect);
end;
end;
procedure TCFToolButton.SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
begin
inherited SetBounds(ALeft, ATop, AWidth, AHeight);
end;
procedure TCFToolButton.SetChecked(const Value: Boolean);
begin
if Value then
Include(FStates, cfmsChecked)
else
Exclude(FStates, cfmsChecked);
UpdateView;
end;
procedure TCFToolButton.SetImageIndex(const Value: Integer);
begin
if FImageIndex <> Value then
begin
FImageIndex := Value;
UpdateView;
end;
end;
procedure TCFToolButton.UpdateView;
begin
Self.Invalidate;
end;
{ TCFMenuButton }
procedure TCFMenuButton.Click;
var
vPt: TPoint;
begin
if Assigned(PopupMenu) then
begin
vPt := Self.ClientToScreen(Point(0, Self.Height));
PopupMenu.Popup(vPt.X, vPt.Y);
end;
end;
function TCFMenuButton.GetTextRect: TRect;
begin
Result := inherited GetTextRect;
Result.Right := Result.Right - 12;
end;
procedure TCFMenuButton.Paint;
var
vRect: TRect;
vText: string;
vBackColor: TColor;
begin
inherited Paint;
vRect := Rect(0, 0, Width, Height);
// 下拉按钮
if False then
begin
Canvas.Pen.Color := $00848484;
Canvas.MoveTo(Width - 16, 2);
Canvas.LineTo(Width - 16, Height - 2);
end;
Canvas.Pen.Color := clBlack;
vRect.Left := Width - 12;
vRect.Top := (Height - 4) div 2;
Canvas.MoveTo(vRect.Left, vRect.Top);
Canvas.LineTo(vRect.Left + 7, vRect.Top);
Canvas.MoveTo(vRect.Left + 1, vRect.Top + 1);
Canvas.LineTo(vRect.Left + 6, vRect.Top + 1);
Canvas.MoveTo(vRect.Left + 2, vRect.Top + 2);
Canvas.LineTo(vRect.Left + 5, vRect.Top + 2);
Canvas.MoveTo(vRect.Left + 3, vRect.Top + 3);
Canvas.LineTo(vRect.Left + 4, vRect.Top + 3);
end;
end.
|
//---------------------------------------------------------------------------
// This software is Copyright (c) 2015 Embarcadero Technologies, Inc.
// You may only use this software if you are an authorized licensee
// of an Embarcadero developer tools product.
// This software is considered a Redistributable as defined under
// the software license agreement that comes with the Embarcadero Products
// and is subject to that software license agreement.
//---------------------------------------------------------------------------
unit FlashLightU;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.Permissions,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.Effects,
FMX.Objects, FMX.Layouts, FMX.Media;
type
TFlashLightForm = class(TForm)
FlashLight: TImage;
ImageOn: TImage;
FlashLightShadow: TShadowEffect;
Light: TImage;
ImageOff: TImage;
ContainerLayout: TLayout;
Camera: TCameraComponent;
GlowEffect1: TGlowEffect;
LayoutButtons: TLayout;
procedure FormCreate(Sender: TObject);
procedure ImageOffClick(Sender: TObject);
procedure ImageOnClick(Sender: TObject);
private
FPermissionCamera: string;
procedure SetFlashlightState(Active: Boolean);
procedure AccessCameraPermissionRequestResult(Sender: TObject; const APermissions: TArray<string>; const AGrantResults: TArray<TPermissionStatus>);
procedure ActivateCameraPermissionRequestResult(Sender: TObject; const APermissions: TArray<string>; const AGrantResults: TArray<TPermissionStatus>);
procedure DisplayRationale(Sender: TObject; const APermissions: TArray<string>; const APostRationaleProc: TProc);
public
{ Public declarations }
end;
var
FlashLightForm: TFlashLightForm;
implementation
uses
{$IFDEF ANDROID}
Androidapi.Helpers,
Androidapi.JNI.JavaTypes,
Androidapi.JNI.Os,
{$ENDIF}
FMX.DialogService;
{$R *.fmx}
{$R *.LgXhdpiPh.fmx ANDROID}
procedure TFlashLightForm.SetFlashlightState(Active: Boolean);
begin
if Active then
Camera.TorchMode := TTorchMode.ModeOn
else
Camera.TorchMode := TTorchMode.ModeOff;
end;
procedure TFlashLightForm.AccessCameraPermissionRequestResult(Sender: TObject; const APermissions: TArray<string>; const AGrantResults: TArray<TPermissionStatus>);
begin
// 1 permission involved: CAMERA
if (Length(AGrantResults) = 1) and (AGrantResults[0] = TPermissionStatus.Granted) then
ImageOff.Enabled := Camera.HasFlash
else
TDialogService.ShowMessage('Cannot access the camera flashlight because the required permission has not been granted');
end;
procedure TFlashLightForm.ActivateCameraPermissionRequestResult(Sender: TObject; const APermissions: TArray<string>; const AGrantResults: TArray<TPermissionStatus>);
begin
// 1 permission involved: CAMERA
if (Length(AGrantResults) = 1) and (AGrantResults[0] = TPermissionStatus.Granted) then
begin
Camera.Active := True;
ImageOff.Visible := False;
ImageOn.Visible := True;
SetFlashlightState(True);
Light.Visible := True;
end
else
TDialogService.ShowMessage('Cannot access the camera flashlight because the required permission has not been granted');
end;
// Optional rationale display routine to display permission requirement rationale to the user
procedure TFlashLightForm.DisplayRationale(Sender: TObject; const APermissions: TArray<string>; const APostRationaleProc: TProc);
begin
// Show an explanation to the user *asynchronously* - don't block this thread waiting for the user's response!
// After the user sees the explanation, invoke the post-rationale routine to request the permissions
TDialogService.ShowMessage('The app needs to access the camera in order to work',
procedure(const AResult: TModalResult)
begin
APostRationaleProc;
end)
end;
procedure TFlashLightForm.FormCreate(Sender: TObject);
begin
{$IFDEF ANDROID}
FPermissionCamera := JStringToString(TJManifest_permission.JavaClass.CAMERA);
{$ENDIF}
PermissionsService.RequestPermissions([FPermissionCamera], AccessCameraPermissionRequestResult, DisplayRationale);
end;
procedure TFlashLightForm.ImageOffClick(Sender: TObject);
begin
PermissionsService.RequestPermissions([FPermissionCamera], ActivateCameraPermissionRequestResult, DisplayRationale);
end;
procedure TFlashLightForm.ImageOnClick(Sender: TObject);
begin
ImageOff.Visible := True;
ImageOn.Visible := False;
SetFlashlightState(False);
Light.Visible := False;
end;
end.
|
//---------------------------------------------------------------------------
// This software is Copyright (c) 2015 Embarcadero Technologies, Inc.
// You may only use this software if you are an authorized licensee
// of an Embarcadero developer tools product.
// This software is considered a Redistributable as defined under
// the software license agreement that comes with the Embarcadero Products
// and is subject to that software license agreement.
//---------------------------------------------------------------------------
unit MusicPlayer.Utils;
interface
uses
{$IFDEF IOS}
FMX.Types,
iOSApi.MediaPlayer, iOSApi.Foundation, Macapi.Helpers,
{$ENDIF}
{$IFDEF ANDROID}
Androidapi.JNI.JavaTypes, Androidapi.JNI.GraphicsContentViewText, Androidapi.Helpers,
{$ENDIF}
System.SysUtils,
FMX.Graphics;
type
TMPControllerType = (App, Ipod);
TMPRepeatMode = (Default, None, One, All);
TMPPlaybackState = (Stopped, Playing, Paused, Interrupted, SeekingForward, SeekingBackward);
TMPSong = record
Album: string;
Artist: string;
Duration: string;
Title: string;
{$IFDEF ANDROID}
Path: string;
class function FromCursor(c: JCursor): TMPSong; static;
{$ENDIF}
{$IFDEF IOS}
MPItem: MPMediaItem;
class function FromMediaItem(Item: MPMediaItem): TMPSong; static;
{$ENDIF}
class function EmptySong: TMPSong; static;
class function DurationToString(duration: Single): string; static;
function Equals(song : TMPSong): Boolean;
end;
TMPAlbum = record
Name: string;
Artist: string;
Album_ID: Integer;
Artwork: TBitmap;
class function AllMusicAlbum: TMPAlbum; static;
end;
TOnSongChangeEvent = procedure (newIndex: Integer) of object;
TOnProcessPlayEvent = procedure (newPos: Single) of object;
{$IFDEF IOS}
function MPMediaItemPropertyTitle: NSString;
function MPMediaItemPropertyAlbumTitle: NSString;
function MPMediaItemPropertyArtist: NSString;
function MPMediaItemPropertyArtwork: NSString;
function MPMediaItemPropertyPlaybackDuration: NSString;
function MPMediaItemPropertyMediaType: NSString;
function MPMediaItemPropertyComposer: NSString;
function MPMediaItemPropertyGenre: NSString;
function MPMediaPlaylistPropertyName: NSString;
function MPMediaItemPropertyPodcastTitle: NSString;
{$ENDIF}
implementation
{ TMPAlbum }
class function TMPAlbum.AllMusicAlbum: TMPAlbum;
begin
Result.Name := 'All Songs';
Result.Artist := '';
Result.Album_ID := -1;
Result.Artwork := nil;
end;
class function TMPSong.EmptySong: TMPSong;
begin
Result.Album := '-';
Result.Artist := '-';
Result.Duration := '-';
Result.Title := '-';
end;
function TMPSong.Equals(song: TMPSong): Boolean;
begin
Result := (Artist = song.Artist) and (Album = song.Album) and (Duration = song.Duration) and (Title = song.Title);
end;
class function TMPSong.DurationToString(duration: Single): string;
var
hours,
minutes,
seconds: Integer;
secondsStr: string;
begin
Result := '';
{$IFDEF IOS}
hours := Trunc(duration) div (60*60);
minutes := (Trunc(duration) mod (60*60)) div 60;
seconds := Trunc(duration) mod 60;
{$ENDIF}
{$IFDEF ANDROID}
hours := Trunc(duration) div (1000*60*60);
minutes := (Trunc(duration) mod (1000*60*60)) div (1000*60);
seconds := ((Trunc(duration) mod (1000*60*60)) mod (1000*60)) div 1000;
{$ENDIF}
if hours > 0 then
if minutes < 10 then
Result := Result + hours.ToString + ':0'
else
Result := Result + hours.ToString + ':';
if seconds < 10 then
secondsStr := '0' + seconds.ToString
else
secondsStr := seconds.ToString;
Result := Result + minutes.ToString + ':' + secondsStr;
end;
{$IFDEF ANDROID}
class function TMPSong.FromCursor(c: JCursor): TMPSong;
begin
Result.Artist := JStringToString(c.getString(0));
if Result.Artist = '<unknown>' then
Result.Artist := 'Unknown';
Result.Title := JStringToString(c.getString(1));
Result.Path := JStringToString(c.getString(2));
Result.Album := JStringToString(c.getString(3));
Result.Duration := TMPSong.DurationToString(c.getFloat(4));
end;
{$ENDIF}
{$IFDEF IOS}
const
libMediaPlayer = '/System/Library/Frameworks/MediaPlayer.framework/MediaPlayer';
class function TMPSong.FromMediaItem(Item: MPMediaItem): TMPSong;
begin
Result.Artist := NSStrToStr(TNSString.Wrap(Item.valueForProperty(MPMediaItemPropertyArtist)));
Result.Album := NSStrToStr(TNSString.Wrap(Item.valueForProperty(MPMediaItemPropertyAlbumTitle)));
Result.Title := NSStrToStr(TNSString.Wrap(Item.valueForProperty(MPMediaItemPropertyTitle)));
Result.Duration := TMPSong.DurationTOString(TNSNumber.Wrap
(Item.valueForProperty(MPMediaItemPropertyPlaybackDuration)).floatValue);
Result.MPItem := Item;
Result.MPItem.retain;
if Result.Artist = '' then
Result.Artist := 'Unknown';
end;
function MPMediaItemPropertyTitle: NSString;
begin
Result := CocoaNSStringConst(libMediaPlayer, 'MPMediaItemPropertyTitle');
end;
function MPMediaItemPropertyAlbumTitle: NSString;
begin
Result := CocoaNSStringConst(libMediaPlayer, 'MPMediaItemPropertyAlbumTitle');
end;
function MPMediaItemPropertyArtist: NSString;
begin
Result := CocoaNSStringConst(libMediaPlayer, 'MPMediaItemPropertyArtist');
end;
function MPMediaItemPropertyArtwork: NSString;
begin
Result := CocoaNSStringConst(libMediaPlayer, 'MPMediaItemPropertyArtwork');
end;
function MPMediaItemPropertyPlaybackDuration: NSString;
begin
Result := CocoaNSStringConst(libMediaPlayer, 'MPMediaItemPropertyPlaybackDuration');
end;
function MPMediaItemPropertyMediaType: NSString;
begin
Result := CocoaNSStringConst(libMediaPlayer, 'MPMediaItemPropertyMediaType');
end;
function MPMediaItemPropertyComposer: NSString;
begin
Result := CocoaNSStringConst(libMediaPlayer, 'MPMediaItemPropertyComposer');
end;
function MPMediaItemPropertyGenre: NSString;
begin
Result := CocoaNSStringConst(libMediaPlayer, 'MPMediaItemPropertyGenre');
end;
function MPMediaPlaylistPropertyName: NSString;
begin
Result := CocoaNSStringConst(libMediaPlayer, 'MPMediaPlaylistPropertyName');
end;
function MPMediaItemPropertyPodcastTitle: NSString;
begin
Result := CocoaNSStringConst(libMediaPlayer, 'MPMediaItemPropertyPodcastTitle');
end;
{$ENDIF}
end.
|
unit World;
{$mode delphi}
interface
uses
SysUtils, Graphics, ExtCtrls, Classes, Contnrs, LCLIntf,
Entity, Car;
type
TWorld = class(TThread)
protected
PaintBox: TPaintBox;
public
EntList: TFPObjectList;
constructor Create;
procedure Execute; override;
procedure LinkPaintBox(PaintBox: TPaintBox);
function TransformWorldPoint(x, y: real): TPoint;
procedure Paint; virtual;
procedure PaintEntities;
procedure Click(X, Y: Real);
{ Property Entities[Index : Integer]: TEntity read EntList; }
end;
implementation
function TWorld.TransformWorldPoint;
begin
Result := Point(Round(x * self.PaintBox.Width),
Round(y * self.PaintBox.Height));
end;
constructor TWorld.Create;
begin
self.EntList := TFPObjectList.Create;
self.EntList.OwnsObjects := true;
self.FreeOnTerminate := True;
inherited Create(true);
Randomize;
end;
procedure TWorld.LinkPaintBox;
var
i: Integer;
begin
self.PaintBox := PaintBox;
for i := 0 to self.EntList.Count - 1 do
(self.EntList.Items[i] as TEntity).LinkPaintBox(PaintBox);
end;
procedure TWorld.Click;
var
i: Integer;
e: TEntity;
begin
for i := 0 to self.EntList.Count - 1 do
begin
e := self.EntList.Items[i] as TEntity;
if (X > e.TopLeft.X) and (X < e.BottomRight.X)
and (Y > e.TopLeft.Y) and (Y < e.BottomRight.Y) then
e.Click;
end;
end;
procedure TWorld.Paint;
begin
with self.PaintBox.Canvas do
begin
Brush.Color := clWhite;
FillRect(ClipRect);
end;
end;
procedure TWorld.PaintEntities;
var
i: Integer;
begin
for i := 0 to self.EntList.Count - 1 do
(self.EntList.Items[i] as TEntity).Paint;
self.PaintBox.Canvas.TextOut(self.PaintBox.Width - 150, self.PaintBox.Height - 20, 'Number of entities: ' + IntToStr(self.EntList.Count));
end;
procedure TWorld.Execute;
var
i, j: Integer;
Now, LastThink: LongInt;
a, b: TEntity;
begin
LastThink := GetTickCount;
while not self.Terminated do
begin
Now := GetTickCount;
if Now - LastThink > 50 then
begin
{ handle touches }
for i := 0 to self.EntList.Count - 1 do
begin
a := self.EntList.Items[i] as TEntity;
for j := 0 to self.EntList.Count - 1 do
begin
if i = j then
continue;
b := self.EntList.Items[j] as TEntity;
if (a.TopLeft.X < b.BottomRight.X)
and (a.BottomRight.X > b.TopLeft.X)
and (a.TopLeft.Y < b.BottomRight.Y)
and (a.BottomRight.Y > b.TopLeft.Y) then
begin
//writeln('intersection');
a.Touch(b);
end;
end;
end;
{ handle thinks }
for i := 0 to self.EntList.Count - 1 do
begin
a := self.EntList.Items[i] as TEntity;
a.Think;
{ update entities' position }
case a.Orientation of
up: a.y := a.y - a.speed * (Now - LastThink) / 1000;
down: a.y := a.y + a.speed * (Now - LastThink) / 1000;
left: a.x := a.x - a.speed * (Now - LastThink) / 1000;
right: a.x := a.x + a.speed * (Now - LastThink) / 1000;
end;
end;
{ delete marked entities }
i := 0;
while i < self.EntList.Count do
begin
if (self.EntList.Items[i] as TEntity).Delete then
self.EntList.Remove(self.EntList.Items[i])
else
inc(i);
end;
{ redraw the scene }
self.Synchronize(self.PaintBox.Repaint);
LastThink := Now;
end;
end;
writeln('beendet');
end;
end.
|
unit SpFoto_JpegInfo;
interface
Uses
Windows, SysUtils, Classes, SpFoto_Types, SpFoto_FileStream;
Type
TIFD = (Primary_IFD, Exif_IFD, GPS_IFD, Interop_IFD);
//
// This is a special ExifStream wrapper to catch if/when
// a runaway parsing of the file run outside the exif
// Section.
//
TmdExifStream = class(TmdFileStream)
Private
FExifOffset : DWord;
Public
Procedure Seek(Pos : LongInt); Override;
Property ExifOffset : DWord Read FExifOffset Write FExifOffset;
end;
//
// Return the Name associated with a TAG value
//
Function TagToStr(IFD : TIFD; Tag : Word; Str:String = '') : String;
//
// Return the Name assosiated with a Type value
//
Function TypeToStr(AType : Word) : String;
//
// Get the Exif information from the file.
// Return false if no information was found
//
Function GetJpegInfoRec(FileName : String; SL : TStrings; ResInfo:TJpegGeneralInfo) : Boolean;
Function GetJpegInfo(FileName : String; SL : TStrings) : Boolean;
//
// This is the actual Exif tag decoding function
//
Function GetIFDData(Img : TmdExifStream; Offset : DWord;
IFD : TIFD; SL : TStrings) : Boolean;
implementation
var pInfo:TJpegGeneralInfo;
Procedure TmdExifStream.Seek(Pos : LongInt);
Begin
If (FExifOffset > 0) AND (Pos > FExifOffset+65535) Then
Raise Exception.Create('Exif section out of bounds');
Inherited Seek(Pos);
end;
Function TagToStr(IFD : TIFD; Tag : Word; Str:String = '') : String;
var i:Integer;
Begin
Result := '';
If (IFD = Primary_IFD) OR (IFD = Exif_IFD) Then
Begin
Case Tag of
$100: Result := 'ImageWidth';
$101: Result := 'ImageLength';
$102: Result := 'BitsPerSample';
$103: Result := 'Compression';
$106: Result := 'PhotometricInterpretation';
$112: Result := 'Orientation';
$115: Result := 'SamplesPerPixel';
$11C: Result := 'PlanarConfiguration';
$212: Result := 'YCbCrSubSampling';
$213: Result := 'YCbCrPositioning';
$11A: begin
Result := 'XResolution';
i:=pos('/',Str);
Delete(Str,i,length(Str)-i+1);
pInfo.XPP:=StrToInt(Str);
end;
$11B: begin
Result := 'YResolution';
i:=pos('/',Str);
Delete(Str,i,length(Str)-i+1);
pInfo.YPP:=StrToInt(Str);
end;
$128: begin
Result := 'ResolutionUnit';
pInfo.ResolutionUnit:=StrToInt(Str);
end;
$111: Result := 'StripOffsets';
$116: Result := 'RowsPerStrip';
$117: Result := 'StripByteCounts';
$201: Result := 'JPEGInterchangeFormat';
$202: Result := 'JPEGInterchangeFormatLength';
$12D: Result := 'TransferFunction';
$13E: Result := 'WhitePoint';
$13F: Result := 'PrimaryChromaticities';
$211: Result := 'YCbCrCoefficients';
$214: Result := 'ReferenceBlackWhite';
$132: Result := 'DateTime';
$10E: Result := 'ImageDescription';
$10F: Result := 'Make';
$110: Result := 'Model';
$131: Result := 'Software';
$13B: Result := 'Artist';
$8298: Result := 'Copyright';
$8769: Result := 'Exif IFD';
// Version
$9000: Result := 'ExifVersion';
$A000: Result := 'FlashPixVersion';
// Color
$A001: Result := 'ColorSpace';
// Image Configuration
$9101: Result := 'ComponentsConfiguration';
$9102: Result := 'CompressedBitsPerPixel';
$A002: begin
Result := 'PixelXDimension';
pInfo.Width:=StrToInt(Str);
end;
$A003: begin
Result := 'PixelYDimension';
pInfo.Height:=StrToInt(Str);
end;
// User Information
$927C: Result := 'MakerNote';
$9286: Result := 'UserComment';
// Date and Time
$9003: Result := 'DateTimeOriginal';
$9004: Result := 'DateTimeDigitized';
$9290: Result := 'SubSecTime';
$9291: Result := 'SubSecTimeOriginal';
$9292: Result := 'SubSecTimeDigitized';
// Picture taking condition
$829A: Result := 'ExposureTime';
$829D: Result := 'FNumber';
$8822: Result := 'ExposureProgram';
$8824: Result := 'SpectralSensitivity';
$8827: Result := 'ISOSpeedRatings';
$8828: Result := 'OECF';
$9201: Result := 'ShutterSpeedValue';
$9202: Result := 'ApertureValue';
$9203: Result := 'BrightnessValue';
$9204: Result := 'ExposureBiasValue';
$9205: Result := 'MaxApertureValue';
$9206: Result := 'SubjectDistance';
$9207: Result := 'MeteringMode';
$9208: Result := 'LightSource';
$9209: Result := 'Flash';
$920A: Result := 'FocalLength';
$A20B: Result := 'FlashEnergy';
$A20C: Result := 'SpatialFrequencyResponse';
$A20E: Result := 'FocalPlaneXResolution';
$A20F: Result := 'FocalPlaneYResolution';
$A210: Result := 'FocalPlaneResolutionUnit';
$A214: Result := 'SubjectLocation';
$A215: Result := 'ExposureIndex';
$A217: Result := 'SensingMethod';
$A300: Result := 'FileSource';
$A301: Result := 'SceneType';
$A302: Result := 'CFAPattern';
// Misc
$A005: Result := 'Interoperability IFD Pointer';
// GPS
$8825: Result := 'GPS Info Pointer';
end;
end
else If IFD = Interop_IFD Then
Begin
Case Tag of
$0001: Result := 'InteroperabilityIndex';
$0002: Result := 'InteroperabilityVersion';
$1000: Result := 'RelatedImageFileFormat';
$1001: Result := 'RelatedImageWidth';
$1002: Result := 'RelatedImageLength';
end;
end
else If IFD = GPS_IFD Then
Begin
Case Tag of
$0000: Result := 'GPSVersionID';
$0001: Result := 'GPSLatitudeRef';
$0002: Result := 'GPSLatitude';
$0003: Result := 'GPSLongitudeRef';
$0004: Result := 'GPSLongitude';
$0005: Result := 'GPSAltitudeRef';
$0006: Result := 'GPSAltitude';
$0007: Result := 'GPSTimeStamp';
$0008: Result := 'GPSSatellites';
$0009: Result := 'GPSStatus';
$000A: Result := 'GPSMeasureMode';
$000B: Result := 'GPSDOP';
$000C: Result := 'GPSSpeedRef';
$000D: Result := 'GPSSpeed';
$000E: Result := 'GPSTrackRef';
$000F: Result := 'GPSTrack';
$0010: Result := 'GPSImgDirectionRef';
$0011: Result := 'GPSImgDirection';
$0012: Result := 'GPSMapDatum';
$0013: Result := 'GPSDestLatitudeRef';
$0014: Result := 'GPSDestLatitude';
$0015: Result := 'GPSDestLongitudeRef';
$0016: Result := 'GPSDestLongitude';
$0017: Result := 'GPSDestBearingRef';
$0018: Result := 'GPSDestBearing';
$0019: Result := 'GPSDestDistanceRef';
$001A: Result := 'GPSDestDistance';
end;
end;
If Result = '' Then
Result := 'Tag '+IntToHex(Tag,4);
end;
Function TypeToStr(AType : Word) : String;
Begin
Result := '';
case AType of
1: Result := 'BYTE';
2: Result := 'ASCII';
3: Result := 'SHORT';
4: Result := 'LONG';
5: Result := 'RATIONAL';
7: Result := 'UNDEFINED';
9: Result := 'SLONG';
10: Result := 'SRATIONAL';
else
Result := 'Type '+IntToStr(AType);
end;
end;
Function CleanStr(Str : String) : String;
Var
Cnt : Integer;
Begin
Result := '';
For Cnt := 1 to Length(Str) do
If Str[Cnt] >= #$20 Then
Result := Result + Str[Cnt];
end;
Function GetJpegInfoRec(FileName : String; SL : TStrings; ResInfo:TJpegGeneralInfo) : Boolean;
begin
pInfo.Width:=-1;
pInfo.Height:=-1;
pInfo.XPP:=-1;
pInfo.YPP:=-1;
pInfo.ResolutionUnit:=-1;
GetJpegInfo(FileName,SL);
ResInfo:=pInfo;
end;
Function GetJpegInfo(FileName : String; SL : TStrings) : Boolean;
Var
Img : TmdExifStream;
Str : String;
TempB : Byte;
TempW : Word;
TempI : DWord;
Begin
Result := False;
Img := TmdExifStream.Create(FileName,
fmOpenRead OR fmShareDenyWrite);
Try
If Img.EOF Then
Exit;
// Check the Jpeg format.
// Read Start Of Image (SOI) Marker
If NOT (Img.GetWord = $FFD8) Then
Exit;
// Search for the Exif section
Repeat
If Img.GetByte = $FF Then
Begin
TempB := Img.GetByte;
case TempB of
$E1 : // Exif Marker found ...
Begin
// Continue load below...
Break;
end;
$D9 : // End Of Image (EOI)
Begin
Exit;
end;
else
Begin
// Unknown section...
// The two bytes following the application marker is
// the length of the section (including the two length bytes).
// We need to skip the section
TempW := Img.GetWord - 2;
Img.Seek(Img.Position+TempW);
end;
end;
end
else
Begin
// Something is very wrong...
Exit;
end;
Until Img.EOF;
// Reading the Exif Section length
Img.GetWord;
// Here we find the Exif "magic" prefix inside the
// the Jpeg Application Section.
// The Exif section start with the four letters "Exif" followed
// by two null bytes.
SetLength(Str,4);
Img.Read(Str, 4);
If Str <> 'Exif' Then
Exit;
If NOT (Img.GetWord = $0000) Then
Exit;
// This is our reference marker!
Img.ExifOffset := Img.Position;
// From here we are talking TIFF format....
// Get char format
TempW := Img.GetWord;
Case TempW of
$4949 :
Begin
Img.Endian := Little;
end;
$4D4D :
Begin
Img.Endian := Big;
end;
else
Begin
// Illigal header value
Exit;
end;
end;
// Get "fixed value"
// (or as the TIFF standard says "An arbitrary but
// carefully chosen number")
TempW := Img.GetWord;
If TempW <> $002A Then
Exit;
// Read the offset value, and find the "start
// position"
TempI := Img.GetInt;
If NOT GetIFDData(Img, TempI, Primary_IFD, SL) Then
Exit;
Finally
Img.Free;
end;
Result := True;
end;
//
// Decode the IFD Data (or tags)
//
Function GetIFDData(Img : TmdExifStream; Offset : DWord;
IFD : TIFD; SL : TStrings) : Boolean;
Var
Cnt : Integer;
Cnt2 : Integer;
Str : String;
IFDRecords : Word;
MyPos : DWord;
MyTag, MyType : Word;
MyCount, MyValue : DWord;
TmpW : Word;
NextIFD : DWord;
Begin
// Try to catch exceptions. The file will return an exception if
// we access outside the file (runaway tags)
Try
Result := True;
Img.Seek(Img.ExifOffset+Offset);
If Img.EOF Then // Sanity check
Exit;
// Get the information count
IFDRecords := Img.GetWord;
For Cnt := 1 to IFDRecords do
Begin
MyPos := Img.Position;
MyTag := Img.GetWord;
MyType := Img.GetWord;
MyCount := Img.GetInt;
MyValue := Img.GetInt;
Str := '';
case MyType of
1: // BYTE
Begin
If MyCount <= 4 Then
Img.Seek(MyPos+8)
else
Img.Seek(MyValue+Img.ExifOffset);
For Cnt2 := 1 To MyCount do
Begin
If Str <> '' Then
Str := Str + ',';
TmpW := Img.GetByte;
Str := Str + IntToStr(TmpW);
end;
end;
2: // ASCII
Begin
If MyCount <= 4 Then
Img.Seek(MyPos+8)
else
Img.Seek(MyValue+Img.ExifOffset);
SetLength(Str, MyCount);
Img.Read(Str, MyCount);
Str := CleanStr(Str);
end;
3: // Short
begin
// We can store two words in a 4 byte area.
// So if there is less (or equal) than two items
// in this section they are stored in the
// Value/Offset area
If MyCount <= 2 Then
Img.Seek(MyPos+8)
else
Img.Seek(MyValue+Img.ExifOffset);
For Cnt2 := 1 To MyCount do
Begin
If Str <> '' Then
Str := Str + ',';
Str := Str + IntToStr(Img.GetWord);
end;
end;
4: // Long
Begin
// We can store one long in a 4 byte area.
// So if there is less (or equal) than one item
// in this section they are stored in the
// Value/Offset area
If MyCount <= 1 Then
Str := IntToStr(MyValue)
else
Begin
Img.Seek(MyValue+Img.ExifOffset);
For Cnt2 := 1 To MyCount do
Begin
If Str <> '' Then
Str := Str + ',';
Str := Str + IntToStr(Img.GetInt);
end;
end;
end;
5: // Rational (LONG / LONG)
Begin
Img.Seek(MyValue+Img.ExifOffset);
For Cnt2 := 1 To MyCount do
Begin
If Str <> '' Then
Str := Str + ',';
Str := Str + IntToStr(Img.GetInt) + '/'+
IntToStr(Img.GetInt);
end;
end;
7: // Undefined
Begin
If MyCount <= 4 Then
Img.Seek(MyPos+8) // The 8 is the "tag record size"
// Minus the value
else
Img.Seek(MyValue+Img.ExifOffset);
Str := '';
For Cnt2 := 1 To MyCount do
Begin
If Str <> '' Then
Str := Str + ' ';
Str := Str + IntToHex(Img.GetByte,2);
end;
end;
9: // Signed Long
Begin
// We can store one long in a 4 byte area.
// So if there is less (or equal) than one item
// in this section they are stored in the
// Value/Offset area
If MyCount <= 1 Then
Begin
Str := IntToStr(Integer(MyValue));
end
else
Begin
Img.Seek(MyValue+Img.ExifOffset);
For Cnt2 := 1 To MyCount do
Begin
If Str <> '' Then
Str := Str + ',';
Str := Str + IntToStr(Integer(Img.GetInt));
end;
end;
end;
10: // Signed Rational (SLONG / SLONG)
Begin
Img.Seek(MyValue+Img.ExifOffset);
For Cnt2 := 1 To MyCount do
Begin
If Str <> '' Then
Str := Str + ',';
Str := Str + IntToStr(Integer(Img.GetInt)) + '/'+
IntToStr(Integer(Img.GetInt));
end;
end;
else
// An undentified code is returned. We bail out of this
// section with an error. Result will depend on location
Result := False;
Exit;
end;
Case MyTag of
$8769:
If NOT GetIFDData(Img, MyValue, Exif_IFD, SL) Then
SL.Add(TagToStr(IFD, MyTag)+'=[ ERROR ]');
$A005:
If NOT GetIFDData(Img, MyValue, Interop_IFD, SL) Then
SL.Add(TagToStr(IFD, MyTag)+'=[ ERROR ]');
$8825:
If NOT GetIFDData(Img, MyValue, GPS_IFD, SL) Then
SL.Add(TagToStr(IFD, MyTag)+'=[ ERROR ]');
else
SL.Add(TagToStr(IFD, MyTag, Str)+'='+Str);
end;
If NOT Result Then
Exit; // We had an error
Img.Seek(MyPos+12); // The 12 is the "tag record size"
end;
NextIFD := Img.GetInt;
If NextIFD > 65535 Then
Begin
Result := False;
Exit; // Error!!
end;
If NextIFD <> 0 Then
Result := GetIFDData(Img, NextIFD, IFD, SL)
else
Result := True;
// If we catch an exception, we'll just return "error"
Except
On Exception do
Result := False;
end;
end;
end.
|
unit tarfile;
interface
uses classes, sysutils, math;
const EXP_FILENAME = 0;
EXP_SIZE = 1;
EXP_DATE = 2;
EXP_BODY = 3;
EXP_ERROR = 4;
EXP_EOF = 5;
SECSIZE = 512;
// SECSPERBLOCK = 120;
BUFSIZE = SECSIZE; // * SECSPERBLOCK;
type
TBuffer = Array [0..Pred(BUFSIZE)] Of byte;
TDateTime = record
sec : integer;
min : integer;
hour : integer;
day : integer;
month : integer;
year : integer;
end;
TTarFile = class
private
FTarF : TFileStream;
FExpecting : byte;
FName : string;
FBuffer : TBuffer;
FLen : longint;
FUnreadSec : integer;
function CrackUnixDateTime( UnixDate : longint) : TDateTime;
procedure AdjustFilename( var filename : string);
public
constructor Create( filename : string);
destructor Free;
function EOF : boolean;
function Progress : integer;
function GetNextFilename : string;
function GetNextSize : longint;
function GetNextDate : TDateTime;
function ReadFile( var buffer; maximum : longint) : longint;
Procedure SkipFile;
protected
end;
implementation
// **************************************************
// Private part
// **************************************************
function TTarFile.CrackUnixDateTime( UnixDate : longint) : TDateTime;
Const monlen : Array [1..12] Of byte
= (31,28,31,30,31,30,31,31,30,31,30,31);
var dt : TDateTime;
begin
dt.sec := UnixDate mod 60;
UnixDate := UnixDate div 60;
dt.min := UnixDate mod 60;
UnixDate := UnixDate div 60;
dt.hour := UnixDate mod 24;
UnixDate := UnixDate div 24;
dt.year := 1970;
while ((UnixDate>=365) and (dt.year mod 4 <> 0)) or
((UnixDate>=366) and (dt.year mod 4 = 0 )) do
begin
if dt.year mod 4 = 0 then UnixDate := UnixDate - 1;
UnixDate := UnixDate - 365;
Inc(dt.year)
end;
dt.month := 1;
if dt.year mod 4 = 0 then Inc(monlen[2]);
while UnixDate>=monlen[dt.month] do
begin
UnixDate := UnixDate - monlen[dt.month];
Inc(dt.month)
end;
if dt.year mod 4 = 0 then Dec(monlen[2]);
dt.day := UnixDate + 1;
Result := dt
end;
Procedure TTarFile.AdjustFilename(Var filename : string);
Const badletter : Set Of char = ['+',' ',':','<','>','|'];
Var i : byte;
Begin { openfile }
For i := Length(filename) DownTo 1 Do
Begin
If filename[i] = '/' Then filename[i] := '\';
If filename[i] In badletter Then filename[i] := '_';
End
end;
// **************************************************
// Public part
// **************************************************
constructor TTarFile.Create( filename : string);
begin
FTarF := TFileStream.Create( filename, fmOpenRead or fmShareDenyWrite);
end;
destructor TTarFile.Free;
begin
FTarF.Free;
end;
function TTarFile.EOF : boolean;
begin
EOF := FTarF.Size = FTarF.Position;
end;
function TTarFile.Progress : integer;
begin
Progress := Floor((FTarF.Position / FTarF.Size) * 100)
end;
function TTarFile.GetNextFilename : string;
var iread : integer;
i : integer;
begin
FName := '';
if (not(EOF) and (FExpecting = EXP_FILENAME)) then
begin
iread := FTarF.Read( FBuffer, SECSIZE);
If iread <> SECSIZE Then FExpecting := EXP_ERROR
else begin
i := 0;
While (FBuffer[i] <> 0) And (i < 254) Do
begin
FName := FName + char(FBuffer[i]);
Inc(i);
end;
if i > 0 then
begin
FExpecting := EXP_SIZE;
AdjustFilename( FName)
end
else begin
i := 0;
// Lazy evaluation needed to prvent reading from FBuffer[SECSIZE]
while (i < SECSIZE) and (FBuffer[i]=0) do Inc(i);
if i < SECSIZE then
FExpecting := EXP_FILENAME
else begin
FExpecting := EXP_EOF;
FTarF.Position := FTarF.Size
end
end
end
end;
Result := FName;
end;
function TTarFile.GetNextSize : longint;
var i : byte;
begin
FLen := 0;
GetNextSize := 0;
if (not(EOF) and (FExpecting = EXP_SIZE)) then
begin
For i := $7C To $86 Do
If (FBuffer[i] >= 48) And (FBuffer[i] <= 55) Then
FLen := 8*FLen + FBuffer[i] - 48;
if FLen > 0 then
FExpecting := EXP_DATE
else
FExpecting := EXP_FILENAME;
GetNextSize := FLen
end;
FUnreadSec := (SECSIZE - (FLen mod SECSIZE)) mod SECSIZE
end;
function TTarFile.GetNextDate : TDateTime;
var UnixDate : longint;
i : byte;
begin
UnixDate := 0;
if FExpecting = EXP_DATE then
begin
For i := $88 To $92 Do
If (FBuffer[i] >= 48) And (FBuffer[i] <= 55) Then
UnixDate := 8*UnixDate + FBuffer[i] - 48;
FExpecting := EXP_BODY
end;
Result := CrackUnixDateTime( UnixDate)
end;
function TTarFile.ReadFile( var buffer; maximum : longint) : longint;
var iread : longint;
buff : TBuffer;
begin
iread := 0;
if (FLen > FTarF.Size - FTarF.Position) or
(FExpecting <> EXP_BODY)
then FExpecting := EXP_ERROR
else begin
iread := FTarF.Read( buffer, min(maximum,FLen));
FLen := FLen - iread;
if FLen = 0 then
begin
FExpecting := EXP_FILENAME;
if FUnreadSec > 0 then FTarF.Read( buff, FUnreadSec)
end
end;
ReadFile := iread
end;
procedure TTarFile.SkipFile;
begin
if (FLen > FTarF.Size - FTarF.Position) or
(FExpecting <> EXP_BODY)
then FExpecting := EXP_ERROR
else begin
FTarF.Position := FTarF.Position + FLen + FUnreadSec;
FExpecting := EXP_FILENAME
end
end;
end.
|
unit Forms.Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, AdvGlowButton, Vcl.ComCtrls,
AdvDateTimePicker, Vcl.DBCtrls, Vcl.ExtCtrls, Modules.Database,
VCL.TMSFNCTypes, VCL.TMSFNCUtils, VCL.TMSFNCGraphics, VCL.TMSFNCGraphicsTypes,
VCL.TMSFNCCustomControl, VCL.TMSFNCWebBrowser, VCL.TMSFNCMaps,
VCL.TMSFNCGoogleMaps, Data.DB, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf,
FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, FireDAC.Comp.DataSet,
FireDAC.Comp.Client;
type
TFrmMain = class(TForm)
Panel1: TPanel;
cbStates: TDBLookupComboBox;
dpDate: TAdvDateTimePicker;
btnQuery: TAdvGlowButton;
Map: TTMSFNCGoogleMaps;
dsStates: TDataSource;
procedure FormCreate(Sender: TObject);
procedure btnQueryClick(Sender: TObject);
private
{ Private declarations }
procedure ShowIncidents( ADate: TDate;
AStateCode: String );
public
{ Public declarations }
end;
var
FrmMain: TFrmMain;
implementation
{$R *.dfm}
uses
System.IOUtils,
Flix.Utils.Maps,
VCL.TMSFNCMapsCommonTypes;
procedure TFrmMain.btnQueryClick(Sender: TObject);
begin
ShowIncidents( dpDate.Date, cbStates.KeyValue );
end;
procedure TFrmMain.FormCreate(Sender: TObject);
begin
var LKeys := TServiceAPIKeys.Create( TPath.Combine( TTMSFNCUtils.GetAppPath, 'apikeys.config' ) );
try
Map.APIKey := LKeys.GetKey( msGoogleMaps );
finally
LKeys.Free;
end;
dpDate.MinDate := DBController.DateFirst;
dpDate.MaxDate := DBController.DateLast;
end;
procedure TFrmMain.ShowIncidents(ADate: TDate; AStateCode: String);
var
lFormat: TFormatSettings;
lDateStr: String;
lQuIncidents: TFDQuery;
lRect: TTMSFNCMapsRectangle;
lCoordS,
lCoordE : TTMSFNCMapsCoordinateRec;
lStartLat,
lStartLon,
lEndLat,
lEndLon : Double;
lCluster : TTMSFNCGoogleMapsCluster;
lMarker : TTMSFNCGoogleMapsMarker;
lSeverity: Integer;
begin
lFormat := TFormatSettings.Create;
lFormat.ShortDateFormat := 'yyyy-mm-dd';
lDateStr := DateToStr( ADate, lFormat );
lQuIncidents := TFDQuery.Create(nil);
try
lQuIncidents.Connection := DBController.Connection;
lQuIncidents.SQL.Text := TSQLStatements.GetIncidents;
lQuIncidents.ParamByName('date').AsString := lDateStr;
lQuIncidents.ParamByName('code').AsString := AStateCode;
lQuIncidents.Open;
if lQuIncidents.RecordCount > 0 then
begin
Map.BeginUpdate;
try
Map.ClearMarkers;
Map.ClearRectangles;
Map.ClearClusters;
lCluster := Map.Clusters.Add;
while not lQuIncidents.Eof do
begin
lStartLat := lQuIncidents.FieldByName('start_lat').AsFloat;
lStartLon := lQuIncidents.FieldByName('start_lng').AsFloat;
lEndLat := lQuIncidents.FieldByName('end_lat').AsFloat;
lEndLon := lQuIncidents.FieldByName('end_lng').AsFloat;
lCoordS := CreateCoordinate( lStartLat, lStartLon );
lCoordE := CreateCoordinate( lEndLat, lEndLon );
lMarker := Map.AddMarker(lCoordS) as TTMSFNCGoogleMapsMarker;
lMarker.Cluster := lCluster;
lMarker.DataInteger := lQuIncidents.FieldByName('id').AsInteger;
if (lCoordE.Longitude <> 0) and (lCoordE.Latitude <> 0) then
begin
lRect := Map.AddRectangle(
CreateBounds( lCoordS, lCoordE )
);
lSeverity := lQuIncidents.FieldByName('severity').AsInteger;
case lSeverity of
1: lRect.FillColor := clGreen;
2: lRect.FillColor := clOlive;
3: lRect.FillColor := clYellow;
4: lRect.FillColor := clRed;
5: lRect.FillColor := clPurple;
else
lRect.FillColor := clWhite;
end;
lRect.FillOpacity := 0.5;
end;
lQuIncidents.Next;
end;
Map.ZoomToBounds( Map.Markers.ToCoordinateArray );
finally
Map.EndUpdate;
end;
end
else
begin
MessageDlg('No accidents recorded for selected state on that day.',
mtInformation, [mbOK], 0 );
end;
finally
lQuIncidents.Free;
end;
end;
end.
|
unit uPctPetSaleSearch;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uParentSearchForm, cxStyles, cxCustomData, cxGraphics, cxFilter,
cxData, cxEdit, DB, cxDBData, DBClient, ExtCtrls, cxGridLevel, cxClasses,
cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxGrid, XiButton, cxMaskEdit, cxDropDownEdit,
cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, mrSuperCombo, StdCtrls,
cxContainer, cxTextEdit;
type
TPctPetSaleSearch = class(TParentSearchForm)
edtSKU: TcxTextEdit;
lbSKU: TLabel;
scBreed: TmrSuperCombo;
scSpecies: TmrSuperCombo;
scStatus: TmrSuperCombo;
cdsSearchIDPet: TIntegerField;
cdsSearchIDSpecies: TIntegerField;
cdsSearchIDPorte: TIntegerField;
cdsSearchIDBreed: TIntegerField;
cdsSearchIDStatus: TIntegerField;
cdsSearchIDBreeder: TIntegerField;
cdsSearchIDModel: TIntegerField;
cdsSearchName: TStringField;
cdsSearchSex: TStringField;
cdsSearchColor: TStringField;
cdsSearchSKU: TStringField;
cdsSearchPenNum: TStringField;
cdsSearchVendorCost: TBCDField;
cdsSearchMSRP: TBCDField;
cdsSearchSalePrice: TBCDField;
cdsSearchPromoPrice: TBCDField;
cdsSearchUSDA: TStringField;
cdsSearchCollar: TStringField;
cdsSearchSire: TStringField;
cdsSearchDam: TStringField;
cdsSearchWhelpDate: TDateTimeField;
cdsSearchPurchaseDate: TDateTimeField;
cdsSearchNotes: TStringField;
cdsSearchSpecies: TStringField;
cdsSearchBreed: TStringField;
cdsSearchStatusCode: TStringField;
cdsSearchStatus: TStringField;
cdsSearchBreeder: TStringField;
cdsSearchIDWarrantyReport: TIntegerField;
cdsSearchWarrantyCustomerName: TStringField;
cdsSearchWCustomerFirstName: TStringField;
cdsSearchWCustomerLastName: TStringField;
cdsSearchWCustomerAddress: TStringField;
cdsSearchWCustomerCity: TStringField;
cdsSearchWCustomerStateID: TStringField;
cdsSearchWCustomerZip: TStringField;
cdsSearchWCustomerPhone: TStringField;
cdsSearchWCustomerEmail: TStringField;
cdsSearchPetSaleDate: TDateTimeField;
cdsSearchPetSaleCost: TBCDField;
cdsSearchPetSaleSold: TBCDField;
cdsSearchPetSaleDiscount: TBCDField;
cdsSearchSaleCustomerName: TStringField;
cdsSearchIDPetSale: TIntegerField;
grdListDBTableViewSex: TcxGridDBColumn;
grdListDBTableViewSKU: TcxGridDBColumn;
grdListDBTableViewPetSaleDate: TcxGridDBColumn;
grdListDBTableViewPetSaleSold: TcxGridDBColumn;
grdListDBTableViewPetSaleDiscount: TcxGridDBColumn;
grdListDBTableViewSaleCustomerName: TcxGridDBColumn;
grdListDBTableViewWarrantyCustomerName: TcxGridDBColumn;
grdListDBTableViewDBColumn1: TcxGridDBColumn;
cdsSearchIDStore: TIntegerField;
grdListDBTableViewInvoiceTotal: TcxGridDBColumn;
cdsSearchInvoiceTotal: TBCDField;
cdsSearchPetNetSale: TBCDField;
grdListDBTableViewPetNetSale: TcxGridDBColumn;
procedure FormCreate(Sender: TObject);
procedure cdsSearchBeforeGetRecords(Sender: TObject;
var OwnerData: OleVariant);
procedure btnOkClick(Sender: TObject);
private
FSKU : String;
protected
procedure AfterSetParams; override;
public
{ Public declarations }
end;
implementation
uses uDMPet, uDMPetCenter, uClasseFunctions, uMRSQLParam, uNTierConsts,
uParamFunctions, mrMsgBox, uDMWarrantyPrintThread, uMRParam;
{$R *.dfm}
procedure TPctPetSaleSearch.FormCreate(Sender: TObject);
begin
inherited;
scBreed.CreateListSource(DMPet.TraceControl, DMPet.DataSetControl, DMPet.UpdateControl, nil, DMPet.SystemUser, '');
scStatus.CreateListSource(DMPet.TraceControl, DMPet.DataSetControl, DMPet.UpdateControl, nil, DMPet.SystemUser, '');
scSpecies.CreateListSource(DMPet.TraceControl, DMPet.DataSetControl, DMPet.UpdateControl, nil, DMPet.SystemUser, '');
grdListDBTableViewInvoiceTotal.Visible := not DMPet.PetIntegration;
end;
procedure TPctPetSaleSearch.cdsSearchBeforeGetRecords(Sender: TObject;
var OwnerData: OleVariant);
begin
inherited;
with TMRSQLParam.Create do
try
if (edtSKU.Text <> '') then
begin
AddKey('P.SKU').AsString := edtSKU.Text;
KeyByName('P.SKU').Condition := tcLike;
end;
if (scBreed.Text <> '') then
begin
AddKey('P.IDBreed').AsString := scBreed.EditValue;
KeyByName('P.IDBreed').Condition := tcEquals;
end;
if (scStatus.Text <> '') then
begin
AddKey('P.IDStatus').AsString := scStatus.EditValue;
KeyByName('P.IDStatus').Condition := tcEquals;
end;
if (scSpecies.Text <> '') then
begin
AddKey('P.IDSpecies').AsString := scSpecies.EditValue;
KeyByName('P.IDSpecies').Condition := tcEquals;
end;
OwnerData := ParamString;
finally
Free;
end;
end;
procedure TPctPetSaleSearch.btnOkClick(Sender: TObject);
var
FDMThread : TDMWarrantyPrintThread;
FReportParam : TMRParams;
begin
if cdsSearch.Active and (cdsSearch.FieldByName('IDPetSale').AsInteger <> 0) then
begin
if (DMPet.ClientRpl or DMPet.CorpRpl) and (DMPet.GetPropertyDomain('PctDefaultStore') <> cdsSearch.FieldByName('IDStore').AsInteger) then
begin
MsgBox('You cannot re-print sales from the other store.', vbInformation + vbOKOnly);
Exit;
end;
try
DMPetCenter.GetWarrantyReport('IDWarrantyReport', cdsSearch.FieldByName('IDWarrantyReport').AsInteger);
FDMThread := TDMWarrantyPrintThread.Create(nil);
try
FReportParam := TMRParams.Create;
try
FReportParam.AddKey(CON_PARAM_TYPE);
FReportParam.KeyByName(CON_PARAM_TYPE).AsString := DMPet.FConType;
FReportParam.AddKey(CON_PARAM_CLIENT_ID);
FReportParam.KeyByName(CON_PARAM_CLIENT_ID).AsString := DMPet.FClientID;
FReportParam.AddKey(CON_PARAM_HOST);
FReportParam.KeyByName(CON_PARAM_HOST).AsString := DMPet.FHost;
FReportParam.AddKey(CON_PARAM_PORT);
FReportParam.KeyByName(CON_PARAM_PORT).AsString := DMPet.FPort;
FReportParam.AddKey(CON_PARAM_SOFTWARE);
FReportParam.KeyByName(CON_PARAM_SOFTWARE).AsString := DMPet.FSoftware;
FDMThread.Preview := (StrToIntDef(DMPet.GetAppProperty('WarrantyRep', 'Preview'), 1) = 1);
FDMThread.DefaulPrinter := DMPet.GetAppProperty('WarrantyRep', 'PrinterName');
FDMThread.cdsRepWarranty.Data := DMPetCenter.cdsRepWarranty.Data;
FDMThread.ConnectionParams := FReportParam;
FDMThread.PrintWarrantyFromPetCenter(cdsSearch.FieldByName('IDPetSale').AsInteger);
finally
FreeAndNil(FReportParam);
end;
finally
FreeAndNil(FDMThread);
end;
except
MsgBox('Report error._Check report configuration', vbCritical + vbOKOnly);
end;
end;
end;
procedure TPctPetSaleSearch.AfterSetParams;
begin
inherited;
FSKU := ParseParam(FParams, 'SKU');
if FSKU <> '' then
begin
edtSKU.Text := FSKU;
RefreshSearchList;
end;
end;
initialization
RegisterClass(TPctPetSaleSearch);
end.
|
program lab14_v30;
type
func = function(const x:real):real;
function bis(x:real):real;
begin
bis := sqrt( 1.96 - (power(x,3)/9) + 1/x ) - x;
end;
function bis1(x:real):real;
begin
bis1 := (power(4,1/3) - power(sin(x/10),2))/(sqrt(x)) -x;
end;
function rootBis(a,b,e:real; f:func):real;
var m:real;
begin
while (abs(a-b)>e) and (bis(a)>e) do begin
m := (a + b) / 2;
if f(a) * f(m) < 0 then b := m
else a := m;
end;
result := (a + b) / 2
end;
function rootIter(a,b,e:real; f:func):real;
var x1,x0:real;
begin
x1 := (a + b) / 2;
repeat
x0 := x1;
x1 := f(x0) + x0;
until abs(x0-x1)<e;
result := x1;
end;
var e,a,b,x:real;
e0:string;
begin
a := 0;
b := 3;
writeln('Введите точность');
readln(e0);
real.TryParse(e0,e);
writeln('Решение методом бисекций = ',rootBis(a,b,e,bis));
writeln(e);
x := rootIter(a,b,e,bis);
writeln('Решение методом итераций = ',x);
writeln('Значение функции в точке x1 = ', bis(x));
writeln;
writeln('#################===================#############');
writeln;
writeln('Решение методом бисекций = ',rootBis(a,b,e,bis1));
writeln(e);
x := rootIter(a,b,e,bis1);
writeln('Решение методом итераций = ',x);
writeln('Значение функции в точке x1 = ', bis1(x));
end.
|
{
Based on XProger' corexgine tool for font generation
}
unit uFont;
{$mode delphi}
interface
uses
windows,
classes,
sysutils;
type
TFontChar = class
ID : Char;
PosX, PosY : LongInt;
OffsetY, Width, Height : LongInt;
Data : PByteArray;
end;
TFontNode = class
constructor Create(const Rect: TRect);
destructor Destroy; override;
public
Block : Boolean;
Node : array [0..1] of TFontNode;
Rect : TRect;
function Insert(Width, Height: LongInt; out X, Y: LongInt): Boolean;
end;
{ TFontGenerator }
TFontGenerator = class
constructor Create; virtual;
destructor Destroy; override;
private
FNT : HFONT;
MDC : HDC;
BMP : HBITMAP;
BI : TBitmapInfo;
CharData : PByteArray;
MaxWidth, MaxHeight : LongInt;
public
TexWidth, TexHeight: LongInt;
TexData : PByteArray;
FontChar : array of TFontChar;
FontData : array [WideChar] of TFontChar;
Text : WideString;
procedure GenInit(const Face: WideString; Size: LongInt; Bold, Italic: Boolean);
procedure GenFree;
function GenChar(c: WideChar): TFontChar;
procedure AddChar(c: WideChar);
procedure AddChars(str: WideString);
procedure ClearChars;
function PackChars: LongInt;
// procedure Save(const FileName: string);
procedure SaveBmpToFile(const FileName: AnsiString);
function SaveBmpToStream(): TStream;
end;
implementation
function Recti(Left, Top, Right, Bottom: LongInt): TRect;
begin
Result.Left := Left;
Result.Top := Top;
Result.Right := Right;
Result.Bottom := Bottom;
end;
function ToPow2(x: LongInt): LongInt;
begin
Result := x - 1;
Result := Result or (Result shr 1);
Result := Result or (Result shr 2);
Result := Result or (Result shr 4);
Result := Result or (Result shr 8);
Result := Result or (Result shr 16);
Result := Result + 1;
end;
{$REGION 'TFontNode'}
constructor TFontNode.Create(const Rect: TRect);
begin
Self.Rect := Rect;
end;
destructor TFontNode.Destroy;
begin
if Node[0] <> nil then Node[0].Free;
if Node[1] <> nil then Node[1].Free;
end;
function TFontNode.Insert(Width, Height: LongInt; out X, Y: LongInt): Boolean;
var
dw, dh : LongInt;
begin
if (Node[0] <> nil) and (Node[1] <> nil) then
begin
Result := Node[0].Insert(Width, Height, X, Y);
if not Result then
Result := Node[1].Insert(Width, Height, X, Y);
end else
begin
dw := Rect.Right - Rect.Left;
dh := Rect.Bottom - Rect.Top;
if (dw < Width) or (dh < Height) or Block then
begin
Result := False;
Exit;
end else
if (dw = Width) and (dh = Height) then
begin
X := Rect.Left;
Y := Rect.Top;
Block := True;
Result := True;
Exit;
end else
with Rect do
if dw - Width > dh - Height then
begin
Node[0] := TFontNode.Create(Recti(Left, Top, Left + Width, Bottom));
Node[1] := TFontNode.Create(Recti(Left + Width, Top, Right, Bottom));
end else
begin
Node[0] := TFontNode.Create(Recti(Left, Top, Right, Top + Height));
Node[1] := TFontNode.Create(Recti(Left, Top + Height, Right, Bottom));
end;
Result := Node[0].Insert(Width, Height, X, Y);
end;
end;
{$ENDREGION}
{$REGION 'TFontDisplay'}
constructor TFontGenerator.Create;
begin
inherited Create();
//GenInit('Arial', 10, True, False);
//AddChars('0123456789');
//AddChars(' !@#$%^&*()_+|{}:"<>?-=\[];'',./~`');
//AddChars(UTF8Decode('abcdefghijklmnopqrstuvwxyz'));
//AddChars(UTF8Decode('ABCDEFGHIJKLMNOPQRSTUVWXYZ'));
//AddChars(UTF8Decode('абвгдеёжзийклмнопрстуфхцчшщъыьэюя'));
//AddChars(UTF8Decode('АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ'));
//PackChars;
//SaveBmpToFile('Arial_10b');
end;
destructor TFontGenerator.Destroy;
begin
GenFree;
ClearChars;
inherited;
end;
procedure TFontGenerator.GenInit(const Face: WideString; Size: LongInt; Bold, Italic: Boolean);
var
Weight : LongInt;
DC : LongWord;
TM : TTextMetricW;
begin
DC := GetDC(0);
if Bold then
Weight := FW_BOLD
else
Weight := FW_NORMAL;
FNT := CreateFontW(-MulDiv(Size, GetDeviceCaps(DC, LOGPIXELSY), 72), 0,
0, 0, Weight, Byte(Italic), 0, 0, DEFAULT_CHARSET, 0, 0,
ANTIALIASED_QUALITY, 0, PWideChar(Face));
if FNT = 0 then
Exit;
MDC := CreateCompatibleDC(DC);
SelectObject(MDC, FNT);
GetTextMetricsW(MDC, @TM);
MaxWidth := TM.tmMaxCharWidth;
MaxHeight := TM.tmHeight;
CharData := GetMemory(MaxWidth * MaxHeight * 4);
BMP := CreateCompatibleBitmap(DC, MaxWidth, MaxHeight);
// Fill Black
SelectObject(MDC, BMP);
SetBkMode(MDC, TRANSPARENT);
SetTextColor(MDC, $FFFFFF);
ZeroMemory(@BI, SizeOf(BI));
with BI.bmiHeader do
begin
biSize := SizeOf(BI.bmiHeader);
biWidth := MaxWidth;
biHeight := MaxHeight;
biPlanes := 1;
biBitCount := 32;
biSizeImage := biWidth * biHeight * biBitCount div 8;
end;
ReleaseDC(0, DC);
end;
procedure TFontGenerator.GenFree;
begin
if TexData <> nil then
begin
FreeMemory(TexData);
TexData := nil;;
end;
FreeMemory(CharData);
DeleteObject(BMP);
DeleteObject(FNT);
DeleteDC(MDC);
end;
function TFontGenerator.GenChar(c: WideChar): TFontChar;
function ScanLine(Offset: LongInt; Vert: Boolean): Boolean;
var
i, c, d : LongInt;
p : ^Byte;
begin
if Vert then
begin
p := @CharData[Offset * 4];
c := MaxWidth * 4;
d := MaxHeight;
end else
begin
p := @CharData[Offset * MaxWidth * 4];
c := 4;
d := MaxWidth;
end;
for i := 0 to d - 1 do
if p^ <> 0 then
begin
Result := True;
Exit;
end else
Inc(Integer(p), c);
Result := False;
end;
var
i, x, y : LongInt;
CharRect : TRect;
Size : Windows.TSize;
begin
CharRect := Recti(0, 0, MaxWidth, MaxHeight);
FillRect(MDC, Windows.TRect(CharRect), GetStockObject(BLACK_BRUSH));
TextOutW(MDC, 0, 0, @c, 1);
// get char bitmap data
GDIFlush;
GetDIBits(MDC, BMP, 0, MaxHeight, CharData, BI, DIB_RGB_COLORS);
GetTextExtentPoint32W(MDC, @c, 1, Size);
CharRect := Recti(0, 0, Size.cx, 1);
// Top
for y := 0 to MaxHeight - 1 do
if ScanLine(MaxHeight - y - 1, False) then
begin
CharRect.Top := y;
break;
end;
// Bottom
for y := MaxHeight - 1 downto 0 do
if ScanLine(MaxHeight - y - 1, False) then
begin
CharRect.Bottom := y;
break;
end;
// Left
for x := 0 to MaxWidth - 1 do
if ScanLine(x, True) then
begin
CharRect.Left := x;
break;
end;
// Right
for x := MaxWidth - 1 downto 0 do
if ScanLine(x, True) then
begin
CharRect.Right := x;
break;
end;
// get char trimmed bitmap data
Result := TFontChar.Create;
Result.ID := c;
Result.OffsetY := CharRect.Top;
Result.Width := CharRect.Right - CharRect.Left + 1;
Result.Height := CharRect.Bottom - CharRect.Top + 1;
Result.Data := GetMemory(Result.Width * Result.Height);
i := 0;
for y := CharRect.Top to CharRect.Bottom do
for x := CharRect.Left to CharRect.Right do
begin
Result.Data[i] := CharData[((MaxHeight - y - 1) * MaxWidth + x) * 4];
Inc(i);
end;
end;
procedure TFontGenerator.AddChar(c: WideChar);
var
f : TFontChar;
i, j : LongInt;
begin
f := GenChar(c);
SetLength(FontChar, Length(FontChar) + 1);
j := Length(FontChar) - 1;
for i := 0 to Length(FontChar) - 2 do
with FontChar[i] do
if Width * Height < f.Width * f.Height then
begin
for j := Length(FontChar) - 1 downto i + 1 do
FontChar[j] := FontChar[j - 1];
j := i;
break;
end;
FontChar[j] := f;
FontData[f.ID] := f;
end;
procedure TFontGenerator.AddChars(str: WideString);
var
i : LongInt;
begin
for i := 1 to Length(str) do
AddChar(str[i]);
end;
procedure TFontGenerator.ClearChars;
var
i : LongInt;
begin
for i := 0 to Length(FontChar) - 1 do
begin
FreeMemory(FontChar[i].Data);
FontChar[i].Free;
end;
SetLength(FontChar, 0);
end;
function TFontGenerator.PackChars: LongInt;
var
i, j : LongInt;
Node : TFontNode;
function Pack(Idx: LongInt): Boolean;
var
i, ix, iy : LongInt;
begin
i := 0;
with FontChar[Idx] do
if Node.Insert(Width + 1, Height + 1, PosX, PosY) then
begin
for iy := PosY to PosY + Height - 1 do
for ix := PosX to PosX + Width - 1 do
begin
TexData[(iy * TexWidth + ix) * 2 + 1] := Data[i]; // write alpha value
Inc(i);
end;
Result := True;
end else
Result := False;
end;
begin
// Get minimum texture area
j := 0;
for i := 0 to Length(FontChar) - 1 do
Inc(j, FontChar[i].Width * FontChar[i].Height);
j := ToPow2(Round(sqrt(j)));
TexWidth := j;
TexHeight := j div 2;
Result := Length(FontChar);
while TexHeight < 4096 do
begin
if TexData <> nil then
FreeMemory(TexData);
TexData := GetMemory(TexWidth * TexHeight * 2);
// fill texture data with default values
for i := 0 to TexWidth * TexHeight - 1 do
begin
TexData[i * 2 + 0] := 255; // luminance
TexData[i * 2 + 1] := 0; // alpha
end;
Result := Length(FontChar);
Node := TFontNode.Create(Recti(0, 0, TexWidth, TexHeight));
for i := 0 to Length(FontChar) - 1 do
if Pack(i) then
Dec(Result)
else
break;
Node.Free;
if Result = 0 then
break;
if TexHeight < TexWidth then
TexHeight := TexHeight * 2
else
TexWidth := TexWidth * 2;
end;
if Result > 0 then
Writeln('Can''t pack ', Result, ' chars');
end;
(*
procedure TFontGenerator.Save(const FileName: string);
const
DDSD_CAPS = $0001;
DDSD_HEIGHT = $0002;
DDSD_WIDTH = $0004;
DDSD_PIXELFORMAT = $1000;
DDSCAPS_TEXTURE = $1000;
DDPF_ALPHAPIXELS = $0001;
DDPF_LUMINANCE = $20000;
var
i : LongInt;
FileChar : record
ID : WideChar;
py : Word;
w, h : Word;
tx, ty, tw, th : Single;
end;
DDS : record
dwMagic : LongWord;
dwSize : LongInt;
dwFlags : LongWord;
dwHeight : LongWord;
dwWidth : LongWord;
dwPOLSize : LongWord;
dwDepth : LongWord;
dwMipMapCount : LongInt;
FontMagic : LongWord;
FontOffset : LongWord;
SomeData1 : array [0..8] of LongWord;
pfSize : LongWord;
pfFlags : LongWord;
pfFourCC : LongWord;
pfRGBbpp : LongWord;
pfRMask : LongWord;
pfGMask : LongWord;
pfBMask : LongWord;
pfAMask : LongWord;
dwCaps1 : LongWord;
dwCaps2 : LongWord;
SomeData3 : array [0..2] of LongWord;
end;
Stream : TglrStream;
begin
Stream := TglrStream.Init(FileName + '.dds', True);
// save dds data
FillChar(DDS, SizeOf(DDS), 0);
with DDS do
begin
dwMagic := $20534444;
dwSize := SizeOf(DDS) - 4; // -4 = Magic size
dwFlags := DDSD_CAPS or DDSD_HEIGHT or DDSD_WIDTH or DDSD_PIXELFORMAT;
dwHeight := TexHeight;
dwWidth := TexWidth;
dwPOLSize := dwWidth * 2;
dwCaps1 := DDSCAPS_TEXTURE;
FontMagic := $2B6E6678;
FontOffset := SizeOf(DDS) + dwWidth * dwHeight * 2;
pfSize := 32;
pfFlags := DDPF_LUMINANCE or DDPF_ALPHAPIXELS;
pfRGBbpp := 16;
pfRMask := $00FF;
pfAMask := $FF00;
end;
Stream.Write(DDS, SizeOf(DDS));
Stream.Write(TexData^, DDS.dwWidth * DDS.dwHeight * 2);
if Stream <> nil then
begin
i := Length(FontChar);
Stream.Write(i, SizeOf(i));
for i := 0 to Length(FontChar) - 1 do
begin
with FontChar[i], FileChar do
begin
py := OffsetY;
tx := PosX / TexWidth;
ty := PosY / TexHeight;
tw := Width / TexWidth;
th := Height / TexHeight;
w := Width;
h := Height;
end;
FileChar.ID := FontChar[i].ID;
Stream.Write(FileChar, SizeOf(FileChar));
end;
Stream.Free;
end;
end;
*)
procedure TFontGenerator.SaveBmpToFile(const FileName: AnsiString);
var
Stream: TFileStream;
fh: BITMAPFILEHEADER;
ih: BITMAPINFOHEADER;
texdata2: PByteArray;
i: LongWord;
FileChar : record
tx, ty, tw, th : Single; // 16 bytes
py : Word; // 2 bytes
w, h : Word; // 4 bytes
ID : AnsiChar; // 1 bytes
end;
begin
Stream := TFileStream.Create(FileName + '.bmp', fmCreate);
FillChar(fh, SizeOf(BITMAPFILEHEADER), 0);
FillChar(ih, SizeOf(BITMAPINFOHEADER), 0);
fh.bfType := $4D42;
fh.bfReserved1 := $0F86;
ih.biSize := SizeOf(BITMAPINFOHEADER);
ih.biWidth := TexWidth;
ih.biHeight := -TexHeight;
ih.biPlanes := 1;
ih.biBitCount := 32;
ih.biSizeImage := TexWidth * TexHeight * 4;
Stream.Write(fh, SizeOf(BITMAPFILEHEADER));
Stream.Write(ih, SizeOf(BITMAPINFOHEADER));
texdata2 := GetMemory(TexWidth * TexHeight * 4);
FillChar(texdata2^, TexWidth * TexHeight * 4, 255);
for i := 0 to (TexWidth * TexHeight - 1) do
texdata2^[i * 4 + 3] := TexData^[i * 2 + 1];
Stream.Write(texdata2^, TexWidth * TexHeight * 4);
FreeMemory(texdata2);
i := Length(FontChar);
Stream.Write(i, SizeOf(i));
for i := 0 to Length(FontChar) - 1 do
begin
with FontChar[i], FileChar do
begin
py := OffsetY;
tx := PosX / TexWidth;
ty := PosY / TexHeight;
tw := Width / TexWidth;
th := Height / TexHeight;
w := Width;
h := Height;
end;
FileChar.ID := FontChar[i].ID;
Stream.Write(FileChar, SizeOf(FileChar));
end;
Stream.Free();
end;
function TFontGenerator.SaveBmpToStream: TStream;
var
fh: BITMAPFILEHEADER;
ih: BITMAPINFOHEADER;
texdata2: PByteArray;
i: Integer;
size: LongInt;
begin
Result := TMemoryStream.Create();
size := SizeOf(BITMAPFILEHEADER) + SizeOf(BITMAPINFOHEADER) + TexWidth * TexHeight * 4;
(Result as TMemoryStream).SetSize(size);
FillChar(fh, SizeOf(BITMAPFILEHEADER), 0);
FillChar(ih, SizeOf(BITMAPINFOHEADER), 0);
fh.bfType := $4D42;
fh.bfReserved1 := $0F86;
ih.biSize := SizeOf(BITMAPINFOHEADER);
ih.biWidth := TexWidth;
ih.biHeight := -TexHeight;
ih.biPlanes := 1;
ih.biBitCount := 32;
ih.biSizeImage := TexWidth * TexHeight * 4;
Result.Write(fh, SizeOf(BITMAPFILEHEADER));
Result.Write(ih, SizeOf(BITMAPINFOHEADER));
texdata2 := GetMemory(TexWidth * TexHeight * 4);
FillChar(texdata2^, TexWidth * TexHeight * 4, 255);
for i := 0 to (TexWidth * TexHeight - 1) do
texdata2^[i * 4 + 3] := TexData^[i * 2 + 1];
Result.Write(texdata2^, TexWidth * TexHeight * 4);
FreeMemory(texdata2);
end;
{$ENDREGION}
end.
|
(***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is TurboPower Async Professional
*
* The Initial Developer of the Original Code is
* TurboPower Software
*
* Portions created by the Initial Developer are Copyright (C) 1991-2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** *)
{*********************************************************}
{* EXVIEW0.PAS 4.06 *}
{*********************************************************}
{**********************Description************************}
{* Views an Async Professional Fax (APF) file. See the *}
(* ViewFax project for a more inclusive example. *)
{*********************************************************}
unit Exview0;
interface
uses
WinTypes, WinProcs, SysUtils, Messages, Classes, Graphics, Controls,
Forms, Dialogs, AdFView, OoMisc;
type
TForm1 = class(TForm)
ApdFaxViewer1: TApdFaxViewer;
OpenDialog1: TOpenDialog;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.FormCreate(Sender: TObject);
begin
if OpenDialog1.Execute then
ApdFaxViewer1.FileName := OpenDialog1.FileName
else
Halt(1);
end;
end.
|
unit feli_crypto;
{$mode objfpc}
interface
type
FeliCrypto = class(TObject)
public
class function hashMD5(payload: ansiString): ansiString; static;
class function generateSalt(saltLength: integer): ansiString; static;
end;
implementation
uses
feli_constants,
feli_stack_tracer,
md5;
class function FeliCrypto.hashMD5(payload: ansiString): ansiString; static;
begin
FeliStackTrace.trace('begin', 'class function FeliCrypto.hashMD5(payload: ansiString): ansiString; static;');
result := MD5Print(MD5String(payload));
FeliStackTrace.trace('end', 'class function FeliCrypto.hashMD5(payload: ansiString): ansiString; static;');
end;
class function FeliCrypto.generateSalt(saltLength: integer): ansiString; static;
var
output: ansiString;
i, charAt: integer;
begin
FeliStackTrace.trace('begin', 'class function FeliCrypto.generateSalt(saltLength: integer): ansiString; static;');
output := '';
for i := 1 To saltLength do
begin
charAt := random(length(chars)) + 1;
output := output + chars[charAt];
end;
result := output;
FeliStackTrace.trace('end', 'class function FeliCrypto.generateSalt(saltLength: integer): ansiString; static;');
end;
end.
|
unit UIOptionsBase;
interface
uses
Windows,
Messages,
SysUtils,
Variants,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
ExtCtrls,
StdCtrls,
Buttons,
ComCtrls,
OmniXML,
uOmniXML,
ActnList,
uI2XConstants,
//uImage2XML,
ImgList,
uStrUtil,
uHashTable,
uFileDir;
type
TOptionsController = class(TObject)
private
protected
FOnChange : TNotifyEvent;
FIsDirty : boolean;
procedure OnChangeHandler();
public
property OnChange : TNotifyEvent read FOnChange write FOnChange;
property IsDirty : boolean read FIsDirty write FIsDirty;
function AsXML() : string; virtual; abstract;
procedure ApplyChanges(); virtual; abstract;
constructor Create(); virtual;
destructor Destroy(); override;
end;
TOnOptionsUpdate = procedure( Options : TOptionsController ) of object;
TOnOptionGroupSelect = procedure( const SelectedGroup : string ) of object;
TOnTreeNodeCheckBoxClick = procedure( Node :TTreeNode; isChecked : boolean ) of object;
TOptionsBaseUI = class(TForm)
pnlLeft: TPanel;
pnlRight: TPanel;
splitter: TSplitter;
pnlBottom: TPanel;
btnCancel: TBitBtn;
btnApply: TBitBtn;
tvOptions: TTreeView;
ActionList1: TActionList;
acApply: TAction;
acCancel: TAction;
ImageList1: TImageList;
procedure btnApplyClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure tvOptionsClick(Sender: TObject);
procedure tvOptionsKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormDestroy(Sender: TObject); virtual;
private
FOnOptionGroupSelect : TOnOptionGroupSelect;
FOnTreeNodeCheckBoxClick : TOnTreeNodeCheckBoxClick;
procedure OptionsChanged( Sender : TObject );
procedure setOptionsController(const Value: TOptionsController);
procedure OnTreeNodeCheckBox(Node: TTreeNode; isChecked: boolean);
protected
FOptionsController : TOptionsController;
FOnOptionsUpdate : TOnOptionsUpdate;
FEventKey : THashStringTable;
FFileDir : CFileDir;
procedure XML2Tree(tree: TTreeView; XMLDoc: IXMLDocument);
Procedure ToggleTreeViewCheckBoxes( Node :TTreeNode; cUnChecked, cChecked, cRadioUnchecked, cRadioChecked :integer );
public
procedure OptionGroupSelected( const SelectedGroup : string ); virtual;
function LoadOptionsAndDisplay( Options : TOptionsController ) : boolean; virtual;
procedure FormCreate(Sender: TObject); overload; virtual;
procedure FormCreate(Sender: TObject; Options : TOptionsController ); overload; virtual;
property OnOptionGroupSelect : TOnOptionGroupSelect read FOnOptionGroupSelect write FOnOptionGroupSelect;
property OnOptionsUpdateEvent : TOnOptionsUpdate read FOnOptionsUpdate write FOnOptionsUpdate;
property OnTreeNodeCheckBoxClickEvent : TOnTreeNodeCheckBoxClick read FOnTreeNodeCheckBoxClick write FOnTreeNodeCheckBoxClick;
property OptionsController : TOptionsController read FOptionsController write setOptionsController;
end;
var
OptionsBaseUI: TOptionsBaseUI;
implementation
{$R *.dfm}
procedure TOptionsBaseUI.XML2Tree(tree: TTreeView;
XMLDoc: IXMLDocument);
var
iNode : IXMLNode;
procedure ProcessNode(
Node : IXMLNode;
tn : TTreeNode);
var
cNode : IXMLNode;
sID, sType, sDesc, sDefault, sEventKey, sTestObjectPtr : string;
begin
if Node = nil then Exit;
with Node do
begin
sID := Node.NodeName;
sType := GetAttr( Node, 'type', '' );
sDesc := GetAttr( Node, 'desc', '' );
sDefault := GetAttr( Node, 'default', '' );
sEventKey := GetAttr( Node, 'eventkey', '' );
sTestObjectPtr := GetAttr( Node, 'ptr', '0' );
if ( Length(sDesc) > 0 ) then
tn := tree.Items.AddChild(tn, sDesc)
else
tn := tree.Items.AddChild(tn, sID);
if ( sTestObjectPtr <> '0' ) then
tn.Data := pointer(strToInt(sTestObjectPtr));
if ( sType = 'checkbox' ) then
if ( uStrUtil.StrToBool( sDefault, 'true', 'false' ) ) then
tn.StateIndex := cFlatChecked
else
tn.StateIndex := cFlatUnCheck;
self.FEventKey.Add( IntToStr(tn.AbsoluteIndex), sEventKey );
end;
cNode := Node.FirstChild;
while cNode <> nil do
begin
ProcessNode(cNode, tn);
cNode := cNode.NextSibling;
end;
end; (*ProcessNode*)
begin
tree.Items.Clear;
//XMLDoc.FileName := ChangeFileExt(ParamStr(0),'.XML');
//XMLDoc.Active := True;
iNode := XMLDoc.DocumentElement.FirstChild;
while iNode <> nil do
begin
ProcessNode(iNode,nil);
iNode := iNode.NextSibling;
end;
End;
procedure TOptionsBaseUI.FormCreate(Sender: TObject);
begin
FEventKey := THashStringTable.Create();
self.OnOptionGroupSelect := OptionGroupSelected;
FFileDir := CFileDir.Create;
end;
procedure TOptionsBaseUI.btnApplyClick(Sender: TObject);
begin
if ( Assigned( self.FOnOptionsUpdate ) ) then
FOnOptionsUpdate( self.FOptionsController );
self.FOptionsController.ApplyChanges;
self.Hide;
end;
procedure TOptionsBaseUI.btnCancelClick(Sender: TObject);
begin
self.Hide;
end;
procedure TOptionsBaseUI.FormCreate(Sender: TObject; Options : TOptionsController );
begin
FEventKey := THashStringTable.Create();
self.OnOptionGroupSelect := OptionGroupSelected;
self.LoadOptionsAndDisplay( Options );
Options.OnChange := self.OptionsChanged;
btnApply.Enabled := false;
FFileDir := CFileDir.Create;
end;
procedure TOptionsBaseUI.FormDestroy(Sender: TObject);
begin
FreeAndNil( FEventKey );
FreeAndNil( FFileDir );
end;
function TOptionsBaseUI.LoadOptionsAndDisplay(Options : TOptionsController) : boolean;
var
FXmlDoc : IXMLDocument;
begin
Result := false;
FXmlDoc := CreateXMLDoc();
if ( FXmlDoc.LoadXML( Options.AsXML )) then begin
XML2Tree( self.tvOptions, FXmlDoc );
Result := true;
end;
self.Refresh;
self.Show;
End;
procedure TOptionsBaseUI.OptionGroupSelected(const SelectedGroup: string);
begin
///
end;
procedure TOptionsBaseUI.OptionsChanged(Sender: TObject);
begin
btnApply.Enabled := self.FOptionsController.IsDirty;
end;
procedure TOptionsBaseUI.setOptionsController(const Value: TOptionsController);
begin
FOptionsController := Value;
FOptionsController.OnChange := self.OptionsChanged;
end;
Procedure TOptionsBaseUI.OnTreeNodeCheckBox( Node :TTreeNode; isChecked : boolean );
Begin
if ( Assigned( self.FOnTreeNodeCheckBoxClick ) ) then
self.FOnTreeNodeCheckBoxClick( Node, isChecked );
End;
// Thank you http://delphi.about.com/od/vclusing/l/aa092104a.htm
Procedure TOptionsBaseUI.ToggleTreeViewCheckBoxes( Node :TTreeNode;
cUnChecked, cChecked, cRadioUnchecked, cRadioChecked :integer);
var
tmp:TTreeNode;
Begin
if Assigned(Node) then
begin
if (Node.StateIndex in [cUnChecked,cChecked]) then begin
if Node.StateIndex = cUnChecked then begin
Node.StateIndex := cChecked;
OnTreeNodeCheckBox( Node, true );
end else if Node.StateIndex = cChecked then begin
Node.StateIndex := cUnChecked;
OnTreeNodeCheckBox( Node, false );
end;
tmp := Node.getFirstChild;
while Assigned(tmp) do
begin
if (tmp.StateIndex in
[cUnChecked,cChecked]) then begin
tmp.StateIndex := Node.StateIndex;
OnTreeNodeCheckBox( tmp, (tmp.StateIndex = cChecked) );
end;
tmp := tmp.getNextSibling;
end;
end else begin
tmp := Node.Parent;
if not Assigned(tmp) then
tmp := TTreeView(Node.TreeView).Items.getFirstNode
else
tmp := tmp.getFirstChild;
while Assigned(tmp) do
begin
if (tmp.StateIndex in
[cRadioUnChecked,cRadioChecked]) then begin
tmp.StateIndex := cRadioUnChecked;
OnTreeNodeCheckBox( tmp, false );
end;
tmp := tmp.getNextSibling;
end;
OnTreeNodeCheckBox( Node, true );
Node.StateIndex := cRadioChecked;
end; // if StateIndex = cRadioUnChecked
end; // if Assigned(Node)
End;
procedure TOptionsBaseUI.tvOptionsClick(Sender: TObject);
Var
P:TPoint;
n : Pointer;
Begin
GetCursorPos(P);
P := tvOptions.ScreenToClient(P);
if (htOnStateIcon in tvOptions.GetHitTestInfoAt(P.X,P.Y)) then begin
//if ( tvOptions.Selected <> nil ) then begin
//n := tvOptions.Selected.Data;
//if ( n <> nil ) then begin
ToggleTreeViewCheckBoxes(
tvOptions.Selected,
cFlatUnCheck,
cFlatChecked,
cFlatRadioUnCheck,
cFlatRadioChecked);
//end;
end;
if ( tvOptions.Selected <> nil ) then
if ( Assigned( self.FOnOptionGroupSelect ) ) then
self.FOnOptionGroupSelect( self.FEventKey[IntToStr(tvOptions.Selected.AbsoluteIndex)] );
End;
procedure TOptionsBaseUI.tvOptionsKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (Key = VK_SPACE) and Assigned(tvOptions.Selected) then
ToggleTreeViewCheckBoxes(tvOptions.Selected,cFlatUnCheck,cFlatChecked,cFlatRadioUnCheck,cFlatRadioChecked);
end;
(*ToggleTreeViewCheckBoxes*)
{ TOptionsController }
constructor TOptionsController.Create;
begin
FIsDirty := false;
end;
destructor TOptionsController.Destroy;
begin
end;
procedure TOptionsController.OnChangeHandler;
begin
self.FIsDirty := true;
if ( Assigned( self.FOnChange )) then
self.FOnChange( self );
end;
END.
|
(*++
Copyright (c) Microsoft Corporation. All rights reserved.
Module Name:
codecapi.h
Abstract:
CodecAPI Definitions.
--*)
// Updated to SDK 10.0.17763.0
// (c) Translation to Pascal by Norbert Sonnleitner
unit Win32.CodecAPI;
{$mode delphi}
interface
uses
Windows, Classes, SysUtils;
const
// Windows CodecAPI Properties
// Legend for the
// Reference VariantType VariantField
// UINT8 VT_UI1 bVal
// UINT16 VT_UI2 uiVal
// UINT32 VT_UI4 ulVal
// UINT64 VT_UI8 ullVal
// INT8 VT_I1 eVal
// INT16 VT_I2 iVal
// INT32 VT_I4 lVal
// INT64 VT_I8 llVal
// BOOL VT_BOOL boolVal
// GUID VT_BSTR bstrVal (guid string)
// UINT32/UNINT32 VT_UI8 ullVal (ratio)
// { Static definitions
STATIC_CODECAPI_AVEncCommonFormatConstraint: TGUID = '{57cbb9b8-116f-4951-b40c-c2a035ed8f17}';
STATIC_CODECAPI_GUID_AVEncCommonFormatUnSpecified: TGUID = '{af46a35a-6024-4525-a48a-094b97f5b3c2}';
STATIC_CODECAPI_GUID_AVEncCommonFormatDVD_V: TGUID = '{cc9598c4-e7fe-451d-b1ca-761bc840b7f3}';
STATIC_CODECAPI_GUID_AVEncCommonFormatDVD_DashVR: TGUID = '{e55199d6-044c-4dae-a488-531ed306235b}';
STATIC_CODECAPI_GUID_AVEncCommonFormatDVD_PlusVR: TGUID = '{e74c6f2e-ec37-478d-9af4-a5e135b6271c}';
STATIC_CODECAPI_GUID_AVEncCommonFormatVCD: TGUID = '{95035bf7-9d90-40ff-ad5c-5cf8cf71ca1d}';
STATIC_CODECAPI_GUID_AVEncCommonFormatSVCD: TGUID = '{51d85818-8220-448c-8066-d69bed16c9ad}';
STATIC_CODECAPI_GUID_AVEncCommonFormatATSC: TGUID = '{8d7b897c-a019-4670-aa76-2edcac7ac296}';
STATIC_CODECAPI_GUID_AVEncCommonFormatDVB: TGUID = '{71830d8f-6c33-430d-844b-c2705baae6db}';
STATIC_CODECAPI_GUID_AVEncCommonFormatMP3: TGUID = '{349733cd-eb08-4dc2-8197-e49835ef828b}';
STATIC_CODECAPI_GUID_AVEncCommonFormatHighMAT: TGUID = '{1eabe760-fb2b-4928-90d1-78db88eee889}';
STATIC_CODECAPI_GUID_AVEncCommonFormatHighMPV: TGUID = '{a2d25db8-b8f9-42c2-8bc7-0b93cf604788}';
STATIC_CODECAPI_AVEncCodecType: TGUID = '{08af4ac1-f3f2-4c74-9dcf-37f2ec79f826}';
STATIC_CODECAPI_GUID_AVEncMPEG1Video: TGUID = '{c8dafefe-da1e-4774-b27d-11830c16b1fe}';
STATIC_CODECAPI_GUID_AVEncMPEG2Video: TGUID = '{046dc19a-6677-4aaa-a31d-c1ab716f4560}';
STATIC_CODECAPI_GUID_AVEncMPEG1Audio: TGUID = '{d4dd1362-cd4a-4cd6-8138-b94db4542b04}';
STATIC_CODECAPI_GUID_AVEncMPEG2Audio: TGUID = '{ee4cbb1f-9c3f-4770-92b5-fcb7c2a8d381}';
STATIC_CODECAPI_GUID_AVEncWMV: TGUID = '{4e0fef9b-1d43-41bd-b8bd-4d7bf7457a2a}';
STATIC_CODECAPI_GUID_AVEndMPEG4Video: TGUID = '{dd37b12a-9503-4f8b-b8d0-324a00c0a1cf}';
STATIC_CODECAPI_GUID_AVEncH264Video: TGUID = '{95044eab-31b3-47de-8e75-38a42bb03e28}';
STATIC_CODECAPI_GUID_AVEncDV: TGUID = '{09b769c7-3329-44fb-8954-fa30937d3d5a}';
STATIC_CODECAPI_GUID_AVEncWMAPro: TGUID = '{1955f90c-33f7-4a68-ab81-53f5657125c4}';
STATIC_CODECAPI_GUID_AVEncWMALossless: TGUID = '{55ca7265-23d8-4761-9031-b74fbe12f4c1}';
STATIC_CODECAPI_GUID_AVEncWMAVoice: TGUID = '{13ed18cb-50e8-4276-a288-a6aa228382d9}';
STATIC_CODECAPI_GUID_AVEncDolbyDigitalPro: TGUID = '{f5be76cc-0ff8-40eb-9cb1-bba94004d44f}';
STATIC_CODECAPI_GUID_AVEncDolbyDigitalConsumer: TGUID = '{c1a7bf6c-0059-4bfa-94ef-ef747a768d52}';
STATIC_CODECAPI_GUID_AVEncDolbyDigitalPlus: TGUID = '{698d1b80-f7dd-415c-971c-42492a2056c6}';
STATIC_CODECAPI_GUID_AVEncDTSHD: TGUID = '{2052e630-469d-4bfb-80ca-1d656e7e918f}';
STATIC_CODECAPI_GUID_AVEncDTS: TGUID = '{45fbcaa2-5e6e-4ab0-8893-5903bee93acf}';
STATIC_CODECAPI_GUID_AVEncMLP: TGUID = '{05f73e29-f0d1-431e-a41c-a47432ec5a66}';
STATIC_CODECAPI_GUID_AVEncPCM: TGUID = '{844be7f4-26cf-4779-b386-cc05d187990c}';
STATIC_CODECAPI_GUID_AVEncSDDS: TGUID = '{1dc1b82f-11c8-4c71-b7b6-ee3eb9bc2b94}';
STATIC_CODECAPI_AVEncCommonRateControlMode: TGUID = '{1c0608e9-370c-4710-8a58-cb6181c42423}';
STATIC_CODECAPI_AVEncCommonLowLatency: TGUID = '{9d3ecd55-89e8-490a-970a-0c9548d5a56e}';
STATIC_CODECAPI_AVEncCommonMultipassMode: TGUID = '{22533d4c-47e1-41b5-9352-a2b7780e7ac4}';
STATIC_CODECAPI_AVEncCommonPassStart: TGUID = '{6a67739f-4eb5-4385-9928-f276a939ef95}';
STATIC_CODECAPI_AVEncCommonPassEnd: TGUID = '{0e3d01bc-c85c-467d-8b60-c41012ee3bf6}';
STATIC_CODECAPI_AVEncCommonRealTime: TGUID = '{143a0ff6-a131-43da-b81e-98fbb8ec378e}';
STATIC_CODECAPI_AVEncCommonQuality: TGUID = '{fcbf57a3-7ea5-4b0c-9644-69b40c39c391}';
STATIC_CODECAPI_AVEncCommonQualityVsSpeed: TGUID = '{98332df8-03cd-476b-89fa-3f9e442dec9f}';
STATIC_CODECAPI_AVEncCommonTranscodeEncodingProfile: TGUID = '{6947787C-F508-4EA9-B1E9-A1FE3A49FBC9}';
STATIC_CODECAPI_AVEncCommonMeanBitRate: TGUID = '{f7222374-2144-4815-b550-a37f8e12ee52}';
STATIC_CODECAPI_AVEncCommonMeanBitRateInterval: TGUID = '{bfaa2f0c-cb82-4bc0-8474-f06a8a0d0258}';
STATIC_CODECAPI_AVEncCommonMaxBitRate: TGUID = '{9651eae4-39b9-4ebf-85ef-d7f444ec7465}';
STATIC_CODECAPI_AVEncCommonMinBitRate: TGUID = '{101405b2-2083-4034-a806-efbeddd7c9ff}';
STATIC_CODECAPI_AVEncCommonBufferSize: TGUID = '{0db96574-b6a4-4c8b-8106-3773de0310cd}';
STATIC_CODECAPI_AVEncCommonBufferInLevel: TGUID = '{d9c5c8db-fc74-4064-94e9-cd19f947ed45}';
STATIC_CODECAPI_AVEncCommonBufferOutLevel: TGUID = '{ccae7f49-d0bc-4e3d-a57e-fb5740140069}';
STATIC_CODECAPI_AVEncCommonStreamEndHandling: TGUID = '{6aad30af-6ba8-4ccc-8fca-18d19beaeb1c}';
STATIC_CODECAPI_AVEncStatCommonCompletedPasses: TGUID = '{3e5de533-9df7-438c-854f-9f7dd3683d34}';
STATIC_CODECAPI_AVEncVideoOutputFrameRate: TGUID = '{ea85e7c3-9567-4d99-87c4-02c1c278ca7c}';
STATIC_CODECAPI_AVEncVideoOutputFrameRateConversion: TGUID = '{8c068bf4-369a-4ba3-82fd-b2518fb3396e}';
STATIC_CODECAPI_AVEncVideoPixelAspectRatio: TGUID = '{3cdc718f-b3e9-4eb6-a57f-cf1f1b321b87}';
STATIC_CODECAPI_AVEncVideoForceSourceScanType: TGUID = '{1ef2065f-058a-4765-a4fc-8a864c103012}';
STATIC_CODECAPI_AVEncVideoNoOfFieldsToEncode: TGUID = '{61e4bbe2-4ee0-40e7-80ab-51ddeebe6291}';
STATIC_CODECAPI_AVEncVideoNoOfFieldsToSkip: TGUID = '{a97e1240-1427-4c16-a7f7-3dcfd8ba4cc5}';
STATIC_CODECAPI_AVEncVideoEncodeDimension: TGUID = '{1074df28-7e0f-47a4-a453-cdd73870f5ce}';
STATIC_CODECAPI_AVEncVideoEncodeOffsetOrigin: TGUID = '{6bc098fe-a71a-4454-852e-4d2ddeb2cd24}';
STATIC_CODECAPI_AVEncVideoDisplayDimension: TGUID = '{de053668-f4ec-47a9-86d0-836770f0c1d5}';
STATIC_CODECAPI_AVEncVideoOutputScanType: TGUID = '{460b5576-842e-49ab-a62d-b36f7312c9db}';
STATIC_CODECAPI_AVEncVideoInverseTelecineEnable: TGUID = '{2ea9098b-e76d-4ccd-a030-d3b889c1b64c}';
STATIC_CODECAPI_AVEncVideoInverseTelecineThreshold: TGUID = '{40247d84-e895-497f-b44c-b74560acfe27}';
STATIC_CODECAPI_AVEncVideoSourceFilmContent: TGUID = '{1791c64b-ccfc-4827-a0ed-2557793b2b1c}';
STATIC_CODECAPI_AVEncVideoSourceIsBW: TGUID = '{42ffc49b-1812-4fdc-8d24-7054c521e6eb}';
STATIC_CODECAPI_AVEncVideoFieldSwap: TGUID = '{fefd7569-4e0a-49f2-9f2b-360ea48c19a2}';
STATIC_CODECAPI_AVEncVideoInputChromaResolution: TGUID = '{bb0cec33-16f1-47b0-8a88-37815bee1739}';
STATIC_CODECAPI_AVEncVideoOutputChromaResolution: TGUID = '{6097b4c9-7c1d-4e64-bfcc-9e9765318ae7}';
STATIC_CODECAPI_AVEncVideoInputChromaSubsampling: TGUID = '{a8e73a39-4435-4ec3-a6ea-98300f4b36f7}';
STATIC_CODECAPI_AVEncVideoOutputChromaSubsampling: TGUID = '{fa561c6c-7d17-44f0-83c9-32ed12e96343}';
STATIC_CODECAPI_AVEncVideoInputColorPrimaries: TGUID = '{c24d783f-7ce6-4278-90ab-28a4f1e5f86c}';
STATIC_CODECAPI_AVEncVideoOutputColorPrimaries: TGUID = '{be95907c-9d04-4921-8985-a6d6d87d1a6c}';
STATIC_CODECAPI_AVEncVideoInputColorTransferFunction: TGUID = '{8c056111-a9c3-4b08-a0a0-ce13f8a27c75}';
STATIC_CODECAPI_AVEncVideoOutputColorTransferFunction: TGUID = '{4a7f884a-ea11-460d-bf57-b88bc75900de}';
STATIC_CODECAPI_AVEncVideoInputColorTransferMatrix: TGUID = '{52ed68b9-72d5-4089-958d-f5405d55081c}';
STATIC_CODECAPI_AVEncVideoOutputColorTransferMatrix: TGUID = '{a9b90444-af40-4310-8fbe-ed6d933f892b}';
STATIC_CODECAPI_AVEncVideoInputColorLighting: TGUID = '{46a99549-0015-4a45-9c30-1d5cfa258316}';
STATIC_CODECAPI_AVEncVideoOutputColorLighting: TGUID = '{0e5aaac6-ace6-4c5c-998e-1a8c9c6c0f89}';
STATIC_CODECAPI_AVEncVideoInputColorNominalRange: TGUID = '{16cf25c6-a2a6-48e9-ae80-21aec41d427e}';
STATIC_CODECAPI_AVEncVideoOutputColorNominalRange: TGUID = '{972835ed-87b5-4e95-9500-c73958566e54}';
STATIC_CODECAPI_AVEncInputVideoSystem: TGUID = '{bede146d-b616-4dc7-92b2-f5d9fa9298f7}';
STATIC_CODECAPI_AVEncVideoHeaderDropFrame: TGUID = '{6ed9e124-7925-43fe-971b-e019f62222b4}';
STATIC_CODECAPI_AVEncVideoHeaderHours: TGUID = '{2acc7702-e2da-4158-bf9b-88880129d740}';
STATIC_CODECAPI_AVEncVideoHeaderMinutes: TGUID = '{dc1a99ce-0307-408b-880b-b8348ee8ca7f}';
STATIC_CODECAPI_AVEncVideoHeaderSeconds: TGUID = '{4a2e1a05-a780-4f58-8120-9a449d69656b}';
STATIC_CODECAPI_AVEncVideoHeaderFrames: TGUID = '{afd5f567-5c1b-4adc-bdaf-735610381436}';
STATIC_CODECAPI_AVEncVideoDefaultUpperFieldDominant: TGUID = '{810167c4-0bc1-47ca-8fc2-57055a1474a5}';
STATIC_CODECAPI_AVEncVideoCBRMotionTradeoff: TGUID = '{0d49451e-18d5-4367-a4ef-3240df1693c4}';
STATIC_CODECAPI_AVEncVideoCodedVideoAccessUnitSize: TGUID = '{b4b10c15-14a7-4ce8-b173-dc90a0b4fcdb}';
STATIC_CODECAPI_AVEncVideoMaxKeyframeDistance: TGUID = '{2987123a-ba93-4704-b489-ec1e5f25292c}';
STATIC_CODECAPI_AVEncH264CABACEnable: TGUID = '{ee6cad62-d305-4248-a50e-e1b255f7caf8}';
STATIC_CODECAPI_AVEncVideoContentType: TGUID = '{66117aca-eb77-459d-930c-a48d9d0683fc}';
STATIC_CODECAPI_AVEncNumWorkerThreads: TGUID = '{b0c8bf60-16f7-4951-a30b-1db1609293d6}';
STATIC_CODECAPI_AVEncVideoEncodeQP: TGUID = '{2cb5696b-23fb-4ce1-a0f9-ef5b90fd55ca}';
STATIC_CODECAPI_AVEncVideoMinQP: TGUID = '{0ee22c6a-a37c-4568-b5f1-9d4c2b3ab886}';
STATIC_CODECAPI_AVEncVideoForceKeyFrame: TGUID = '{398c1b98-8353-475a-9ef2-8f265d260345}';
STATIC_CODECAPI_AVEncH264SPSID: TGUID = '{50f38f51-2b79-40e3-b39c-7e9fa0770501}';
STATIC_CODECAPI_AVEncH264PPSID: TGUID = '{bfe29ec2-056c-4d68-a38d-ae5944c8582e}';
STATIC_CODECAPI_AVEncAdaptiveMode: TGUID = '{4419b185-da1f-4f53-bc76-097d0c1efb1e}';
STATIC_CODECAPI_AVEncVideoTemporalLayerCount: TGUID = '{19caebff-b74d-4cfd-8c27-c2f9d97d5f52}';
STATIC_CODECAPI_AVEncVideoUsage: TGUID = '{1f636849-5dc1-49f1-b1d8-ce3cf62ea385}';
STATIC_CODECAPI_AVEncVideoSelectLayer: TGUID = '{eb1084f5-6aaa-4914-bb2f-6147227f12e7}';
STATIC_CODECAPI_AVEncVideoRateControlParams: TGUID = '{87d43767-7645-44ec-b438-d3322fbca29f}';
STATIC_CODECAPI_AVEncVideoSupportedControls: TGUID = '{d3f40fdd-77b9-473d-8196-061259e69cff}';
STATIC_CODECAPI_AVEncVideoEncodeFrameTypeQP: TGUID = '{aa70b610-e03f-450c-ad07-07314e639ce7}';
STATIC_CODECAPI_AVEncSliceControlMode: TGUID = '{e9e782ef-5f18-44c9-a90b-e9c3c2c17b0b}';
STATIC_CODECAPI_AVEncSliceControlSize: TGUID = '{92f51df3-07a5-4172-aefe-c69ca3b60e35}';
STATIC_CODECAPI_AVEncSliceGenerationMode: TGUID = '{8a6bc67f-9497-4286-b46b-02db8d60edbc}';
STATIC_CODECAPI_AVEncVideoMaxNumRefFrame: TGUID = '{964829ed-94f9-43b4-b74d-ef40944b69a0}';
STATIC_CODECAPI_AVEncVideoMeanAbsoluteDifference: TGUID = '{e5c0c10f-81a4-422d-8c3f-b474a4581336}';
STATIC_CODECAPI_AVEncVideoMaxQP: TGUID = '{3daf6f66-a6a7-45e0-a8e5-f2743f46a3a2}';
STATIC_CODECAPI_AVEncVideoLTRBufferControl: TGUID = '{a4a0e93d-4cbc-444c-89f4-826d310e92a7}';
STATIC_CODECAPI_AVEncVideoMarkLTRFrame: TGUID = '{e42f4748-a06d-4ef9-8cea-3d05fde3bd3b}';
STATIC_CODECAPI_AVEncVideoUseLTRFrame: TGUID = '{00752db8-55f7-4f80-895b-27639195f2ad}';
STATIC_CODECAPI_AVEncVideoROIEnabled: TGUID = '{d74f7f18-44dd-4b85-aba3-05d9f42a8280}';
STATIC_CODECAPI_AVEncVideoDirtyRectEnabled: TGUID = '{8acb8fdd-5e0c-4c66-8729-b8f629ab04fb}';
STATIC_CODECAPI_AVScenarioInfo: TGUID = '{b28a6e64-3ff9-446a-8a4b-0d7a53413236}';
STATIC_CODECAPI_AVEncMPVGOPSizeMin: TGUID = '{7155cf20-d440-4852-ad0f-9c4abfe37a6a}';
STATIC_CODECAPI_AVEncMPVGOPSizeMax: TGUID = '{fe7de4c4-1936-4fe2-bdf7-1f18ca1d001f}';
STATIC_CODECAPI_AVEncVideoMaxCTBSize: TGUID = '{822363ff-cec8-43e5-92fd-e097488485e9}';
STATIC_CODECAPI_AVEncVideoCTBSize: TGUID = '{d47db8b2-e73b-4cb9-8c3e-bd877d06d77b}';
STATIC_CODECAPI_VideoEncoderDisplayContentType: TGUID = '{79b90b27-f4b1-42dc-9dd7-cdaf8135c400}';
STATIC_CODECAPI_AVEncEnableVideoProcessing: TGUID = '{006f4bf6-0ea3-4d42-8702-b5d8be0f7a92}';
STATIC_CODECAPI_AVEncVideoGradualIntraRefresh: TGUID = '{8f347dee-cb0d-49ba-b462-db6927ee2101}';
STATIC_CODECAPI_GetOPMContext: TGUID = '{2f036c05-4c14-4689-8839-294c6d73e053}';
STATIC_CODECAPI_SetHDCPManagerContext: TGUID = '{6d2d1fc8-3dc9-47eb-a1a2-471c80cd60d0}';
STATIC_CODECAPI_AVEncVideoMaxTemporalLayers: TGUID = '{9c668cfe-08e1-424a-934e-b764b064802a}';
STATIC_CODECAPI_AVEncVideoNumGOPsPerIDR: TGUID = '{83bc5bdb-5b89-4521-8f66-33151c373176}';
STATIC_CODECAPI_AVEncCommonAllowFrameDrops: TGUID = '{d8477dcb-9598-48e3-8d0c-752bf206093e}';
STATIC_CODECAPI_AVEncVideoIntraLayerPrediction: TGUID = '{d3af46b8-bf47-44bb-a283-69f0b0228ff9}';
STATIC_CODECAPI_AVEncVideoInstantTemporalUpSwitching: TGUID = '{a3308307-0d96-4ba4-b1f0-b91a5e49df10}';
STATIC_CODECAPI_AVEncLowPowerEncoder: TGUID = '{b668d582-8bad-4f6a-9141-375a95358b6d}';
STATIC_CODECAPI_AVEnableInLoopDeblockFilter: TGUID = '{d2e8e399-0623-4bf3-92a8-4d1818529ded}';
STATIC_CODECAPI_AVEncMuxOutputStreamType: TGUID = '{cedd9e8f-34d3-44db-a1d8-f81520254f3e}';
STATIC_CODECAPI_AVEncStatVideoOutputFrameRate: TGUID = '{be747849-9ab4-4a63-98fe-f143f04f8ee9}';
STATIC_CODECAPI_AVEncStatVideoCodedFrames: TGUID = '{d47f8d61-6f5a-4a26-bb9f-cd9518462bcd}';
STATIC_CODECAPI_AVEncStatVideoTotalFrames: TGUID = '{fdaa9916-119a-4222-9ad6-3f7cab99cc8b}';
STATIC_CODECAPI_AVEncAudioIntervalToEncode: TGUID = '{866e4b4d-725a-467c-bb01-b496b23b25f9}';
STATIC_CODECAPI_AVEncAudioIntervalToSkip: TGUID = '{88c15f94-c38c-4796-a9e8-96e967983f26}';
STATIC_CODECAPI_AVEncAudioDualMono: TGUID = '{3648126b-a3e8-4329-9b3a-5ce566a43bd3}';
STATIC_CODECAPI_AVEncAudioMeanBitRate: TGUID = '{921295bb-4fca-4679-aab8-9e2a1d753384}';
STATIC_CODECAPI_AVEncAudioMapDestChannel0: TGUID = '{bc5d0b60-df6a-4e16-9803-b82007a30c8d}';
STATIC_CODECAPI_AVEncAudioMapDestChannel1: TGUID = '{bc5d0b61-df6a-4e16-9803-b82007a30c8d}';
STATIC_CODECAPI_AVEncAudioMapDestChannel2: TGUID = '{bc5d0b62-df6a-4e16-9803-b82007a30c8d}';
STATIC_CODECAPI_AVEncAudioMapDestChannel3: TGUID = '{bc5d0b63-df6a-4e16-9803-b82007a30c8d}';
STATIC_CODECAPI_AVEncAudioMapDestChannel4: TGUID = '{bc5d0b64-df6a-4e16-9803-b82007a30c8d}';
STATIC_CODECAPI_AVEncAudioMapDestChannel5: TGUID = '{bc5d0b65-df6a-4e16-9803-b82007a30c8d}';
STATIC_CODECAPI_AVEncAudioMapDestChannel6: TGUID = '{bc5d0b66-df6a-4e16-9803-b82007a30c8d}';
STATIC_CODECAPI_AVEncAudioMapDestChannel7: TGUID = '{bc5d0b67-df6a-4e16-9803-b82007a30c8d}';
STATIC_CODECAPI_AVEncAudioMapDestChannel8: TGUID = '{bc5d0b68-df6a-4e16-9803-b82007a30c8d}';
STATIC_CODECAPI_AVEncAudioMapDestChannel9: TGUID = '{bc5d0b69-df6a-4e16-9803-b82007a30c8d}';
STATIC_CODECAPI_AVEncAudioMapDestChannel10: TGUID = '{bc5d0b6a-df6a-4e16-9803-b82007a30c8d}';
STATIC_CODECAPI_AVEncAudioMapDestChannel11: TGUID = '{bc5d0b6b-df6a-4e16-9803-b82007a30c8d}';
STATIC_CODECAPI_AVEncAudioMapDestChannel12: TGUID = '{bc5d0b6c-df6a-4e16-9803-b82007a30c8d}';
STATIC_CODECAPI_AVEncAudioMapDestChannel13: TGUID = '{bc5d0b6d-df6a-4e16-9803-b82007a30c8d}';
STATIC_CODECAPI_AVEncAudioMapDestChannel14: TGUID = '{bc5d0b6e-df6a-4e16-9803-b82007a30c8d}';
STATIC_CODECAPI_AVEncAudioMapDestChannel15: TGUID = '{bc5d0b6f-df6a-4e16-9803-b82007a30c8d}';
STATIC_CODECAPI_AVEncAudioInputContent: TGUID = '{3e226c2b-60b9-4a39-b00b-a7b40f70d566}';
STATIC_CODECAPI_AVEncStatAudioPeakPCMValue: TGUID = '{dce7fd34-dc00-4c16-821b-35d9eb00fb1a}';
STATIC_CODECAPI_AVEncStatAudioAveragePCMValue: TGUID = '{979272f8-d17f-4e32-bb73-4e731c68ba2d}';
STATIC_CODECAPI_AVEncStatAudioAverageBPS: TGUID = '{ca6724db-7059-4351-8b43-f82198826a14}';
STATIC_CODECAPI_AVEncStatAverageBPS: TGUID = '{ca6724db-7059-4351-8b43-f82198826a14}';
STATIC_CODECAPI_AVEncStatHardwareProcessorUtilitization: TGUID = '{995dc027-cb95-49e6-b91b-5967753cdcb8}';
STATIC_CODECAPI_AVEncStatHardwareBandwidthUtilitization: TGUID = '{0124ba9b-dc41-4826-b45f-18ac01b3d5a8}';
STATIC_CODECAPI_AVEncMPVGOPSize: TGUID = '{95f31b26-95a4-41aa-9303-246a7fc6eef1}';
STATIC_CODECAPI_AVEncMPVGOPOpen: TGUID = '{b1d5d4a6-3300-49b1-ae61-a09937ab0e49}';
STATIC_CODECAPI_AVEncMPVDefaultBPictureCount: TGUID = '{8d390aac-dc5c-4200-b57f-814d04babab2}';
STATIC_CODECAPI_AVEncMPVProfile: TGUID = '{dabb534a-1d99-4284-975a-d90e2239baa1}';
STATIC_CODECAPI_AVEncMPVLevel: TGUID = '{6ee40c40-a60c-41ef-8f50-37c2249e2cb3}';
STATIC_CODECAPI_AVEncMPVFrameFieldMode: TGUID = '{acb5de96-7b93-4c2f-8825-b0295fa93bf4}';
STATIC_CODECAPI_AVEncMPVAddSeqEndCode: TGUID = '{a823178f-57df-4c7a-b8fd-e5ec8887708d}';
STATIC_CODECAPI_AVEncMPVGOPSInSeq: TGUID = '{993410d4-2691-4192-9978-98dc2603669f}';
STATIC_CODECAPI_AVEncMPVUseConcealmentMotionVectors: TGUID = '{ec770cf3-6908-4b4b-aa30-7fb986214fea}';
STATIC_CODECAPI_AVEncMPVSceneDetection: TGUID = '{552799f1-db4c-405b-8a3a-c93f2d0674dc}';
STATIC_CODECAPI_AVEncMPVGenerateHeaderSeqExt: TGUID = '{d5e78611-082d-4e6b-98af-0f51ab139222}';
STATIC_CODECAPI_AVEncMPVGenerateHeaderSeqDispExt: TGUID = '{6437aa6f-5a3c-4de9-8a16-53d9c4ad326f}';
STATIC_CODECAPI_AVEncMPVGenerateHeaderPicExt: TGUID = '{1b8464ab-944f-45f0-b74e-3a58dad11f37}';
STATIC_CODECAPI_AVEncMPVGenerateHeaderPicDispExt: TGUID = '{c6412f84-c03f-4f40-a00c-4293df8395bb}';
STATIC_CODECAPI_AVEncMPVGenerateHeaderSeqScaleExt: TGUID = '{0722d62f-dd59-4a86-9cd5-644f8e2653d8}';
STATIC_CODECAPI_AVEncMPVScanPattern: TGUID = '{7f8a478e-7bbb-4ae2-b2fc-96d17fc4a2d6}';
STATIC_CODECAPI_AVEncMPVIntraDCPrecision: TGUID = '{a0116151-cbc8-4af3-97dc-d00cceb82d79}';
STATIC_CODECAPI_AVEncMPVQScaleType: TGUID = '{2b79ebb7-f484-4af7-bb58-a2a188c5cbbe}';
STATIC_CODECAPI_AVEncMPVIntraVLCTable: TGUID = '{a2b83ff5-1a99-405a-af95-c5997d558d3a}';
STATIC_CODECAPI_AVEncMPVQuantMatrixIntra: TGUID = '{9bea04f3-6621-442c-8ba1-3ac378979698}';
STATIC_CODECAPI_AVEncMPVQuantMatrixNonIntra: TGUID = '{87f441d8-0997-4beb-a08e-8573d409cf75}';
STATIC_CODECAPI_AVEncMPVQuantMatrixChromaIntra: TGUID = '{9eb9ecd4-018d-4ffd-8f2d-39e49f07b17a}';
STATIC_CODECAPI_AVEncMPVQuantMatrixChromaNonIntra: TGUID = '{1415b6b1-362a-4338-ba9a-1ef58703c05b}';
STATIC_CODECAPI_AVEncMPALayer: TGUID = '{9d377230-f91b-453d-9ce0-78445414c22d}';
STATIC_CODECAPI_AVEncMPACodingMode: TGUID = '{b16ade03-4b93-43d7-a550-90b4fe224537}';
STATIC_CODECAPI_AVEncDDService: TGUID = '{d2e1bec7-5172-4d2a-a50e-2f3b82b1ddf8}';
STATIC_CODECAPI_AVEncDDDialogNormalization: TGUID = '{d7055acf-f125-437d-a704-79c79f0404a8}';
STATIC_CODECAPI_AVEncDDCentreDownMixLevel: TGUID = '{e285072c-c958-4a81-afd2-e5e0daf1b148}';
STATIC_CODECAPI_AVEncDDSurroundDownMixLevel: TGUID = '{7b20d6e5-0bcf-4273-a487-506b047997e9}';
STATIC_CODECAPI_AVEncDDProductionInfoExists: TGUID = '{b0b7fe5f-b6ab-4f40-964d-8d91f17c19e8}';
STATIC_CODECAPI_AVEncDDProductionRoomType: TGUID = '{dad7ad60-23d8-4ab7-a284-556986d8a6fe}';
STATIC_CODECAPI_AVEncDDProductionMixLevel: TGUID = '{301d103a-cbf9-4776-8899-7c15b461ab26}';
STATIC_CODECAPI_AVEncDDCopyright: TGUID = '{8694f076-cd75-481d-a5c6-a904dcc828f0}';
STATIC_CODECAPI_AVEncDDOriginalBitstream: TGUID = '{966ae800-5bd3-4ff9-95b9-d30566273856}';
STATIC_CODECAPI_AVEncDDDigitalDeemphasis: TGUID = '{e024a2c2-947c-45ac-87d8-f1030c5c0082}';
STATIC_CODECAPI_AVEncDDDCHighPassFilter: TGUID = '{9565239f-861c-4ac8-bfda-e00cb4db8548}';
STATIC_CODECAPI_AVEncDDChannelBWLowPassFilter: TGUID = '{e197821d-d2e7-43e2-ad2c-00582f518545}';
STATIC_CODECAPI_AVEncDDLFELowPassFilter: TGUID = '{d3b80f6f-9d15-45e5-91be-019c3fab1f01}';
STATIC_CODECAPI_AVEncDDSurround90DegreeePhaseShift: TGUID = '{25ecec9d-3553-42c0-bb56-d25792104f80}';
STATIC_CODECAPI_AVEncDDSurround3dBAttenuation: TGUID = '{4d43b99d-31e2-48b9-bf2e-5cbf1a572784}';
STATIC_CODECAPI_AVEncDDDynamicRangeCompressionControl: TGUID = '{cfc2ff6d-79b8-4b8d-a8aa-a0c9bd1c2940}';
STATIC_CODECAPI_AVEncDDRFPreEmphasisFilter: TGUID = '{21af44c0-244e-4f3d-a2cc-3d3068b2e73f}';
STATIC_CODECAPI_AVEncDDSurroundExMode: TGUID = '{91607cee-dbdd-4eb6-bca2-aadfafa3dd68}';
STATIC_CODECAPI_AVEncDDPreferredStereoDownMixMode: TGUID = '{7f4e6b31-9185-403d-b0a2-763743e6f063}';
STATIC_CODECAPI_AVEncDDLtRtCenterMixLvl_x10: TGUID = '{dca128a2-491f-4600-b2da-76e3344b4197}';
STATIC_CODECAPI_AVEncDDLtRtSurroundMixLvl_x10: TGUID = '{212246c7-3d2c-4dfa-bc21-652a9098690d}';
STATIC_CODECAPI_AVEncDDLoRoCenterMixLvl_x10: TGUID = '{1cfba222-25b3-4bf4-9bfd-e7111267858c}';
STATIC_CODECAPI_AVEncDDLoRoSurroundMixLvl_x10: TGUID = '{e725cff6-eb56-40c7-8450-2b9367e91555}';
STATIC_CODECAPI_AVEncDDAtoDConverterType: TGUID = '{719f9612-81a1-47e0-9a05-d94ad5fca948}';
STATIC_CODECAPI_AVEncDDHeadphoneMode: TGUID = '{4052dbec-52f5-42f5-9b00-d134b1341b9d}';
STATIC_CODECAPI_AVEncWMVKeyFrameDistance: TGUID = '{5569055e-e268-4771-b83e-9555ea28aed3}';
STATIC_CODECAPI_AVEncWMVInterlacedEncoding: TGUID = '{e3d00f8a-c6f5-4e14-a588-0ec87a726f9b}';
STATIC_CODECAPI_AVEncWMVDecoderComplexity: TGUID = '{f32c0dab-f3cb-4217-b79f-8762768b5f67}';
STATIC_CODECAPI_AVEncWMVKeyFrameBufferLevelMarker: TGUID = '{51ff1115-33ac-426c-a1b1-09321bdf96b4}';
STATIC_CODECAPI_AVEncWMVProduceDummyFrames: TGUID = '{d669d001-183c-42e3-a3ca-2f4586d2396c}';
STATIC_CODECAPI_AVEncStatWMVCBAvg: TGUID = '{6aa6229f-d602-4b9d-b68c-c1ad78884bef}';
STATIC_CODECAPI_AVEncStatWMVCBMax: TGUID = '{e976bef8-00fe-44b4-b625-8f238bc03499}';
STATIC_CODECAPI_AVEncStatWMVDecoderComplexityProfile: TGUID = '{89e69fc3-0f9b-436c-974a-df821227c90d}';
STATIC_CODECAPI_AVEncStatMPVSkippedEmptyFrames: TGUID = '{32195fd3-590d-4812-a7ed-6d639a1f9711}';
STATIC_CODECAPI_AVEncMP12PktzSTDBuffer: TGUID = '{0b751bd0-819e-478c-9435-75208926b377}';
STATIC_CODECAPI_AVEncMP12PktzStreamID: TGUID = '{c834d038-f5e8-4408-9b60-88f36493fedf}';
STATIC_CODECAPI_AVEncMP12PktzInitialPTS: TGUID = '{2a4f2065-9a63-4d20-ae22-0a1bc896a315}';
STATIC_CODECAPI_AVEncMP12PktzPacketSize: TGUID = '{ab71347a-1332-4dde-a0e5-ccf7da8a0f22}';
STATIC_CODECAPI_AVEncMP12PktzCopyright: TGUID = '{c8f4b0c1-094c-43c7-8e68-a595405a6ef8}';
STATIC_CODECAPI_AVEncMP12PktzOriginal: TGUID = '{6b178416-31b9-4964-94cb-6bff866cdf83}';
STATIC_CODECAPI_AVEncMP12MuxPacketOverhead: TGUID = '{e40bd720-3955-4453-acf9-b79132a38fa0}';
STATIC_CODECAPI_AVEncMP12MuxNumStreams: TGUID = '{f7164a41-dced-4659-a8f2-fb693f2a4cd0}';
STATIC_CODECAPI_AVEncMP12MuxEarliestPTS: TGUID = '{157232b6-f809-474e-9464-a7f93014a817}';
STATIC_CODECAPI_AVEncMP12MuxLargestPacketSize: TGUID = '{35ceb711-f461-4b92-a4ef-17b6841ed254}';
STATIC_CODECAPI_AVEncMP12MuxInitialSCR: TGUID = '{3433ad21-1b91-4a0b-b190-2b77063b63a4}';
STATIC_CODECAPI_AVEncMP12MuxMuxRate: TGUID = '{ee047c72-4bdb-4a9d-8e21-41926c823da7}';
STATIC_CODECAPI_AVEncMP12MuxPackSize: TGUID = '{f916053a-1ce8-4faf-aa0b-ba31c80034b8}';
STATIC_CODECAPI_AVEncMP12MuxSysSTDBufferBound: TGUID = '{35746903-b545-43e7-bb35-c5e0a7d5093c}';
STATIC_CODECAPI_AVEncMP12MuxSysRateBound: TGUID = '{05f0428a-ee30-489d-ae28-205c72446710}';
STATIC_CODECAPI_AVEncMP12MuxTargetPacketizer: TGUID = '{d862212a-2015-45dd-9a32-1b3aa88205a0}';
STATIC_CODECAPI_AVEncMP12MuxSysFixed: TGUID = '{cefb987e-894f-452e-8f89-a4ef8cec063a}';
STATIC_CODECAPI_AVEncMP12MuxSysCSPS: TGUID = '{7952ff45-9c0d-4822-bc82-8ad772e02993}';
STATIC_CODECAPI_AVEncMP12MuxSysVideoLock: TGUID = '{b8296408-2430-4d37-a2a1-95b3e435a91d}';
STATIC_CODECAPI_AVEncMP12MuxSysAudioLock: TGUID = '{0fbb5752-1d43-47bf-bd79-f2293d8ce337}';
STATIC_CODECAPI_AVEncMP12MuxDVDNavPacks: TGUID = '{c7607ced-8cf1-4a99-83a1-ee5461be3574}';
STATIC_CODECAPI_AVEncMPACopyright: TGUID = '{a6ae762a-d0a9-4454-b8ef-f2dbeefdd3bd}';
STATIC_CODECAPI_AVEncMPAOriginalBitstream: TGUID = '{3cfb7855-9cc9-47ff-b829-b36786c92346}';
STATIC_CODECAPI_AVEncMPAEnableRedundancyProtection: TGUID = '{5e54b09e-b2e7-4973-a89b-0b3650a3beda}';
STATIC_CODECAPI_AVEncMPAPrivateUserBit: TGUID = '{afa505ce-c1e3-4e3d-851b-61b700e5e6cc}';
STATIC_CODECAPI_AVEncMPAEmphasisType: TGUID = '{2d59fcda-bf4e-4ed6-b5df-5b03b36b0a1f}';
STATIC_CODECAPI_AVDecCommonMeanBitRate: TGUID = '{59488217-007a-4f7a-8e41-5c48b1eac5c6}';
STATIC_CODECAPI_AVDecCommonMeanBitRateInterval: TGUID = '{0ee437c6-38a7-4c5c-944c-68ab42116b85}';
STATIC_CODECAPI_AVDecCommonInputFormat: TGUID = '{e5005239-bd89-4be3-9c0f-5dde317988cc}';
STATIC_CODECAPI_AVDecCommonOutputFormat: TGUID = '{3c790028-c0ce-4256-b1a2-1b0fc8b1dcdc}';
STATIC_CODECAPI_GUID_AVDecAudioOutputFormat_PCM_Stereo_MatrixEncoded: TGUID = '{696e1d30-548f-4036-825f-7026c60011bd}';
STATIC_CODECAPI_GUID_AVDecAudioOutputFormat_PCM: TGUID = '{696e1d31-548f-4036-825f-7026c60011bd}';
STATIC_CODECAPI_GUID_AVDecAudioOutputFormat_SPDIF_PCM: TGUID = '{696e1d32-548f-4036-825f-7026c60011bd}';
STATIC_CODECAPI_GUID_AVDecAudioOutputFormat_SPDIF_Bitstream: TGUID = '{696e1d33-548f-4036-825f-7026c60011bd}';
STATIC_CODECAPI_GUID_AVDecAudioOutputFormat_PCM_Headphones: TGUID = '{696e1d34-548f-4036-825f-7026c60011bd}';
STATIC_CODECAPI_GUID_AVDecAudioOutputFormat_PCM_Stereo_Auto: TGUID = '{696e1d35-548f-4036-825f-7026c60011bd}';
STATIC_CODECAPI_AVDecVideoImageSize: TGUID = '{5ee5747c-6801-4cab-aaf1-6248fa841ba4}';
STATIC_CODECAPI_AVDecVideoInputScanType: TGUID = '{38477e1f-0ea7-42cd-8cd1-130ced57c580}';
STATIC_CODECAPI_AVDecVideoPixelAspectRatio: TGUID = '{b0cf8245-f32d-41df-b02c-87bd304d12ab}';
STATIC_CODECAPI_AVDecVideoAcceleration_MPEG2: TGUID = '{f7db8a2e-4f48-4ee8-ae31-8b6ebe558ae2}';
STATIC_CODECAPI_AVDecVideoAcceleration_H264: TGUID = '{f7db8a2f-4f48-4ee8-ae31-8b6ebe558ae2}';
STATIC_CODECAPI_AVDecVideoAcceleration_VC1: TGUID = '{f7db8a30-4f48-4ee8-ae31-8b6ebe558ae2}';
STATIC_CODECAPI_AVDecVideoProcDeinterlaceCSC: TGUID = '{f7db8a31-4f48-4ee8-ae31-8b6ebe558ae2}';
STATIC_CODECAPI_AVDecVideoThumbnailGenerationMode: TGUID = '{2efd8eee-1150-4328-9cf5-66dce933fcf4}';
STATIC_CODECAPI_AVDecVideoDropPicWithMissingRef: TGUID = '{f8226383-14c2-4567-9734-5004e96ff887}';
STATIC_CODECAPI_AVDecVideoSoftwareDeinterlaceMode: TGUID = '{0c08d1ce-9ced-4540-bae3-ceb380141109}';
STATIC_CODECAPI_AVDecVideoFastDecodeMode: TGUID = '{6b529f7d-d3b1-49c6-a999-9ec6911bedbf}';
STATIC_CODECAPI_AVLowLatencyMode: TGUID = '{9c27891a-ed7a-40e1-88e8-b22727a024ee}';
STATIC_CODECAPI_AVDecVideoH264ErrorConcealment: TGUID = '{ececace8-3436-462c-9294-cd7bacd758a9}';
STATIC_CODECAPI_AVDecVideoMPEG2ErrorConcealment: TGUID = '{9d2bfe18-728d-48d2-b358-bc7e436c6674}';
STATIC_CODECAPI_AVDecVideoCodecType: TGUID = '{434528e5-21f0-46b6-b62c-9b1b6b658cd1}';
STATIC_CODECAPI_AVDecVideoDXVAMode: TGUID = '{f758f09e-7337-4ae7-8387-73dc2d54e67d}';
STATIC_CODECAPI_AVDecVideoDXVABusEncryption: TGUID = '{42153c8b-fd0b-4765-a462-ddd9e8bcc388}';
STATIC_CODECAPI_AVDecVideoSWPowerLevel: TGUID = '{fb5d2347-4dd8-4509-aed0-db5fa9aa93f4}';
STATIC_CODECAPI_AVDecVideoMaxCodedWidth: TGUID = '{5ae557b8-77af-41f5-9fa6-4db2fe1d4bca}';
STATIC_CODECAPI_AVDecVideoMaxCodedHeight: TGUID = '{7262a16a-d2dc-4e75-9ba8-65c0c6d32b13}';
STATIC_CODECAPI_AVDecNumWorkerThreads: TGUID = '{9561c3e8-ea9e-4435-9b1e-a93e691894d8}';
STATIC_CODECAPI_AVDecSoftwareDynamicFormatChange: TGUID = '{862e2f0a-507b-47ff-af47-01e2624298b7}';
STATIC_CODECAPI_AVDecDisableVideoPostProcessing: TGUID = '{f8749193-667a-4f2c-a9e8-5d4af924f08f}';
STATIC_CODECAPI_GUID_AVDecAudioInputWMA: TGUID = '{c95e8dcf-4058-4204-8c42-cb24d91e4b9b}';
STATIC_CODECAPI_GUID_AVDecAudioInputWMAPro: TGUID = '{0128b7c7-da72-4fe3-bef8-5c52e3557704}';
STATIC_CODECAPI_GUID_AVDecAudioInputDolby: TGUID = '{8e4228a0-f000-4e0b-8f54-ab8d24ad61a2}';
STATIC_CODECAPI_GUID_AVDecAudioInputDTS: TGUID = '{600bc0ca-6a1f-4e91-b241-1bbeb1cb19e0}';
STATIC_CODECAPI_GUID_AVDecAudioInputPCM: TGUID = '{f2421da5-bbb4-4cd5-a996-933c6b5d1347}';
STATIC_CODECAPI_GUID_AVDecAudioInputMPEG: TGUID = '{91106f36-02c5-4f75-9719-3b7abf75e1f6}';
STATIC_CODECAPI_GUID_AVDecAudioInputAAC: TGUID = '{97df7828-b94a-47e2-a4bc-51194db22a4d}';
STATIC_CODECAPI_GUID_AVDecAudioInputHEAAC: TGUID = '{16efb4aa-330e-4f5c-98a8-cf6ac55cbe60}';
STATIC_CODECAPI_GUID_AVDecAudioInputDolbyDigitalPlus: TGUID = '{0803e185-8f5d-47f5-9908-19a5bbc9fe34}';
STATIC_CODECAPI_AVDecAACDownmixMode: TGUID = '{01274475-f6bb-4017-b084-81a763c942d4}';
STATIC_CODECAPI_AVDecHEAACDynamicRangeControl: TGUID = '{287c8abe-69a4-4d39-8080-d3d9712178a0}';
STATIC_CODECAPI_AVDecAudioDualMono: TGUID = '{4a52cda8-30f8-4216-be0f-ba0b2025921d}';
STATIC_CODECAPI_AVDecAudioDualMonoReproMode: TGUID = '{a5106186-cc94-4bc9-8cd9-aa2f61f6807e}';
STATIC_CODECAPI_AVAudioChannelCount: TGUID = '{1d3583c4-1583-474e-b71a-5ee463c198e4}';
STATIC_CODECAPI_AVAudioChannelConfig: TGUID = '{17f89cb3-c38d-4368-9ede-63b94d177f9f}';
STATIC_CODECAPI_AVAudioSampleRate: TGUID = '{971d2723-1acb-42e7-855c-520a4b70a5f2}';
STATIC_CODECAPI_AVDDSurroundMode: TGUID = '{99f2f386-98d1-4452-a163-abc78a6eb770}';
STATIC_CODECAPI_AVDecDDOperationalMode: TGUID = '{d6d6c6d1-064e-4fdd-a40e-3ecbfcb7ebd0}';
STATIC_CODECAPI_AVDecDDMatrixDecodingMode: TGUID = '{ddc811a5-04ed-4bf3-a0ca-d00449f9355f}';
STATIC_CODECAPI_AVDecDDDynamicRangeScaleHigh: TGUID = '{50196c21-1f33-4af5-b296-11426d6c8789}';
STATIC_CODECAPI_AVDecDDDynamicRangeScaleLow: TGUID = '{044e62e4-11a5-42d5-a3b2-3bb2c7c2d7cf}';
STATIC_CODECAPI_AVDecDDStereoDownMixMode: TGUID = '{6ce4122c-3ee9-4182-b4ae-c10fc088649d}';
STATIC_CODECAPI_AVDSPLoudnessEqualization: TGUID = '{8afd1a15-1812-4cbf-9319-433a5b2a3b27}';
STATIC_CODECAPI_AVDSPSpeakerFill: TGUID = '{5612bca1-56da-4582-8da1-ca8090f92768}';
STATIC_CODECAPI_AVPriorityControl: TGUID = '{54ba3dc8-bdde-4329-b187-2018bc5c2ba1}';
STATIC_CODECAPI_AVRealtimeControl: TGUID = '{6f440632-c4ad-4bf7-9e52-456942b454b0}';
STATIC_CODECAPI_AVEncMaxFrameRate: TGUID = '{b98e1b31-19fa-4d4f-9931-d6a5b8aab93c}';
STATIC_CODECAPI_AVEncNoInputCopy: TGUID = '{d2b46a2a-e8ee-4ec5-869e-449b6c62c81a}';
STATIC_CODECAPI_AVEncChromaEncodeMode: TGUID = '{8a47ab5a-4798-4c93-b5a5-554f9a3b9f50}';
// end of static definitions
// Common Parameters
// AVEncCommonFormatConstraint (GUID)
AVEncCommonFormatConstraint: TGUID = '{57cbb9b8-116f-4951-b40c-c2a035ed8f17}';
GUID_AVEncCommonFormatUnSpecified: TGUID = '{af46a35a-6024-4525-a48a-094b97f5b3c2}';
GUID_AVEncCommonFormatDVD_V: TGUID = '{cc9598c4-e7fe-451d-b1ca-761bc840b7f3}';
GUID_AVEncCommonFormatDVD_DashVR: TGUID = '{e55199d6-044c-4dae-a488-531ed306235b}';
GUID_AVEncCommonFormatDVD_PlusVR: TGUID = '{e74c6f2e-ec37-478d-9af4-a5e135b6271c}';
GUID_AVEncCommonFormatVCD: TGUID = '{95035bf7-9d90-40ff-ad5c-5cf8cf71ca1d}';
GUID_AVEncCommonFormatSVCD: TGUID = '{51d85818-8220-448c-8066-d69bed16c9ad}';
GUID_AVEncCommonFormatATSC: TGUID = '{8d7b897c-a019-4670-aa76-2edcac7ac296}';
GUID_AVEncCommonFormatDVB: TGUID = '{71830d8f-6c33-430d-844b-c2705baae6db}';
GUID_AVEncCommonFormatMP3: TGUID = '{349733cd-eb08-4dc2-8197-e49835ef828b}';
GUID_AVEncCommonFormatHighMAT: TGUID = '{1eabe760-fb2b-4928-90d1-78db88eee889}';
GUID_AVEncCommonFormatHighMPV: TGUID = '{a2d25db8-b8f9-42c2-8bc7-0b93cf604788}';
// AVEncCodecType (GUID)
AVEncCodecType: TGUID = '{08af4ac1-f3f2-4c74-9dcf-37f2ec79f826}';
GUID_AVEncMPEG1Video: TGUID = '{c8dafefe-da1e-4774-b27d-11830c16b1fe}';
GUID_AVEncMPEG2Video: TGUID = '{046dc19a-6677-4aaa-a31d-c1ab716f4560}';
GUID_AVEncMPEG1Audio: TGUID = '{d4dd1362-cd4a-4cd6-8138-b94db4542b04}';
GUID_AVEncMPEG2Audio: TGUID = '{ee4cbb1f-9c3f-4770-92b5-fcb7c2a8d381}';
GUID_AVEncWMV: TGUID = '{4e0fef9b-1d43-41bd-b8bd-4d7bf7457a2a}';
GUID_AVEndMPEG4Video: TGUID = '{dd37b12a-9503-4f8b-b8d0-324a00c0a1cf}';
GUID_AVEncH264Video: TGUID = '{95044eab-31b3-47de-8e75-38a42bb03e28}';
GUID_AVEncDV: TGUID = '{09b769c7-3329-44fb-8954-fa30937d3d5a}';
GUID_AVEncWMAPro: TGUID = '{1955f90c-33f7-4a68-ab81-53f5657125c4}';
GUID_AVEncWMALossless: TGUID = '{55ca7265-23d8-4761-9031-b74fbe12f4c1}';
GUID_AVEncWMAVoice: TGUID = '{13ed18cb-50e8-4276-a288-a6aa228382d9}';
GUID_AVEncDolbyDigitalPro: TGUID = '{f5be76cc-0ff8-40eb-9cb1-bba94004d44f}';
GUID_AVEncDolbyDigitalConsumer: TGUID = '{c1a7bf6c-0059-4bfa-94ef-ef747a768d52}';
GUID_AVEncDolbyDigitalPlus: TGUID = '{698d1b80-f7dd-415c-971c-42492a2056c6}';
GUID_AVEncDTSHD: TGUID = '{2052e630-469d-4bfb-80ca-1d656e7e918f}';
GUID_AVEncDTS: TGUID = '{45fbcaa2-5e6e-4ab0-8893-5903bee93acf}';
GUID_AVEncMLP: TGUID = '{05f73e29-f0d1-431e-a41c-a47432ec5a66}';
GUID_AVEncPCM: TGUID = '{844be7f4-26cf-4779-b386-cc05d187990c}';
GUID_AVEncSDDS: TGUID = '{1dc1b82f-11c8-4c71-b7b6-ee3eb9bc2b94}';
// AVEncCommonRateControlMode (UINT32)
AVEncCommonRateControlMode: TGUID = '{1c0608e9-370c-4710-8a58-cb6181c42423}';
// AVEncCommonLowLatency (BOOL)
AVEncCommonLowLatency: TGUID = '{9d3ecd55-89e8-490a-970a-0c9548d5a56e}';
// AVEncCommonMultipassMode (UINT32)
AVEncCommonMultipassMode: TGUID = '{22533d4c-47e1-41b5-9352-a2b7780e7ac4}'; // 22533d4c-47e1-41b5-93-52-a2-b7-78-0e-7a-c4 )
// AVEncCommonPassStart (UINT32)
AVEncCommonPassStart: TGUID = '{6a67739f-4eb5-4385-9928-f276a939ef95}'; // 6a67739f-4eb5-4385-99-28-f2-76-a9-39-ef-95 )
// AVEncCommonPassEnd (UINT32)
AVEncCommonPassEnd: TGUID = '{0e3d01bc-c85c-467d-8b60-c41012ee3bf6}'; // 0e3d01bc-c85c-467d-8b-60-c4-10-12-ee-3b-f6 )
// AVEncCommonRealTime (BOOL)
AVEncCommonRealTime: TGUID = '{143a0ff6-a131-43da-b81e-98fbb8ec378e}'; // 143a0ff6-a131-43da-b8-1e-98-fb-b8-ec-37-8e )
// AVEncCommonQuality (UINT32)
AVEncCommonQuality: TGUID = '{fcbf57a3-7ea5-4b0c-9644-69b40c39c391}'; // fcbf57a3-7ea5-4b0c-96-44-69-b4-0c-39-c3-91 )
// AVEncCommonQualityVsSpeed (UINT32)
AVEncCommonQualityVsSpeed: TGUID = '{98332df8-03cd-476b-89fa-3f9e442dec9f}'; // 98332df8-03cd-476b-89-fa-3f-9e-44-2d-ec-9f )
// AVEncCommonTranscodeEncodingProfile (BSTR)
AVEncCommonTranscodeEncodingProfile: TGUID = '{6947787C-F508-4EA9-B1E9-A1FE3A49FBC9}'; // 6947787C-F508-4EA9-B1-E9-A1-FE-3A-49-FB-C9 )
// AVEncCommonMeanBitRate (UINT32)
AVEncCommonMeanBitRate: TGUID = '{f7222374-2144-4815-b550-a37f8e12ee52}'; // f7222374-2144-4815-b5-50-a3-7f-8e-12-ee-52 )
// AVEncCommonMeanBitRateInterval (UINT64)
AVEncCommonMeanBitRateInterval: TGUID = '{bfaa2f0c-cb82-4bc0-8474-f06a8a0d0258}'; // bfaa2f0c-cb82-4bc0-84-74-f0-6a-8a-0d-02-58 )
// AVEncCommonMaxBitRate (UINT32)
AVEncCommonMaxBitRate: TGUID = '{9651eae4-39b9-4ebf-85ef-d7f444ec7465}'; // 9651eae4-39b9-4ebf-85-ef-d7-f4-44-ec-74-65 )
// AVEncCommonMinBitRate (UINT32)
AVEncCommonMinBitRate: TGUID = '{101405b2-2083-4034-a806-efbeddd7c9ff}'; // 101405b2-2083-4034-a8-06-ef-be-dd-d7-c9-ff )
// AVEncCommonBufferSize (UINT32)
AVEncCommonBufferSize: TGUID = '{0db96574-b6a4-4c8b-8106-3773de0310cd}'; // 0db96574-b6a4-4c8b-81-06-37-73-de-03-10-cd )
// AVEncCommonBufferInLevel (UINT32)
AVEncCommonBufferInLevel: TGUID = '{d9c5c8db-fc74-4064-94e9-cd19f947ed45}'; // d9c5c8db-fc74-4064-94-e9-cd-19-f9-47-ed-45 )
// AVEncCommonBufferOutLevel (UINT32)
AVEncCommonBufferOutLevel: TGUID = '{ccae7f49-d0bc-4e3d-a57e-fb5740140069}'; // ccae7f49-d0bc-4e3d-a5-7e-fb-57-40-14-00-69 )
// AVEncCommonStreamEndHandling (UINT32)
AVEncCommonStreamEndHandling: TGUID = '{6aad30af-6ba8-4ccc-8fca-18d19beaeb1c}'; // 6aad30af-6ba8-4ccc-8f-ca-18-d1-9b-ea-eb-1c )
// Common Post Encode Statistical Parameters
// AVEncStatCommonCompletedPasses (UINT32)
AVEncStatCommonCompletedPasses: TGUID = '{3e5de533-9df7-438c-854f-9f7dd3683d34}'; // 3e5de533-9df7-438c-85-4f-9f-7d-d3-68-3d-34 )
// Common Video Parameters
// AVEncVideoOutputFrameRate (UINT32)
AVEncVideoOutputFrameRate: TGUID = '{ea85e7c3-9567-4d99-87c4-02c1c278ca7c}'; // ea85e7c3-9567-4d99-87-c4-02-c1-c2-78-ca-7c )
// AVEncVideoOutputFrameRateConversion (UINT32)
AVEncVideoOutputFrameRateConversion: TGUID = '{8c068bf4-369a-4ba3-82fd-b2518fb3396e}'; // 8c068bf4-369a-4ba3-82-fd-b2-51-8f-b3-39-6e )
// AVEncVideoPixelAspectRatio (UINT32 as UINT16/UNIT16) <---- You have WORD in the doc
AVEncVideoPixelAspectRatio: TGUID = '{3cdc718f-b3e9-4eb6-a57f-cf1f1b321b87}'; // 3cdc718f-b3e9-4eb6-a5-7f-cf-1f-1b-32-1b-87 )
// AVDecVideoAcceleration_MPEG2 (UINT32)
AVDecVideoAcceleration_MPEG2: TGUID = '{f7db8a2e-4f48-4ee8-ae31-8b6ebe558ae2}'; // f7db8a2e-4f48-4ee8-ae-31-8b-6e-be-55-8a-e2 )
AVDecVideoAcceleration_H264: TGUID = '{f7db8a2f-4f48-4ee8-ae31-8b6ebe558ae2}'; // f7db8a2f-4f48-4ee8-ae-31-8b-6e-be-55-8a-e2 )
AVDecVideoAcceleration_VC1: TGUID = '{f7db8a30-4f48-4ee8-ae31-8b6ebe558ae2}'; // f7db8a30-4f48-4ee8-ae-31-8b-6e-be-55-8a-e2 )
// AVDecVideoProcDeinterlaceCSC (UINT32)
AVDecVideoProcDeinterlaceCSC: TGUID = '{f7db8a31-4f48-4ee8-ae31-8b6ebe558ae2}'; // f7db8a31-4f48-4ee8-ae-31-8b-6e-be-55-8a-e2 )
// AVDecVideoThumbnailGenerationMode (BOOL)
// Related to video thumbnail generation.
// Video decoders can have special configurations for fast thumbnail generation.
// For example:
// - They can use only one decoding thread so that multiple instances can be used at the same time.
// - They can also decode I frames only.
AVDecVideoThumbnailGenerationMode: TGUID = '{2EFD8EEE-1150-4328-9CF5-66DCE933FCF4}'; // 2efd8eee-1150-4328-9c-f5-66-dc-e9-33-fc-f4)
// AVDecVideoMaxCodedWidth and AVDecVideoMaxCodedHeight
// Maximum codec width and height for current stream.
// This is used to optimize memory usage for a particular stream.
AVDecVideoMaxCodedWidth: TGUID = '{5AE557B8-77AF-41f5-9FA6-4DB2FE1D4BCA}'; // 5ae557b8-77af-41f5-9f-a6-4d-b2-fe-1d-4b-ca)
AVDecVideoMaxCodedHeight: TGUID = '{7262A16A-D2DC-4e75-9BA8-65C0C6D32B13}'; // 7262a16a-d2dc-4e75-9b-a8-65-c0-c6-d3-2b-13)
// AVDecNumWorkerThreads (INT32)
// Number of worker threads used in decoder core.
// If this number is set to -1, it means that the decoder will decide how many threads to create.
AVDecNumWorkerThreads: TGUID = '{9561C3E8-EA9E-4435-9B1E-A93E691894D8}'; // 9561c3e8-ea9e-4435-9b-1e-a9-3e-69-18-94-d8)
// AVDecSoftwareDynamicFormatChange (BOOL)
// Set whether to use software dynamic format change to internal resizing
AVDecSoftwareDynamicFormatChange: TGUID = '{862E2F0A-507B-47FF-AF47-01E2624298B7}'; // 862e2f0a-507b-47ff-af-47-1-e2-62-42-98-b7)
// AVDecDisableVideoPostProcessing (UINT32)
// Default value is 0
// If this is non-zero, decoder should not do post processing like deblocking/deringing. This only controls the out of loop post processing
// all processing required by video standard (like in-loop deblocking) should still be performed.
AVDecDisableVideoPostProcessing: TGUID = '{F8749193-667A-4F2C-A9E8-5D4AF924F08F}'; // f8749193-667a-4f2c-a9-e8-5d-4a-f9-24-f0-8f);
// AVDecVideoDropPicWithMissingRef (BOOL)
// Related to Video decoding mode of whether to drop pictures with missing references.
// For DVD playback, we may want to do so to avoid bad blocking. For Digital TV, we may
// want to decode all pictures no matter what.
AVDecVideoDropPicWithMissingRef: TGUID = '{F8226383-14C2-4567-9734-5004E96FF887}'; // f8226383-14c2-4567-97-34-50-4-e9-6f-f8-87)
// AVDecSoftwareVideoDeinterlaceMode (UINT32)
AVDecVideoSoftwareDeinterlaceMode: TGUID = '{0c08d1ce-9ced-4540-bae3-ceb380141109}'; // 0c08d1ce-9ced-4540-ba-e3-ce-b3-80-14-11-09);
// AVDecVideoFastDecodeMode (UINT32)
// 0: normal decoding
// 1-32 : Where 32 is fastest decoding. Any value between (and including) 1 to 32 is valid
AVDecVideoFastDecodeMode: TGUID = '{6B529F7D-D3B1-49c6-A999-9EC6911BEDBF}'; // 6b529f7d-d3b1-49c6-a9-99-9e-c6-91-1b-ed-bf);
// AVLowLatencyMode (DWORD)
// Related to low latency processing/decoding.
// This GUID lets the application to decrease latency.
AVLowLatencyMode: TGUID = '{9C27891A-ED7A-40e1-88E8-B22727A024EE}'; // 9c27891a-ed7a-40e1-88-e8-b2-27-27-a0-24-ee)
// AVDecVideoH264ErrorConcealment (UINT32)
// Related to Video decoding mode of whether to conceal pictures with corruptions.
// For DVD playback, we may not want to do so to avoid unnecessary computation. For Digital TV, we may
// want to perform error concealment.
AVDecVideoH264ErrorConcealment: TGUID = '{ECECACE8-3436-462c-9294-CD7BACD758A9}'; // ececace8-3436-462c-92-94-cd-7b-ac-d7-58-a9)
// AVDecVideoMPEG2ErrorConcealment (UINT32)
// Related to Video decoding mode of whether to conceal pictures with corruptions.
// For DVD playback, we may not want to do so to avoid unnecessary computation. For Digital TV, we may
// want to perform error concealment.
AVDecVideoMPEG2ErrorConcealment: TGUID = '{9D2BFE18-728D-48d2-B358-BC7E436C6674}'; // 9d2bfe18-728d-48d2-b3-58-bc-7e-43-6c-66-74)
// CODECAPI_AVDecVideoCodecType (UINT32)
AVDecVideoCodecType: TGUID = '{434528E5-21F0-46b6-B62C-9B1B6B658CD1}'; // 434528e5-21f0-46b6-b6-2c-9b-1b-6b-65-8c-d1);
// CODECAPI_AVDecVideoDXVAMode (UINT32)
AVDecVideoDXVAMode: TGUID = '{F758F09E-7337-4ae7-8387-73DC2D54E67D}'; // f758f09e-7337-4ae7-83-87-73-dc-2d-54-e6-7d);
// CODECAPI_AVDecVideoDXVABusEncryption (UINT32)
AVDecVideoDXVABusEncryption: TGUID = '{42153C8B-FD0B-4765-A462-DDD9E8BCC388}'; // 42153c8b-fd0b-4765-a4-62-dd-d9-e8-bc-c3-88);
// AVEncVideoForceSourceScanType (UINT32)
AVEncVideoForceSourceScanType: TGUID = '{1ef2065f-058a-4765-a4fc-8a864c103012}'; // 1ef2065f-058a-4765-a4-fc-8a-86-4c-10-30-12 )
// AVEncVideoNoOfFieldsToEncode (UINT64)
AVEncVideoNoOfFieldsToEncode: TGUID = '{61e4bbe2-4ee0-40e7-80ab-51ddeebe6291}'; // 61e4bbe2-4ee0-40e7-80-ab-51-dd-ee-be-62-91 )
// AVEncVideoNoOfFieldsToSkip (UINT64)
AVEncVideoNoOfFieldsToSkip: TGUID = '{a97e1240-1427-4c16-a7f7-3dcfd8ba4cc5}'; // a97e1240-1427-4c16-a7-f7-3d-cf-d8-ba-4c-c5 )
// AVEncVideoEncodeDimension (UINT32)
AVEncVideoEncodeDimension: TGUID = '{1074df28-7e0f-47a4-a453-cdd73870f5ce}'; // 1074df28-7e0f-47a4-a4-53-cd-d7-38-70-f5-ce )
// AVEncVideoEncodeOffsetOrigin (UINT32)
AVEncVideoEncodeOffsetOrigin: TGUID = '{6bc098fe-a71a-4454-852e-4d2ddeb2cd24}'; // 6bc098fe-a71a-4454-85-2e-4d-2d-de-b2-cd-24 )
// AVEncVideoDisplayDimension (UINT32)
AVEncVideoDisplayDimension: TGUID = '{de053668-f4ec-47a9-86d0-836770f0c1d5}'; // de053668-f4ec-47a9-86-d0-83-67-70-f0-c1-d5 )
// AVEncVideoOutputScanType (UINT32)
AVEncVideoOutputScanType: TGUID = '{460b5576-842e-49ab-a62d-b36f7312c9db}'; // 460b5576-842e-49ab-a6-2d-b3-6f-73-12-c9-db )
// AVEncVideoInverseTelecineEnable (BOOL)
AVEncVideoInverseTelecineEnable: TGUID = '{2ea9098b-e76d-4ccd-a030-d3b889c1b64c}'; // 2ea9098b-e76d-4ccd-a0-30-d3-b8-89-c1-b6-4c )
// AVEncVideoInverseTelecineThreshold (UINT32)
AVEncVideoInverseTelecineThreshold: TGUID = '{40247d84-e895-497f-b44c-b74560acfe27}'; // 40247d84-e895-497f-b4-4c-b7-45-60-ac-fe-27 )
// AVEncVideoSourceFilmContent (UINT32)
AVEncVideoSourceFilmContent: TGUID = '{1791c64b-ccfc-4827-a0ed-2557793b2b1c}'; // 1791c64b-ccfc-4827-a0-ed-25-57-79-3b-2b-1c )
// AVEncVideoSourceIsBW (BOOL)
AVEncVideoSourceIsBW: TGUID = '{42ffc49b-1812-4fdc-8d24-7054c521e6eb}'; // 42ffc49b-1812-4fdc-8d-24-70-54-c5-21-e6-eb )
// AVEncVideoFieldSwap (BOOL)
AVEncVideoFieldSwap: TGUID = '{fefd7569-4e0a-49f2-9f2b-360ea48c19a2}'; // fefd7569-4e0a-49f2-9f-2b-36-0e-a4-8c-19-a2 )
// AVEncVideoInputChromaResolution (UINT32)
// AVEncVideoOutputChromaSubsamplingFormat (UINT32)
AVEncVideoInputChromaResolution: TGUID = '{bb0cec33-16f1-47b0-8a88-37815bee1739}'; // bb0cec33-16f1-47b0-8a-88-37-81-5b-ee-17-39 )
AVEncVideoOutputChromaResolution: TGUID = '{6097b4c9-7c1d-4e64-bfcc-9e9765318ae7}'; // 6097b4c9-7c1d-4e64-bf-cc-9e-97-65-31-8a-e7 )
// AVEncVideoInputChromaSubsampling (UINT32)
// AVEncVideoOutputChromaSubsampling (UINT32)
AVEncVideoInputChromaSubsampling: TGUID = '{a8e73a39-4435-4ec3-a6ea-98300f4b36f7}'; // a8e73a39-4435-4ec3-a6-ea-98-30-0f-4b-36-f7 )
AVEncVideoOutputChromaSubsampling: TGUID = '{fa561c6c-7d17-44f0-83c9-32ed12e96343}'; // fa561c6c-7d17-44f0-83-c9-32-ed-12-e9-63-43 )
// AVEncVideoInputColorPrimaries (UINT32)
// AVEncVideoOutputColorPrimaries (UINT32)
AVEncVideoInputColorPrimaries: TGUID = '{c24d783f-7ce6-4278-90ab-28a4f1e5f86c}'; // c24d783f-7ce6-4278-90-ab-28-a4-f1-e5-f8-6c )
AVEncVideoOutputColorPrimaries: TGUID = '{be95907c-9d04-4921-8985-a6d6d87d1a6c}'; // be95907c-9d04-4921-89-85-a6-d6-d8-7d-1a-6c )
// AVEncVideoInputColorTransferFunction (UINT32)
// AVEncVideoOutputColorTransferFunction (UINT32)
AVEncVideoInputColorTransferFunction: TGUID = '{8c056111-a9c3-4b08-a0a0-ce13f8a27c75}'; // 8c056111-a9c3-4b08-a0-a0-ce-13-f8-a2-7c-75 )
AVEncVideoOutputColorTransferFunction: TGUID = '{4a7f884a-ea11-460d-bf57-b88bc75900de}'; // 4a7f884a-ea11-460d-bf-57-b8-8b-c7-59-00-de )
// AVEncVideoInputColorTransferMatrix (UINT32)
// AVEncVideoOutputColorTransferMatrix (UINT32)
AVEncVideoInputColorTransferMatrix: TGUID = '{52ed68b9-72d5-4089-958d-f5405d55081c}'; // 52ed68b9-72d5-4089-95-8d-f5-40-5d-55-08-1c )
AVEncVideoOutputColorTransferMatrix: TGUID = '{a9b90444-af40-4310-8fbe-ed6d933f892b}'; // a9b90444-af40-4310-8f-be-ed-6d-93-3f-89-2b )
// AVEncVideoInputColorLighting (UINT32)
// AVEncVideoOutputColorLighting (UINT32)
AVEncVideoInputColorLighting: TGUID = '{46a99549-0015-4a45-9c30-1d5cfa258316}'; // 46a99549-0015-4a45-9c-30-1d-5c-fa-25-83-16 )
AVEncVideoOutputColorLighting: TGUID = '{0e5aaac6-ace6-4c5c-998e-1a8c9c6c0f89}'; // 0e5aaac6-ace6-4c5c-99-8e-1a-8c-9c-6c-0f-89 )
// AVEncVideoInputColorNominalRange (UINT32)
// AVEncVideoOutputColorNominalRange (UINT32)
AVEncVideoInputColorNominalRange: TGUID = '{16cf25c6-a2a6-48e9-ae80-21aec41d427e}'; // 16cf25c6-a2a6-48e9-ae-80-21-ae-c4-1d-42-7e )
AVEncVideoOutputColorNominalRange: TGUID = '{972835ed-87b5-4e95-9500-c73958566e54}'; // 972835ed-87b5-4e95-95-00-c7-39-58-56-6e-54 )
// AVEncInputVideoSystem (UINT32)
AVEncInputVideoSystem: TGUID = '{bede146d-b616-4dc7-92b2-f5d9fa9298f7}'; // bede146d-b616-4dc7-92-b2-f5-d9-fa-92-98-f7 )
// AVEncVideoHeaderDropFrame (UINT32)
AVEncVideoHeaderDropFrame: TGUID = '{6ed9e124-7925-43fe-971b-e019f62222b4}'; // 6ed9e124-7925-43fe-97-1b-e0-19-f6-22-22-b4 )
// AVEncVideoHeaderHours (UINT32)
AVEncVideoHeaderHours: TGUID = '{2acc7702-e2da-4158-bf9b-88880129d740}'; // 2acc7702-e2da-4158-bf-9b-88-88-01-29-d7-40 )
// AVEncVideoHeaderMinutes (UINT32)
AVEncVideoHeaderMinutes: TGUID = '{dc1a99ce-0307-408b-880b-b8348ee8ca7f}'; // dc1a99ce-0307-408b-88-0b-b8-34-8e-e8-ca-7f )
// AVEncVideoHeaderSeconds (UINT32)
AVEncVideoHeaderSeconds: TGUID = '{4a2e1a05-a780-4f58-8120-9a449d69656b}'; // 4a2e1a05-a780-4f58-81-20-9a-44-9d-69-65-6b )
// AVEncVideoHeaderFrames (UINT32)
AVEncVideoHeaderFrames: TGUID = '{afd5f567-5c1b-4adc-bdaf-735610381436}'; // afd5f567-5c1b-4adc-bd-af-73-56-10-38-14-36 )
// AVEncVideoDefaultUpperFieldDominant (BOOL)
AVEncVideoDefaultUpperFieldDominant: TGUID = '{810167c4-0bc1-47ca-8fc2-57055a1474a5}'; // 810167c4-0bc1-47ca-8f-c2-57-05-5a-14-74-a5 )
// AVEncVideoCBRMotionTradeoff (UINT32)
AVEncVideoCBRMotionTradeoff: TGUID = '{0d49451e-18d5-4367-a4ef-3240df1693c4}'; // 0d49451e-18d5-4367-a4-ef-32-40-df-16-93-c4 )
// AVEncVideoCodedVideoAccessUnitSize (UINT32)
AVEncVideoCodedVideoAccessUnitSize: TGUID = '{b4b10c15-14a7-4ce8-b173-dc90a0b4fcdb}'; // b4b10c15-14a7-4ce8-b1-73-dc-90-a0-b4-fc-db )
// AVEncVideoMaxKeyframeDistance (UINT32)
AVEncVideoMaxKeyframeDistance: TGUID = '{2987123a-ba93-4704-b489-ec1e5f25292c}'; // 2987123a-ba93-4704-b4-89-ec-1e-5f-25-29-2c )
// AVEncH264CABACEnable (BOOL)
AVEncH264CABACEnable: TGUID = '{EE6CAD62-D305-4248-A50E-E1B255F7CAF8}'; // ee6cad62-d305-4248-a5-e-e1-b2-55-f7-ca-f8 )
// AVEncVideoContentType (UINT32)
AVEncVideoContentType: TGUID = '{66117ACA-EB77-459D-930C-A48D9D0683FC}'; // 66117aca-eb77-459d-93-c-a4-8d-9d-6-83-fc )
// AVEncNumWorkerThreads (UINT32)
AVEncNumWorkerThreads: TGUID = '{B0C8BF60-16F7-4951-A30B-1DB1609293D6}'; // b0c8bf60-16f7-4951-a3-b-1d-b1-60-92-93-d6 )
// AVEncVideoEncodeQP (UINT64)
AVEncVideoEncodeQP: TGUID = '{2cb5696b-23fb-4ce1-a0f9-ef5b90fd55ca}'; // 2cb5696b-23fb-4ce1-a0-f9-ef-5b-90-fd-55-ca )
// AVEncVideoMinQP (UINT32)
AVEncVideoMinQP: TGUID = '{0ee22c6a-a37c-4568-b5f1-9d4c2b3ab886}'; // ee22c6a-a37c-4568, : TGUID = '{b5-f1-9d-4c-2b-3a-b8-86 )
// AVEncVideoForceKeyFrame (UINT32)
AVEncVideoForceKeyFrame: TGUID = '{398c1b98-8353-475a-9ef2-8f265d260345}'; // 398c1b98-8353-475a-9e-f2-8f-26-5d-26-3-45 )
// AVEncH264SPSID (UINT32)
AVEncH264SPSID: TGUID = '{50f38f51-2b79-40e3-b39c-7e9fa0770501}'; // 50f38f51-2b79-40e3-b3-9c-7e-9f-a0-77-5-1 )
// AVEncH264PPSID (UINT32)
AVEncH264PPSID: TGUID = '{BFE29EC2-056C-4D68-A38D-AE5944C8582E}'; // bfe29ec2-56c-4d68-a3-8d-ae-59-44-c8-58-2e )
// AVEncAdaptiveMode (UINT32)
AVEncAdaptiveMode: TGUID = '{4419b185-da1f-4f53-bc76-097d0c1efb1e}'; // 4419b185-da1f-4f53-bc-76-9-7d-c-1e-fb-1e )
// AVScenarioInfo (UINT32)
AVScenarioInfo: TGUID = '{b28a6e64-3ff9-446a-8a4b-0d7a53413236}'; // b28a6e64-3ff9-446a-8a-4b-0d-7a-53-41-32-36 )
// AVEncMPVGOPSizeMin (UINT32)
AVEncMPVGOPSizeMin: TGUID = '{7155cf20-d440-4852-ad0f-9c4abfe37a6a}'; // 7155cf20-d440-4852-ad-0f-9c-4a-bf-e3-7a-6a )
//AVEncMPVGOPSizeMax (UINT32)
AVEncMPVGOPSizeMax: TGUID = '{fe7de4c4-1936-4fe2-bdf7-1f18ca1d001f}'; // fe7de4c4-1936-4fe2-bd-f7-1f-18-ca-1d-00-1f )
// AVEncVideoMaxCTBSize (UINT32)
AVEncVideoMaxCTBSize: TGUID = '{822363ff-cec8-43e5-92fd-e097488485e9}'; // 822363ff-cec8-43e5-92-fd-e0-97-48-84-85-e9 )
// AVEncVideoCTBSize (UINT32)
AVEncVideoCTBSize: TGUID = '{d47db8b2-e73b-4cb9-8c3e-bd877d06d77b}'; // d47db8b2-e73b-4cb9-8c-3e-bd-87-7d-06-d7-7b )
// VideoEncoderDisplayContentType (UINT32)
VideoEncoderDisplayContentType: TGUID = '{79b90b27-f4b1-42dc-9dd7-cdaf8135c400}'; // 79b90b27-f4b1-42dc-9d-d7-cd-af-81-35-c4-00 )
// AVEncEnableVideoProcessing (UINT32)
AVEncEnableVideoProcessing: TGUID = '{006f4bf6-0ea3-4d42-8702-b5d8be0f7a92}'; // 006f4bf6-0ea3-4d42-87-02-b5-d8-be-0f-7a-92 )
// AVEncVideoGradualIntraRefresh (UINT32)
AVEncVideoGradualIntraRefresh: TGUID = '{8f347dee-cb0d-49ba-b462-db6927ee2101}'; // 8f347dee-cb0d-49ba-b4-62-db-69-27-ee-21-01 )
// GetOPMContext (UINT64)
GetOPMContext: TGUID = '{2f036c05-4c14-4689-8839-294c6d73e053}'; // 2f036c05-4c14-4689-88-39-29-4c-6d-73-e0-53 )
// SetHDCPManagerContext (VOID)
SetHDCPManagerContext: TGUID = '{6d2d1fc8-3dc9-47eb-a1a2-471c80cd60d0}'; // 6d2d1fc8-3dc9-47eb-a1-a2-47-1c-80-cd-60-d0 )
// AVEncVideoMaxTemporalLayers (UINT32)
AVEncVideoMaxTemporalLayers: TGUID = '{9c668cfe-08e1-424a-934e-b764b064802a}'; // 9c668cfe-08e1-424a-93-4e-b7-64-b0-64-80-2a )
// AVEncVideoNumGOPsPerIDR (UINT32)
AVEncVideoNumGOPsPerIDR: TGUID = '{83bc5bdb-5b89-4521-8f66-33151c373176}'; // 83bc5bdb-5b89-4521-8f-66-33-15-1c-37-31-76 )
// AVEncCommonAllowFrameDrops (UINT32)
AVEncCommonAllowFrameDrops: TGUID = '{d8477dcb-9598-48e3-8d0c-752bf206093e}'; // d8477dcb-9598-48e3-8d-0c-75-2b-f2-06-09-3e )
// AVEncVideoIntraLayerPrediction (UINT32)
AVEncVideoIntraLayerPrediction: TGUID = '{d3af46b8-bf47-44bb-a283-69f0b0228ff9}'; // d3af46b8-bf47-44bb-a2-83-69-f0-b0-22-8f-f9 )
// AVEncVideoInstantTemporalUpSwitching (UINT32)
AVEncVideoInstantTemporalUpSwitching: TGUID = '{a3308307-0d96-4ba4-b1f0-b91a5e49df10}'; // a3308307-0d96-4ba4-b1-f0-b9-1a-5e-49-df-10 )
// AVEncLowPowerEncoder (UINT32)
AVEncLowPowerEncoder: TGUID = '{b668d582-8bad-4f6a-9141-375a95358b6d}'; // b668d582-8bad-4f6a-91-41-37-5a-95-35-8b-6d )
// AVEnableInLoopDeblockFilter (UINT32)
AVEnableInLoopDeblockFilter: TGUID = '{d2e8e399-0623-4bf3-92a8-4d1818529ded}'; // d2e8e399-0623-4bf3-92-a8-4d-18-18-52-9d-ed )
// AVEncVideoSelectLayer (UINT32)
AVEncVideoSelectLayer: TGUID = '{EB1084F5-6AAA-4914-BB2F-6147227F12E7}'; // eb1084f5-6aaa-4914-bb-2f-61-47-22-7f-12-e7 )
// AVEncVideoTemporalLayerCount (UINT32)
AVEncVideoTemporalLayerCount: TGUID = '{19CAEBFF-B74D-4CFD-8C27-C2F9D97D5F52}'; // 19caebff-b74d-4cfd-8c-27-c2-f9-d9-7d-5f-52 )
// AVEncVideoUsage (UINT32)
AVEncVideoUsage: TGUID = '{1f636849-5dc1-49f1-b1d8-ce3cf62ea385}'; // 1f636849-5dc1-49f1-b1-d8-ce-3c-f6-2e-a3-85 )
// AVEncVideoRateControlParams (UINT64)
AVEncVideoRateControlParams: TGUID = '{87D43767-7645-44ec-B438-D3322FBCA29F}'; // 87d43767-7645-44ec-b4-38-d3-32-2f-bc-a2-9f )
// AVEncVideoSupportedControls (UINT64)
AVEncVideoSupportedControls: TGUID = '{D3F40FDD-77B9-473d-8196-061259E69CFF}'; // d3f40fdd-77b9-473d-81-96-06-12-59-e6-9c-ff )
// AVEncVideoEncodeFrameTypeQP (UINT64)
AVEncVideoEncodeFrameTypeQP: TGUID = '{aa70b610-e03f-450c-ad07-07314e639ce7}'; // aa70b610-e03f-450c-ad-07-07-31-4e-63-9c-e7 )
// AVEncSliceControlMode (UINT32)
AVEncSliceControlMode: TGUID = '{e9e782ef-5f18-44c9-a90b-e9c3c2c17b0b}'; // e9e782ef-5f18-44c9-a9-0b-e9-c3-c2-c1-7b-0b )
// AVEncSliceControlSize (UINT32)
AVEncSliceControlSize: TGUID = '{92f51df3-07a5-4172-aefe-c69ca3b60e35}'; // 92f51df3-07a5-4172-ae-fe-c6-9c-a3-b6-0e-35 )
// CODECAPI_AVEncSliceGenerationMode (UINT32)
AVEncSliceGenerationMode: TGUID = '{8a6bc67f-9497-4286-b46b-02db8d60edbc}'; // 8a6bc67f-9497-4286-b4-6b-02-db-8d-60-ed-bc )
// AVEncVideoMaxNumRefFrame (UINT32)
AVEncVideoMaxNumRefFrame: TGUID = '{964829ed-94f9-43b4-b74d-ef40944b69a0}'; // 964829ed-94f9-43b4-b7-4d-ef-40-94-4b-69-a0 )
// AVEncVideoMeanAbsoluteDifference (UINT32)
AVEncVideoMeanAbsoluteDifference: TGUID = '{e5c0c10f-81a4-422d-8c3f-b474a4581336}'; // e5c0c10f-81a4-422d-8c-3f-b4-74-a4-58-13-36 )
// AVEncVideoMaxQP (UINT32)
AVEncVideoMaxQP: TGUID = '{3daf6f66-a6a7-45e0-a8e5-f2743f46a3a2}'; // 3daf6f66-a6a7-45e0-a8-e5-f2-74-3f-46-a3-a2 )
// AVEncVideoLTRBufferControl (UINT32)
AVEncVideoLTRBufferControl: TGUID = '{a4a0e93d-4cbc-444c-89f4-826d310e92a7}'; // a4a0e93d-4cbc-444c-89-f4-82-6d-31-0e-92-a7 )
// AVEncVideoMarkLTRFrame (UINT32)
AVEncVideoMarkLTRFrame: TGUID = '{e42f4748-a06d-4ef9-8cea-3d05fde3bd3b}'; // e42f4748-a06d-4ef9-8c-ea-3d-05-fd-e3-bd-3b )
// AVEncVideoUseLTRFrame (UINT32)
AVEncVideoUseLTRFrame: TGUID = '{00752db8-55f7-4f80-895b-27639195f2ad}'; // 00752db8-55f7-4f80-89-5b-27-63-91-95-f2-ad )
// AVEncVideoROIEnabled (UINT32)
AVEncVideoROIEnabled: TGUID = '{d74f7f18-44dd-4b85-aba3-05d9f42a8280}'; // d74f7f18-44dd-4b85-ab-a3-5-d9-f4-2a-82-80 )
// AVEncVideoDirtyRectEnabled (UINT32)
AVEncVideoDirtyRectEnabled: TGUID = '{8acb8fdd-5e0c-4c66-8729-b8f629ab04fb}'; // 8acb8fdd-5e0c-4c66-87-29-b8-f6-29-ab-04-fb )
// AVEncMaxFrameRate (UINT64)
AVEncMaxFrameRate: TGUID = '{B98E1B31-19FA-4D4F-9931-D6A5B8AAB93C}'; // b98e1b31-19fa-4d4f-99-31-d6-a5-b8-aa-b9-3c )
// Audio/Video Mux
// AVEncMuxOutputStreamType (UINT32)
AVEncMuxOutputStreamType: TGUID = '{CEDD9E8F-34D3-44db-A1D8-F81520254F3E}'; // cedd9e8f-34d3-44db-a1-d8-f8-15-20-25-4f-3e)
// Common Post-Encode Video Statistical Parameters
// AVEncStatVideoOutputFrameRate (UINT32/UINT32)
AVEncStatVideoOutputFrameRate: TGUID = '{be747849-9ab4-4a63-98fe-f143f04f8ee9}'; // be747849-9ab4-4a63-98-fe-f1-43-f0-4f-8e-e9 )
// AVEncStatVideoCodedFrames (UINT32)
AVEncStatVideoCodedFrames: TGUID = '{d47f8d61-6f5a-4a26-bb9f-cd9518462bcd}'; // d47f8d61-6f5a-4a26-bb-9f-cd-95-18-46-2b-cd )
// AVEncStatVideoTotalFrames (UINT32)
AVEncStatVideoTotalFrames: TGUID = '{fdaa9916-119a-4222-9ad6-3f7cab99cc8b}'; // fdaa9916-119a-4222-9a-d6-3f-7c-ab-99-cc-8b )
// Common Audio Parameters
// AVEncAudioIntervalToEncode (UINT64)
AVEncAudioIntervalToEncode: TGUID = '{866e4b4d-725a-467c-bb01-b496b23b25f9}'; // 866e4b4d-725a-467c-bb-01-b4-96-b2-3b-25-f9 )
// AVEncAudioIntervalToSkip (UINT64)
AVEncAudioIntervalToSkip: TGUID = '{88c15f94-c38c-4796-a9e8-96e967983f26}'; // 88c15f94-c38c-4796-a9-e8-96-e9-67-98-3f-26 )
// AVEncAudioDualMono (UINT32) - Read/Write
// Some audio encoders can encode 2 channel input as "dual mono". Use this
// property to set the appropriate field in the bitstream header to indicate that the
// 2 channel bitstream is or isn't dual mono.
// For encoding MPEG audio, use the DualChannel option in AVEncMPACodingMode instead
AVEncAudioDualMono: TGUID = '{3648126b-a3e8-4329-9b3a-5ce566a43bd3}'; // 3648126b-a3e8-4329-9b-3a-5c-e5-66-a4-3b-d3 )
// AVEncAudioMeanBitRate (UINT32) - Read/Write - Used to specify audio bitrate (in bits per second) when the encoder is instantiated as an audio+video encoder.
AVEncAudioMeanBitRate: TGUID = '{921295bb-4fca-4679-aab8-9e2a1d753384}'; // 921295bb-4fca-4679-aa-b8-9e-2a-1d-75-33-84 )
// AVEncAudioMapDestChannel0..15 (UINT32)
AVEncAudioMapDestChannel0: TGUID = '{bc5d0b60-df6a-4e16-9803-b82007a30c8d}'; // bc5d0b60-df6a-4e16-98-03-b8-20-07-a3-0c-8d )
AVEncAudioMapDestChannel1: TGUID = '{bc5d0b61-df6a-4e16-9803-b82007a30c8d}'; // bc5d0b61-df6a-4e16-98-03-b8-20-07-a3-0c-8d )
AVEncAudioMapDestChannel2: TGUID = '{bc5d0b62-df6a-4e16-9803-b82007a30c8d}'; // bc5d0b62-df6a-4e16-98-03-b8-20-07-a3-0c-8d )
AVEncAudioMapDestChannel3: TGUID = '{bc5d0b63-df6a-4e16-9803-b82007a30c8d}'; // bc5d0b63-df6a-4e16-98-03-b8-20-07-a3-0c-8d )
AVEncAudioMapDestChannel4: TGUID = '{bc5d0b64-df6a-4e16-9803-b82007a30c8d}'; // bc5d0b64-df6a-4e16-98-03-b8-20-07-a3-0c-8d )
AVEncAudioMapDestChannel5: TGUID = '{bc5d0b65-df6a-4e16-9803-b82007a30c8d}'; // bc5d0b65-df6a-4e16-98-03-b8-20-07-a3-0c-8d )
AVEncAudioMapDestChannel6: TGUID = '{bc5d0b66-df6a-4e16-9803-b82007a30c8d}'; // bc5d0b66-df6a-4e16-98-03-b8-20-07-a3-0c-8d )
AVEncAudioMapDestChannel7: TGUID = '{bc5d0b67-df6a-4e16-9803-b82007a30c8d}'; // bc5d0b67-df6a-4e16-98-03-b8-20-07-a3-0c-8d )
AVEncAudioMapDestChannel8: TGUID = '{bc5d0b68-df6a-4e16-9803-b82007a30c8d}'; // bc5d0b68-df6a-4e16-98-03-b8-20-07-a3-0c-8d )
AVEncAudioMapDestChannel9: TGUID = '{bc5d0b69-df6a-4e16-9803-b82007a30c8d}'; // bc5d0b69-df6a-4e16-98-03-b8-20-07-a3-0c-8d )
AVEncAudioMapDestChannel10: TGUID = '{bc5d0b6a-df6a-4e16-9803-b82007a30c8d}'; // bc5d0b6a-df6a-4e16-98-03-b8-20-07-a3-0c-8d )
AVEncAudioMapDestChannel11: TGUID = '{bc5d0b6b-df6a-4e16-9803-b82007a30c8d}'; // bc5d0b6b-df6a-4e16-98-03-b8-20-07-a3-0c-8d )
AVEncAudioMapDestChannel12: TGUID = '{bc5d0b6c-df6a-4e16-9803-b82007a30c8d}'; // bc5d0b6c-df6a-4e16-98-03-b8-20-07-a3-0c-8d )
AVEncAudioMapDestChannel13: TGUID = '{bc5d0b6d-df6a-4e16-9803-b82007a30c8d}'; // bc5d0b6d-df6a-4e16-98-03-b8-20-07-a3-0c-8d )
AVEncAudioMapDestChannel14: TGUID = '{bc5d0b6e-df6a-4e16-9803-b82007a30c8d}'; // bc5d0b6e-df6a-4e16-98-03-b8-20-07-a3-0c-8d )
AVEncAudioMapDestChannel15: TGUID = '{bc5d0b6f-df6a-4e16-9803-b82007a30c8d}'; // bc5d0b6f-df6a-4e16-98-03-b8-20-07-a3-0c-8d )
// AVEncAudioInputContent (UINT32) <---- You have ENUM in the doc
AVEncAudioInputContent: TGUID = '{3e226c2b-60b9-4a39-b00b-a7b40f70d566}'; // 3e226c2b-60b9-4a39-b0-0b-a7-b4-0f-70-d5-66 )
// Common Post-Encode Audio Statistical Parameters
// AVEncStatAudioPeakPCMValue (UINT32)
AVEncStatAudioPeakPCMValue: TGUID = '{dce7fd34-dc00-4c16-821b-35d9eb00fb1a}'; // dce7fd34-dc00-4c16-82-1b-35-d9-eb-00-fb-1a )
// AVEncStatAudioAveragePCMValue (UINT32)
AVEncStatAudioAveragePCMValue: TGUID = '{979272f8-d17f-4e32-bb73-4e731c68ba2d}'; // 979272f8-d17f-4e32-bb-73-4e-73-1c-68-ba-2d )
// AVEncStatAverageBPS (UINT32)
AVEncStatAudioAverageBPS: TGUID = '{ca6724db-7059-4351-8b43-f82198826a14}'; // ca6724db-7059-4351-8b-43-f8-21-98-82-6a-14 )
AVEncStatAverageBPS: TGUID = '{ca6724db-7059-4351-8b43-f82198826a14}'; // ca6724db-7059-4351-8b-43-f8-21-98-82-6a-14 )
// AVEncStatHardwareProcessorUtilitization (UINT32)
// HW usage % x 1000
AVEncStatHardwareProcessorUtilitization: TGUID = '{995dc027-cb95-49e6-b91b-5967753cdcb8}'; // 995dc027-cb95-49e6-b9-1b-59-67-75-3c-dc-b8 )
// AVEncStatHardwareBandwidthUtilitization (UINT32)
// HW usage % x 1000
AVEncStatHardwareBandwidthUtilitization: TGUID = '{0124ba9b-dc41-4826-b45f-18ac01b3d5a8}'; // 0124ba9b-dc41-4826-b4-5f-18-ac-01-b3-d5-a8 )
// MPEG Video Encoding Interface
// MPV Encoder Specific Parameters
// AVEncMPVGOPSize (UINT32)
AVEncMPVGOPSize: TGUID = '{95f31b26-95a4-41aa-9303-246a7fc6eef1}'; // 95f31b26-95a4-41aa-93-03-24-6a-7f-c6-ee-f1 )
// AVEncMPVGOPOpen (BOOL)
AVEncMPVGOPOpen: TGUID = '{b1d5d4a6-3300-49b1-ae61-a09937ab0e49}'; // b1d5d4a6-3300-49b1-ae-61-a0-99-37-ab-0e-49 )
// AVEncMPVDefaultBPictureCount (UINT32)
AVEncMPVDefaultBPictureCount: TGUID = '{8d390aac-dc5c-4200-b57f-814d04babab2}'; // 8d390aac-dc5c-4200-b5-7f-81-4d-04-ba-ba-b2 )
// AVEncMPVProfile (UINT32) <---- You have GUID in the doc
AVEncMPVProfile: TGUID = '{dabb534a-1d99-4284-975a-d90e2239baa1}'; // dabb534a-1d99-4284-97-5a-d9-0e-22-39-ba-a1 )
// AVEncMPVLevel (UINT32) <---- You have GUID in the doc
AVEncMPVLevel: TGUID = '{6ee40c40-a60c-41ef-8f50-37c2249e2cb3}'; // 6ee40c40-a60c-41ef-8f-50-37-c2-24-9e-2c-b3 )
// AVEncMPVFrameFieldMode (UINT32)
AVEncMPVFrameFieldMode: TGUID = '{acb5de96-7b93-4c2f-8825-b0295fa93bf4}'; // acb5de96-7b93-4c2f-88-25-b0-29-5f-a9-3b-f4 )
// Advanced MPV Encoder Specific Parameters
// AVEncMPVAddSeqEndCode (BOOL)
AVEncMPVAddSeqEndCode: TGUID = '{a823178f-57df-4c7a-b8fd-e5ec8887708d}'; // a823178f-57df-4c7a-b8-fd-e5-ec-88-87-70-8d )
// AVEncMPVGOPSInSeq (UINT32)
AVEncMPVGOPSInSeq: TGUID = '{993410d4-2691-4192-9978-98dc2603669f}'; // 993410d4-2691-4192-99-78-98-dc-26-03-66-9f )
// AVEncMPVUseConcealmentMotionVectors (BOOL)
AVEncMPVUseConcealmentMotionVectors: TGUID = '{ec770cf3-6908-4b4b-aa30-7fb986214fea}'; // ec770cf3-6908-4b4b-aa-30-7f-b9-86-21-4f-ea )
// AVEncMPVSceneDetection (UINT32)
AVEncMPVSceneDetection: TGUID = '{552799f1-db4c-405b-8a3a-c93f2d0674dc}'; // 552799f1-db4c-405b-8a-3a-c9-3f-2d-06-74-dc )
// AVEncMPVGenerateHeaderSeqExt (BOOL)
AVEncMPVGenerateHeaderSeqExt: TGUID = '{d5e78611-082d-4e6b-98af-0f51ab139222}'; // d5e78611-082d-4e6b-98-af-0f-51-ab-13-92-22 )
// AVEncMPVGenerateHeaderSeqDispExt (BOOL)
AVEncMPVGenerateHeaderSeqDispExt: TGUID = '{6437aa6f-5a3c-4de9-8a16-53d9c4ad326f}'; // 6437aa6f-5a3c-4de9-8a-16-53-d9-c4-ad-32-6f )
// AVEncMPVGenerateHeaderPicExt (BOOL)
AVEncMPVGenerateHeaderPicExt: TGUID = '{1b8464ab-944f-45f0-b74e-3a58dad11f37}'; // 1b8464ab-944f-45f0-b7-4e-3a-58-da-d1-1f-37 )
// AVEncMPVGenerateHeaderPicDispExt (BOOL)
AVEncMPVGenerateHeaderPicDispExt: TGUID = '{c6412f84-c03f-4f40-a00c-4293df8395bb}'; // c6412f84-c03f-4f40-a0-0c-42-93-df-83-95-bb )
// AVEncMPVGenerateHeaderSeqScaleExt (BOOL)
AVEncMPVGenerateHeaderSeqScaleExt: TGUID = '{0722d62f-dd59-4a86-9cd5-644f8e2653d8}'; // 0722d62f-dd59-4a86-9c-d5-64-4f-8e-26-53-d8 )
// AVEncMPVScanPattern (UINT32)
AVEncMPVScanPattern: TGUID = '{7f8a478e-7bbb-4ae2-b2fc-96d17fc4a2d6}'; // 7f8a478e-7bbb-4ae2-b2-fc-96-d1-7f-c4-a2-d6 )
// AVEncMPVIntraDCPrecision (UINT32)
AVEncMPVIntraDCPrecision: TGUID = '{a0116151-cbc8-4af3-97dc-d00cceb82d79}'; // a0116151-cbc8-4af3-97-dc-d0-0c-ce-b8-2d-79 )
// AVEncMPVQScaleType (UINT32)
AVEncMPVQScaleType: TGUID = '{2b79ebb7-f484-4af7-bb58-a2a188c5cbbe}'; // 2b79ebb7-f484-4af7-bb-58-a2-a1-88-c5-cb-be )
// AVEncMPVIntraVLCTable (UINT32)
AVEncMPVIntraVLCTable: TGUID = '{a2b83ff5-1a99-405a-af95-c5997d558d3a}'; // a2b83ff5-1a99-405a-af-95-c5-99-7d-55-8d-3a )
// AVEncMPVQuantMatrixIntra (BYTE[64] encoded as a string of 128 hex digits)
AVEncMPVQuantMatrixIntra: TGUID = '{9bea04f3-6621-442c-8ba1-3ac378979698}'; // 9bea04f3-6621-442c-8b-a1-3a-c3-78-97-96-98 )
// AVEncMPVQuantMatrixNonIntra (BYTE[64] encoded as a string of 128 hex digits)
AVEncMPVQuantMatrixNonIntra: TGUID = '{87f441d8-0997-4beb-a08e-8573d409cf75}'; // 87f441d8-0997-4beb-a0-8e-85-73-d4-09-cf-75 )
// AVEncMPVQuantMatrixChromaIntra (BYTE[64] encoded as a string of 128 hex digits)
AVEncMPVQuantMatrixChromaIntra: TGUID = '{9eb9ecd4-018d-4ffd-8f2d-39e49f07b17a}'; // 9eb9ecd4-018d-4ffd-8f-2d-39-e4-9f-07-b1-7a )
// AVEncMPVQuantMatrixChromaNonIntra (BYTE[64] encoded as a string of 128 hex digits)
AVEncMPVQuantMatrixChromaNonIntra: TGUID = '{1415b6b1-362a-4338-ba9a-1ef58703c05b}'; // 1415b6b1-362a-4338-ba-9a-1e-f5-87-03-c0-5b )
// MPEG1 Audio Encoding Interface
// MPEG1 Audio Specific Parameters
// AVEncMPALayer (UINT)
AVEncMPALayer: TGUID = '{9d377230-f91b-453d-9ce0-78445414c22d}'; // 9d377230-f91b-453d-9c-e0-78-44-54-14-c2-2d )
// AVEncMPACodingMode (UINT)
AVEncMPACodingMode: TGUID = '{b16ade03-4b93-43d7-a550-90b4fe224537}'; // b16ade03-4b93-43d7-a5-50-90-b4-fe-22-45-37 )
// AVEncMPACopyright (BOOL) - default state to encode into the stream (may be overridden by input)
// 1 (true) - copyright protected
// 0 (false) - not copyright protected
AVEncMPACopyright: TGUID = '{a6ae762a-d0a9-4454-b8ef-f2dbeefdd3bd}'; // a6ae762a-d0a9-4454-b8-ef-f2-db-ee-fd-d3-bd )
// AVEncMPAOriginalBitstream (BOOL) - default value to encode into the stream (may be overridden by input)
// 1 (true) - for original bitstream
// 0 (false) - for copy bitstream
AVEncMPAOriginalBitstream: TGUID = '{3cfb7855-9cc9-47ff-b829-b36786c92346}'; // 3cfb7855-9cc9-47ff-b8-29-b3-67-86-c9-23-46 )
// AVEncMPAEnableRedundancyProtection (BOOL)
// 1 (true) - Redundancy should be added to facilitate error detection and concealment (CRC)
// 0 (false) - No redundancy should be added
AVEncMPAEnableRedundancyProtection: TGUID = '{5e54b09e-b2e7-4973-a89b-0b3650a3beda}'; // 5e54b09e-b2e7-4973-a8-9b-0b-36-50-a3-be-da )
// AVEncMPAPrivateUserBit (UINT) - User data bit value to encode in the stream
AVEncMPAPrivateUserBit: TGUID = '{afa505ce-c1e3-4e3d-851b-61b700e5e6cc}'; // afa505ce-c1e3-4e3d-85-1b-61-b7-00-e5-e6-cc )
// AVEncMPAEmphasisType (UINT)
// Indicates type of de-emphasis filter to be used
AVEncMPAEmphasisType: TGUID = '{2d59fcda-bf4e-4ed6-b5df-5b03b36b0a1f}'; // 2d59fcda-bf4e-4ed6-b5-df-5b-03-b3-6b-0a-1f )
// Dolby Digital(TM) Audio Encoding Interface
// Dolby Digital(TM) Audio Specific Parameters
// AVEncDDService (UINT)
AVEncDDService: TGUID = '{d2e1bec7-5172-4d2a-a50e-2f3b82b1ddf8}'; // d2e1bec7-5172-4d2a-a5-0e-2f-3b-82-b1-dd-f8 )
// AVEncDDDialogNormalization (UINT32)
AVEncDDDialogNormalization: TGUID = '{d7055acf-f125-437d-a704-79c79f0404a8}'; // d7055acf-f125-437d-a7-04-79-c7-9f-04-04-a8 )
// AVEncDDCentreDownMixLevel (UINT32)
AVEncDDCentreDownMixLevel: TGUID = '{e285072c-c958-4a81-afd2-e5e0daf1b148}'; // e285072c-c958-4a81-af-d2-e5-e0-da-f1-b1-48 )
// AVEncDDSurroundDownMixLevel (UINT32)
AVEncDDSurroundDownMixLevel: TGUID = '{7b20d6e5-0bcf-4273-a487-506b047997e9}'; // 7b20d6e5-0bcf-4273-a4-87-50-6b-04-79-97-e9 )
// AVEncDDProductionInfoExists (BOOL)
AVEncDDProductionInfoExists: TGUID = '{b0b7fe5f-b6ab-4f40-964d-8d91f17c19e8}'; // b0b7fe5f-b6ab-4f40-96-4d-8d-91-f1-7c-19-e8 )
// AVEncDDProductionRoomType (UINT32)
AVEncDDProductionRoomType: TGUID = '{dad7ad60-23d8-4ab7-a284-556986d8a6fe}'; // dad7ad60-23d8-4ab7-a2-84-55-69-86-d8-a6-fe )
// AVEncDDProductionMixLevel (UINT32)
AVEncDDProductionMixLevel: TGUID = '{301d103a-cbf9-4776-8899-7c15b461ab26}'; // 301d103a-cbf9-4776-88-99-7c-15-b4-61-ab-26 )
// AVEncDDCopyright (BOOL)
AVEncDDCopyright: TGUID = '{8694f076-cd75-481d-a5c6-a904dcc828f0}'; // 8694f076-cd75-481d-a5-c6-a9-04-dc-c8-28-f0 )
// AVEncDDOriginalBitstream (BOOL)
AVEncDDOriginalBitstream: TGUID = '{966ae800-5bd3-4ff9-95b9-d30566273856}'; // 966ae800-5bd3-4ff9-95-b9-d3-05-66-27-38-56 )
// AVEncDDDigitalDeemphasis (BOOL)
AVEncDDDigitalDeemphasis: TGUID = '{e024a2c2-947c-45ac-87d8-f1030c5c0082}'; // e024a2c2-947c-45ac-87-d8-f1-03-0c-5c-00-82 )
// AVEncDDDCHighPassFilter (BOOL)
AVEncDDDCHighPassFilter: TGUID = '{9565239f-861c-4ac8-bfda-e00cb4db8548}'; // 9565239f-861c-4ac8-bf-da-e0-0c-b4-db-85-48 )
// AVEncDDChannelBWLowPassFilter (BOOL)
AVEncDDChannelBWLowPassFilter: TGUID = '{e197821d-d2e7-43e2-ad2c-00582f518545}'; // e197821d-d2e7-43e2-ad-2c-00-58-2f-51-85-45 )
// AVEncDDLFELowPassFilter (BOOL)
AVEncDDLFELowPassFilter: TGUID = '{d3b80f6f-9d15-45e5-91be-019c3fab1f01}'; // d3b80f6f-9d15-45e5-91-be-01-9c-3f-ab-1f-01 )
// AVEncDDSurround90DegreeePhaseShift (BOOL)
AVEncDDSurround90DegreeePhaseShift: TGUID = '{25ecec9d-3553-42c0-bb56-d25792104f80}'; // 25ecec9d-3553-42c0-bb-56-d2-57-92-10-4f-80 )
// AVEncDDSurround3dBAttenuation (BOOL)
AVEncDDSurround3dBAttenuation: TGUID = '{4d43b99d-31e2-48b9-bf2e-5cbf1a572784}'; // 4d43b99d-31e2-48b9-bf-2e-5c-bf-1a-57-27-84 )
// AVEncDDDynamicRangeCompressionControl (UINT32)
AVEncDDDynamicRangeCompressionControl: TGUID = '{cfc2ff6d-79b8-4b8d-a8aa-a0c9bd1c2940}'; // cfc2ff6d-79b8-4b8d-a8-aa-a0-c9-bd-1c-29-40 )
// AVEncDDRFPreEmphasisFilter (BOOL)
AVEncDDRFPreEmphasisFilter: TGUID = '{21af44c0-244e-4f3d-a2cc-3d3068b2e73f}'; // 21af44c0-244e-4f3d-a2-cc-3d-30-68-b2-e7-3f )
// AVEncDDSurroundExMode (UINT32)
AVEncDDSurroundExMode: TGUID = '{91607cee-dbdd-4eb6-bca2-aadfafa3dd68}'; // 91607cee-dbdd-4eb6-bc-a2-aa-df-af-a3-dd-68 )
// AVEncDDPreferredStereoDownMixMode (UINT32)
AVEncDDPreferredStereoDownMixMode: TGUID = '{7f4e6b31-9185-403d-b0a2-763743e6f063}'; // 7f4e6b31-9185-403d-b0-a2-76-37-43-e6-f0-63 )
// AVEncDDLtRtCenterMixLvl_x10 (INT32)
AVEncDDLtRtCenterMixLvl_x10: TGUID = '{dca128a2-491f-4600-b2da-76e3344b4197}'; // dca128a2-491f-4600-b2-da-76-e3-34-4b-41-97 )
// AVEncDDLtRtSurroundMixLvl_x10 (INT32)
AVEncDDLtRtSurroundMixLvl_x10: TGUID = '{212246c7-3d2c-4dfa-bc21-652a9098690d}'; // 212246c7-3d2c-4dfa-bc-21-65-2a-90-98-69-0d )
// AVEncDDLoRoCenterMixLvl (INT32)
AVEncDDLoRoCenterMixLvl_x10: TGUID = '{1cfba222-25b3-4bf4-9bfd-e7111267858c}'; // 1cfba222-25b3-4bf4-9b-fd-e7-11-12-67-85-8c )
// AVEncDDLoRoSurroundMixLvl_x10 (INT32)
AVEncDDLoRoSurroundMixLvl_x10: TGUID = '{e725cff6-eb56-40c7-8450-2b9367e91555}'; // e725cff6-eb56-40c7-84-50-2b-93-67-e9-15-55 )
// AVEncDDAtoDConverterType (UINT32)
AVEncDDAtoDConverterType: TGUID = '{719f9612-81a1-47e0-9a05-d94ad5fca948}'; // 719f9612-81a1-47e0-9a-05-d9-4a-d5-fc-a9-48 )
// AVEncDDHeadphoneMode (UINT32)
AVEncDDHeadphoneMode: TGUID = '{4052dbec-52f5-42f5-9b00-d134b1341b9d}'; // 4052dbec-52f5-42f5-9b-00-d1-34-b1-34-1b-9d )
// WMV Video Encoding Interface
// WMV Video Specific Parameters
// AVEncWMVKeyFrameDistance (UINT32)
AVEncWMVKeyFrameDistance: TGUID = '{5569055e-e268-4771-b83e-9555ea28aed3}'; // 5569055e-e268-4771-b8-3e-95-55-ea-28-ae-d3 )
// AVEncWMVInterlacedEncoding (UINT32)
AVEncWMVInterlacedEncoding: TGUID = '{e3d00f8a-c6f5-4e14-a588-0ec87a726f9b}'; // e3d00f8a-c6f5-4e14-a5-88-0e-c8-7a-72-6f-9b )
// AVEncWMVDecoderComplexity (UINT32)
AVEncWMVDecoderComplexity: TGUID = '{f32c0dab-f3cb-4217-b79f-8762768b5f67}'; // f32c0dab-f3cb-4217-b7-9f-87-62-76-8b-5f-67 )
// AVEncWMVHasKeyFrameBufferLevelMarker (BOOL)
AVEncWMVKeyFrameBufferLevelMarker: TGUID = '{51ff1115-33ac-426c-a1b1-09321bdf96b4}'; // 51ff1115-33ac-426c-a1-b1-09-32-1b-df-96-b4 )
// AVEncWMVProduceDummyFrames (UINT32)
AVEncWMVProduceDummyFrames: TGUID = '{d669d001-183c-42e3-a3ca-2f4586d2396c}'; // d669d001-183c-42e3-a3-ca-2f-45-86-d2-39-6c )
// WMV Post-Encode Statistical Parameters
// AVEncStatWMVCBAvg (UINT32/UINT32)
AVEncStatWMVCBAvg: TGUID = '{6aa6229f-d602-4b9d-b68c-c1ad78884bef}'; // 6aa6229f-d602-4b9d-b6-8c-c1-ad-78-88-4b-ef )
// AVEncStatWMVCBMax (UINT32/UINT32)
AVEncStatWMVCBMax: TGUID = '{e976bef8-00fe-44b4-b625-8f238bc03499}'; // e976bef8-00fe-44b4-b6-25-8f-23-8b-c0-34-99 )
// AVEncStatWMVDecoderComplexityProfile (UINT32)
AVEncStatWMVDecoderComplexityProfile: TGUID = '{89e69fc3-0f9b-436c-974a-df821227c90d}'; // 89e69fc3-0f9b-436c-97-4a-df-82-12-27-c9-0d )
// AVEncStatMPVSkippedEmptyFrames (UINT32)
AVEncStatMPVSkippedEmptyFrames: TGUID = '{32195fd3-590d-4812-a7ed-6d639a1f9711}'; // 32195fd3-590d-4812-a7-ed-6d-63-9a-1f-97-11 )
// MPEG1/2 Multiplexer Interfaces
// MPEG1/2 Packetizer Interface
// Shared with Mux:
// AVEncMP12MuxEarliestPTS (UINT32)
// AVEncMP12MuxLargestPacketSize (UINT32)
// AVEncMP12MuxSysSTDBufferBound (UINT32)
// AVEncMP12PktzSTDBuffer (UINT32)
AVEncMP12PktzSTDBuffer: TGUID = '{0b751bd0-819e-478c-9435-75208926b377}'; // 0b751bd0-819e-478c-94-35-75-20-89-26-b3-77 )
// AVEncMP12PktzStreamID (UINT32)
AVEncMP12PktzStreamID: TGUID = '{c834d038-f5e8-4408-9b60-88f36493fedf}'; // c834d038-f5e8-4408-9b-60-88-f3-64-93-fe-df )
// AVEncMP12PktzInitialPTS (UINT32)
AVEncMP12PktzInitialPTS: TGUID = '{2a4f2065-9a63-4d20-ae22-0a1bc896a315}'; // 2a4f2065-9a63-4d20-ae-22-0a-1b-c8-96-a3-15 )
// AVEncMP12PktzPacketSize (UINT32)
AVEncMP12PktzPacketSize: TGUID = '{ab71347a-1332-4dde-a0e5-ccf7da8a0f22}'; // ab71347a-1332-4dde-a0-e5-cc-f7-da-8a-0f-22 )
// AVEncMP12PktzCopyright (BOOL)
AVEncMP12PktzCopyright: TGUID = '{c8f4b0c1-094c-43c7-8e68-a595405a6ef8}'; // c8f4b0c1-094c-43c7-8e-68-a5-95-40-5a-6e-f8 )
// AVEncMP12PktzOriginal (BOOL)
AVEncMP12PktzOriginal: TGUID = '{6b178416-31b9-4964-94cb-6bff866cdf83}'; // 6b178416-31b9-4964-94-cb-6b-ff-86-6c-df-83 )
// MPEG1/2 Multiplexer Interface
// AVEncMP12MuxPacketOverhead (UINT32)
AVEncMP12MuxPacketOverhead: TGUID = '{e40bd720-3955-4453-acf9-b79132a38fa0}'; // e40bd720-3955-4453-ac-f9-b7-91-32-a3-8f-a0 )
// AVEncMP12MuxNumStreams (UINT32)
AVEncMP12MuxNumStreams: TGUID = '{f7164a41-dced-4659-a8f2-fb693f2a4cd0}'; // f7164a41-dced-4659-a8-f2-fb-69-3f-2a-4c-d0 )
// AVEncMP12MuxEarliestPTS (UINT32)
AVEncMP12MuxEarliestPTS: TGUID = '{157232b6-f809-474e-9464-a7f93014a817}'; // 157232b6-f809-474e-94-64-a7-f9-30-14-a8-17 )
// AVEncMP12MuxLargestPacketSize (UINT32)
AVEncMP12MuxLargestPacketSize: TGUID = '{35ceb711-f461-4b92-a4ef-17b6841ed254}'; // 35ceb711-f461-4b92-a4-ef-17-b6-84-1e-d2-54 )
// AVEncMP12MuxInitialSCR (UINT32)
AVEncMP12MuxInitialSCR: TGUID = '{3433ad21-1b91-4a0b-b190-2b77063b63a4}'; // 3433ad21-1b91-4a0b-b1-90-2b-77-06-3b-63-a4 )
// AVEncMP12MuxMuxRate (UINT32)
AVEncMP12MuxMuxRate: TGUID = '{ee047c72-4bdb-4a9d-8e21-41926c823da7}'; // ee047c72-4bdb-4a9d-8e-21-41-92-6c-82-3d-a7 )
// AVEncMP12MuxPackSize (UINT32)
AVEncMP12MuxPackSize: TGUID = '{f916053a-1ce8-4faf-aa0b-ba31c80034b8}'; // f916053a-1ce8-4faf-aa-0b-ba-31-c8-00-34-b8 )
// AVEncMP12MuxSysSTDBufferBound (UINT32)
AVEncMP12MuxSysSTDBufferBound: TGUID = '{35746903-b545-43e7-bb35-c5e0a7d5093c}'; // 35746903-b545-43e7-bb-35-c5-e0-a7-d5-09-3c )
// AVEncMP12MuxSysRateBound (UINT32)
AVEncMP12MuxSysRateBound: TGUID = '{05f0428a-ee30-489d-ae28-205c72446710}'; // 05f0428a-ee30-489d-ae-28-20-5c-72-44-67-10 )
// AVEncMP12MuxTargetPacketizer (UINT32)
AVEncMP12MuxTargetPacketizer: TGUID = '{d862212a-2015-45dd-9a32-1b3aa88205a0}'; // d862212a-2015-45dd-9a-32-1b-3a-a8-82-05-a0 )
// AVEncMP12MuxSysFixed (UINT32)
AVEncMP12MuxSysFixed: TGUID = '{cefb987e-894f-452e-8f89-a4ef8cec063a}'; // cefb987e-894f-452e-8f-89-a4-ef-8c-ec-06-3a )
// AVEncMP12MuxSysCSPS (UINT32)
AVEncMP12MuxSysCSPS: TGUID = '{7952ff45-9c0d-4822-bc82-8ad772e02993}'; // 7952ff45-9c0d-4822-bc-82-8a-d7-72-e0-29-93 )
// AVEncMP12MuxSysVideoLock (BOOL)
AVEncMP12MuxSysVideoLock: TGUID = '{b8296408-2430-4d37-a2a1-95b3e435a91d}'; // b8296408-2430-4d37-a2-a1-95-b3-e4-35-a9-1d )
// AVEncMP12MuxSysAudioLock (BOOL)
AVEncMP12MuxSysAudioLock: TGUID = '{0fbb5752-1d43-47bf-bd79-f2293d8ce337}'; // 0fbb5752-1d43-47bf-bd-79-f2-29-3d-8c-e3-37 )
// AVEncMP12MuxDVDNavPacks (BOOL)
AVEncMP12MuxDVDNavPacks: TGUID = '{c7607ced-8cf1-4a99-83a1-ee5461be3574}'; // c7607ced-8cf1-4a99-83-a1-ee-54-61-be-35-74 )
// Decoding Interface
// format values are GUIDs as VARIANT BSTRs
AVDecCommonInputFormat: TGUID = '{E5005239-BD89-4be3-9C0F-5DDE317988CC}'; // e5005239-bd89-4be3-9c-0f-5d-de-31-79-88-cc)
AVDecCommonOutputFormat: TGUID = '{3c790028-c0ce-4256-b1a2-1b0fc8b1dcdc}'; // 3c790028-c0ce-4256-b1-a2-1b-0f-c8-b1-dc-dc)
// AVDecCommonMeanBitRate - Mean bitrate in mbits/sec (UINT32)
AVDecCommonMeanBitRate: TGUID = '{59488217-007A-4f7a-8E41-5C48B1EAC5C6}'; // 59488217-007a-4f7a-8e-41-5c-48-b1-ea-c5-c6)
// AVDecCommonMeanBitRateInterval - Mean bitrate interval (in 100ns) (UINT64)
AVDecCommonMeanBitRateInterval: TGUID = '{0EE437C6-38A7-4c5c-944C-68AB42116B85}'; // 0ee437c6-38a7-4c5c-94-4c-68-ab-42-11-6b-85)
// Audio Decoding Interface
// Value GUIDS
// The following 6 GUIDs are values of the AVDecCommonOutputFormat property
// Stereo PCM output using matrix-encoded stereo down mix (aka Lt/Rt)
GUID_AVDecAudioOutputFormat_PCM_Stereo_MatrixEncoded: TGUID = '{696E1D30-548F-4036-825F-7026C60011BD}';
// 696e1d30-548f-4036-82-5f-70-26-c6-00-11-bd)
// Regular PCM output (any number of channels)
GUID_AVDecAudioOutputFormat_PCM: TGUID = '{696E1D31-548F-4036-825F-7026C60011BD}'; // 696e1d31-548f-4036-82-5f-70-26-c6-00-11-bd)
// SPDIF PCM (IEC 60958) stereo output. Type of stereo down mix should
// be specified by the application.
GUID_AVDecAudioOutputFormat_SPDIF_PCM: TGUID = '{696E1D32-548F-4036-825F-7026C60011BD}'; // 696e1d32-548f-4036-82-5f-70-26-c6-00-11-bd)
// SPDIF bitstream (IEC 61937) output, such as AC3, MPEG or DTS.
GUID_AVDecAudioOutputFormat_SPDIF_Bitstream: TGUID = '{696E1D33-548F-4036-825F-7026C60011BD}'; // 696e1d33-548f-4036-82-5f-70-26-c6-00-11-bd)
// Stereo PCM output using regular stereo down mix (aka Lo/Ro)
GUID_AVDecAudioOutputFormat_PCM_Headphones: TGUID = '{696E1D34-548F-4036-825F-7026C60011BD}'; // 696e1d34-548f-4036-82-5f-70-26-c6-00-11-bd)
// Stereo PCM output using automatic selection of stereo down mix
// mode (Lo/Ro or Lt/Rt). Use this when the input stream includes
// information about the preferred downmix mode (such as Annex D of AC3).
// Default down mix mode should be specified by the application.
GUID_AVDecAudioOutputFormat_PCM_Stereo_Auto: TGUID = '{696E1D35-548F-4036-825F-7026C60011BD}'; // 696e1d35-548f-4036-82-5f-70-26-c6-00-11-bd)
// Video Decoder properties
// AVDecVideoImageSize (UINT32) - High UINT16 width, low UINT16 height
AVDecVideoImageSize: TGUID = '{5EE5747C-6801-4cab-AAF1-6248FA841BA4}'; // 5ee5747c-6801-4cab-aa-f1-62-48-fa-84-1b-a4)
// AVDecVideoPixelAspectRatio (UINT32 as UINT16/UNIT16) - High UINT16 width, low UINT16 height
AVDecVideoPixelAspectRatio: TGUID = '{B0CF8245-F32D-41df-B02C-87BD304D12AB}'; // b0cf8245-f32d-41df-b0-2c-87-bd-30-4d-12-ab)
// AVDecVideoInputScanType (UINT32)
AVDecVideoInputScanType: TGUID = '{38477E1F-0EA7-42cd-8CD1-130CED57C580}'; // 38477e1f-0ea7-42cd-8c-d1-13-0c-ed-57-c5-80)
// AVDecVideoSWPowerLevel (UINT32)
// Related to video decoder software power saving level in MPEG4 Part 2, VC1 and H264.
// "SW Power Level" will take a range from 0 to 100 to indicate the current power saving level. 0 - Optimize for battery life, 50 - balanced, 100 - Optimize for video quality.
AVDecVideoSWPowerLevel: TGUID = '{FB5D2347-4DD8-4509-AED0-DB5FA9AA93F4}'; // fb5d2347-4dd8-4509-ae-d0-db-5f-a9-aa-93-f4)
// Audio Decoder properties
GUID_AVDecAudioInputWMA: TGUID = '{C95E8DCF-4058-4204-8C42-CB24D91E4B9B}'; // c95e8dcf-4058-4204-8c-42-cb-24-d9-1e-4b-9b)
GUID_AVDecAudioInputWMAPro: TGUID = '{0128B7C7-DA72-4fe3-BEF8-5C52E3557704}'; // 0128b7c7-da72-4fe3-be-f8-5c-52-e3-55-77-04)
GUID_AVDecAudioInputDolby: TGUID = '{8E4228A0-F000-4e0b-8F54-AB8D24AD61A2}'; // 8e4228a0-f000-4e0b-8f-54-ab-8d-24-ad-61-a2)
GUID_AVDecAudioInputDTS: TGUID = '{600BC0CA-6A1F-4e91-B241-1BBEB1CB19E0}'; // 600bc0ca-6a1f-4e91-b2-41-1b-be-b1-cb-19-e0)
GUID_AVDecAudioInputPCM: TGUID = '{F2421DA5-BBB4-4cd5-A996-933C6B5D1347}'; // f2421da5-bbb4-4cd5-a9-96-93-3c-6b-5d-13-47)
GUID_AVDecAudioInputMPEG: TGUID = '{91106F36-02C5-4f75-9719-3B7ABF75E1F6}'; // 91106f36-02c5-4f75-97-19-3b-7a-bf-75-e1-f6)
GUID_AVDecAudioInputAAC: TGUID = '{97DF7828-B94A-47e2-A4BC-51194DB22A4D}'; // 97df7828-b94a-47e2-a4-bc-51-19-4d-b2-2a-4d)
GUID_AVDecAudioInputHEAAC: TGUID = '{16EFB4AA-330E-4f5c-98A8-CF6AC55CBE60}'; // 16efb4aa-330e-4f5c-98-a8-cf-6a-c5-5c-be-60)
GUID_AVDecAudioInputDolbyDigitalPlus: TGUID = '{0803E185-8F5D-47f5-9908-19A5BBC9FE34}'; // 0803e185-8f5d-47f5-99-08-19-a5-bb-c9-fe-34)
// AVDecAACDownmixMode (UINT32)
// AAC/HE-AAC Decoder uses standard ISO/IEC MPEG-2/MPEG-4 stereo downmix equations or uses
// non-standard downmix. An example of a non standard downmix would be the one defined by ARIB document STD-B21 version 4.4.
AVDecAACDownmixMode: TGUID = '{01274475-F6BB-4017-B084-81A763C942D4}'; // 1274475-f6bb-4017, : TGUID = '{b0-84-81-a7-63-c9-42-d4)
// AVDecHEAACDynamicRangeControl (UINT32)
// Set this property on an AAC/HE-AAC decoder to select whether Dynamic Range Control (DRC) should be applied or not.
// If DRC is ON and the AAC/HE-AAC stream includes extension payload of type EXT_DYNAMIC_RANGE, DRC will be applied.
AVDecHEAACDynamicRangeControl: TGUID = '{287C8ABE-69A4-4d39-8080-D3D9712178A0}'; // 287c8abe-69a4-4d39-80-80-d3-d9-71-21-78-a0);
// AVDecAudioDualMono (UINT32) - Read only
// The input bitstream header might have a field indicating whether the 2-ch bitstream
// is dual mono or not. Use this property to read this field.
// If it's dual mono, the application can set AVDecAudioDualMonoReproMode to determine
// one of 4 reproduction modes
AVDecAudioDualMono: TGUID = '{4a52cda8-30f8-4216-be0f-ba0b2025921d}'; // 4a52cda8-30f8-4216-be-0f-ba-0b-20-25-92-1d )
// AVDecAudioDualMonoReproMode (UINT32)
// Reproduction modes for programs containing two independent mono channels (Ch1 & Ch2).
// In case of 2-ch input, the decoder should get AVDecAudioDualMono to check if the input
// is regular stereo or dual mono. If dual mono, the application can ask the user to set the playback
// mode by setting AVDecAudioDualReproMonoMode. If output is not stereo, use AVDecDDMatrixDecodingMode or
// equivalent.
AVDecAudioDualMonoReproMode: TGUID = '{a5106186-cc94-4bc9-8cd9-aa2f61f6807e}'; // a5106186-cc94-4bc9-8c-d9-aa-2f-61-f6-80-7e )
// Audio Common Properties
// AVAudioChannelCount (UINT32)
// Total number of audio channels, including LFE if it exists.
AVAudioChannelCount: TGUID = '{1d3583c4-1583-474e-b71a-5ee463c198e4}'; // 1d3583c4-1583-474e-b7-1a-5e-e4-63-c1-98-e4 )
// AVAudioChannelConfig (UINT32)
// A bit-wise OR of any number of enum values specified by eAVAudioChannelConfig
AVAudioChannelConfig: TGUID = '{17f89cb3-c38d-4368-9ede-63b94d177f9f}'; // 17f89cb3-c38d-4368-9e-de-63-b9-4d-17-7f-9f )
// Enumerated values for AVAudioChannelConfig are identical
// to the speaker positions defined in ksmedia.h and used
// in WAVE_FORMAT_EXTENSIBLE. Configurations for 5.1 and
// 7.1 channels should be identical to KSAUDIO_SPEAKER_5POINT1_SURROUND
// and KSAUDIO_SPEAKER_7POINT1_SURROUND in ksmedia.h. This means:
// 5.1 ch -> LOW_FREQUENCY | FRONT_LEFT | FRONT_RIGHT | FRONT_CENTER | SIDE_LEFT | SIDE_RIGHT
// 7.1 ch -> LOW_FREQUENCY | FRONT_LEFT | FRONT_RIGHT | FRONT_CENTER | SIDE_LEFT | SIDE_RIGHT | BACK_LEFT | BACK_RIGHT
// AVAudioSampleRate (UINT32)
// In samples per second (Hz)
AVAudioSampleRate: TGUID = '{971d2723-1acb-42e7-855c-520a4b70a5f2}'; // 971d2723-1acb-42e7-85-5c-52-0a-4b-70-a5-f2 )
// Dolby Digital(TM) Audio Specific Parameters
// AVDDSurroundMode (UINT32) common to encoder/decoder
AVDDSurroundMode: TGUID = '{99f2f386-98d1-4452-a163-abc78a6eb770}'; // 99f2f386-98d1-4452-a1-63-ab-c7-8a-6e-b7-70 )
// AVDecDDOperationalMode (UINT32)
AVDecDDOperationalMode: TGUID = '{d6d6c6d1-064e-4fdd-a40e-3ecbfcb7ebd0}'; // d6d6c6d1-064e-4fdd-a4-0e-3e-cb-fc-b7-eb-d0 )
// AVDecDDMatrixDecodingMode(UINT32)
// A ProLogic decoder has a built-in auto-detection feature. When the Dolby Digital decoder
// is set to the 6-channel output configuration and it is fed a 2/0 bit stream to decode, it can
// do one of the following:
// a) decode the bit stream and output it on the two front channels (eAVDecDDMatrixDecodingMode_OFF),
// b) decode the bit stream followed by ProLogic decoding to create 6-channels (eAVDecDDMatrixDecodingMode_ON).
// c) the decoder will look at the Surround bit ("dsurmod") in the bit stream to determine whether
// apply ProLogic decoding or not (eAVDecDDMatrixDecodingMode_AUTO).
AVDecDDMatrixDecodingMode: TGUID = '{ddc811a5-04ed-4bf3-a0ca-d00449f9355f}'; // ddc811a5-04ed-4bf3-a0-ca-d0-04-49-f9-35-5f )
// AVDecDDDynamicRangeScaleHigh (UINT32)
// Indicates what fraction of the dynamic range compression
// to apply. Relevant for negative values of dynrng only.
// Linear range 0-100, where:
// 0 - No dynamic range compression (preserve full dynamic range)
// 100 - Apply full dynamic range compression
AVDecDDDynamicRangeScaleHigh: TGUID = '{50196c21-1f33-4af5-b296-11426d6c8789}'; // 50196c21-1f33-4af5-b2-96-11-42-6d-6c-87-89 )
// AVDecDDDynamicRangeScaleLow (UINT32)
// Indicates what fraction of the dynamic range compression
// to apply. Relevant for positive values of dynrng only.
// Linear range 0-100, where:
// 0 - No dynamic range compression (preserve full dynamic range)
// 100 - Apply full dynamic range compression
AVDecDDDynamicRangeScaleLow: TGUID = '{044e62e4-11a5-42d5-a3b2-3bb2c7c2d7cf}'; // 044e62e4-11a5-42d5-a3-b2-3b-b2-c7-c2-d7-cf )
// AVDecDDStereoDownMixMode (UINT32)
// A Dolby Digital Decoder may apply stereo downmix in one of several ways, after decoding multichannel PCM.
// Use one of the UINT32 values specified by eAVDecDDStereoDownMixMode to set stereo downmix mode.
// Only relevant when the decoder's output is set to stereo.
AVDecDDStereoDownMixMode: TGUID = '{6CE4122C-3EE9-4182-B4AE-C10FC088649D}'; // 6ce4122c-3ee9-4182-b4-ae-c1-0f-c0-88-64-9d )
// AVDSPLoudnessEqualization (UINT32)
// Related to audio digital signal processing (DSP).
// Apply "Loudness Equalization" to the audio stream, so users will not have to adjust volume control when audio stream changes.
AVDSPLoudnessEqualization: TGUID = '{8AFD1A15-1812-4cbf-9319-433A5B2A3B27}'; // 8afd1a15-1812-4cbf-93-19-43-3a-5b-2a-3b-27)
// AVDSPSpeakerFill (UINT32)
// Related to audio digital signal processing (DSP).
// "Speaker Fill" will take a mono or stereo audio stream and convert it to a multi channel (e.g. 5.1) audio stream.
AVDSPSpeakerFill: TGUID = '{5612BCA1-56DA-4582-8DA1-CA8090F92768}'; // 5612bca1-56da-4582-8d-a1-ca-80-90-f9-27-68)
// AVPriorityControl (UINT32)
// Indicates the task priority when not realtime (0..15)
// Linear range 0-15, where:
// 0 - idle
// 15 - Highest
AVPriorityControl: TGUID = '{54ba3dc8-bdde-4329-b187-2018bc5c2ba1}'; // 54ba3dc8-bdde-4329-b1-87-20-18-bc-5c-2b-a1 )
// AVRealtimeControl (UINT32)
// Indicates the task is realtime or not
// Linear range 0-1, where:
// 0 - no realtime
// 1 - realtime
AVRealtimeControl: TGUID = '{6f440632-c4ad-4bf7-9e52-456942b454b0}'; // 6f440632-c4ad-4bf7-9e-52-45-69-42-b4-54-b0 )
// AVEncNoInputCopy (UINT32)
// Enables the encoder to avoid copying the input buffer
// 0 - default behavior (copy input buffer to encoder internal buffer)
// 1 - use input buffer directly
// Input color space must be IYUV or YV12 for this to be effective. Input buffers must be fully contiguous. Input buffers
// must be macroblock-aligned (width and height divisible by 16).
AVEncNoInputCopy: TGUID = '{d2b46a2a-e8ee-4ec5-869e-449b6c62c81a}'; // d2b46a2a-e8ee-4ec5-86-9e-44-9b-6c-62-c8-1a )
// AVEncChromaEncodeMode (UINT32)
// Change the mode used to encode chroma-only frames
// A member of the eAVChromaEncodeMode structure, where:
// eAVChromaEncodeMode_420 - default encoding
// eAVChromaEncodeMode_444 - enhanced encoding of chroma for repeated input frames
// eAVChromaEncodeMode_444_v2 - encoder will skip non-chroma macroblocks, in addition to functionality for eAVChromaEncodeMode_444
AVEncChromaEncodeMode: TGUID = '{8a47ab5a-4798-4c93-b5a5-554f9a3b9f50}'; // 8a47ab5a-4798-4c93-b5-a5-55-4f-9a-3b-9f-50 )
const
AVENC_H263V_LEVELCOUNT = 8;
AVENC_H264V_LEVELCOUNT = 16;
AVENC_H264V_MAX_MBBITS = 3200; //Only applies to Baseline, Main, Extended profiles
type
eAVEncCommonRateControlMode = (
eAVEncCommonRateControlMode_CBR = 0,
eAVEncCommonRateControlMode_PeakConstrainedVBR = 1,
eAVEncCommonRateControlMode_UnconstrainedVBR = 2,
eAVEncCommonRateControlMode_Quality = 3,
eAVEncCommonRateControlMode_LowDelayVBR = 4,
eAVEncCommonRateControlMode_GlobalVBR = 5,
eAVEncCommonRateControlMode_GlobalLowDelayVBR = 6);
eAVEncCommonStreamEndHandling = (
eAVEncCommonStreamEndHandling_DiscardPartial = 0,
eAVEncCommonStreamEndHandling_EnsureComplete = 1);
eAVEncVideoOutputFrameRateConversion = (
eAVEncVideoOutputFrameRateConversion_Disable = 0,
eAVEncVideoOutputFrameRateConversion_Enable = 1,
eAVEncVideoOutputFrameRateConversion_Alias = 2);
eAVDecVideoSoftwareDeinterlaceMode = (
eAVDecVideoSoftwareDeinterlaceMode_NoDeinterlacing = 0, // do not use software deinterlace
eAVDecVideoSoftwareDeinterlaceMode_ProgressiveDeinterlacing = 1, // Use progressive deinterlace
eAVDecVideoSoftwareDeinterlaceMode_BOBDeinterlacing = 2, // BOB deinterlacing
eAVDecVideoSoftwareDeinterlaceMode_SmartBOBDeinterlacing = 3 // Smart BOB deinterlacing
);
eAVFastDecodeMode = (
eVideoDecodeCompliant = 0,
eVideoDecodeOptimalLF = 1, // Optimal Loop Filter
eVideoDecodeDisableLF = 2, // Disable Loop Filter
eVideoDecodeFastest = 32
);
eAVDecVideoH264ErrorConcealment = (
eErrorConcealmentTypeDrop = 0, // ERR_CONCEALMENT_TYPE_DROP
eErrorConcealmentTypeBasic = 1, // ERR_CONCEALMENT_TYPE_BASIC (the default, and good mode used most of the time)
eErrorConcealmentTypeAdvanced = 2, // ERR_CONCEALMENT_TYPE_ADVANCED
eErrorConcealmentTypeDXVASetBlack = 3 // ERR_CONCEALMENT_TYPE_DXVA_SET_BLACK
);
eAVDecVideoMPEG2ErrorConcealment = (
eErrorConcealmentOff = 0,
eErrorConcealmentOn = 1 // the default and good mode used most of the time
);
eAVDecVideoCodecType = (
eAVDecVideoCodecType_NOTPLAYING = 0,
eAVDecVideoCodecType_MPEG2 = 1,
eAVDecVideoCodecType_H264 = 2);
eAVDecVideoDXVAMode = (
eAVDecVideoDXVAMode_NOTPLAYING = 0,
eAVDecVideoDXVAMode_SW = 1,
eAVDecVideoDXVAMode_MC = 2,
eAVDecVideoDXVAMode_IDCT = 3,
eAVDecVideoDXVAMode_VLD = 4);
eAVDecVideoDXVABusEncryption = (
eAVDecVideoDXVABusEncryption_NONE = 0,
eAVDecVideoDXVABusEncryption_PRIVATE = 1,
eAVDecVideoDXVABusEncryption_AES = 2);
eAVEncVideoSourceScanType = (
eAVEncVideoSourceScan_Automatic = 0,
eAVEncVideoSourceScan_Interlaced = 1,
eAVEncVideoSourceScan_Progressive = 2
);
eAVEncVideoOutputScanType = (
eAVEncVideoOutputScan_Progressive = 0,
eAVEncVideoOutputScan_Interlaced = 1,
eAVEncVideoOutputScan_SameAsInput = 2,
eAVEncVideoOutputScan_Automatic = 3);
eAVEncVideoFilmContent = (
eAVEncVideoFilmContent_VideoOnly = 0,
eAVEncVideoFilmContent_FilmOnly = 1,
eAVEncVideoFilmContent_Mixed = 2);
eAVEncVideoChromaResolution = (
eAVEncVideoChromaResolution_SameAsSource = 0,
eAVEncVideoChromaResolution_444 = 1,
eAVEncVideoChromaResolution_422 = 2,
eAVEncVideoChromaResolution_420 = 3,
eAVEncVideoChromaResolution_411 = 4);
eAVEncVideoChromaSubsampling = (
eAVEncVideoChromaSubsamplingFormat_SameAsSource = 0,
eAVEncVideoChromaSubsamplingFormat_ProgressiveChroma = $8,
eAVEncVideoChromaSubsamplingFormat_Horizontally_Cosited = $4,
eAVEncVideoChromaSubsamplingFormat_Vertically_Cosited = $2,
eAVEncVideoChromaSubsamplingFormat_Vertically_AlignedChromaPlanes = $1
);
eAVEncVideoColorPrimaries = (
eAVEncVideoColorPrimaries_SameAsSource = 0,
eAVEncVideoColorPrimaries_Reserved = 1,
eAVEncVideoColorPrimaries_BT709 = 2,
eAVEncVideoColorPrimaries_BT470_2_SysM = 3,
eAVEncVideoColorPrimaries_BT470_2_SysBG = 4,
eAVEncVideoColorPrimaries_SMPTE170M = 5,
eAVEncVideoColorPrimaries_SMPTE240M = 6,
eAVEncVideoColorPrimaries_EBU3231 = 7,
eAVEncVideoColorPrimaries_SMPTE_C = 8);
eAVEncVideoColorTransferFunction = (
eAVEncVideoColorTransferFunction_SameAsSource = 0,
eAVEncVideoColorTransferFunction_10 = 1, // (Linear, scRGB)
eAVEncVideoColorTransferFunction_18 = 2,
eAVEncVideoColorTransferFunction_20 = 3,
eAVEncVideoColorTransferFunction_22 = 4, // (BT470-2 SysM)
eAVEncVideoColorTransferFunction_22_709 = 5, // (BT709, SMPTE296M, SMPTE170M, BT470, SMPTE274M, BT.1361)
eAVEncVideoColorTransferFunction_22_240M = 6, // (SMPTE240M, interim 274M)
eAVEncVideoColorTransferFunction_22_8bit_sRGB = 7, // (sRGB)
eAVEncVideoColorTransferFunction_28 = 8
);
eAVEncVideoColorTransferMatrix = (
eAVEncVideoColorTransferMatrix_SameAsSource = 0,
eAVEncVideoColorTransferMatrix_BT709 = 1,
eAVEncVideoColorTransferMatrix_BT601 = 2, // (601, BT470-2 B,B, 170M)
eAVEncVideoColorTransferMatrix_SMPTE240M = 3);
eAVEncVideoColorLighting = (
eAVEncVideoColorLighting_SameAsSource = 0,
eAVEncVideoColorLighting_Unknown = 1,
eAVEncVideoColorLighting_Bright = 2,
eAVEncVideoColorLighting_Office = 3,
eAVEncVideoColorLighting_Dim = 4,
eAVEncVideoColorLighting_Dark = 5);
eAVEncVideoColorNominalRange = (
eAVEncVideoColorNominalRange_SameAsSource = 0,
eAVEncVideoColorNominalRange_0_255 = 1, // (8 bit: 0..255, 10 bit: 0..1023)
eAVEncVideoColorNominalRange_16_235 = 2, // (16..235, 64..940 (16*4...235*4)
eAVEncVideoColorNominalRange_48_208 = 3 // (48..208)
);
eAVEncInputVideoSystem = (
eAVEncInputVideoSystem_Unspecified = 0,
eAVEncInputVideoSystem_PAL = 1,
eAVEncInputVideoSystem_NTSC = 2,
eAVEncInputVideoSystem_SECAM = 3,
eAVEncInputVideoSystem_MAC = 4,
eAVEncInputVideoSystem_HDV = 5,
eAVEncInputVideoSystem_Component = 6);
eAVEncVideoContentType = (
eAVEncVideoContentType_Unknown = 0,
eAVEncVideoContentType_FixedCameraAngle = 1);
eAVEncAdaptiveMode = (
eAVEncAdaptiveMode_None = 0,
eAVEncAdaptiveMode_Resolution = 1,
eAVEncAdaptiveMode_FrameRate = 2
);
eAVScenarioInfo = (
eAVScenarioInfo_Unknown = 0,
eAVScenarioInfo_DisplayRemoting = 1,
eAVScenarioInfo_VideoConference = 2,
eAVScenarioInfo_Archive = 3,
eAVScenarioInfo_LiveStreaming = 4,
eAVScenarioInfo_CameraRecord = 5,
eAVScenarioInfo_DisplayRemotingWithFeatureMap = 6);
eVideoEncoderDisplayContentType = (
eVideoEncoderDisplayContent_Unknown = 0,
eVideoEncoderDisplayContent_FullScreenVideo = 1);
eAVEncMuxOutput = (
eAVEncMuxOutputAuto = 0, // Decision is made automatically be the mux (elementary stream, program stream or transport stream)
eAVEncMuxOutputPS = 1, // Program stream
eAVEncMuxOutputTS = 2 // Transport stream
);
eAVEncAudioDualMono = (
eAVEncAudioDualMono_SameAsInput = 0, // As indicated by input media type
eAVEncAudioDualMono_Off = 1, // 2-ch output bitstream should not be dual mono
eAVEncAudioDualMono_On = 2 // 2-ch output bitstream should be dual mono
);
eAVEncAudioInputContent = (
AVEncAudioInputContent_Unknown = 0,
AVEncAudioInputContent_Voice = 1,
AVEncAudioInputContent_Music = 2);
eAVEncMPVProfile = (
eAVEncMPVProfile_unknown = 0,
eAVEncMPVProfile_Simple = 1,
eAVEncMPVProfile_Main = 2,
eAVEncMPVProfile_High = 3,
eAVEncMPVProfile_422 = 4);
eAVEncMPVLevel = (
eAVEncMPVLevel_Low = 1,
eAVEncMPVLevel_Main = 2,
eAVEncMPVLevel_High1440 = 3,
eAVEncMPVLevel_High = 4);
eAVEncH263VProfile = (
eAVEncH263VProfile_Base = 0,
eAVEncH263VProfile_CompatibilityV2 = 1,
eAVEncH263VProfile_CompatibilityV1 = 2,
eAVEncH263VProfile_WirelessV2 = 3,
eAVEncH263VProfile_WirelessV3 = 4,
eAVEncH263VProfile_HighCompression = 5,
eAVEncH263VProfile_Internet = 6,
eAVEncH263VProfile_Interlace = 7,
eAVEncH263VProfile_HighLatency = 8);
eAVEncH264VProfile = (
eAVEncH264VProfile_unknown = 0,
eAVEncH264VProfile_Simple = 66,
eAVEncH264VProfile_Base = 66,
eAVEncH264VProfile_Main = 77,
eAVEncH264VProfile_High = 100,
eAVEncH264VProfile_422 = 122,
eAVEncH264VProfile_High10 = 110,
eAVEncH264VProfile_444 = 244,
eAVEncH264VProfile_Extended = 88,
// UVC 1.2 H.264 extension
eAVEncH264VProfile_ScalableBase = 83,
eAVEncH264VProfile_ScalableHigh = 86,
eAVEncH264VProfile_MultiviewHigh = 118,
eAVEncH264VProfile_StereoHigh = 128,
eAVEncH264VProfile_ConstrainedBase = 256,
eAVEncH264VProfile_UCConstrainedHigh = 257,
eAVEncH264VProfile_ConstrainedHigh = 257,
eAVEncH264VProfile_UCScalableConstrainedBase = 258,
eAVEncH264VProfile_UCScalableConstrainedHigh = 259);
eAVEncH265VProfile = (
eAVEncH265VProfile_unknown = 0,
eAVEncH265VProfile_Main_420_8 = 1,
eAVEncH265VProfile_Main_420_10 = 2,
eAVEncH265VProfile_Main_420_12 = 3,
eAVEncH265VProfile_Main_422_10 = 4,
eAVEncH265VProfile_Main_422_12 = 5,
eAVEncH265VProfile_Main_444_8 = 6,
eAVEncH265VProfile_Main_444_10 = 7,
eAVEncH265VProfile_Main_444_12 = 8,
eAVEncH265VProfile_Monochrome_12 = 9,
eAVEncH265VProfile_Monochrome_16 = 10,
eAVEncH265VProfile_MainIntra_420_8 = 11,
eAVEncH265VProfile_MainIntra_420_10 = 12,
eAVEncH265VProfile_MainIntra_420_12 = 13,
eAVEncH265VProfile_MainIntra_422_10 = 14,
eAVEncH265VProfile_MainIntra_422_12 = 15,
eAVEncH265VProfile_MainIntra_444_8 = 16,
eAVEncH265VProfile_MainIntra_444_10 = 17,
eAVEncH265VProfile_MainIntra_444_12 = 18,
eAVEncH265VProfile_MainIntra_444_16 = 19,
eAVEncH265VProfile_MainStill_420_8 = 20,
eAVEncH265VProfile_MainStill_444_8 = 21,
eAVEncH265VProfile_MainStill_444_16 = 22);
eAVEncVP9VProfile = (
eAVEncVP9VProfile_unknown = 0,
eAVEncVP9VProfile_420_8 = 1,
eAVEncVP9VProfile_420_10 = 2,
eAVEncVP9VProfile_420_12 = 3);
eAVEncH263PictureType = (
eAVEncH263PictureType_I = 0,
eAVEncH263PictureType_P,
eAVEncH263PictureType_B);
eAVEncH264PictureType = (
eAVEncH264PictureType_IDR = 0,
eAVEncH264PictureType_P,
eAVEncH264PictureType_B);
eAVEncH263VLevel = (
eAVEncH263VLevel1 = 10,
eAVEncH263VLevel2 = 20,
eAVEncH263VLevel3 = 30,
eAVEncH263VLevel4 = 40,
eAVEncH263VLevel4_5 = 45,
eAVEncH263VLevel5 = 50,
eAVEncH263VLevel6 = 60,
eAVEncH263VLevel7 = 70);
eAVEncH264VLevel = (
eAVEncH264VLevel1 = 10,
eAVEncH264VLevel1_b = 11,
eAVEncH264VLevel1_1 = 11,
eAVEncH264VLevel1_2 = 12,
eAVEncH264VLevel1_3 = 13,
eAVEncH264VLevel2 = 20,
eAVEncH264VLevel2_1 = 21,
eAVEncH264VLevel2_2 = 22,
eAVEncH264VLevel3 = 30,
eAVEncH264VLevel3_1 = 31,
eAVEncH264VLevel3_2 = 32,
eAVEncH264VLevel4 = 40,
eAVEncH264VLevel4_1 = 41,
eAVEncH264VLevel4_2 = 42,
eAVEncH264VLevel5 = 50,
eAVEncH264VLevel5_1 = 51,
eAVEncH264VLevel5_2 = 52);
eAVEncH265VLevel = (
eAVEncH265VLevel1 = 30,
eAVEncH265VLevel2 = 60,
eAVEncH265VLevel2_1 = 63,
eAVEncH265VLevel3 = 90,
eAVEncH265VLevel3_1 = 93,
eAVEncH265VLevel4 = 120,
eAVEncH265VLevel4_1 = 123,
eAVEncH265VLevel5 = 150,
eAVEncH265VLevel5_1 = 153,
eAVEncH265VLevel5_2 = 156,
eAVEncH265VLevel6 = 180,
eAVEncH265VLevel6_1 = 183,
eAVEncH265VLevel6_2 = 186);
eAVEncMPVFrameFieldMode = (
eAVEncMPVFrameFieldMode_FieldMode = 0,
eAVEncMPVFrameFieldMode_FrameMode = 1);
eAVEncMPVSceneDetection = (
eAVEncMPVSceneDetection_None = 0,
eAVEncMPVSceneDetection_InsertIPicture = 1,
eAVEncMPVSceneDetection_StartNewGOP = 2,
eAVEncMPVSceneDetection_StartNewLocatableGOP = 3
);
eAVEncMPVScanPattern = (
eAVEncMPVScanPattern_Auto = 0,
eAVEncMPVScanPattern_ZigZagScan = 1,
eAVEncMPVScanPattern_AlternateScan = 2);
eAVEncMPVQScaleType = (
eAVEncMPVQScaleType_Auto = 0,
eAVEncMPVQScaleType_Linear = 1,
eAVEncMPVQScaleType_NonLinear = 2);
eAVEncMPVIntraVLCTable = (
eAVEncMPVIntraVLCTable_Auto = 0,
eAVEncMPVIntraVLCTable_MPEG1 = 1,
eAVEncMPVIntraVLCTable_Alternate = 2);
eAVEncMPALayer = (
eAVEncMPALayer_1 = 1,
eAVEncMPALayer_2 = 2,
eAVEncMPALayer_3 = 3);
eAVEncMPACodingMode = (
eAVEncMPACodingMode_Mono = 0,
eAVEncMPACodingMode_Stereo = 1,
eAVEncMPACodingMode_DualChannel = 2,
eAVEncMPACodingMode_JointStereo = 3,
eAVEncMPACodingMode_Surround = 4);
eAVEncMPAEmphasisType = (
eAVEncMPAEmphasisType_None = 0,
eAVEncMPAEmphasisType_50_15 = 1,
eAVEncMPAEmphasisType_Reserved = 2,
eAVEncMPAEmphasisType_CCITT_J17 = 3);
eAVEncDDService = (
eAVEncDDService_CM = 0, // (Main Service: Complete Main)
eAVEncDDService_ME = 1, // (Main Service: Music and Effects (ME))
eAVEncDDService_VI = 2, // (Associated Service: Visually-Impaired (VI)
eAVEncDDService_HI = 3, // (Associated Service: Hearing-Impaired (HI))
eAVEncDDService_D = 4, // (Associated Service: Dialog (D))
eAVEncDDService_C = 5, // (Associated Service: Commentary (C))
eAVEncDDService_E = 6, // (Associated Service: Emergency (E))
eAVEncDDService_VO = 7 // (Associated Service: Voice Over (VO) / Karaoke)
);
eAVEncDDProductionRoomType = (
eAVEncDDProductionRoomType_NotIndicated = 0,
eAVEncDDProductionRoomType_Large = 1,
eAVEncDDProductionRoomType_Small = 2);
eAVEncDDDynamicRangeCompressionControl = (
eAVEncDDDynamicRangeCompressionControl_None = 0,
eAVEncDDDynamicRangeCompressionControl_FilmStandard = 1,
eAVEncDDDynamicRangeCompressionControl_FilmLight = 2,
eAVEncDDDynamicRangeCompressionControl_MusicStandard = 3,
eAVEncDDDynamicRangeCompressionControl_MusicLight = 4,
eAVEncDDDynamicRangeCompressionControl_Speech = 5);
eAVEncDDSurroundExMode = (
eAVEncDDSurroundExMode_NotIndicated = 0,
eAVEncDDSurroundExMode_No = 1,
eAVEncDDSurroundExMode_Yes = 2);
eAVEncDDPreferredStereoDownMixMode = (
eAVEncDDPreferredStereoDownMixMode_LtRt = 0,
eAVEncDDPreferredStereoDownMixMode_LoRo = 1);
eAVEncDDAtoDConverterType = (
eAVEncDDAtoDConverterType_Standard = 0,
eAVEncDDAtoDConverterType_HDCD = 1);
eAVEncDDHeadphoneMode = (
eAVEncDDHeadphoneMode_NotIndicated = 0,
eAVEncDDHeadphoneMode_NotEncoded = 1,
eAVEncDDHeadphoneMode_Encoded = 2);
eAVDecVideoInputScanType = (
eAVDecVideoInputScan_Unknown = 0,
eAVDecVideoInputScan_Progressive = 1,
eAVDecVideoInputScan_Interlaced_UpperFieldFirst = 2,
eAVDecVideoInputScan_Interlaced_LowerFieldFirst = 3);
eAVDecVideoSWPowerLevel = (
eAVDecVideoSWPowerLevel_BatteryLife = 0,
eAVDecVideoSWPowerLevel_Balanced = 50,
eAVDecVideoSWPowerLevel_VideoQuality = 100);
eAVDecAACDownmixMode = (
eAVDecAACUseISODownmix = 0,
eAVDecAACUseARIBDownmix = 1);
eAVDecHEAACDynamicRangeControl = (
eAVDecHEAACDynamicRangeControl_OFF = 0,
eAVDecHEAACDynamicRangeControl_ON = 1);
eAVDecAudioDualMono = (
eAVDecAudioDualMono_IsNotDualMono = 0, // 2-ch bitstream input is not dual mono
eAVDecAudioDualMono_IsDualMono = 1, // 2-ch bitstream input is dual mono
eAVDecAudioDualMono_UnSpecified = 2 // There is no indication in the bitstream
);
eAVDecAudioDualMonoReproMode = (
eAVDecAudioDualMonoReproMode_STEREO = 0, // Ch1+Ch2 for mono output, (Ch1 left, Ch2 right) for stereo output
eAVDecAudioDualMonoReproMode_LEFT_MONO = 1, // Ch1 for mono output, (Ch1 left, Ch1 right) for stereo output
eAVDecAudioDualMonoReproMode_RIGHT_MONO = 2, // Ch2 for mono output, (Ch2 left, Ch2 right) for stereo output
eAVDecAudioDualMonoReproMode_MIX_MONO = 3 // Ch1+Ch2 for mono output, (Ch1+Ch2 left, Ch1+Ch2 right) for stereo output
);
eAVAudioChannelConfig = (
eAVAudioChannelConfig_FRONT_LEFT = $1,
eAVAudioChannelConfig_FRONT_RIGHT = $2,
eAVAudioChannelConfig_FRONT_CENTER = $4,
eAVAudioChannelConfig_LOW_FREQUENCY = $8, // aka LFE
eAVAudioChannelConfig_BACK_LEFT = $10,
eAVAudioChannelConfig_BACK_RIGHT = $20,
eAVAudioChannelConfig_FRONT_LEFT_OF_CENTER = $40,
eAVAudioChannelConfig_FRONT_RIGHT_OF_CENTER = $80,
eAVAudioChannelConfig_BACK_CENTER = $100, // aka Mono Surround
eAVAudioChannelConfig_SIDE_LEFT = $200, // aka Left Surround
eAVAudioChannelConfig_SIDE_RIGHT = $400, // aka Right Surround
eAVAudioChannelConfig_TOP_CENTER = $800,
eAVAudioChannelConfig_TOP_FRONT_LEFT = $1000,
eAVAudioChannelConfig_TOP_FRONT_CENTER = $2000,
eAVAudioChannelConfig_TOP_FRONT_RIGHT = $4000,
eAVAudioChannelConfig_TOP_BACK_LEFT = $8000,
eAVAudioChannelConfig_TOP_BACK_CENTER = $10000,
eAVAudioChannelConfig_TOP_BACK_RIGHT = $20000);
eAVDDSurroundMode = (
eAVDDSurroundMode_NotIndicated = 0,
eAVDDSurroundMode_No = 1,
eAVDDSurroundMode_Yes = 2);
eAVDecDDOperationalMode = (
eAVDecDDOperationalMode_NONE = 0,
eAVDecDDOperationalMode_LINE = 1,// Dialnorm enabled, dialogue at -31dBFS, dynrng used, high/low scaling allowed
eAVDecDDOperationalMode_RF = 2,
// Dialnorm enabled, dialogue at -20dBFS, dynrng & compr used, high/low scaling NOT allowed (always fully compressed)
eAVDecDDOperationalMode_CUSTOM0 = 3,// Analog dialnorm (dialogue normalization not part of the decoder)
eAVDecDDOperationalMode_CUSTOM1 = 4,// Digital dialnorm (dialogue normalization is part of the decoder)
eAVDecDDOperationalMode_PORTABLE8 = 5,
// Dialnorm enabled, dialogue at -8dBFS, dynrng & compr used, high/low scaling NOT allowed (always fully compressed)
eAVDecDDOperationalMode_PORTABLE11 = 6,
// Dialnorm enabled, dialogue at -11dBFS, dynrng & compr used, high/low scaling NOT allowed (always fully compressed)
eAVDecDDOperationalMode_PORTABLE14 =
7 // Dialnorm enabled, dialogue at -14dBFS, dynrng & compr used, high/low scaling NOT allowed (always fully compressed)
);
eAVDecDDMatrixDecodingMode = (
eAVDecDDMatrixDecodingMode_OFF = 0,
eAVDecDDMatrixDecodingMode_ON = 1,
eAVDecDDMatrixDecodingMode_AUTO = 2);
eAVDecDDStereoDownMixMode = (
eAVDecDDStereoDownMixMode_Auto = 0, // Automatic detection
eAVDecDDStereoDownMixMode_LtRt = 1, // Surround compatible (Lt/Rt)
eAVDecDDStereoDownMixMode_LoRo = 2 // Stereo (Lo/Ro)
);
eAVDSPLoudnessEqualization = (
eAVDSPLoudnessEqualization_OFF = 0,
eAVDSPLoudnessEqualization_ON = 1,
eAVDSPLoudnessEqualization_AUTO = 2);
eAVDSPSpeakerFill = (
eAVDSPSpeakerFill_OFF = 0,
eAVDSPSpeakerFill_ON = 1,
eAVDSPSpeakerFill_AUTO = 2);
eAVEncChromaEncodeMode = (
eAVEncChromaEncodeMode_420,
eAVEncChromaEncodeMode_444,
eAVEncChromaEncodeMode_444_v2);
implementation
end.
|
unit Tool;
interface
uses
Windows,SysUtils,Tlhelp32 ;
Function KillTask( ExeFileName: String ): Integer ; //关闭进程
Function EnableDebugPrivilege: Boolean ; //提升权限
Function FindProcessId( ExeFileName: String ): THandle ; //查找进程
implementation
Function FindProcessId( ExeFileName: String ): THandle ;
Var
ContinueLoop: BOOL ;
FSnapshotHandle: THandle ;
FProcessEntry32: TProcessEntry32 ;
Begin
result := 0 ;
FSnapshotHandle := CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 ) ;
FProcessEntry32.dwSize := Sizeof( FProcessEntry32 ) ;
ContinueLoop := Process32First( FSnapshotHandle, FProcessEntry32 ) ;
While integer( ContinueLoop ) <> 0 Do
Begin
If UpperCase( FProcessEntry32.szExeFile ) = UpperCase( ExeFileName ) Then
Begin
result := FProcessEntry32.th32ProcessID ;
break ;
End ;
ContinueLoop := Process32Next( FSnapshotHandle, FProcessEntry32 ) ;
End ;
CloseHandle( FSnapshotHandle ) ;
End ;
Function KillTask( ExeFileName: String ): Integer ;
Const
PROCESS_TERMINATE = $0001 ;
Var
ContinueLoop: boolean ;
FSnapshotHandle: THandle ;
FProcessEntry32: TProcessEntry32 ;
Begin
Result := 0 ;
FSnapshotHandle := CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 ) ;
FProcessEntry32.dwSize := SizeOf( FProcessEntry32 ) ;
ContinueLoop := Process32First( FSnapshotHandle, FProcessEntry32 ) ;
While Integer( ContinueLoop ) <> 0 Do
Begin
If ( ( UpperCase( ExtractFileName( FProcessEntry32.szExeFile ) ) =
UpperCase( ExeFileName ) ) Or ( UpperCase( FProcessEntry32.szExeFile ) =
UpperCase( ExeFileName ) ) ) Then
Result := Integer( TerminateProcess(
OpenProcess( PROCESS_TERMINATE,
BOOL( 0 ),
FProcessEntry32.th32ProcessID ),
0 ) ) ;
ContinueLoop := Process32Next( FSnapshotHandle, FProcessEntry32 ) ;
End ;
CloseHandle( FSnapshotHandle ) ;
End ;
//但是对于服务程序,它会提示"拒绝访问".其实只要程序拥有Debug权限即可:
Function EnableDebugPrivilege: Boolean ;
Function EnablePrivilege( hToken: Cardinal ;PrivName: String ;bEnable: Boolean ): Boolean ;
Var
TP: TOKEN_PRIVILEGES ;
Dummy: Cardinal ;
Begin
TP.PrivilegeCount := 1 ;
LookupPrivilegeValue( Nil, pchar( PrivName ), TP.Privileges[ 0 ].Luid ) ;
If bEnable Then
TP.Privileges[ 0 ].Attributes := SE_PRIVILEGE_ENABLED
Else
TP.Privileges[ 0 ].Attributes := 0 ;
AdjustTokenPrivileges( hToken, False, TP, SizeOf( TP ), Nil, Dummy ) ;
Result := GetLastError = ERROR_SUCCESS ;
End ;
Var
hToken: Cardinal ;
Begin
OpenProcessToken( GetCurrentProcess, TOKEN_ADJUST_PRIVILEGES, hToken ) ;
result := EnablePrivilege( hToken, 'SeDebugPrivilege', True ) ;
CloseHandle( hToken ) ;
End ;
end.
|
unit OSVVCommEngine;
interface
uses Windows,Messages,ShellApi,SysUtils,Palette,Dialogs;
const
// OS Message Types Listing
SHP_ACCESS = 12345234; // Load SHP File on OS SHP Builder
VOXEL_ACCESS = 12345235; // Load Voxel File on VXLSE III, OS: VV, HVA Builder
HVA_ACCESS = 12345236; // Load HVA File on HVA Builder
OS_PALETTE_ACCESS = 12345237; // Load Palette from string here
OS_SCHEME_ACCESS = 12345238; // Load Custom Scheme from string here
PALETTE_ACCESS = 12345239; // Load Palette File here
CSCHEME_ACCESS = 12345240; // Load Custom Scheme File here
MY_HANDLE = 12345250; // Establish Conection: Receiver's Handle
function TextToPalette( const FullText : AnsiString): TPalette;
function PaletteToText( const Palette : TPalette): AnsiString;
function GetPaletteParameters (const Hwnd : THandle) : AnsiString;
function UpdateHwndList(Hwnd : THandle; var WasAdded: boolean): integer; overload;
procedure RunAProgram (const theProgram, itsParameters, defaultDirectory : AnsiString);
function SendExternalMessage(const Hwnd : THandle; const Destination : Cardinal; const ParameterString : string): Boolean;
var
HwndList : array of THandle;
implementation
uses FormMain;
function TextToPalette( const FullText : AnsiString): TPalette;
var
colour : byte;
letter : integer;
r,g,b : byte;
begin
letter := 1;
for colour := 0 to 255 do
begin
r := Byte(FullText[letter]);
inc(letter);
g := Byte(FullText[letter]);
inc(letter);
b := Byte(FullText[letter]);
inc(letter);
Result[colour] := RGB(r,g,b);
end;
end;
function PaletteToText( const Palette : TPalette): AnsiString;
var
colour : byte;
begin
Result := '';
for colour := 0 to 255 do
begin
Result := Result + Char(GetRValue(Palette[colour])) + Char(GetGValue(Palette[colour])) + Char(GetBValue(Palette[colour]));
end;
Result := Result + #0;
end;
function GetPaletteParameters (const Hwnd : THandle) : AnsiString;
begin
Result := '-palette ' + IntToStr(Hwnd);
end;
// -------------------------------------------------------------
// The set of function below deals with the handle list.
function UpdateHwndList(Hwnd : THandle; var WasAdded: boolean): integer; overload;
var
counter: integer;
begin
WasAdded := false;
// Is the list empty?
if High(HwndList) > 0 then
begin
// Search handle inside the list
for counter := Low(HwndList) to High(HwndList) do
begin
// If the handle is inside...
if HwndList[counter] = Hwnd then
begin
Result := counter;
exit;
end;
end;
end;
// Now, we are sure that Hwnd isn't in the list.
// Let's add an element to this array.
SetLength(HwndList,High(HwndList)+1);
HwndList[High(HwndList)] := Hwnd;
WasAdded := true;
Result := High(HwndList);
end;
function UpdateHwndList(Hwnd : String; var WasAdded: boolean): integer; overload;
var
Value : Integer;
begin
Value := StrToIntDef(Hwnd,0);
Result := UpdateHwndList(THandle(Value),WasAdded);
end;
// The two function below were ripped by OS SHP Builder 3.39 beta
// Both were written by Stucuk.
// Interpretates comunications from other OS Tools windows
// Check SHP Builder project source (PostMessage commands)
// CopyData has been modified to return the message to someone
// else interpret
function CopyData(var Msg: TMessage): string;
var
cd: ^TCOPYDATASTRUCT;
PointerChar : PChar;
IsNewHandle : boolean;
Position : Integer;
begin
cd:=Pointer(msg.lParam);
msg.result:=0;
if cd^.dwData=(VOXEL_ACCESS) then
begin
try
PointerChar := cd^.lpData;
PointerChar := PChar(copy(PointerChar,2,length(PointerChar)));
Result := String(PointerChar);
if Fileexists(Result) then
VVFrmMain.OpenVoxel(Result);
{ process data }
msg.result:=-1;
except
end;
end
else if cd^.dwData=(MY_HANDLE) then
begin
try
PointerChar := cd^.lpData;
PointerChar := PChar(copy(PointerChar,2,length(PointerChar)));
Result := String(PointerChar);
// work out handle in the HwndList.
Position := UpdateHwndList(Result,IsNewHandle);
{ process data }
msg.result:=-1;
except
end;
end;
end;
procedure RunAProgram (const theProgram, itsParameters, defaultDirectory : AnsiString);
var rslt : integer;
msg : string;
begin
rslt := ShellExecute (0, 'open',
pChar (theProgram),
pChar (itsParameters),
pChar (defaultDirectory),
sw_ShowNormal);
if rslt <= 32
then begin
case rslt of
0,
se_err_OOM : msg := 'Out of memory/resources';
error_File_Not_Found : msg := 'File "' + theProgram + '" not found';
error_Path_Not_Found : msg := 'Path not found';
error_Bad_Format : msg := 'Damaged or invalid exe';
se_err_AccessDenied : msg := 'Access denied';
se_err_NoAssoc,
se_err_AssocIncomplete : msg := 'Filename association invalid';
se_err_DDEBusy,
se_err_DDEFail,
se_err_DDETimeOut : msg := 'DDE error';
se_err_Share : msg := 'Sharing violation';
else msg := 'no text';
end; // of case
raise Exception.Create ('ShellExecute error #' + IntToStr (rslt) + ': ' + msg);
end;
end;
function SendExternalMessage(const Hwnd : THandle; const Destination : Cardinal; const ParameterString : string): Boolean;
var
cd: ^TCOPYDATASTRUCT;
begin
Result := false;
if IsWindow(Hwnd) then
begin
// Generate data and send
cd.dwData:= Destination;
cd.cbData:= length(ParameterString)+1;
cd.lpData:= PChar(ParameterString);
SendMessage(Hwnd,wm_copydata,3,integer(@cd));
Result := true;
end;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.