text
stringlengths
14
6.51M
unit f2PicturePool; interface uses d2dInterfaces, d2dClasses; type Tf2PicturePool = class(Td2dProtoObject, Id2dPictureProvider) private function Id2dPictureProvider.GetByID = GetPicture; function GetPicture(const aPictureName: string): Id2dPicture; public class function Make: Id2dPictureProvider; end; implementation uses Types, JclStringLists, StrUtils, SysUtils, d2dTypes, d2dCore, d2dSimplePicture; function CutByColon(const aStr: string): IJclStringList; var l_StartPos, l_EndPos: Integer; l_Str: AnsiString; begin Result := JclStringList; if aStr = '' then Exit; l_StartPos := 1; while True do begin l_EndPos := PosEx(':', aStr, l_StartPos); if l_EndPos > 0 then begin l_Str := Copy(aStr, l_StartPos, l_EndPos-l_StartPos); Result.Add(l_Str); l_StartPos := l_EndPos+1; end else begin l_Str := Copy(aStr, l_StartPos, MaxInt); if l_Str <> '' then Result.Add(l_Str); Break; end; end; end; function Tf2PicturePool.GetPicture(const aPictureName: string): Id2dPicture; var l_Params: IJclStringList; l_X, l_Y, l_W, l_H: Integer; l_Color: Longword; l_Tex: Id2dTexture; l_PicSize: TPoint; begin l_Params := CutByColon(aPictureName); Assert(l_Params.Count = 6); l_Tex := gD2DE.Texture_Load(l_Params[0], False, True, False, @l_PicSize); if l_Tex <> nil then begin l_X := StrToIntDef(l_Params[1], 0); l_Y := StrToIntDef(l_Params[2], 0); l_W := StrToIntDef(l_Params[3], 0); l_H := StrToIntDef(l_Params[4], 0); l_Color := ((StrToIntDef(l_Params[5], $FF) and $FF) shl 24) or $FFFFFF; if l_W = 0 then l_W := l_PicSize.X - l_X; if l_H = 0 then l_H := l_PicSize.Y - l_Y; if (l_W < 0) or (l_H < 0) then Exit; Result := Td2dSimplePicture.Make(aPictureName, l_Tex, l_X, l_Y, l_W, l_H, l_Color); end; end; class function Tf2PicturePool.Make: Id2dPictureProvider; var l_PP: Tf2PicturePool; begin l_PP := Tf2PicturePool.Create; try Result := l_PP; finally FreeAndNil(l_PP); end; end; end.
unit define_deal; interface uses define_datetime, define_dealitem, define_dealmarket, define_price; const DealType_Unknown = 0; // DealType_Buy = 1; // 买盘 DealType_Sale = 2; // 卖盘 DealType_Neutral = 3; // 中性盘 DealType_Cancel = 4; // 撤单 DealResult_Unknown = 0; // 未知 DealResult_None = 1; // 未成交 DealResult_Part = 2; // 部分成交 DealResult_All = 3; // 全部成交 DealResult_Cancel = 4; // 撤单 DealResult_Fail = 5; // 出错 type // 下单 TRT_DealRequest = packed record { 22 } // ??? DataVersion : Word; ActionDate : TDateStock; ActionTime : TDayTimeM0; // 9:00 3600 * ActionID : integer; Price : TRT_PricePack; Num : Integer; ResultCode : Word; // 0 未成交 // 1 部分成交 // 2 全部成交 // 3 撤单 RequestNo : Integer; //AnsiString; // 委托编号 //RequestSeqNo : AnsiString; // 委托序号 end; // 成交 TRT_DealResultClose = packed record { 28 } // ??? DataVersion : Word; ActionDate : TDateStock; ActionTime : TDayTimeM0; // 9:00 3600 * ActionID : integer; TargetID : Integer; // --> request.ActionID Price : TRT_PricePack; // 成交价格 Num : Integer; // 成交数量 Amount : Integer; // 金额 Fee : Integer; // 手续费 等等 end; // 撤单 TRT_DealResultCancel = packed record { 16 } // ??? DataVersion : Word; ActionDate : TDateStock; ActionTime : TDayTimeM0; // 9:00 3600 * ActionID : Integer; // 4 - 12 TargetID : Integer; // 16 --> request.ActionID end; // 交易请求 TStore_DealRequest = packed record { 32 } RequestId : LongWord; // 4 DealType : Byte; // 1 DealResult : Byte; // 1 RequestDate : TDateStock; // 2 8 RequestTime : TDayTimeM0; // 2 10 9:00 3600 * DealMarket : TStore_DealMarketCode; // 2 12 DealItem : TStore_DealItemCode; // 4 16 Price : TStore_Price; // 4 DealPrice : TStore_Price; // 4 Num : LongWord; // 4 DealNum : LongWord; // 4 end; implementation end.
{$IfNDef kwCompiledVar_imp} // Модуль: "w:\common\components\rtl\Garant\ScriptEngine\kwCompiledVar.imp.pas" // Стереотип: "Impurity" // Элемент модели: "kwCompiledVar" MUID: (52D3E2EE0244) // Имя типа: "_kwCompiledVar_" {$Define kwCompiledVar_imp} {$If NOT Defined(NoScripts)} _kwCompiledVar_ = {abstract} class(_kwCompiledVar_Parent_) private f_Value: TtfwStackValue; f_TypeInfo: TtfwWordInfo; protected procedure DoDoIt(const aCtx: TtfwContext); override; procedure Cleanup; override; {* Функция очистки полей объекта. } function pm_GetResultTypeInfo(const aCtx: TtfwContext): TtfwWordInfo; override; public procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; function GetValue(const aCtx: TtfwContext): TtfwStackValue; override; function IsVarLike: Boolean; override; procedure SetResultTypeInfo(aValue: TtfwWordInfo; const aCtx: TtfwContext); override; function CanClearInRecursiveCalls: Boolean; override; end;//_kwCompiledVar_ {$Else NOT Defined(NoScripts)} _kwCompiledVar_ = _kwCompiledVar_Parent_; {$IfEnd} // NOT Defined(NoScripts) {$Else kwCompiledVar_imp} {$IfNDef kwCompiledVar_imp_impl} {$Define kwCompiledVar_imp_impl} {$If NOT Defined(NoScripts)} procedure _kwCompiledVar_.DoDoIt(const aCtx: TtfwContext); //#UC START# *4DAEEDE10285_52D3E2EE0244_var* //#UC END# *4DAEEDE10285_52D3E2EE0244_var* begin //#UC START# *4DAEEDE10285_52D3E2EE0244_impl* TtfwThreadVar.Instance.PushValue(Self, @f_Value, aCtx); //#UC END# *4DAEEDE10285_52D3E2EE0244_impl* end;//_kwCompiledVar_.DoDoIt procedure _kwCompiledVar_.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_52D3E2EE0244_var* //var // l_V : PtfwStackValue; //#UC END# *479731C50290_52D3E2EE0244_var* begin //#UC START# *479731C50290_52D3E2EE0244_impl* //l_V := TtfwThreadVar.Instance.Check(Self, @f_Value); //Finalize(l_V^); //l3FillChar(l_V^, SizeOf(l_V^)); Finalize(f_Value); l3FillChar(f_Value, SizeOf(f_Value)); f_TypeInfo := nil; inherited; //#UC END# *479731C50290_52D3E2EE0244_impl* end;//_kwCompiledVar_.Cleanup function _kwCompiledVar_.pm_GetResultTypeInfo(const aCtx: TtfwContext): TtfwWordInfo; //#UC START# *52CFC11603C8_52D3E2EE0244get_var* //#UC END# *52CFC11603C8_52D3E2EE0244get_var* begin //#UC START# *52CFC11603C8_52D3E2EE0244get_impl* if (f_TypeInfo = nil) then Result := TtfwWordInfoE.Instance else Result := f_TypeInfo; //#UC END# *52CFC11603C8_52D3E2EE0244get_impl* end;//_kwCompiledVar_.pm_GetResultTypeInfo procedure _kwCompiledVar_.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); //#UC START# *52D00B00031A_52D3E2EE0244_var* //#UC END# *52D00B00031A_52D3E2EE0244_var* begin //#UC START# *52D00B00031A_52D3E2EE0244_impl* TtfwThreadVar.Instance.SetValue(Self, @f_Value, aValue); //#UC END# *52D00B00031A_52D3E2EE0244_impl* end;//_kwCompiledVar_.SetValuePrim function _kwCompiledVar_.GetValue(const aCtx: TtfwContext): TtfwStackValue; //#UC START# *52D399A00173_52D3E2EE0244_var* //#UC END# *52D399A00173_52D3E2EE0244_var* begin //#UC START# *52D399A00173_52D3E2EE0244_impl* Result := TtfwThreadVar.Instance.GetValue(Self, @f_Value); //#UC END# *52D399A00173_52D3E2EE0244_impl* end;//_kwCompiledVar_.GetValue function _kwCompiledVar_.IsVarLike: Boolean; //#UC START# *52D399D40140_52D3E2EE0244_var* //#UC END# *52D399D40140_52D3E2EE0244_var* begin //#UC START# *52D399D40140_52D3E2EE0244_impl* Result := true; //#UC END# *52D399D40140_52D3E2EE0244_impl* end;//_kwCompiledVar_.IsVarLike procedure _kwCompiledVar_.SetResultTypeInfo(aValue: TtfwWordInfo; const aCtx: TtfwContext); //#UC START# *52EA6A2C0111_52D3E2EE0244_var* //#UC END# *52EA6A2C0111_52D3E2EE0244_var* begin //#UC START# *52EA6A2C0111_52D3E2EE0244_impl* f_TypeInfo := aValue.Clone; //#UC END# *52EA6A2C0111_52D3E2EE0244_impl* end;//_kwCompiledVar_.SetResultTypeInfo function _kwCompiledVar_.CanClearInRecursiveCalls: Boolean; //#UC START# *559A470F0288_52D3E2EE0244_var* //#UC END# *559A470F0288_52D3E2EE0244_var* begin //#UC START# *559A470F0288_52D3E2EE0244_impl* Result := true; //#UC END# *559A470F0288_52D3E2EE0244_impl* end;//_kwCompiledVar_.CanClearInRecursiveCalls {$IfEnd} // NOT Defined(NoScripts) {$EndIf kwCompiledVar_imp_impl} {$EndIf kwCompiledVar_imp}
unit TTSAGENTTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TTTSAGENTRecord = record PLenderNum: String[4]; PAgentID: String[8]; PLine1: String[40]; PLine2: String[40]; PLine3: String[40]; PLine4: String[40]; PPhone: String[40]; PEMail: String[80]; End; TTTSAGENTBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TTTSAGENTRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEITTSAGENT = (TTSAGENTPrimaryKey); TTTSAGENTTable = class( TDBISAMTableAU ) private FDFLenderNum: TStringField; FDFAgentID: TStringField; FDFLine1: TStringField; FDFLine2: TStringField; FDFLine3: TStringField; FDFLine4: TStringField; FDFPhone: TStringField; FDFEMail: TStringField; procedure SetPLenderNum(const Value: String); function GetPLenderNum:String; procedure SetPAgentID(const Value: String); function GetPAgentID:String; procedure SetPLine1(const Value: String); function GetPLine1:String; procedure SetPLine2(const Value: String); function GetPLine2:String; procedure SetPLine3(const Value: String); function GetPLine3:String; procedure SetPLine4(const Value: String); function GetPLine4:String; procedure SetPPhone(const Value: String); function GetPPhone:String; procedure SetPEMail(const Value: String); function GetPEMail:String; procedure SetEnumIndex(Value: TEITTSAGENT); function GetEnumIndex: TEITTSAGENT; protected procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TTTSAGENTRecord; procedure StoreDataBuffer(ABuffer:TTTSAGENTRecord); property DFLenderNum: TStringField read FDFLenderNum; property DFAgentID: TStringField read FDFAgentID; property DFLine1: TStringField read FDFLine1; property DFLine2: TStringField read FDFLine2; property DFLine3: TStringField read FDFLine3; property DFLine4: TStringField read FDFLine4; property DFPhone: TStringField read FDFPhone; property DFEMail: TStringField read FDFEMail; property PLenderNum: String read GetPLenderNum write SetPLenderNum; property PAgentID: String read GetPAgentID write SetPAgentID; property PLine1: String read GetPLine1 write SetPLine1; property PLine2: String read GetPLine2 write SetPLine2; property PLine3: String read GetPLine3 write SetPLine3; property PLine4: String read GetPLine4 write SetPLine4; property PPhone: String read GetPPhone write SetPPhone; property PEMail: String read GetPEMail write SetPEMail; published property Active write SetActive; property EnumIndex: TEITTSAGENT read GetEnumIndex write SetEnumIndex; end; { TTTSAGENTTable } procedure Register; implementation procedure TTTSAGENTTable.CreateFields; begin FDFLenderNum := CreateField( 'LenderNum' ) as TStringField; FDFAgentID := CreateField( 'AgentID' ) as TStringField; FDFLine1 := CreateField( 'Line1' ) as TStringField; FDFLine2 := CreateField( 'Line2' ) as TStringField; FDFLine3 := CreateField( 'Line3' ) as TStringField; FDFLine4 := CreateField( 'Line4' ) as TStringField; FDFPhone := CreateField( 'Phone' ) as TStringField; FDFEMail := CreateField( 'EMail' ) as TStringField; end; { TTTSAGENTTable.CreateFields } procedure TTTSAGENTTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TTTSAGENTTable.SetActive } procedure TTTSAGENTTable.SetPLenderNum(const Value: String); begin DFLenderNum.Value := Value; end; function TTTSAGENTTable.GetPLenderNum:String; begin result := DFLenderNum.Value; end; procedure TTTSAGENTTable.SetPAgentID(const Value: String); begin DFAgentID.Value := Value; end; function TTTSAGENTTable.GetPAgentID:String; begin result := DFAgentID.Value; end; procedure TTTSAGENTTable.SetPLine1(const Value: String); begin DFLine1.Value := Value; end; function TTTSAGENTTable.GetPLine1:String; begin result := DFLine1.Value; end; procedure TTTSAGENTTable.SetPLine2(const Value: String); begin DFLine2.Value := Value; end; function TTTSAGENTTable.GetPLine2:String; begin result := DFLine2.Value; end; procedure TTTSAGENTTable.SetPLine3(const Value: String); begin DFLine3.Value := Value; end; function TTTSAGENTTable.GetPLine3:String; begin result := DFLine3.Value; end; procedure TTTSAGENTTable.SetPLine4(const Value: String); begin DFLine4.Value := Value; end; function TTTSAGENTTable.GetPLine4:String; begin result := DFLine4.Value; end; procedure TTTSAGENTTable.SetPPhone(const Value: String); begin DFPhone.Value := Value; end; function TTTSAGENTTable.GetPPhone:String; begin result := DFPhone.Value; end; procedure TTTSAGENTTable.SetPEMail(const Value: String); begin DFEMail.Value := Value; end; function TTTSAGENTTable.GetPEMail:String; begin result := DFEMail.Value; end; procedure TTTSAGENTTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('LenderNum, String, 4, N'); Add('AgentID, String, 8, N'); Add('Line1, String, 40, N'); Add('Line2, String, 40, N'); Add('Line3, String, 40, N'); Add('Line4, String, 40, N'); Add('Phone, String, 40, N'); Add('EMail, String, 80, N'); end; end; procedure TTTSAGENTTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, LenderNum;AgentID, Y, Y, N, N'); end; end; procedure TTTSAGENTTable.SetEnumIndex(Value: TEITTSAGENT); begin case Value of TTSAGENTPrimaryKey : IndexName := ''; end; end; function TTTSAGENTTable.GetDataBuffer:TTTSAGENTRecord; var buf: TTTSAGENTRecord; begin fillchar(buf, sizeof(buf), 0); buf.PLenderNum := DFLenderNum.Value; buf.PAgentID := DFAgentID.Value; buf.PLine1 := DFLine1.Value; buf.PLine2 := DFLine2.Value; buf.PLine3 := DFLine3.Value; buf.PLine4 := DFLine4.Value; buf.PPhone := DFPhone.Value; buf.PEMail := DFEMail.Value; result := buf; end; procedure TTTSAGENTTable.StoreDataBuffer(ABuffer:TTTSAGENTRecord); begin DFLenderNum.Value := ABuffer.PLenderNum; DFAgentID.Value := ABuffer.PAgentID; DFLine1.Value := ABuffer.PLine1; DFLine2.Value := ABuffer.PLine2; DFLine3.Value := ABuffer.PLine3; DFLine4.Value := ABuffer.PLine4; DFPhone.Value := ABuffer.PPhone; DFEMail.Value := ABuffer.PEMail; end; function TTTSAGENTTable.GetEnumIndex: TEITTSAGENT; var iname : string; begin result := TTSAGENTPrimaryKey; iname := uppercase(indexname); if iname = '' then result := TTSAGENTPrimaryKey; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'TTS Tables', [ TTTSAGENTTable, TTTSAGENTBuffer ] ); end; { Register } function TTTSAGENTBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..8] of string = ('LENDERNUM','AGENTID','LINE1','LINE2','LINE3','LINE4' ,'PHONE','EMAIL' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 8) and (flist[x] <> s) do inc(x); if x <= 8 then result := x else result := 0; end; function TTTSAGENTBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftString; 4 : result := ftString; 5 : result := ftString; 6 : result := ftString; 7 : result := ftString; 8 : result := ftString; end; end; function TTTSAGENTBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PLenderNum; 2 : result := @Data.PAgentID; 3 : result := @Data.PLine1; 4 : result := @Data.PLine2; 5 : result := @Data.PLine3; 6 : result := @Data.PLine4; 7 : result := @Data.PPhone; 8 : result := @Data.PEMail; end; end; end.
{ *************************************************************************** } { } { } { Copyright (C) Amarildo Lacerda } { } { https://github.com/amarildolacerda } { } { } { *************************************************************************** } { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } { *************************************************************************** } { 12/07/2016 * trocado TTask por TTHread para compatibilidade com versões anteriores do XE - Amarildo Lacerda unit System.LogEvents.Progress; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, System.SyncObjs, System.Generics.Collections, System.LogEvents, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Grids, Vcl.ValEdit, Vcl.ExtCtrls, Vcl.Buttons, Vcl.StdCtrls, Vcl.ComCtrls; type IProgressEvents = interface ['{291F6DA5-5606-412B-9CD6-76A4E25A9C95}'] procedure SetCanCancel(const Value: Boolean); function GetCanCancel: Boolean; procedure SetText(const Value: string); function GetText: string; procedure SetMaxThreads(const Value: Integer); function GetMaxThreads: Integer; procedure SetMax(const Value: Integer); function GetMax: Integer; property Max: Integer read GetMax write SetMax; property MaxThreads: Integer read GetMaxThreads write SetMaxThreads; procedure execute(const ACaption: String); procedure WaitFor(const ASleep: Integer = 100); procedure WaitForAll(const ASleep: Integer = 100); function Count: Integer; procedure Add(sender: TObject; AMsg: string; proc: TProc<TObject>); overload; procedure Add(AIndex: Integer; AMsg: string; proc: TProc<Integer>); overload; procedure Add(AValue: string; AMsg: string; proc: TProc<string>); overload; property Text: string read GetText write SetText; property CanCancel: Boolean read GetCanCancel write SetCanCancel; function Terminated: Boolean; end; TProgressEvents = class(TForm, IProgressEvents) Panel1: TPanel; Panel2: TPanel; ValueListEditor1: TValueListEditor; SpeedButton1: TSpeedButton; lbPosition: TLabel; lblErro: TLabel; procedure FormCreate(sender: TObject); procedure FormDestroy(sender: TObject); procedure SpeedButton1Click(sender: TObject); procedure FormCloseQuery(sender: TObject; var CanClose: Boolean); procedure lblErroClick(sender: TObject); private FTerminated: Boolean; FInited: Boolean; FSLock: TCriticalSection; FLocal: Integer; FMax: Integer; FPosision: Integer; FMaxThreads: Integer; FCanCancel: Boolean; { Private declarations } procedure DoProgressEvent(sender: TObject; ATipo: TLogEventType; msg: string; APosition: double); procedure DoErro(sender: TObject; msg: string); procedure SetMax(const Value: Integer); function GetMax: Integer; procedure UpdatePosition; procedure incPos(x: Integer); procedure CheckThreads; procedure SetMaxThreads(const Value: Integer); function GetMaxThreads: Integer; procedure lock; procedure Unlock; procedure SetText(const Value: string); function GetText: string; procedure WaitForAll(const ASleep: Integer = 100); procedure SetCanCancel(const Value: Boolean); function GetCanCancel: Boolean; public { Public declarations } procedure execute(const ACaption: String); property Max: Integer read GetMax write SetMax; property MaxThreads: Integer read GetMaxThreads write SetMaxThreads; class function new: IProgressEvents; static; procedure Add(sender: TObject; AMsg: string; proc: TProc<TObject>); overload; procedure Add(AIndex: Integer; AMsg: string; proc: TProc<Integer>); overload; procedure Add(AValue, AMsg: string; proc: TProc<string>); overload; procedure WaitFor(const ASleep: Integer = 100); function Count: Integer; function Terminated: Boolean; property Text: string read GetText write SetText; property CanCancel: Boolean read GetCanCancel write SetCanCancel; end; implementation {$R *.dfm} //uses System.Threading; procedure TProgressEvents.Add(AIndex: Integer; AMsg: string; proc: TProc<Integer>); begin if not FInited then execute(''); lock; try DoProgressEvent(self, etCreating, AMsg, 0); InterlockedIncrement(FLocal); if FMaxThreads <= 0 then begin // nao usa Thread... DoProgressEvent(self, etStarting, AMsg, 0); proc(AIndex); DoProgressEvent(self, etFinished, AMsg, 0); end else begin DoProgressEvent(self, etWaiting, AMsg, 0); TThread.CreateAnonymousThread( procedure begin DoProgressEvent(self, etStarting, AMsg, 0); proc(AIndex); DoProgressEvent(self, etFinished, AMsg, 0); end).start; end; finally Unlock; end; CheckThreads; end; procedure TProgressEvents.Add(AValue: String; AMsg: string; proc: TProc<String>); begin if not FInited then execute(''); lock; try DoProgressEvent(self, etCreating, AMsg, 0); InterlockedIncrement(FLocal); DoProgressEvent(self, etStarting, AMsg, 0); if FMaxThreads <= 1 then begin proc(AValue); DoProgressEvent(self, etFinished, AMsg, 0); end else TThread.CreateAnonymousThread( procedure begin proc(AValue); DoProgressEvent(self, etFinished, AMsg, 0); end).start; finally Unlock; end; CheckThreads; end; procedure TProgressEvents.Add(sender: TObject; AMsg: string; proc: TProc<TObject>); begin if not FInited then execute(''); lock; try DoProgressEvent(self, etCreating, AMsg, 0); InterlockedIncrement(FLocal); DoProgressEvent(self, etStarting, AMsg, 0); if FMaxThreads <= 1 then begin proc(sender); DoProgressEvent(self, etFinished, AMsg, 0); end else TThread.CreateAnonymousThread( procedure begin proc(sender); DoProgressEvent(self, etFinished, AMsg, 0); end).start; finally Unlock; end; CheckThreads; end; procedure TProgressEvents.CheckThreads; begin if Count > FMaxThreads then WaitFor(100); end; function TProgressEvents.Count: Integer; begin lock; try result := (FLocal - FPosision); finally Unlock; end; end; procedure TProgressEvents.DoErro(sender: TObject; msg: string); begin lblErro.caption := msg; end; procedure TProgressEvents.DoProgressEvent(sender: TObject; ATipo: TLogEventType; msg: string; APosition: double); var i: Integer; begin if not FInited then begin SpeedButton1.tag := ord(FCanCancel); execute(''); end; TThread.Queue(nil, procedure begin if ATipo = etAllFinished then begin SpeedButton1.Enabled := true; SpeedButton1.tag := 0; WaitForAll(100); SpeedButton1.caption := 'OK'; end else begin i := ValueListEditor1.Strings.IndexOfName(msg); if i >= 0 then begin case ATipo of etCreating: ValueListEditor1.Strings.Values[msg] := 'Criando..'; etWaiting: ValueListEditor1.Strings.Values[msg] := 'na fila'; etStarting: ValueListEditor1.Strings.Values[msg] := 'Iniciado..'; etEnding: ValueListEditor1.Strings.Values[msg] := 'finalizando'; etWorking: begin ValueListEditor1.Strings.Values[msg] := 'Em andamento'; end; etFinished: begin ValueListEditor1.Strings.Values[msg] := 'Concluído '; incPos(1); end end; end else begin ValueListEditor1.Strings.Add(msg+'=...'); ValueListEditor1.Perform(WM_VSCROLL, SB_BOTTOM, 0); UpdatePosition; end; end; end); end; procedure TProgressEvents.execute(const ACaption: String); begin if ACaption <> '' then caption := ACaption; if FCanCancel then begin SpeedButton1.caption := 'Cancelar'; SpeedButton1.Enabled := true; end; show; FInited := true; end; procedure TProgressEvents.FormCloseQuery(sender: TObject; var CanClose: Boolean); begin FTerminated := true; end; procedure TProgressEvents.FormCreate(sender: TObject); begin FMaxThreads := 5; FTerminated := false; ValueListEditor1.Strings.clear; FInited := false; FSLock := TCriticalSection.create; FMax := 0; LogEvents.MostraDataHora := false; LogEvents.register(self, DoProgressEvent, 0); LogEvents.register(self, DoErro, 0); SpeedButton1.Enabled := false; end; procedure TProgressEvents.FormDestroy(sender: TObject); begin LogEvents.unregister(self); FSLock.free; end; function TProgressEvents.GetCanCancel: Boolean; begin result := FCanCancel; end; function TProgressEvents.GetMax: Integer; begin result := FMax; end; function TProgressEvents.GetMaxThreads: Integer; begin result := FMaxThreads; end; function TProgressEvents.GetText: string; begin lock; try result := Panel1.caption; finally Unlock; end; end; procedure TProgressEvents.incPos(x: Integer); begin FPosision := FPosision + x; UpdatePosition; end; procedure TProgressEvents.lblErroClick(sender: TObject); begin showMessage(lblErro.caption); end; procedure TProgressEvents.lock; begin FSLock.Acquire; end; class function TProgressEvents.new: IProgressEvents; begin result := TProgressEvents.create(nil); end; procedure TProgressEvents.SetCanCancel(const Value: Boolean); begin FCanCancel := Value; end; procedure TProgressEvents.SetMax(const Value: Integer); begin FMax := Value; UpdatePosition; end; procedure TProgressEvents.SetMaxThreads(const Value: Integer); begin FMaxThreads := Value; end; procedure TProgressEvents.SetText(const Value: string); begin TThread.Synchronize(nil, procedure begin lock; try Panel1.caption := Value; finally Unlock; end; end); end; procedure TProgressEvents.SpeedButton1Click(sender: TObject); begin FTerminated := true; close; end; function TProgressEvents.Terminated: Boolean; begin lock; try result := FTerminated; if result then; // como parar a TASK finally Unlock; end; end; procedure TProgressEvents.Unlock; begin FSLock.Release; end; procedure TProgressEvents.UpdatePosition; var t: Integer; begin TThread.Queue(nil, procedure begin lbPosition.caption := ''; t := FMax; if t = 0 then t := ValueListEditor1.Strings.Count; lbPosition.caption := intToStr(FPosision) + ' de ' + intToStr(t); end); end; procedure TProgressEvents.WaitFor(const ASleep: Integer); begin while Count > FMaxThreads do begin TThread.Sleep(ASleep); Application.ProcessMessages; if Terminated then break; end; end; procedure TProgressEvents.WaitForAll(const ASleep: Integer); begin while Count > 0 do begin TThread.Sleep(ASleep); Application.ProcessMessages; if Terminated then break; end; end; end.
unit uFrame; interface uses uComponente; type TFrame = class(TComponente) protected procedure Reposicionar(aX, aY: Integer); override; procedure Redimensionar(aAltura, aLargura: Integer); override; public procedure AdicionaComponente(aComponente: TComponente); override; procedure RemoveComponente(aComponente: TComponente); override; end; { Deverá ter sua largura e sua altura redimensionados proporcionalmente as novas largura e altura do Formulario além de ser reposicionado nas coordenadas x e y proporcionais as novas dimensões do Formulario; } implementation { TFrame } procedure TFrame.Redimensionar(aAltura, aLargura: Integer); begin inherited; if Parent.Altura > 0 then Self.Altura := (Self.Altura*aAltura) div Parent.Altura; if Parent.Largura > 0 then Self.Largura := (Self.Largura*aLargura) div Parent.Largura; end; procedure TFrame.Reposicionar(aX, aY: Integer); begin inherited; Self.X := Self.X+aX-Parent.X; Self.Y := Self.Y+aY-Parent.Y; end; procedure TFrame.AdicionaComponente(aComponente: TComponente); begin aComponente.Parent := Self; SetLength(FComponentes, Length(FComponentes)+1); FComponentes[High(FComponentes)] := aComponente; end; procedure TFrame.RemoveComponente(aComponente: TComponente); var I, J: Integer; begin for I := Low(FComponentes) to High(FComponentes) do begin if FComponentes[I] = aComponente then begin for J := I to High(FComponentes)-1 do FComponentes[I] := FComponentes[I+1]; SetLength(FComponentes, Length(FComponentes)-1); end; end; end; end.
//ENG:Deprecated module. In future removed!!! Now all functions marked as comment. //ENG:for revert changes remove "(*" comment. //RUS:Устаревший модуль. В будущем будет удалён. Сейчас весь функционал просто закоментирован. //RUS:Для отмены изменений удалите "(*" коментарии (* A.Voitov zprokuror(cyka)narod.ru LAZARUS-FPC-LINUX codeset conversion routines The goal is easy-and-on-fly *.lrs conversion from codeset used by developer to user's system codeset without gettext, without separate message files etc. Now I only have to set my codeset below (by default it's mine - UTF-8) - DON'T FORGET ABOUT IT - and call LocalizeForm('TFormClassName') right after {$I TFormClassName.lrs} - see example below. This way form resource file will be converted to system codeset when form is creating. For gtk/gnome there's only one conversion routine function Localize(source:string):ansistring; For gtk2 resource MUST, I guess, be converted to UTF-8 anyway (if it's not yet), so I set current_codeset to UTF-8 with FORCE_UTF8 definition. Though if developer's codeset is UTF-8 then no form resource conversion needed. Localize is published function so it can be used again to convert string constants, resource strings in most cases with no care about user's and developer's codeset. But it's not enough sometime (file names, inifiles etc. can be wrong when gtk2 works in koi8-r locale). That's why we've got some stuff th handle it without care. 1. First one is TIconv object (I'm not sure it's best way to do maybe it would class? if so uncomment $DEFINE OBJ_IS_CLASS below) 2. Second are uiconv_xxx functions They can be used to easy implement any valid conversions. EXAMPLES: 1. Auto form conversion - set my codeset below: {$DEFINE DC_UTF8} - add LocalizeForm('TFormClassName') after {$I TFormClassName.lrs} <CODE> unit1; [...] initialization {$I unit1.lrs} LocalizeForm('TForm1'); end. </CODE> 2. TIconv object example: object is local variable here, but it can be global (create at startup, dead in the end) if it's always in-use. <CODE> function koi8r_to_utf8(S:string):string; var iConverter:pIconv; begin iConverter:=NewIconv('CP1251', 'UTF-8'); Result:=iConverter.iconv(S); iConverter.Free; end; </CODE> 3. uiconv_xxx example - obvious. APPENDIX i. KNOWN DEVELOPER'S CODESET DEFENITIONS: $DC_KOI8 (obvious) $DC_UTF8 (obvious) - default $DC_WIN (CP1251) - not tested yet ii. GTK2 NOTES As I found there's something wrong with some strings when gtk2 is used under koi8-r locale. OpenDialog.FileName is stored in my inifile as koi8-r string and then can't be loaded in MRU menu. So I've got a couple of functions here for that case: str2gtk and gtk2str. 'str' means current codeset (locale) iii. This unit tested with dc_utf8 and user's locale koi8-r only *) unit rxiconv; (* {* Developer's codeset. Must be set on design-time. Default is UTF8} {.$DEFINE DC_KOI8} {$DEFINE DC_WIN} {.$DEFINE DC_UTF8} //nothing defined so DC_UTF8 will be defined here {$IFNDEF DC_UTF8} {$IFNDEF DC_KOI8} {$IFNDEF DC_WIN} {$DEFINE DC_UTF8} {$ENDIF DC_WIN} {$ENDIF DC_KOI8} {$ENDIF DC_UTF8} {* user acces to iconv functions} {$DEFINE USER_ICONV} {* TIconv object} {$DEFINE USE_OBJECT} {* Ticonv is class(TObject)} {$DEFINE OBJ_IS_CLASS} {* form-localization needed only with gtk1 or with gtk2 if developer's codeset is not utf-8. First turn it of.} {$UNDEF USE_LOCALIZE} {* if widgetset is GTK2 ($IFDEF LCLGtk2) and developer's codeset is not DC_UTF8 then we'd FORCE_UTF8 and turn on USE_LOCALIZE. And if widgetset is GTK1 then we USE_LOCALIZE too.} {$IFDEF LCLGtk2} {$IFNDEF DC_UTF8} {$DEFINE USE_LOCALIZE} {$DEFINE FORCE_UTF8} {$ENDIF DC_UTF8} {$ELSE LCLGtk2} {$DEFINE USE_LOCALIZE} {$ENDIF LCLGtk2} {$mode objfpc} *) interface (* {$IFNDEF WINDOWS} uses {$IFDEF USE_LOCALIZE} LResources, Classes,{$ENDIF} initc, SysUtils; {* returns current codeset} function GetCodeset():ansistring; {$IFDEF USE_LOCALIZE} {* returns true if current codeset<>developer's codeset} function InvalidCodeset():boolean; {$ENDIF USE_LOCALIZE} {* basic string conversion - enough for localization. conversion from developer's codeset 2 user's codeset} function Localize(source:ansistring):ansistring; {with gtk2 converts utf8 to locale codeset and back} {$IFDEF LCLGtk2} function str2gtk(source:ansistring):ansistring; function gtk2str(source:ansistring):ansistring; {$ENDIF LCLGtk2} {* public access 2 iconv} {$IFDEF USER_ICONV} function uiconv(ic_usr:pointer; source:ansistring):ansistring ; function uiconv_open(ic_from, ic_to:ansistring):pointer ; procedure uiconv_close(ic_usr:pointer) ; {$ENDIF USER_ICONV} {* form conversion} procedure LocalizeForm(form_classname:ansistring); procedure LocalizeAllForm; {* iconv object/class} {$IFDEF USE_OBJECT} type {$IFDEF OBJ_IS_CLASS} Ticonv=class(TObject) {$ELSE OBJ_IS_CLASS} pIconv=^Ticonv; Ticonv=object protected {$ENDIF OBJ_IS_CLASS} hIconv:pointer; public destructor Destroy;{$IFDEF OBJ_IS_CLASS}virtual;{$ENDIF OBJ_IS_CLASS} {$IFNDEF OBJ_IS_CLASS} procedure Free; {$ENDIF OBJ_IS_CLASS} constructor Create{$IFDEF OBJ_IS_CLASS}(cs_from, cs_to:ansistring){$ENDIF OBJ_IS_CLASS}; function iconv(source:ansistring):ansistring; end; {$IFNDEF OBJ_IS_CLASS} function NewIconv(cs_from, cs_to:ansistring):TIconv ; {$ENDIF OBJ_IS_CLASS} {$ENDIF USE_OBJECT} {$ENDIF} *) implementation (* {$IFNDEF WINDOWS} uses dialogs; {$linklib c} const libiconvname='c'; __LC_CTYPE = 0; _NL_CTYPE_CLASS = (__LC_CTYPE shl 16); _NL_CTYPE_CODESET_NAME = (_NL_CTYPE_CLASS)+14; CODESET = _NL_CTYPE_CODESET_NAME; {developer's codeset names} {$IFDEF DC_KOI8} DEV_CODESET='KOI8-R'; DC_NAME='KOI'; DC_NAME_EXT='R'; {$ENDIF DC_KOI8} {$IFDEF DC_UTF8} DEV_CODESET='UTF-8'; DC_NAME='UTF'; DC_NAME_EXT='8'; {$ENDIF DC_UTF8} {$IFDEF DC_WIN} DEV_CODESET='CP1251'; DC_NAME='1251'; DC_NAME_EXT='1251'; {$ENDIF DC_WIN} type size_t = cardinal; pSize = ^size_t; psize_t = pSize; cInt = longint; piconv_t = ^iconv_t; iconv_t = pointer; nl_item = cint; var //iconv pointers {$IFDEF LCLGtk2} ic_str2gtk, ic_gtk2str, {$ENDIF LCLGtk2} ic_localize : iconv_t; function nl_langinfo(__item:nl_item):pchar;cdecl;external libiconvname name 'nl_langinfo'; function iconv_open(__tocode:pchar; __fromcode:pchar):iconv_t;cdecl;external libiconvname name 'iconv_open'; function iconv(__cd:iconv_t; __inbuf:ppchar; __inbytesleft:psize_t; __outbuf:ppchar; __outbytesleft:psize_t):size_t;cdecl;external libiconvname name 'iconv'; function iconv_close(__cd:iconv_t):cint;cdecl;external libiconvname name 'iconv_close'; {* common procedures} function GetCodeset():ansistring; begin Result:= ansistring(nl_langinfo(CODESET)); end; function CodesetIs(CSNAME, CSEXT:ansistring):boolean ; var CS:ansistring; begin CS:=UpperCase(GetCodeSet); if ((pos(CSNAME,CS)<>0) and (pos(CSEXT,CS)<>0)) then Result:=true else Result:=false; end; {* main conversion procedure} function _iconv(hiconv:iconv_t; source:ansistring):ansistring; const ESysEILSEQ = 84; ESysE2BIG = 7; var len:SizeInt; outlength, outoffset, outleft : size_t; srcpos, destpos: pchar; mynil : pchar; my0 : size_t; begin mynil:=nil; my0:=0; // extra space len:=length(source); outlength:=len*3+1; //setlength(result,outlength); Result:=StringOfChar(#0, outlength); //outlength:=len+1; srcpos:=pChar(source); destpos:=pchar(result); outleft:=outlength*2; while iconv(hiconv,@srcpos,@len,@destpos,@outleft)=size_t(-1) do begin case fpgetCerrno of ESysEILSEQ: begin { skip and set to '?' } inc(srcpos); pwidechar(destpos)^:='?'; inc(destpos,2); dec(outleft,2); { reset } iconv(hiconv,@mynil,@my0,@mynil,@my0); end; ESysE2BIG: begin outoffset:=destpos-pchar(result); { extend } setlength(result,outlength+len); inc(outleft,len*2); inc(outlength,len); { string could have been moved } destpos:=pchar(result)+outoffset; end; else raise EConvertError.Create('iconv error '+IntToStr(fpgetCerrno)); end; end; //setlength(result,length(result)-outleft div 2); // truncate string Result:=TrimRight(Result);// not shure it always works right end; {$IFDEF USE_OBJECT} {* Ticonv *} {$IFNDEF OBJ_IS_CLASS} function _NewIconv(cs_from, cs_to:ansistring):pIconv ; begin New( Result, Create); Result^.hIconv:=Pointer(iconv_open(pChar(cs_to), pChar(cs_from))); end; function NewIconv(cs_from, cs_to:ansistring):TIconv ; begin Result:=_NewIconv(cs_from, cs_to)^; end; procedure Ticonv.Free(); begin if @Self<>nil then Self.Destroy; end; {$ENDIF OBJ_IS_CLASS} constructor Ticonv.Create{$IFDEF OBJ_IS_CLASS}(cs_from, cs_to:ansistring){$ENDIF OBJ_IS_CLASS}; begin {$IFDEF OBJ_IS_CLASS} inherited Create; hIconv:=Pointer(iconv_open(pChar(cs_to), pChar(cs_from))); {$ENDIF OBJ_IS_CLASS} end; destructor Ticonv.Destroy; begin iconv_close(hIconv); Inherited; end; function Ticonv.iconv(source:ansistring):ansistring; begin Result:=_iconv(hIconv, source); end; {$ENDIF USE_OBJECT} {$IFDEF USER_ICONV} function uiconv(ic_usr:pointer; source:ansistring):ansistring ; begin Result:=_iconv(iconv_t(ic_usr), pchar(source)); end; function uiconv_open(ic_from, ic_to:ansistring):pointer ; begin Result:= iconv_open(pchar(ic_to), pchar(ic_from)); end; procedure uiconv_close(ic_usr:pointer) ; begin iconv_close(iconv_t(ic_usr)); end; {$ENDIF USER_ICONV} function Localize(source:ansistring):ansistring; begin Result:=_iconv(ic_localize, source); end; {$IFDEF LCLGtk2} function str2gtk(source:ansistring):ansistring; begin Result:=_iconv(ic_str2gtk, source); end; function gtk2str(source:ansistring):ansistring; begin Result:=_iconv(ic_gtk2str, source); end; {$ENDIF LCLGtk2} {* form localization - only if use_localize} {$IFDEF USE_LOCALIZE} function InvalidCodeset():boolean; begin Result:=False; {$IFNDEF FORCE_UTF8} Result:= not (CodesetIs(DC_NAME, DC_NAME_EXT));{$ENDIF FORCE_UTF8} end; {* converts form resource from developer's codeset to env codeset. it's empty procedure if widgetSet is gtk2 and dev's codeset is utf8. So USE_LOCCALIZE definition used } procedure LocalizeForm(form_classname:ansistring); var res : TLResource; S : ansistring; RS, MS : TMemoryStream; begin {$IFNDEF FORCE_UTF8} //always convert to utf8 if not InvalidCodeset then exit; {$ENDIF FORCE_UTF8} {find resource} res:=LazarusResources.Find(form_classname); RS:=TMemoryStream.create; MS:=TMemoryStream.create; {read form 2 RS} RS.Write(res.Value[1],length(res.Value)); RS.Position:=0; {convert 2 text} LRSObjectBinaryToText( RS, MS); MS.Position:=0; {copy 2 string} SetLength(S, MS.Size); MS.Read(S[1], MS.Size); {convert 2 ccs or utf8 - under gtk2} S:=Localize(S); {copy back to ms} S:=Trim(S) + #0#0#0#0; //doesn't work without it... MS.Position:=0; MS.Write(S[1],length(S)); MS.Position:=0; RS.SetSize(0); {convert 2 binary RS} LRSObjectTextToBinary(MS, RS); RS.Position:=0; SetLength(S, RS.Size); {write 2 resource} RS.Read(S[1],RS.Size); res.Value:=S; MS.Free; RS.Free; end; procedure LocalizeAllForm; var i:integer; begin for i:=0 to LazarusResources.Count - 1 do begin if LazarusResources.Items[i].ValueType = 'FORMDATA' then LocalizeForm(LazarusResources.Items[i].Name); end; end; {$ELSE USE_LOCALIZE} {* dummy proc for easy testing} procedure LocalizeForm(form_classname:ansistring);begin {*} end; procedure LocalizeAllForm; begin end; {$ENDIF USE_LOCALIZE} initialization {$IFNDEF FORCE_UTF8} ic_localize := iconv_open(nl_langinfo(CODESET), DEV_CODESET); //main {$ELSE FORCE_UTF8} ic_localize := iconv_open('UTF-8', DEV_CODESET); {$ENDIF FORCE_UTF8} {$IFDEF LCLGtk2} ic_str2gtk:= iconv_open('UTF-8', nl_langinfo(CODESET)); ic_gtk2str:= iconv_open(nl_langinfo(CODESET), 'UTF-8'); {$ENDIF LCLGtk2} finalization iconv_close(ic_localize); {$IFDEF LCLGtk2} iconv_close(ic_str2gtk); iconv_close(ic_gtk2str); {$ENDIF LCLGtk2} {$ENDIF} *) end.
{*********************************************************************************************************************** * * TERRA Game Engine * ========================================== * * Copyright (C) 2003, 2014 by SÚrgio Flores (relfos@gmail.com) * *********************************************************************************************************************** * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ********************************************************************************************************************** * TERRA_MeshFX * Implements Mesh geometry effects (eg: explosions) *********************************************************************************************************************** } Unit TERRA_MeshFX; {$I terra.inc} Interface Uses TERRA_Utils, TERRA_Mesh, TERRA_MeshFilter, TERRA_Vector3D, TERRA_Vector2D, TERRA_Quaternion, TERRA_Matrix4x4, TERRA_Color, TERRA_VertexFormat; Type MeshDebris = Record Center:Vector3D; Direction:Vector3D; Duration:Single; Strength:Single; Count:Integer; StartVertex:Integer; Rotation:Quaternion; End; MeshExplosion = Class(MeshFX) Protected _StartTime:Cardinal; _Duration:Integer; _Radius:Single; _Positions:Array Of Vector3D; _Debris:Array Of MeshDebris; _DebrisCount:Integer; _Indices:Array Of Integer; _Initialized:Boolean; Procedure InitTarget(); Procedure InitDebris(StartVertex, Index:Integer; Normal:Vector3D); Public Constructor Create(Duration:Integer); Function Update():Boolean; Override; End; Implementation Uses TERRA_OS, TERRA_Math; { MeshExplosion } Constructor MeshExplosion.Create(Duration:Integer); Begin _Duration := Duration; _Initialized := False; End; Procedure MeshExplosion.InitTarget(); Var I,J,K, N:Integer; Group:MeshGroup; P, OP:Vector3D; V:VertexIterator; TempVertices:VertexData; T:PTriangle; CurrentDebris:Integer; Begin If Target = Nil Then Exit; TempVertices := Nil; For I:=0 To Pred(Target.GroupCount) Do Begin Group := Target.GetGroup(I); Group.Flags := Group.Flags Or meshGroupDoubleSided; Group.CalculateTriangleNormals(); _Radius := Group.GetBoundingBox.Radius * 2; TempVertices := Group.Vertices.Clone(); TempVertices.CopyBuffer(Group.Vertices); _DebrisCount := Trunc(Group.TriangleCount * RandomFloat(0.2, 0.5)); SetLength(_Debris, _DebrisCount); SetLength(_Indices, Group.TriangleCount); Group.VertexCount := Group.TriangleCount * 3; SetLength(_Positions, Group.VertexCount); CurrentDebris := 0; InitDebris(0, 0, Group.GetTriangleNormal(0)); For J:=0 To Pred(Group.TriangleCount) Do Begin T := Group.GetTrianglePointer(J); If (_Debris[CurrentDebris].Count>2+Random(2)) And (CurrentDebris<Pred(_DebrisCount)) Then Begin _Debris[CurrentDebris].Center.Scale(1/_Debris[CurrentDebris].Count); For K:=_Debris[CurrentDebris].StartVertex To Pred(J*3) Do _Positions[K].Subtract(_Debris[CurrentDebris].Center); Inc(CurrentDebris); InitDebris(J*3, CurrentDebris, Group.GetTriangleNormal(J)); End; Inc(_Debris[CurrentDebris].Count); _Indices[J] := CurrentDebris; For K:=0 To 2 Do Begin N := J*3 + K; TempVertices.GetVector3D(T.Indices[K], vertexPosition, P); Group.Vertices.SetVector3D(N, vertexPosition, P); _Positions[J*3 + K] := P; _Debris[CurrentDebris].Center.Add(P); T.Indices[K] := J*3 + K; End; { For K:=0 To 2 Do Begin P := Group.GetVertexPointer(J*3 + K); P^ := Vertices[T.Indices[K]]; _Positions[J*3 + K] := P^.Position; _Debris[CurrentDebris].Center.Add(P^.Position); T.Indices[K] := J*3 + K; End;} End; ReleaseObject(TempVertices); End; _StartTime := Application.GetTime(); End; Procedure MeshExplosion.InitDebris(StartVertex, Index: Integer; Normal:Vector3D); Begin _Debris[Index].Center := VectorZero; _Debris[Index].StartVertex := StartVertex; _Debris[Index].Direction := VectorCreate(RandomFloat(-10, 10), RandomFloat(-10, 10), RandomFloat(-10, 10)); _Debris[Index].Direction.Normalize(); _Debris[Index].Direction := VectorInterpolate(Normal, _Debris[Index].Direction, RandomFloat(0.3, 0.8)); _Debris[Index].Direction.Normalize(); _Debris[Index].Duration := RandomFloat(0.7, 1); _Debris[Index].Strength := RandomFloat(0.3, 1.2); _Debris[Index].Rotation := QuaternionFromAxisAngle(Normal, 360*RAD); End; Function MeshExplosion.Update():Boolean; Const FadeDelta = 0.8; Var I,J,K:Integer; Group:MeshGroup; PP, Delta:Single; T:Triangle; FinalPos, CurrentPosition:Vector3D; Alpha:Single; DebrisIndex:Integer; Q:Quaternion; M:Matrix4x4; It:VertexIterator; Temp:VertexData; V:MeshVertex; P:PVector3D; Begin If Target = Nil Then Begin Result := False; Exit; End; If Not _Initialized Then Begin _Initialized := True; Self.InitTarget(); End; Delta := Application.GetTime - _StartTime; Delta := Delta / _Duration; If (Delta<0) Then Delta := 0 Else If (Delta>1) Then Delta := 1; For I:=0 To Pred(Target.GroupCount) Do Begin Group := Target.GetGroup(I); Temp := Group.LockVertices(); It := Temp.GetIteratorForClass(MeshVertex); For J:=0 To Pred(Group.TriangleCount) Do Begin T := Group.GetTriangle(J); DebrisIndex := _Indices[J]; If (Delta>_Debris[DebrisIndex].Duration) Then PP := 1.0 Else PP := Delta/_Debris[DebrisIndex].Duration; FinalPos := VectorAdd(_Debris[DebrisIndex].Center, VectorScale(_Debris[DebrisIndex].Direction, _Radius * _Debris[DebrisIndex].Strength)); FinalPos.Y := Abs(Sin(PP*180*RAD)) * _Radius * _Debris[DebrisIndex].Strength; CurrentPosition := VectorInterpolate(_Debris[DebrisIndex].Center, FinalPos, PP); Q := QuaternionSlerp(QuaternionZero, _Debris[DebrisIndex].Rotation, Delta); M := QuaternionMatrix4x4(Q); If (PP>FadeDelta) Then Alpha := 1.0 - ((PP-FadeDelta)/(1-FadeDelta)) Else Alpha := 1.0; For K:=0 To 2 Do Begin If Not It.HasNext() Then Break; V := MeshVertex(It.Value); V.Position := M.Transform(_Positions[It.Position]); V.Position.Add(CurrentPosition); V.BoneIndex := 0; V.BaseColor.A := Trunc(255*Alpha); End; End; ReleaseObject(It); Group.UnlockVertices(); End; Result := Delta<1.0; End; End.
unit SDFrameDealItemViewer; interface uses Windows, Messages, Forms, BaseFrame, StdCtrls, Classes, Controls, ExtCtrls, Dialogs, Sysutils, VirtualTrees, define_dealitem, define_dealmarket, DealItemsTreeView; type TfmeDealItemViewerData = record DealItemTree: TDealItemTreeCtrl; OnDealItemChange: TOnDealItemEvent; end; TfmeDealItemViewer = class(TfmeBase) pnlLeftBottom: TPanel; btnClear: TButton; btnSaveDic: TButton; btnSaveTxt: TButton; btnCheckEnd: TButton; btnOpen: TButton; btnSaveIni: TButton; btnRefresh: TButton; procedure btnClearClick(Sender: TObject); procedure btnOpenClick(Sender: TObject); procedure btnSaveDicClick(Sender: TObject); procedure btnSaveIniClick(Sender: TObject); procedure btnRefreshClick(Sender: TObject); protected { Private declarations } fDealItemViewerData: TfmeDealItemViewerData; procedure DealItemChange(Sender: TBaseVirtualTree; Node: PVirtualNode); procedure SaveDealItemDBAsDic(AFileUrl: string); procedure SaveDealItemDBAsIni(AFileUrl: string); public { Public declarations } procedure Initialize; override; property OnDealItemChange: TOnDealItemEvent read fDealItemViewerData.OnDealItemChange write fDealItemViewerData.OnDealItemChange; end; implementation uses UtilsHttp, win.iobuffer, HTMLParserAll3, BaseStockFormApp, db_dealitem_loadIni, db_dealitem_load, db_dealitem_save; {$R *.dfm} procedure TfmeDealItemViewer.Initialize; begin fDealItemViewerData.DealItemTree := TDealItemTreeCtrl.Create(Self); fDealItemViewerData.DealItemTree.InitializeDealItemsTree(fDealItemViewerData.DealItemTree.TreeView); fDealItemViewerData.DealItemTree.AddDealItemsTreeColumn_FirstDeal; //fFormSDConsoleData.DealItemTree.AddDealItemsTreeColumn_lastDeal; fDealItemViewerData.DealItemTree.AddDealItemsTreeColumn_EndDeal; fDealItemViewerData.DealItemTree.TreeView.Clear; fDealItemViewerData.DealItemTree.BuildDealItemsTreeNodes(TBaseStockApp(App).StockIndexDB); fDealItemViewerData.DealItemTree.BuildDealItemsTreeNodes(TBaseStockApp(App).StockItemDB); TVirtualStringTree(fDealItemViewerData.DealItemTree.TreeView).TreeOptions.SelectionOptions := TVirtualStringTree(fDealItemViewerData.DealItemTree.TreeView).TreeOptions.SelectionOptions + [toMultiSelect]; TVirtualStringTree(fDealItemViewerData.DealItemTree.TreeView).OnChange := DealItemChange; btnClear.OnClick := btnClearClick; btnOpen.OnClick := btnOpenClick; btnSaveDic.OnClick := btnSaveDicClick; btnSaveIni.OnClick := btnSaveIniClick; btnRefresh.OnClick := btnRefreshClick; end; procedure TfmeDealItemViewer.DealItemChange(Sender: TBaseVirtualTree; Node: PVirtualNode); var tmpNode: PDealItemNode; begin if nil <> Node then begin tmpNode := fDealItemViewerData.DealItemTree.TreeView.GetNodeData(Node); if nil <> tmpNode then begin //LoadDayDataTreeView(tmpNode); if Assigned(OnDealItemChange) then begin OnDealItemChange(tmpNode.DealItem); end; end; end; end; procedure TfmeDealItemViewer.btnOpenClick(Sender: TObject); var tmpFileUrl: string; tmpOpenDlg: TOpenDialog; i: integer; tmpIsDone: Boolean; begin tmpOpenDlg := TOpenDialog.Create(Self); try tmpOpenDlg.InitialDir := ExtractFilePath(ParamStr(0)); tmpOpenDlg.DefaultExt := '.dic'; tmpOpenDlg.Filter := 'dic file|*.dic|ini file|*.ini'; tmpOpenDlg.Options := tmpOpenDlg.Options + [ofAllowMultiSelect]; //tmpOpenDlg.OptionsEx := []; if not tmpOpenDlg.Execute then exit; tmpIsDone := false; for i := 0 to tmpOpenDlg.Files.Count - 1 do begin tmpFileUrl := tmpOpenDlg.Files[i]; if 0 < Pos('.ini', lowercase(tmpFileUrl)) then begin db_dealItem_LoadIni.LoadDBStockItemIniFromFile(App, TBaseStockApp(App).StockItemDB, tmpFileUrl); tmpIsDone := true; end; if 0 < Pos('.dic', lowercase(tmpFileUrl)) then begin db_dealItem_Load.LoadDBStockItemDicFromFile(App, TBaseStockApp(App).StockItemDB, tmpFileUrl); tmpIsDone := true; end; end; if tmpIsDone then begin fDealItemViewerData.DealItemTree.BuildDealItemsTreeNodes(TBaseStockApp(App).StockItemDB); end; finally tmpOpenDlg.Free; end; end; type PParseRecord = ^TParseRecord; TParseRecord = record HeadParse: THttpHeadParseSession; HtmlDoc: PHtmlDocDomNode; IsInDiv: Integer; Stocks: TStringList; end; function getNodeText(ANode: PHtmlDomNode): string; var i: integer; tmpNode: PHtmlDomNode; begin Result := ''; if nil = ANode then exit; Result := ANode.NodeValue; if nil <> ANode.ChildNodes then begin for i := 0 to ANode.ChildNodes.Length - 1 do begin tmpNode := ANode.ChildNodes.item(i); Result := result + tmpNode.NodeValue; end; end; end; function getAttribValue(ANode: PHtmlDomNode; AttribName: string): string; var i: integer; tmpNode: PHtmlDomNode; begin Result := ''; if nil = ANode then exit; if '' = AttribName then exit; for i := 0 to ANode.attributes.length - 1 do begin tmpNode := ANode.attributes.item(i); if SameText(AttribName, tmpNode.nodeName) then begin Result := getNodeText(tmpNode); end; end; end; function HtmlParse_StockItem(AParseRecord: PParseRecord; ANode: PHtmlDomNode): Boolean; var i, tmpcnt: Integer; tmpNode: PHtmlDomNode; tmpValue: string; tmpOldIsInDiv: integer; tmpDealItem: PRT_DealItem; tmpStockCode: string; tmpStockName: string; tmpIsStock: Boolean; begin result := false; tmpOldIsInDiv := AParseRecord.IsInDiv; try // div class="quotebody" if 0 = AParseRecord.IsInDiv then begin if SameText('div', string(lowercase(ANode.nodeName))) then begin if nil <> ANode.attributes then begin for i := 0 to ANode.attributes.length - 1 do begin tmpNode := ANode.attributes.item(i); if SameText('class', tmpNode.nodeName) then begin tmpValue := getNodeText(tmpNode); if SameText('quotebody', tmpValue) then begin AParseRecord.IsInDiv := 1; end; end; end; end; end; end; if 1 = AParseRecord.IsInDiv then begin if SameText('li', string(lowercase(ANode.nodeName))) then begin AParseRecord.IsInDiv := 2; end; end; if 2 = AParseRecord.IsInDiv then begin if SameText('a', string(lowercase(ANode.nodeName))) then begin tmpValue := getAttribValue(ANode, 'href'); if '' <> tmpValue then begin tmpValue := getNodeText(ANode); if '' <> tmpValue then begin i := Pos('(', tmpValue); if 0 < i then begin tmpStockName := Copy(tmpValue, 1, i - 1); tmpStockCode := Copy(tmpValue, i + 1, maxint); tmpStockCode := Trim(StringReplace(tmpStockCode, ')', '', [rfReplaceAll])); if '' <> tmpStockCode then begin if 6 = Length(tmpStockCode) then begin tmpIsStock := ('6' = tmpStockCode[1]) or (('0' = tmpStockCode[1]) and ('0' = tmpStockCode[2])) or ('3' = tmpStockCode[1]); if tmpIsStock then begin if nil <> GlobalBaseStockApp then begin if nil <> GlobalBaseStockApp.StockItemDB then begin tmpDealItem := GlobalBaseStockApp.StockItemDB.FindDealItemByCode(tmpStockCode); if nil = tmpDealItem then begin if ('6' = tmpStockCode[1]) then begin tmpDealItem := GlobalBaseStockApp.StockItemDB.AddDealItem(Market_SH, tmpStockCode); end else begin tmpDealItem := GlobalBaseStockApp.StockItemDB.AddDealItem(Market_SZ, tmpStockCode); end; tmpDealItem.Name := tmpStockName; end; end; end; if ('6' = tmpStockCode[1]) then begin AParseRecord.Stocks.Add(Market_SH + tmpStockCode + ',' + tmpStockName); end else begin AParseRecord.Stocks.Add(Market_SZ + tmpStockCode + ',' + tmpStockName); end; end; end; end; end; end; end; end; end; if nil <> ANode.childNodes then begin tmpcnt := ANode.childNodes.length; for i := 0 to tmpcnt - 1 do begin tmpNode := ANode.childNodes.item(i); if not result then begin result := HtmlParse_StockItem(AParseRecord, tmpNode); end else begin HtmlParse_StockItem(AParseRecord, tmpNode); end; end; end; finally AParseRecord.IsInDiv := tmpOldIsInDiv; end; end; procedure TfmeDealItemViewer.btnRefreshClick(Sender: TObject); var tmpUrl: string; tmpParseRec: TParseRecord; tmpHttpSession: THttpClientSession; tmpHttpData: PIOBuffer; tmpStr: string; begin inherited; FillChar(tmpHttpSession, SizeOf(tmpHttpSession), 0); tmpUrl := 'http://quote.eastmoney.com/stocklist.html'; tmpHttpData := nil; tmpHttpData := GetHttpUrlData(tmpUrl, @tmpHttpSession, tmpHttpData); if nil <> tmpHttpData then begin FillChar(tmpParseRec, SizeOf(tmpParseRec), 0); tmpParseRec.Stocks := TStringList.Create; HttpBufferHeader_Parser(tmpHttpData, @tmpParseRec.HeadParse); if (199 < tmpParseRec.HeadParse.RetCode) and (300 > tmpParseRec.HeadParse.RetCode)then begin try tmpParseRec.HtmlDoc := HtmlParserparseString(WideString(AnsiString(PAnsiChar(@tmpHttpData.Data[tmpParseRec.HeadParse.HeadEndPos + 1])))); if tmpParseRec.HtmlDoc <> nil then begin try HtmlParse_StockItem(@tmpParseRec, PHtmlDomNode(tmpParseRec.HtmlDoc)); tmpParseRec.Stocks.Delimiter := '|'; tmpStr := tmpParseRec.Stocks.Text; if '' <> tmpStr then begin tmpParseRec.Stocks.Text := StringReplace(tmpStr, #13#10, '|', [rfReplaceAll]); end; //tmpParseRec.Stocks.SaveToFile('e:\stock.txt'); TBaseStockApp(App).StockItemDB.Sort; fDealItemViewerData.DealItemTree.BuildDealItemsTreeNodes(TBaseStockApp(App).StockItemDB); finally HtmlDomNodeFree(PHtmlDomNode(tmpParseRec.HtmlDoc)); tmpParseRec.HtmlDoc := nil; end; end; except end; end; end; end; procedure TfmeDealItemViewer.btnClearClick(Sender: TObject); begin inherited; fDealItemViewerData.DealItemTree.Clear; TBaseStockApp(App).StockItemDB.Clear; end; procedure TfmeDealItemViewer.SaveDealItemDBAsDic(AFileUrl: string); begin TBaseStockApp(App).StockItemDB.Sort; db_dealItem_Save.SaveDBStockItemToDicFile(App, TBaseStockApp(App).StockItemDB, AFileUrl); end; procedure TfmeDealItemViewer.SaveDealItemDBAsIni(AFileUrl: string); begin TBaseStockApp(App).StockItemDB.Sort; db_dealItem_Save.SaveDBStockItemToIniFile(App, TBaseStockApp(App).StockItemDB, AFileUrl); end; procedure TfmeDealItemViewer.btnSaveDicClick(Sender: TObject); var tmpFileUrl: string; tmpSaveDlg: TSaveDialog; begin tmpFileUrl := ''; tmpSaveDlg := TSaveDialog.Create(Self); try tmpSaveDlg.InitialDir := ExtractFilePath(ParamStr(0)); tmpSaveDlg.DefaultExt := '.dic'; tmpSaveDlg.Filter := 'dic file|*.dic'; if not tmpSaveDlg.Execute then exit; tmpFileUrl := tmpSaveDlg.FileName; if '' <> Trim(tmpFileUrl) then begin SaveDealItemDBAsDic(tmpFileUrl); end; finally tmpSaveDlg.Free; end; end; procedure TfmeDealItemViewer.btnSaveIniClick(Sender: TObject); var tmpFileUrl: string; tmpSaveDlg: TSaveDialog; begin tmpFileUrl := ''; tmpSaveDlg := TSaveDialog.Create(Self); try tmpSaveDlg.InitialDir := ExtractFilePath(ParamStr(0)); tmpSaveDlg.DefaultExt := '.ini'; tmpSaveDlg.Filter := 'ini file|*.ini'; if not tmpSaveDlg.Execute then exit; tmpFileUrl := tmpSaveDlg.FileName; if '' <> Trim(tmpFileUrl) then begin SaveDealItemDBAsIni(tmpFileUrl); end; finally tmpSaveDlg.Free; end; end; end.
unit sslClient10Main; {$MODE Delphi} interface { SIMPLE INDY 10 SSL CLIENT Written by Ralph Sickinger, Best Manufacturing Practices Center of Excellence (BMPCOE) e-mail: ralph@bmpcoe.org This program is a simply TCP Client that makes an SSL connection on port 3000. To connect to a server, enter the IP address of the server in the box labeled "Host:", and then press the "Connect" button. Once a connection has been established, the client displays any text received from the server in the memo area. To send text to the server, enter it in the available edit box, and then press [enter]. Note: in order to run this program, you must have libeay32.dll and ssleay32.dll installed where the application can find them (either in the Windows System32 folder, or in the same folder as the application itself. These files can be downloaded from: http://indy.fulgan.com/SSL/ Changes from Indy 9: * In order to compile the application, you'll have to add the Indy 10 source folders to the Project/Options/Directories-Conditionals/Search Path; e.g: C:\Indy10\Lib\Core;C:\Indy10\Lib\System;C:\Indy10\Lib\Protocols * All instances of IdTCPClient.ReadLn (or WriteLn) must be changed to IdTCPClient.IOHandler.ReadLn } uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, IdIOHandler, IdIOHandlerSocket, IdSSLOpenSSL, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, Buttons, IdIOHandlerStack, IdSSL, IdGlobal; type TForm1 = class(TForm) Panel1: TPanel; ledConnected: TShape; btnConnect: TButton; edtHostAddr: TEdit; Label1: TLabel; Panel2: TPanel; Edit1: TEdit; Panel3: TPanel; Memo1: TMemo; btnExit: TSpeedButton; IdTCPClient: TIdTCPClient; IdSSLIOHandlerSocketOpenSSL: TIdSSLIOHandlerSocketOpenSSL; procedure btnConnectClick(Sender: TObject); procedure Edit1KeyPress(Sender: TObject; var Key: Char); procedure FormCreate(Sender: TObject); procedure btnExitClick(Sender: TObject); private { Private declarations } public { Public declarations } end; { TForm1 } var Form1: TForm1; {===================================================================================} {===================================================================================} implementation {$R *.lfm} {===================================================================================} procedure TForm1.FormCreate(Sender: TObject); begin left:= 80; top:= 540; //80 IdSSLIOHandlerSocketOpenSSL:=TIdSSLIOHandlerSocketOpenSSL.Create; With IdSSLIOHandlerSocketOpenSSL do begin Destination := ':3000'; MaxLineAction := maException; Port := 3000; DefaultPort := 0; SSLOptions.Method := sslvTLSv1; SSLOptions.Mode := sslmUnassigned; SSLOptions.VerifyMode := []; SSLOptions.VerifyDepth := 0; //Left = 344 //Top = 8 end; IdTCPClient:= TIdTCPClient.Create; With IdTCPClient do begin IOHandler := IdSSLIOHandlerSocketOpenSSL; ConnectTimeout := 0; IPVersion := Id_IPv4; Port := 3000; ReadTimeout := 0; //Left = 304 //Top = 8 end; end; { FORM CREATE } {===================================================================================} procedure TForm1.btnConnectClick(Sender: TObject); var line: string; begin btnConnect.enabled:= false; IdTCPClient.Host:= edtHostAddr.text; try IdTCPClient.Connect; ledConnected.brush.color:= clLime; edit1.SetFocus; except btnConnect.Enabled:= true; end; { try/except } try line:= IdTCPClient.IOHandler.ReadLn; memo1.lines.add(line); except btnConnect.enabled:= true; end; { try/except } if btnConnect.Enabled then ledConnected.brush.color:= clRed; end; { BTN CONNECT CLICK } {===================================================================================} procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char); var line: string; begin if (key = #13) then begin key:=#0; try IdTCPClient.IOHandler.writeln(edit1.text); { Send the text to the server } edit1.text:= ''; line:= IdTCPClient.IOHandler.ReadLn; { Now wait for the server's response } memo1.lines.add(line); except btnConnect.enabled:= true; ledConnected.brush.color:= clRed; end; { try/except } end; { if (key = #13) } end; { EDIT1 KEY PRESS } {===================================================================================} procedure TForm1.btnExitClick(Sender: TObject); begin close; end; { BTN EXIT CLICK } {===================================================================================} {===================================================================================} end. {*}
unit csCommandsTypes; {$I ProjectDefine.inc} interface uses l3Base, Classes, CsDataPipe, ddAppConfigTypes, csProcessTask, l3SimpleObject; type TcsCommandRequirement = (cs_crAll, cs_crSystem, cs_crUserList, cs_crGroupList); TcsCommand = class(Tl3SimpleObject) private f_Caption: AnsiString; f_CommandID: Integer; f_NeedRespond: Boolean; f_OnExecute: TNotifyEvent; f_LinkTask: TddProcessTask; f_Requirement: TcsCommandRequirement; f_RootTaskFolder: AnsiString; function pm_GetCaption: AnsiString; function pm_GetCommandID: Integer; function pm_GetNeedRespond: Boolean; procedure pm_SetCaption(const Value: AnsiString); procedure pm_SetCommandID(const Value: Integer); procedure pm_SetNeedRespond(const Value: Boolean); procedure pm_SetRootTaskFolder(const Value: AnsiString); protected procedure Cleanup; override; public constructor Create; procedure Execute(aTask: TddProcessTask); procedure ExecuteOnServer(aPipe: TcsDataPipe); procedure Load(aStream: TStream); procedure Save(aStream: TStream); property Caption: AnsiString read pm_GetCaption write pm_SetCaption; property CommandID: Integer read pm_GetCommandID write pm_SetCommandID; property NeedRespond: Boolean read pm_GetNeedRespond write pm_SetNeedRespond; property LinkTask: TddProcessTask read f_LinkTask write f_LinkTask; property Requirement: TcsCommandRequirement read f_Requirement write f_Requirement; property RootTaskFolder: AnsiString read f_RootTaskFolder write pm_SetRootTaskFolder; property OnExecute: TNotifyEvent read f_OnExecute write f_OnExecute; end; TcsCommands = (acmdNone, // служба acmdStart, acmdStop, acmdPause, acmdContinue, acmdRestart, // задания acmdStopAndGoAll, acmdDeleteTask, acmdConfig, acmdSendMessage, acmdAutoLogoff, acmdLogMessages, acmdCheckTables, acmdUpdateTables, acmdLockBase, acmdUnlockBase, acmdCompileDictionaries, acmdUpdateText, acmdDoEverydayUpdate, acmdBuildTextIndex, acmdCheckFreeSpace, acmdCheckTexts, acmdClearLocks, acmdEmailNotify, acmdFamilyBackup, acmdFullBackup, acmdGardocBridge, acmdIsDeltaReady, acmdLoadDelta, acmdLoadEQ, acmdLoadKW, acmdMakeDelta, acmdMakeLoadDelta, acmdPauseTask, acmdPreventiveUpdate, acmdRefresh, acmdRestoreFamily, acmdRunTask, acmdSetHighestPriority, acmdSetHighPriority, acmdSetLowestPriority, acmdSetLowPriority, acmdSetNormalPriority, acmdStack2Log, acmdStopNGoAnnoExport, acmdStopNGoExport, acmdStopNGoImport, acmdSwitchToRealBase, acmdSwitchToTempBase, acmdUndoRestore, acmdUpdateDictEntryIndex, acmdUpdateHeaderIndex, acmdUpdateIndex, acmdUserInfo, acmdWeeklyUpdate ); implementation uses SysUtils, ddStreamUtils, ddAppConfigStrings, dt_Serv, l3Memory, DT_UserConst, ddServerTask, l3FileUtils; constructor TcsCommand.Create; begin inherited; f_CommandID:= 0; f_Caption:= ''; f_NeedRespond:= False; (* f_LinkTask:= TddAppConfigNode.Create('LinkTask', 'Параметры'); f_LinkTask.AddItem(TddStringConfigItem.Make('Caption', 'Описание')); f_LinkTask.AddItem(TddIntegerConfigItem.Create('ID', 'ID', 0)); *) f_Requirement := cs_crAll; end; procedure TcsCommand.Cleanup; begin FreeAndNil(f_LinkTask); inherited; end; procedure TcsCommand.Execute(aTask: TddProcessTask); begin if Assigned(f_OnExecute) then f_OnExecute(aTask); end; procedure TcsCommand.ExecuteOnServer(aPipe: TcsDataPipe); var l_Stream: TStream; begin aPipe.Write(GlobalHtServer.CurUserID); //l_Stream:= Tl3MemoryStream.Create; //try //Save(l_Stream); //aPipe.Write(l_Stream); //finally // FreeAndNil(l_Stream); //end; aPipe.Write(CommandID); end; procedure TcsCommand.Load(aStream: TStream); begin aStream.Read(f_CommandID, SizeOf(f_CommandID)); ReadString(aStream, f_Caption); aStream.Read(f_NeedRespond, SizeOf(f_NeedRespond)); {$IFDEF Linktask} f_LinkTask:= TddTaskItem.MakeFrom(usServerService, aStream, GetUniqFileName(RootTaskFolder, 'Task', ''), True) as TddProcessTask; {$ENDIF} end; function TcsCommand.pm_GetCaption: AnsiString; begin //Result := f_LinkTask.AsString['Caption']; Result:= f_Caption; end; function TcsCommand.pm_GetCommandID: Integer; begin //Result := f_LinkTask.AsInteger['ID']; Result:= f_CommandID; end; function TcsCommand.pm_GetNeedRespond: Boolean; begin Result := f_NeedRespond; end; procedure TcsCommand.pm_SetCaption(const Value: AnsiString); begin //f_LinkTask.AsString['Caption']:= Value; f_Caption:= Value; end; procedure TcsCommand.pm_SetCommandID(const Value: Integer); begin //f_LinkTask.AsInteger['ID']:= Value; f_CommandID:= Value; end; procedure TcsCommand.pm_SetNeedRespond(const Value: Boolean); begin f_NeedRespond := Value; end; procedure TcsCommand.pm_SetRootTaskFolder(const Value: AnsiString); begin f_RootTaskFolder := Value; end; procedure TcsCommand.Save(aStream: TStream); begin aStream.Write(f_CommandID, SizeOf(f_CommandID)); WriteString(aStream, f_Caption); aStream.Write(f_NeedRespond, SizeOf(f_NeedRespond)); {$IFDEF Linktask} //тут нет задачи - ее нужно создать в присвоении Linktask f_LinkTask.SaveTo(aStream, true); {$ENDIF} end; end.
unit aeOGLRenderer; interface uses windows, aeSceneNode, dglOpenGL, aeSceneGraph, System.Generics.Collections, strutils, aeGeometry, aeMesh, aeCamera, aeMaterial, aeMaths, aeBoundingVolume, aeOBB, types, aeRenderable, aeTerrain, aeConst, aePrimitiveShapes; type TaeOGLRenderer = class Constructor Create(renderHandle: THandle; width, height: cardinal); procedure setRenderSize(width, height: cardinal); procedure clearRenderDisplay(); procedure render; // lol procedure setSceneGraph(sg: TaeSceneGraph); procedure setCamera(cam: TaeCamera); function getCamera(): TaeCamera; procedure SetGeometryRenderDistance(dist: single); function GetGeometryRenderDistance: single; protected DC: HDC; // Handle auf Zeichenfläche RC: HGLRC; // Rendering Context _scene: TaeSceneGraph; _activeCamera: TaeCamera; _geometry_render_distance: single; procedure drawGrid(size, step: cardinal); end; implementation { TaeOGLRenderer } constructor TaeOGLRenderer.Create(renderHandle: THandle; width, height: cardinal); begin if (InitOpenGL()) then begin self.DC := GetDC(renderHandle); self.RC := CreateRenderingContext(self.DC, // Device Context [opDoubleBuffered], // Options 32, // ColorBits 24, // ZBits 0, // StencilBits 0, // AccumBits 0, // AuxBuffers 0); // Layer ActivateRenderingContext(self.DC, self.RC); self.setRenderSize(width, height); glEnable(GL_DEPTH_TEST); // we want depth testing! // Set8087CW($133F); // disable all floating-point exceptions for performance reasons self.SetGeometryRenderDistance(500.0); end; end; function TaeOGLRenderer.getCamera: TaeCamera; begin Result := self._activeCamera; end; function TaeOGLRenderer.GetGeometryRenderDistance: single; begin Result := self._geometry_render_distance; end; procedure TaeOGLRenderer.render; var sceneGeo: TList<TaeSceneNode>; meshes: TList<TaeMesh>; primitiveshapeNode: TaePrimitiveShapeNode; i, e: integer; geo: TaeGeometry; // bounding volume stuff meshBoundingVolume: TaeBoundingVolume; meshAABB: TaeOBB; // ******** // debug camera stuff // cam_p: TPoint3D; // cam: TaeCameraArcball; // playerNode: TaeSceneNode; // ******** // ******** // terrain stuff terrain_tiles: TaeVisableTerrainTiles; terrain: TaeTerrain; terrain_tile: TaeTerrainTile; // ******** geo_matrix: TaeMatrix44; debug_modelview_matrix: Array [0 .. 15] of single; serializedCameraMatrix, serializedGeoMatrix: TaeSerializedMatrix44; terrain_counter: integer; begin glEnableClientState(GL_VERTEX_ARRAY); // why do I have to re-toggle this every frame? // glClearColor(0.137255, 0.419608, 0.556863, 1); glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); // switch to modelview matrix. glMatrixMode(GL_MODELVIEW); // rest the modelview matrix! glLoadIdentity; // We need to do our camera stuff at start! // This is because every following transform will be multiplied with the camera matrix! if (self._activeCamera <> nil) then begin // gluLookAt(150, 150, 150, 0, 0, 0, 0, 1, 0); // glGetFloatv(GL_MODELVIEW_MATRIX, @debug_modelview_matrix[0]); // glLoadIdentity; serializedCameraMatrix := self._activeCamera.GetTransformMatrix.SerializeMatrix44(true); glMultMatrixf(@serializedCameraMatrix[0]); end; // self.drawGrid(250, 1); // First, we need a list of what to actually render sceneGeo := self._scene.ListChildren; // okay, let's loop all this stuff. // DEBUG // cam := TaeCameraArcball(self._activeCamera); // playerNode := self._scene.GetChildByName('player_node'); // glColor3ub(255, 0, 100); // glBegin(GL_LINES); // glVertex3f(cam.getPosition.X, cam.getPosition.Y-2, cam.getPosition.Z); // glVertex3f(playerNode.getPosition.X, playerNode.getPosition.Y, playerNode.getPosition.Z); // glEnd; // DEBUG END for i := 0 to sceneGeo.Count - 1 do begin // alright, we need to load this into vram, right? case sceneGeo[i].getType of AE_SCENENODE_TYPE_GEOMETRY: begin glPushMatrix; geo := TaeGeometry(sceneGeo[i]); // check if geo is too far away to render! // if (geo.getPosition.Distance(self._activeCamera.getPosition) < self._geometry_render_distance) then begin serializedGeoMatrix := geo.GetWorldTransformationMatrix.SerializeMatrix44; glMultMatrixf(@serializedGeoMatrix[0]); meshes := geo.getMeshes; case geo.Material.Rendermode of AE_MATERIAL_RENDERMODE_TRIANGLES: begin glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); // glEnable(GL_CULL_FACE); //glDisable(GL_CULL_FACE); end; AE_MATERIAL_RENDERMODE_WIREMESH: begin // glEnable(GL_CULL_FACE); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); // glEnable(GL_CULL_FACE); glDisable(GL_CULL_FACE); end; end; for e := 0 to meshes.Count - 1 do begin glColor3ub(geo.Material.Color.getRed, geo.Material.Color.getGreen, geo.Material.Color.getBlue); // vbo manager checks if needed already! meshes[e].render; end; glColor3ub(0, 128, 128); // geo.getBoundingVolume.getBox.render(GL_LINE_STRIP); end; glPopMatrix; end; AE_SCENENODE_TYPE_LIGHT: begin // lightning... end; AE_SCENENODE_TYPE_TERRAIN: begin glPushMatrix; glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); terrain := TaeTerrain(sceneGeo[i]); serializedGeoMatrix := terrain.GetWorldTransformationMatrix.SerializeMatrix44; glMultMatrixf(@serializedGeoMatrix[0]); // glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); // glEnable(GL_CULL_FACE); terrain_tiles := terrain.GetVisableTiles; if (terrain_tiles.Count > 0) then for terrain_counter := 0 to terrain_tiles.Count - 1 do begin terrain_tile := terrain_tiles.tiles[terrain_counter]; case terrain_tile.GetLOD of AE_MESH_LOD_HIGH: glColor3ub(0, 255, 0); AE_MESH_LOD_MID: glColor3ub(255, 0, 0); AE_MESH_LOD_LOW: glColor3ub(128, 0, 128); end; // vbo manager checks if needed already! terrain_tile.render; // self.RenderBoundingVolume(terrain_tile.getBoundingVolume); end; glPopMatrix; end; AE_SCENENODE_TYPE_PRIMITIVESHAPE: begin glPushMatrix; glColor3ub(0, 255, 128); primitiveshapeNode := TaePrimitiveShapeNode(sceneGeo[i]); serializedGeoMatrix := primitiveshapeNode.GetWorldTransformationMatrix.SerializeMatrix44; glMultMatrixf(@serializedGeoMatrix[0]); primitiveshapeNode.RenderShapes; // glBegin(GL_LINES); // glVertex3f(0, 0, 0); // glVertex3f(0, 1111, 0); // glEnd; glPopMatrix; end; end; end; swapBuffers(self.DC); sceneGeo.Free; end; procedure TaeOGLRenderer.clearRenderDisplay; begin glClear(GL_COLOR_BUFFER_BIT); glClearColor(0.3, 0.4, 0.7, 0.0); end; procedure TaeOGLRenderer.setCamera(cam: TaeCamera); begin self._activeCamera := cam; end; procedure TaeOGLRenderer.SetGeometryRenderDistance(dist: single); begin self._geometry_render_distance := dist; end; procedure TaeOGLRenderer.setRenderSize(width, height: cardinal); var sm: TaeSerializedMatrix44; begin glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); if (self.getCamera <> nil) then begin self.getCamera.SetViewPortSize(width, height); sm := self.getCamera.GetProjectionMatrix.SerializeMatrix44(); glLoadMatrixf(@sm[0]); end else begin glLoadIdentity; gluPerspective(60.0, width / height, 0.1, 10000.0); end; glMatrixMode(GL_MODELVIEW); end; procedure TaeOGLRenderer.setSceneGraph(sg: TaeSceneGraph); begin self._scene := sg; end; procedure TaeOGLRenderer.drawGrid(size, step: cardinal); var i: integer; begin glBegin(GL_LINES); glColor3f(0.3, 0.3, 0.3); for i := 1 to (size - step) - 1 do begin glVertex3f(-size, 0, i); // lines parallel to X-axis glVertex3f(size, 0, i); glVertex3f(-size, 0, -i); // lines parallel to X-axis glVertex3f(size, 0, -i); glVertex3f(i, 0, -size); // lines parallel to Z-axis glVertex3f(i, 0, size); glVertex3f(-i, 0, -size); // lines parallel to Z-axis glVertex3f(-i, 0, size); end; // x-axis glColor3f(1.0, 0, 0); glVertex3f(size, 0, 0); glColor3f(0.5, 0, 0); glVertex3f(-size, 0, 0); // y-axis glColor3f(0, 1.0, 0); glVertex3f(0, size, 0); glColor3f(0, 0.5, 0); glVertex3f(0, -size, 0); // z-axis glColor3f(0, 0, 1.0); glVertex3f(0, 0, size); glColor3f(0, 0, 0.5); glVertex3f(0, 0, -size); glEnd(); end; end.
unit UGeFluxoCaixa; interface uses UGrPadraoCadastro, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ImgList, IBCustomDataSet, IBUpdateSQL, DB, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Menus, StdCtrls, DBClient, Provider, ACBrBase, ACBrExtenso, frxClass, frxDBSet, IBQuery, IBTable, JvDBControls, DBCtrls, JvExMask, JvToolEdit, Mask, Buttons, ExtCtrls, Grids, DBGrids, ComCtrls, cxButtons, ToolWin, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.Comp.Client, dxSkinsCore, dxSkinMcSkin, dxSkinOffice2007Green, dxSkinOffice2010Black, dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinOffice2013DarkGray, dxSkinOffice2013LightGray, dxSkinOffice2013White; type TfrmGeFluxoCaixa = class(TfrmGrPadraoCadastro) lblData: TLabel; lblContaCorrentePesq: TLabel; dtsContaCorrente: TDataSource; dtsFormaPagto: TDataSource; IbDtstTabelaANO: TSmallintField; IbDtstTabelaNUMERO: TIntegerField; IbDtstTabelaCAIXA_ANO: TSmallintField; IbDtstTabelaCAIXA_NUM: TIntegerField; IbDtstTabelaCONTA_CORRENTE: TIntegerField; IbDtstTabelaFORMA_PAGTO: TSmallintField; IbDtstTabelaDATAHORA: TDateTimeField; IbDtstTabelaTIPO: TIBStringField; IbDtstTabelaHISTORICO: TIBStringField; IbDtstTabelaVALOR: TIBBCDField; IbDtstTabelaSITUACAO: TSmallintField; IbDtstTabelaVENDA_ANO: TSmallintField; IbDtstTabelaVENDA_NUM: TIntegerField; IbDtstTabelaCLIENTE: TIBStringField; IbDtstTabelaCOMPRA_ANO: TSmallintField; IbDtstTabelaCOMPRA_NUM: TIntegerField; IbDtstTabelaEMPRESA: TIBStringField; IbDtstTabelaFORNECEDOR: TIntegerField; IbDtstTabelaUSUARIO: TIBStringField; pnlConsolidacao: TPanel; Bevel5: TBevel; IbDtstTabelaFORMA_PAGTO_DESC: TIBStringField; IbDtstTabelaNOME_CLENTE: TIBStringField; IbDtstTabelaNOME_FORNECEDOR: TIBStringField; IbDtstTabelaVALOR_CREDITO: TIBBCDField; IbDtstTabelaVALOR_DEBITO: TIBBCDField; IbDtstTabelaDATA: TDateField; IbDtstTabelaHORA: TTimeField; IbDtstTabelaVENDA: TIBStringField; IbDtstTabelaTITULO: TIBStringField; IbDtstTabelaCOMPRA: TIBStringField; IbDtstTabelaDUPLICATA: TIBStringField; dtsSaldosDias: TDataSource; pnlSaldosDias: TPanel; Panel1: TPanel; dbLContaCorrente: TDBText; Bevel6: TBevel; Panel2: TPanel; Panel3: TPanel; Panel4: TPanel; dbLDataFinal: TDBText; BvDataFinal: TBevel; dbLDataInicial: TDBText; Bevel9: TBevel; dbLDataAnterior: TDBText; Bevel10: TBevel; Panel5: TPanel; dbLSaldoFinal: TDBText; BvSaldoFinal: TBevel; dbLSaldoInicial: TDBText; Bevel12: TBevel; dbLSaldoAnterior: TDBText; Bevel13: TBevel; Bevel14: TBevel; Bevel15: TBevel; Bevel16: TBevel; Bevel17: TBevel; lblDataMov: TLabel; dbTipo: TDBLookupComboBox; lblTipo: TLabel; dbContaCorrente: TDBLookupComboBox; lblContaCorrente: TLabel; dbSituacao: TDBEdit; lblSituacao: TLabel; lblMovCaixaCancelado: TLabel; dtsTipoMovimento: TDataSource; lblCaixa: TLabel; d1Caixa: TDBEdit; d2Caixa: TDBEdit; lblFormaPagto: TLabel; dbFormaPagto: TDBLookupComboBox; GrpBxCreditoDebito: TGroupBox; lblHistorico: TLabel; dbHistorico: TDBEdit; dbValorMov: TDBEdit; lblValorMov: TLabel; lblCliente: TLabel; lblFornecedor: TLabel; lblVenda: TLabel; dbVenda: TDBEdit; lblTitulo: TLabel; dbTitulo: TDBEdit; lblCompra: TLabel; dbCompra: TDBEdit; dbDuplicata: TDBEdit; lblDuplicata: TLabel; GrbBxObs: TGroupBox; memObservacoes: TMemo; Bevel7: TBevel; Bevel11: TBevel; Bevel18: TBevel; lblUsuario: TLabel; dbUsuario: TDBEdit; IbDtstTabelaSITUACAO_CAIXA: TSmallintField; IbDtstTabelaDATA_FECH: TDateField; IbDtstTabelaDATA_CANCEL: TDateField; dtsConsolidadoFormaPagto: TDataSource; Panel6: TPanel; dbtDESCRICAO_FULL: TDBText; Bevel19: TBevel; Bevel20: TBevel; Panel7: TPanel; dbgConsolidadoFormaPagto: TDBGrid; qryFluxoSintetico: TIBQuery; frdFluxoSintetico: TfrxDBDataset; frdFluxoAnalitico: TfrxDBDataset; qryFluxoAnalitico: TIBQuery; frrFluxoAnalitico: TfrxReport; qryFluxoSaldos: TIBQuery; frdFluxoSaldos: TfrxDBDataset; dtsEmpresa: TDataSource; lblEmpresa: TLabel; dbEmpresa: TDBLookupComboBox; dtsTpDespesa: TDataSource; lblTipoDespesa: TLabel; dbTipoDespesa: TDBLookupComboBox; IbDtstTabelaTIPO_DESPESA: TSmallintField; IbDtstTabelaCLIENTE_COD: TIntegerField; ppImprimir: TPopupMenu; nmImprimirExtrato: TMenuItem; nmImprimirReciboA5: TMenuItem; FrReciboA5: TfrxReport; FrdRecibo: TfrxDBDataset; ACBrExtenso: TACBrExtenso; QryRecibo: TIBQuery; DspRecibo: TDataSetProvider; CdsRecibo: TClientDataSet; CdsReciboVALOR_BAIXA_EXTENSO: TStringField; dbCliente: TJvDBComboEdit; dbFornecedor: TJvDBComboEdit; dbDataMov: TJvDBDateEdit; e1Data: TJvDateEdit; e2Data: TJvDateEdit; edContaCorrentePesq: TComboBox; CdsReciboANO: TSmallintField; CdsReciboNUMERO: TIntegerField; CdsReciboTIPO: TWideStringField; CdsReciboNUMERO_RECIBO: TWideStringField; CdsReciboANOLANC: TSmallintField; CdsReciboNUMLANC: TIntegerField; CdsReciboPARCELA: TSmallintField; CdsReciboNOMEEMP: TWideStringField; CdsReciboCODFORN: TIntegerField; CdsReciboNOMEFORN: TWideStringField; CdsReciboPESSOA_FISICA: TSmallintField; CdsReciboCNPJ: TWideStringField; CdsReciboNOTFISC: TWideStringField; CdsReciboTIPPAG: TWideStringField; CdsReciboDTEMISS: TDateField; CdsReciboDTVENC: TDateField; CdsReciboDTPAG: TDateField; CdsReciboVALORPAG: TBCDField; CdsReciboBANCO: TIntegerField; CdsReciboBCO_NOME: TWideStringField; CdsReciboNUMCHQ: TWideStringField; CdsReciboPAGO_: TWideStringField; CdsReciboDOCBAIX: TWideStringField; CdsReciboQUITADO: TIntegerField; CdsReciboCODTPDESP: TSmallintField; CdsReciboSEQ: TIntegerField; CdsReciboDATA_PAGTO: TDateField; CdsReciboFORMA_PAGTO: TSmallintField; CdsReciboFORMA_PAGTO_DESC: TWideStringField; CdsReciboHISTORICO: TWideStringField; CdsReciboVALOR_BAIXA: TBCDField; lblTipoReceita: TLabel; dbTipoReceita: TDBLookupComboBox; IbDtstTabelaTIPO_RECEITA: TSmallintField; dtsTpReceita: TDataSource; nmImprimirReciboA4: TMenuItem; FrReciboA4: TfrxReport; btnRecalcularSaldo: TcxButton; bvlRecalcularSaldo: TBevel; fdQryEmpresa: TFDQuery; fdQryFormaPagto: TFDQuery; fdQryContaCorrente: TFDQuery; fdQryTipoMovimento: TFDQuery; fdQryTipoDespesa: TFDQuery; fdQryTipoReceita: TFDQuery; fdQrySaldosDias: TFDQuery; fdQrySaldosDiasSALDO_ANTERIOR_DATA: TDateField; fdQrySaldosDiasSALDO_ANTERIOR_VALOR: TBCDField; fdQrySaldosDiasSALDO_INICIAL_DATA: TDateField; fdQrySaldosDiasSALDO_INICIAL_VALOR: TBCDField; fdQrySaldosDiasSALDO_FINAL_DATA: TDateField; fdQrySaldosDiasSALDO_FINAL_VALOR: TBCDField; fdQryConsolidadoFormaPagto: TFDQuery; fdQryConsolidadoFormaPagtoDATA: TDateField; fdQryConsolidadoFormaPagtoFORMA_PAGTO: TIntegerField; fdQryConsolidadoFormaPagtoFORMA_PAGTO_DESC: TStringField; fdQryConsolidadoFormaPagtoSALDO: TBCDField; fdQryConsolidadoFormaPagtoENTRADA: TBCDField; fdQryConsolidadoFormaPagtoSAIDA: TBCDField; fdQryConsolidadoFormaPagtoSaldoDIsplay: TStringField; procedure FormCreate(Sender: TObject); procedure edContaCorrentePesqChange(Sender: TObject); procedure btnFiltrarClick(Sender: TObject); procedure IbDtstTabelaNewRecord(DataSet: TDataSet); procedure IbDtstTabelaSITUACAOGetText(Sender: TField; var Text: String; DisplayText: Boolean); procedure dbgDadosDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure DtSrcTabelaStateChange(Sender: TObject); procedure DtSrcTabelaDataChange(Sender: TObject; Field: TField); procedure dbClienteButtonClick(Sender: TObject); procedure dbFornecedorButtonClick(Sender: TObject); procedure btbtnSalvarClick(Sender: TObject); procedure ControlEditExit(Sender: TObject); procedure btbtnAlterarClick(Sender: TObject); procedure btbtnExcluirClick(Sender: TObject); procedure btbtnListaClick(Sender: TObject); procedure frrFluxoAnaliticoGetValue(const VarName: String; var Value: Variant); procedure btbtnIncluirClick(Sender: TObject); procedure nmImprimirExtratoClick(Sender: TObject); procedure nmImprimirReciboClick(Sender: TObject); procedure FrReciboGetValue(const VarName: String; var Value: Variant); procedure CdsReciboCalcFields(DataSet: TDataSet); procedure FormShow(Sender: TObject); procedure btnRecalcularSaldoClick(Sender: TObject); procedure pgcGuiasChange(Sender: TObject); procedure fdQryConsolidadoFormaPagtoCalcFields(DataSet: TDataSet); private { Private declarations } sGeneratorName : String; FImprimirCabecalho : Boolean; procedure CarregarContaCorrente; procedure CarregarSaldos; procedure DefinirControle; procedure CarregarTipoDespesa(const ApenasAtivos : Boolean); procedure CarregarTipoReceita(const ApenasAtivos : Boolean); procedure RegistrarNovaRotinaSistema; procedure pgcGuiasOnChange; override; function BloquearAlteracaoExclusao : Boolean; function GetRotinaRecalcularSaldoID : String; public { Public declarations } property RotinaRecalcularSaldoID : String read GetRotinaRecalcularSaldoID; end; (* Tabelas: - TBCAIXA_MOVIMENTO - TBEMPRESA - TBCLIENTE - TBFORNECEDOR - TBFORMPAGTO - TBCAIXA - TBTPDESPESA - TBTPRECEITA - TBCONTPAG - TBCONTREC - TBBANCO_BOLETO Views: - VW_EMPRESA - VW_CONTA_CORRENTE - VW_TIPO_MOVIMENTO_CAIXA Procedures: - GET_CONTA_CORRENTE_SALDO - GET_FLUXO_CAIXA *) var frmGeFluxoCaixa: TfrmGeFluxoCaixa; procedure MostrarTabelaFluxoCaixas(const AOwner : TComponent); const TIPO_MOVIMENTO_CREDITO = 'C'; TIPO_MOVIMENTO_DEBITO = 'D'; implementation uses DateUtils, UDMBusiness, UGeCliente, UGeFornecedor, UGeCaixa, UDMNFe, UConstantesDGE, UDMRecursos; {$R *.dfm} procedure MostrarTabelaFluxoCaixas(const AOwner : TComponent); var frm : TfrmGeFluxoCaixa; whr : String; begin frm := TfrmGeFluxoCaixa.Create(AOwner); try whr := '(m.Empresa = ' + QuotedStr(gUsuarioLogado.Empresa) + ') and ' + '(cast(m.Datahora as date) between ' + QuotedStr( FormatDateTime('yyyy-mm-dd', frm.e1Data.Date) ) + ' and ' + QuotedStr( FormatDateTime('yyyy-mm-dd', frm.e2Data.Date) ) + ') and ' + 'm.Conta_corrente = ' + IntToStr( frm.fdQryContaCorrente.FieldByName('codigo').AsInteger ); with frm, IbDtstTabela do begin Close; SelectSQL.Add('where ' + whr); SelectSQL.Add('order by ' + CampoOrdenacao); Open; end; frm.CarregarSaldos; frm.ShowModal; finally frm.Destroy; end; end; procedure TfrmGeFluxoCaixa.FormCreate(Sender: TObject); begin (* IMR - 14/10/2014 : Bloco de códigos referentes a propriedade GeneratorField do dataset descontinuado por está gerando erro e campo não localizado. *) sGeneratorName := 'GEN_CX_MOVIMENTO_' + FormatFloat('0000', YearOf(GetDateDB)); inherited; // SQL_Consolidado := TStringList.Create; // SQL_Consolidado.Clear; // SQL_Consolidado.AddStrings( cdsCosolidado.SelectSQL ); // // SQL_Movimento := TStringList.Create; // SQL_Movimento.Clear; // SQL_Movimento.AddStrings( qryMovimento.SelectSQL ); // // SQL_CaixaSintetico := TStringList.Create; // SQL_CaixaSintetico.Clear; // SQL_CaixaSintetico.AddStrings( qryCaixaSintetico.SQL ); // // SQL_CaixaAnalitico := TStringList.Create; // SQL_CaixaAnalitico.Clear; // SQL_CaixaAnalitico.AddStrings( qryCaixaAnalitico.SQL ); // e1Data.Date := Date; e2Data.Date := Date; ControlFirstEdit := dbDataMov; CarregarLista(fdQryEmpresa); CarregarLista(fdQryFormaPagto); CarregarLista(fdQryTipoMovimento); CarregarTipoReceita(False); CarregarTipoDespesa(False); CarregarContaCorrente; RotinaID := ROTINA_FIN_TESOURARIA_ID; DisplayFormatCodigo := '###0000000'; ControlFirstEdit := dbDataMov; NomeTabela := 'TBCAIXA_MOVIMENTO'; CampoCodigo := 'm.Numero'; CampoDescricao := 'm.Historico'; CampoOrdenacao := 'm.Ano, m.Numero'; (* with IbDtstTabela, GeneratorField do begin Field := CampoCodigo; Generator := sGeneratorName; IncrementBy := 1; end; *) // // FAbrirCaixa := False; // FFecharCaixa := False; end; procedure TfrmGeFluxoCaixa.FormShow(Sender: TObject); begin inherited; RegistrarNovaRotinaSistema; btnRecalcularSaldo.Visible := (not btbtnSelecionar.Visible) and GetPermissaoRotinaInterna(btnRecalcularSaldo, False); Self.Caption := Self.Caption + ' - (' + GetNomeFantasiaEmpresa(gUsuarioLogado.Empresa) + ')'; end; procedure TfrmGeFluxoCaixa.edContaCorrentePesqChange(Sender: TObject); begin if ( not fdQryContaCorrente.IsEmpty ) then fdQryContaCorrente.Locate('Descricao_FULL', edContaCorrentePesq.Text, []); end; procedure TfrmGeFluxoCaixa.fdQryConsolidadoFormaPagtoCalcFields( DataSet: TDataSet); begin if ( fdQryConsolidadoFormaPagtoFORMA_PAGTO.AsInteger > 0 ) then fdQryConsolidadoFormaPagtoSaldoDisplay.AsString := EmptyStr else if ( fdQryConsolidadoFormaPagtoSALDO.AsCurrency >= 0 ) then fdQryConsolidadoFormaPagtoSaldoDisplay.AsString := FormatFloat(',0.00', fdQryConsolidadoFormaPagtoSALDO.AsCurrency) else fdQryConsolidadoFormaPagtoSaldoDisplay.AsString := FormatFloat('"- ",0.00', fdQryConsolidadoFormaPagtoSALDO.AsCurrency); end; procedure TfrmGeFluxoCaixa.btnFiltrarClick(Sender: TObject); var aData : TDateTime; begin WaitAMoment(WAIT_AMOMENT_LoadData); try with fdQryContaCorrente do begin if not Locate('Descricao_FULL', edContaCorrentePesq.Text, []) then begin WaitAMomentFree; ShowWarning('Favor selecionar Conta Corrente para pesquisa!'); Abort; end; WhereAdditional := '(m.Empresa = ' + QuotedStr(gUsuarioLogado.Empresa) + ') and ' + '(cast(m.Datahora as date) between ' + QuotedStr( FormatDateTime('yyyy-mm-dd', e1Data.Date) ) + ' and ' + QuotedStr( FormatDateTime('yyyy-mm-dd', e2Data.Date) ) + ') and ' + 'm.Conta_corrente = ' + IntToStr( FieldByName('codigo').AsInteger ); // Recalcular Saldo da Conta Corrente if ( FieldByName('codigo').AsInteger > 0 ) then begin aData := e1Data.Date; // O saldo é recalculado apenas para o período máximo de 30 dias if ( (e2Data.Date - aData) > 30 ) then aData := e2Data.Date - 30; while aData <= e2Data.Date do begin GerarSaldoContaCorrente(FieldByName('codigo').AsInteger, aData); aData := aData + 1; end; end; end; CarregarSaldos; inherited; finally WaitAMomentFree; end; end; procedure TfrmGeFluxoCaixa.btnRecalcularSaldoClick(Sender: TObject); var dData : TDateTime; begin if not GetPermissaoRotinaInterna(Sender, True) then Abort; if not ShowConfirmation('Ao executar o recálculo dos saldos diários da Conta Corrente ' + 'selecionada, possivelmente os valores sejam alterados no período informado.' + #13#13 + 'Deseja continuar com o recálculo dos saldos?') then Exit; WaitAMoment(WAIT_AMOMENT_Process); try with fdQryContaCorrente do begin if not Locate('Descricao_FULL', edContaCorrentePesq.Text, []) then Exit; // Recalcular Saldo da Conta Corrente if ( FieldByName('codigo').AsInteger > 0 ) then begin dData := e1Data.Date; while dData <= e2Data.Date do begin GerarSaldoContaCorrente(FieldByName('codigo').AsInteger, dData); dData := dData + 1; end; end; end; CarregarSaldos; finally WaitAMomentFree; end; end; procedure TfrmGeFluxoCaixa.CarregarSaldos; begin dbLDataFinal.Visible := (e1Data.Date <> e2Data.Date); BvDataFinal.Visible := (e1Data.Date <> e2Data.Date); dbLSaldoFinal.Visible := (e1Data.Date <> e2Data.Date); BvSaldoFinal.Visible := (e1Data.Date <> e2Data.Date); with fdQrySaldosDias do begin Close; ParamByName('Conta').AsInteger := fdQryContaCorrente.FieldByName('codigo').AsInteger; ParamByName('DataInicial').AsDate := e1Data.Date; ParamByName('DataFinal').AsDate := e2Data.Date; Open; end; with fdQryConsolidadoFormaPagto do begin Close; ParamByName('Conta_Corrente').AsInteger := fdQryContaCorrente.FieldByName('codigo').AsInteger; ParamByName('Data_Inicial').AsDate := e1Data.Date; ParamByName('Data_Final').AsDate := e2Data.Date; Open; end; end; procedure TfrmGeFluxoCaixa.CarregarTipoDespesa(const ApenasAtivos: Boolean); begin with fdQryTipoDespesa, Params do begin Close; ParamByName('ativo').AsInteger := IfThen(ApenasAtivos, 1, 0); ParamByName('todos').AsInteger := IfThen(ApenasAtivos, 0, 1); Open; Prior; Last; end; end; procedure TfrmGeFluxoCaixa.CarregarTipoReceita(const ApenasAtivos: Boolean); begin with fdQryTipoReceita, Params do begin Close; ParamByName('ativo').AsInteger := IfThen(ApenasAtivos, 1, 0); ParamByName('todos').AsInteger := IfThen(ApenasAtivos, 0, 1); Open; Prior; Last; end; end; procedure TfrmGeFluxoCaixa.IbDtstTabelaNewRecord(DataSet: TDataSet); begin inherited; IbDtstTabelaEMPRESA.Value := gUsuarioLogado.Empresa; IbDtstTabelaANO.Value := YearOf(GetDateTimeDB); IbDtstTabelaDATAHORA.Value := GetDateTimeDB; IbDtstTabelaSITUACAO.Value := 1; IbDtstTabelaTIPO.Value := TIPO_MOVIMENTO_CREDITO; IbDtstTabelaUSUARIO.Value := GetUserApp; IbDtstTabelaDATA.Value := GetDateDB; IbDtstTabelaHORA.Value := GetTimeDB; IbDtstTabelaTIPO_RECEITA.Clear; IbDtstTabelaTIPO_DESPESA.Clear; IbDtstTabelaCLIENTE.Clear; IbDtstTabelaCLIENTE_COD.Clear; IbDtstTabelaFORNECEDOR.Clear; IbDtstTabelaFORMA_PAGTO.Clear; IbDtstTabelaFORMA_PAGTO_DESC.Clear; IbDtstTabelaNOME_CLENTE.Clear; IbDtstTabelaNOME_FORNECEDOR.Clear; IbDtstTabelaVALOR_CREDITO.Clear; IbDtstTabelaVALOR_DEBITO.Clear; IbDtstTabelaVENDA.Clear; IbDtstTabelaTITULO.Clear; IbDtstTabelaCOMPRA.Clear; IbDtstTabelaDUPLICATA.Clear; end; procedure TfrmGeFluxoCaixa.IbDtstTabelaSITUACAOGetText(Sender: TField; var Text: String; DisplayText: Boolean); begin if ( Sender.IsNull ) then Exit; Case Sender.AsInteger of 0 : Text := 'Cancelado'; 1 : Text := 'Confirmado'; end; end; procedure TfrmGeFluxoCaixa.dbgDadosDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin inherited; if ( Sender = dbgDados ) then begin // Destacar Movimentos de Caixas Cancelados if ( IbDtstTabelaSITUACAO.AsInteger = 0 ) then dbgDados.Canvas.Font.Color := lblMovCaixaCancelado.Font.Color; dbgDados.DefaultDrawDataCell(Rect, dbgDados.Columns[DataCol].Field, State); end else if ( Sender = dbgConsolidadoFormaPagto ) then begin ShowScrollBar(TDBGrid(Sender).Handle, SB_HORZ, False); //ShowScrollBar(TDBGrid(Sender).Handle, SB_VERT, False); end; end; procedure TfrmGeFluxoCaixa.DefinirControle; begin memObservacoes.Lines.Clear; btnRecalcularSaldo.Enabled := (pgcGuias.ActivePage = tbsTabela); if ( IbDtstTabelaTIPO.AsString = TIPO_MOVIMENTO_CREDITO ) then begin lblCliente.Enabled := True; dbCliente.Enabled := True; lblFornecedor.Enabled := False; dbFornecedor.Enabled := False; lblTipoDespesa.Enabled := False; dbTipoDespesa.Enabled := False; end else if ( IbDtstTabelaTIPO.AsString = TIPO_MOVIMENTO_DEBITO ) then begin lblCliente.Enabled := False; dbCliente.Enabled := False; lblFornecedor.Enabled := True; dbFornecedor.Enabled := True; lblTipoDespesa.Enabled := True; dbTipoDespesa.Enabled := True; end; if ( IbDtstTabelaVENDA_ANO.AsInteger > 0 ) then begin memObservacoes.Lines.Add( 'Movimento de fluxo de caixa relacionada a VENDA CONFIRMADA de No. ' + IbDtstTabelaVENDA.AsString + '. Este tipo de movimento não poderá ser alterado e nem excluído, com isso a única forma de seu ' + 'valor não ser considerado para o cálculo do saldo diário da conta corrente é CANCELAR A VENDA ' + 'responsável por este movimento.'); end else if ( IbDtstTabelaCOMPRA_ANO.AsInteger > 0 ) then begin memObservacoes.Lines.Add( 'Movimento de fluxo de caixa relacionada a COMPRA CONFIRMADA de No. ' + IbDtstTabelaCOMPRA.AsString + '. Este tipo de movimento não poderá ser alterado e nem excluído, com isso a única forma de seu ' + 'valor não ser considerado para o cálculo do saldo diário da conta corrente é CANCELAR A COMPRA ' + 'responsável por este movimento.'); end else if ( Trim(IbDtstTabelaTITULO.AsString) <> EmptyStr ) then begin memObservacoes.Lines.Add( 'Movimento de fluxo de caixa relacionado ao TÍTULO de No. ' + IbDtstTabelaTITULO.AsString); memObservacoes.Lines.Add('(Contas A Receber).'); memObservacoes.Lines.Add(''); memObservacoes.Lines.Add( 'Este tipo de movimento não poderá ser alterado e nem excluído, com isso a única forma de seu ' + 'valor não ser considerado para o cálculo do saldo diário da conta corrente é CANCELAR A BAIXA ' + 'responsável por este movimento.'); end else if ( Trim(IbDtstTabelaDUPLICATA.AsString) <> EmptyStr ) then begin memObservacoes.Lines.Add( 'Movimento de fluxo de caixa relacionado a DUPLICATA de No. ' + IbDtstTabelaDUPLICATA.AsString); memObservacoes.Lines.Add('(Contas A Pagar).'); memObservacoes.Lines.Add(''); memObservacoes.Lines.Add( 'Este tipo de movimento não poderá ser alterado e nem excluído, com isso a única forma de seu ' + 'valor não ser considerado para o cálculo do saldo diário da conta corrente é CANCELAR A BAIXA ' + 'responsável por este movimento.'); end; end; procedure TfrmGeFluxoCaixa.DtSrcTabelaStateChange(Sender: TObject); begin inherited; if ( IbDtstTabela.State in [dsEdit, dsInsert] ) then DefinirControle; CarregarTipoReceita( (IbDtstTabela.State in [dsEdit, dsInsert]) ); CarregarTipoDespesa( (IbDtstTabela.State in [dsEdit, dsInsert]) ); end; procedure TfrmGeFluxoCaixa.DtSrcTabelaDataChange(Sender: TObject; Field: TField); begin if ( Field = IbDtstTabela.FieldByName('TIPO') ) then DefinirControle; end; procedure TfrmGeFluxoCaixa.pgcGuiasChange(Sender: TObject); begin DefinirControle; end; procedure TfrmGeFluxoCaixa.pgcGuiasOnChange; begin DefinirControle; end; procedure TfrmGeFluxoCaixa.dbClienteButtonClick(Sender: TObject); var iCodigo : Integer; sCNPJ , sNome : String; begin if ( IbDtstTabela.State in [dsEdit, dsInsert] ) then if ( SelecionarCliente(Self, iCodigo, sCNPJ, sNome) ) then begin IbDtstTabelaCLIENTE_COD.AsInteger := iCodigo; IbDtstTabelaCLIENTE.AsString := sCNPJ; IbDtstTabelaNOME_CLENTE.AsString := sNome; end; end; procedure TfrmGeFluxoCaixa.dbFornecedorButtonClick(Sender: TObject); var iCodigo : Integer; sNome : String; begin if ( IbDtstTabela.State in [dsEdit, dsInsert] ) then if ( SelecionarFornecedor(Self, iCodigo, sNome) ) then begin IbDtstTabelaFORNECEDOR.AsInteger := iCodigo; IbDtstTabelaNOME_FORNECEDOR.AsString := sNome; end; end; procedure TfrmGeFluxoCaixa.btbtnSalvarClick(Sender: TObject); var CxAno, CxNumero, CxContaCorrente : Integer; begin IbDtstTabelaCLIENTE.Required := ( IbDtstTabelaTIPO.AsString = TIPO_MOVIMENTO_CREDITO ); IbDtstTabelaFORNECEDOR.Required := ( IbDtstTabelaTIPO.AsString = TIPO_MOVIMENTO_DEBITO ); IbDtstTabelaTIPO_RECEITA.Required := ( IbDtstTabelaTIPO.AsString = TIPO_MOVIMENTO_CREDITO ); IbDtstTabelaTIPO_DESPESA.Required := ( IbDtstTabelaTIPO.AsString = TIPO_MOVIMENTO_DEBITO ); if ( CaixaAberto(IbDtstTabelaEMPRESA.AsString, IbDtstTabelaUSUARIO.AsString, IbDtstTabelaDATAHORA.AsDateTime, IbDtstTabelaFORMA_PAGTO.AsInteger, CxAno, CxNumero, CxContaCorrente) ) then if ( CxContaCorrente <> IbDtstTabelaCONTA_CORRENTE.AsInteger ) then begin IbDtstTabelaCAIXA_ANO.Clear; IbDtstTabelaCAIXA_NUM.Clear; end; IbDtstTabelaDATA.Value := IbDtstTabelaDATAHORA.AsDateTime; IbDtstTabelaHORA.Value := IbDtstTabelaDATAHORA.AsDateTime; if ( IbDtstTabelaVALOR.AsCurrency <= 0 ) then IbDtstTabelaVALOR.Clear; if ( IbDtstTabelaTIPO.AsString = TIPO_MOVIMENTO_CREDITO ) then begin IbDtstTabelaVALOR_CREDITO.Value := IbDtstTabelaVALOR.Value; IbDtstTabelaVALOR_DEBITO.Value := 0.0; end else if ( IbDtstTabelaTIPO.AsString = TIPO_MOVIMENTO_DEBITO ) then begin IbDtstTabelaVALOR_CREDITO.Value := 0.0; IbDtstTabelaVALOR_DEBITO.Value := IbDtstTabelaVALOR.Value; end; inherited; if ( not OcorreuErro ) then begin GerarSaldoContaCorrente(IbDtstTabelaCONTA_CORRENTE.AsInteger, IbDtstTabelaDATAHORA.AsDateTime); CarregarSaldos; end; end; procedure TfrmGeFluxoCaixa.ControlEditExit(Sender: TObject); var CxAno, CxNumero, CxContaCorrente : Integer; begin inherited; if ( Sender = dbFormaPagto ) then if ( IbDtstTabela.State in [dsEdit, dsInsert] ) then if ( CaixaAberto(IbDtstTabelaEMPRESA.AsString, IbDtstTabelaUSUARIO.AsString, IbDtstTabelaDATAHORA.AsDateTime, IbDtstTabelaFORMA_PAGTO.AsInteger, CxAno, CxNumero, CxContaCorrente) ) then begin IbDtstTabelaCONTA_CORRENTE.AsInteger := CxContaCorrente; IbDtstTabelaCAIXA_ANO.AsInteger := CxAno; IbDtstTabelaCAIXA_NUM.AsInteger := CxNumero; end else begin IbDtstTabelaCONTA_CORRENTE.Value := fdQryContaCorrente.FieldByName('codigo').AsInteger; IbDtstTabelaCAIXA_ANO.Clear; IbDtstTabelaCAIXA_NUM.Clear; end; end; function TfrmGeFluxoCaixa.BloquearAlteracaoExclusao : Boolean; var Return : Boolean; begin Return := False; if ( (IbDtstTabelaVENDA_NUM.AsInteger > 0) or (IbDtstTabelaCOMPRA_NUM.AsInteger > 0) ) then begin DefinirControle; ShowWarning('Movimento de Fluxo de Caixa bloqueado para edição ou exclusão!'); pgcGuias.ActivePage := tbsCadastro; Return := True; end else if ( Trim(IbDtstTabelaTITULO.AsString) <> EmptyStr ) then begin DefinirControle; ShowWarning('Movimentos de Fluxo de Caixa associados a Títulos não podem ser editados ou excluídos!' + #13#13 + 'Favor promover essas alterações direto no registro de baixa do Título (Contas A Receber).'); pgcGuias.ActivePage := tbsCadastro; Return := True; end else if ( Trim(IbDtstTabelaDUPLICATA.AsString) <> EmptyStr ) then begin DefinirControle; ShowWarning('Movimentos de Fluxo de Caixa associados a Duplicatas não podem ser editados ou excluídos!' + #13#13 + 'Favor promover essas alterações direto no registro de baixa da Duplicata (Contas A Pagar).'); pgcGuias.ActivePage := tbsCadastro; Return := True; end else if ( IbDtstTabelaSITUACAO_CAIXA.AsInteger <> STATUS_CAIXA_ABERTO ) then begin ShowWarning('O Controle de Caixa referente a referente a este movimento não está aberto!'); Return := True; end; Result := Return; end; procedure TfrmGeFluxoCaixa.btbtnAlterarClick(Sender: TObject); begin if ( BloquearAlteracaoExclusao ) then Exit; inherited; end; procedure TfrmGeFluxoCaixa.btbtnExcluirClick(Sender: TObject); begin if ( BloquearAlteracaoExclusao ) then Exit; inherited; end; procedure TfrmGeFluxoCaixa.RegistrarNovaRotinaSistema; begin if ( Trim(RotinaID) <> EmptyStr ) then begin if btnRecalcularSaldo.Visible then SetRotinaSistema(ROTINA_TIPO_FUNCAO, RotinaRecalcularSaldoID, btnRecalcularSaldo.Caption, RotinaID); end; end; procedure TfrmGeFluxoCaixa.btbtnListaClick(Sender: TObject); begin inherited; if ( IbDtstTabela.IsEmpty ) then Exit; ppImprimir.Popup(btbtnLista.ClientOrigin.X, btbtnLista.ClientOrigin.Y + btbtnLista.Height); end; procedure TfrmGeFluxoCaixa.frrFluxoAnaliticoGetValue(const VarName: String; var Value: Variant); begin inherited; if ( VarName = 'Periodo_Desc' ) then if ( e1Data.Date = e2Data.Date ) then Value := 'D a t a' else Value := 'P e r í o d o'; if ( VarName = 'Periodo' ) then if ( e1Data.Date = e2Data.Date ) then Value := FormatDateTime('dd/mm/yyyy', e1Data.Date) else Value := FormatDateTime('dd/mm/yyyy', e1Data.Date) + ' a ' + FormatDateTime('dd/mm/yyyy', e2Data.Date); end; function TfrmGeFluxoCaixa.GetRotinaRecalcularSaldoID: String; begin Result := GetRotinaInternaID(btnRecalcularSaldo); end; procedure TfrmGeFluxoCaixa.btbtnIncluirClick(Sender: TObject); var iAno , iNum : Integer; begin (* IMR - 14/10/2014 : Inserção deste bloco de código para substituir a função da propriedade GeneratorField do dataset por está gerando erro de campo não localizado. *) iAno := YearOf(GetDateDB); iNum := GetGeneratorID(sGeneratorName); inherited; if ( not OcorreuErro ) then begin IbDtstTabelaANO.AsInteger := iAno; IbDtstTabelaNUMERO.AsInteger := iNum; IbDtstTabelaCONTA_CORRENTE.Value := fdQryContaCorrente.FieldByName('codigo').AsInteger; end; end; procedure TfrmGeFluxoCaixa.nmImprimirExtratoClick(Sender: TObject); var Data : TDateTime; begin if ( IbDtstTabela.IsEmpty ) then Exit; try WaitAMoment(WAIT_AMOMENT_PrintPrepare); Data := e1Data.Date; // O saldo é recalculado apenas para o período máximo de 30 dias if ( (e2Data.Date - Data) > 30 ) then Data := e2Data.Date - 30; while Data <= e2Data.Date do begin GerarSaldoContaCorrente(IbDtstTabela.FieldByName('CONTA_CORRENTE').AsInteger, Data); Data := Data + 1; end; with DMNFe do begin with qryEmitente do begin Close; ParamByName('Cnpj').AsString := gUsuarioLogado.Empresa; Open; end; with qryFluxoSaldos do begin Close; ParamByName('Conta').AsInteger := fdQryContaCorrente.FieldByName('codigo').AsInteger; ParamByName('DataInicial').AsDateTime := e1Data.Date; ParamByName('DataFinal').AsDateTime := e2Data.Date; Open; end; with qryFluxoSintetico do begin Close; ParamByName('Conta_Corrente').AsInteger := fdQryContaCorrente.FieldByName('codigo').AsInteger; ParamByName('Data_Inicial').AsDateTime := e1Data.Date; ParamByName('Data_Final').AsDateTime := e2Data.Date; Open; end; with qryFluxoAnalitico do begin Close; ParamByName('Conta_Corrente').AsInteger := fdQryContaCorrente.FieldByName('codigo').AsInteger; ParamByName('Data_Inicial').AsDateTime := e1Data.Date; ParamByName('Data_Final').AsDateTime := e2Data.Date; Open; end; WaitAMomentFree; if ( not qryFluxoAnalitico.IsEmpty ) then frrFluxoAnalitico.ShowReport; end; finally WaitAMomentFree; end; end; procedure TfrmGeFluxoCaixa.nmImprimirReciboClick(Sender: TObject); begin if ( IbDtstTabela.IsEmpty ) then Exit; with CdsRecibo, Params do begin Close; ParamByName('ano').AsInteger := IbDtstTabelaANO.AsInteger; ParamByName('numero').AsInteger := IbDtstTabelaNUMERO.AsInteger; Open; if IsEmpty then Exit; end; FImprimirCabecalho := ShowConfirmation('Recibo', 'Deseja imprimir no recibo o Cabeçalho com informações da empresa?'); if (Sender = nmImprimirReciboA4) then frReport := FrReciboA4 else if (Sender = nmImprimirReciboA5) then frReport := FrReciboA5; SetVariablesDefault(frReport); frReport.PrepareReport; frReport.ShowReport; end; procedure TfrmGeFluxoCaixa.FrReciboGetValue(const VarName: String; var Value: Variant); begin if ( VarName = VAR_TITLE ) then Value := 'RECIBO'; if ( VarName = VAR_EMPRESA ) then Value := GetEmpresaNomeDefault; if ( VarName = VAR_USER ) then Value := GetUserApp; if ( VarName = VAR_SYSTEM ) then Value := Application.Title + ' - versão ' + ver.FileVersion; if ( VarName = 'Imprimir_Cabecalho' ) then Value := IfThen(FImprimirCabecalho, 1, 0); end; procedure TfrmGeFluxoCaixa.CdsReciboCalcFields(DataSet: TDataSet); begin CdsReciboVALOR_BAIXA_EXTENSO.AsString := AnsiUpperCase(ACBrExtenso.ValorToTexto(CdsReciboVALOR_BAIXA.AsCurrency, ACBrExtenso.Formato)); end; procedure TfrmGeFluxoCaixa.CarregarContaCorrente; begin edContaCorrentePesq.OnChange := nil; try with fdQryContaCorrente do begin Filter := 'cnpj = ' + QuotedStr(gUsuarioLogado.Empresa); Filtered := True; Open; edContaCorrentePesq.Clear; while not Eof do begin edContaCorrentePesq.Items.Add( FieldByName('descricao_full').AsString ); Next; end; end; edContaCorrentePesq.ItemIndex := 0; finally edContaCorrentePesq.OnChange := edContaCorrentePesqChange; end; end; initialization FormFunction.RegisterForm('frmGeFluxoCaixa', TfrmGeFluxoCaixa); end.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clFirewallUtils; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Classes; {$ELSE} System.Classes; {$ENDIF} const DefaultFirewallPort = 1080; type TclFirewallType = (ftSocks4, ftSocks5); TclFirewallSettings = class(TPersistent) private FPort: Integer; FPassword: string; FFirewallType: TclFirewallType; FUserName: string; FServer: string; FNeedResolveIP: Boolean; public constructor Create; procedure Assign(Source: TPersistent); override; procedure Clear; published property FirewallType: TclFirewallType read FFirewallType write FFirewallType default ftSocks4; property UserName: string read FUserName write FUserName; property Password: string read FPassword write FPassword; property Server: string read FServer write FServer; property Port: Integer read FPort write FPort default DefaultFirewallPort; property NeedResolveIP: Boolean read FNeedResolveIP write FNeedResolveIP default True; end; implementation { TclFirewallSettings } procedure TclFirewallSettings.Assign(Source: TPersistent); var Src: TclFirewallSettings; begin if (Source is TclFirewallSettings) then begin Src := (Source as TclFirewallSettings); FirewallType := Src.FirewallType; UserName := Src.UserName; Password := Src.Password; Server := Src.Server; Port := Src.Port; NeedResolveIP := Src.NeedResolveIP; end else begin inherited Assign(Source); end; end; procedure TclFirewallSettings.Clear; begin FFirewallType := ftSocks4; FPort := DefaultFirewallPort; FUserName := ''; FPassword := ''; FServer := ''; FNeedResolveIP := True; end; constructor TclFirewallSettings.Create; begin inherited Create; Clear(); end; end.
unit Introspected_streaming_class; interface uses classes,streaming_class_lib, TypInfo; type TIntrospectedStreamingClass = class (TStreamingClass) private procedure RecursiveEnsure(our_root,aowner: TIntrospectedStreamingClass); protected procedure myGetPropInfo(propPath: string; out instance: TPersistent; out fPropInfo: PPropInfo); function OwnedBy(Component, Owner: TComponent): Boolean; public function GetComponentValue(Component,LookUpRoot: TComponent): string; function GetFloatProperty(aPath: string): Real; function NameExistsSomewhere(proposedName: string; me: TComponent=nil): boolean; virtual; //есть ли "внутри нас" компонент с таким именем procedure ensureCorrectName(proposedName: string; aowner: TComponent); //убедиться, что при вставке в aowner не возникнет проблемы с нашим именем procedure ensureCorrectNames(aowner: TIntrospectedStreamingClass); //и у всех наших "подчиненных" имена нормальные end; implementation uses sysUtils; function TIntrospectedStreamingClass.NameExistsSomewhere(proposedName: string; me: TComponent=nil): boolean; var i: integer; c: TComponent; begin c:=FindComponent(proposedName); Result:=Assigned(c) and (c<>me); if not Result then for i:=0 to ComponentCount-1 do begin if Components[i] is TIntrospectedStreamingClass then begin Result:=Result or TIntrospectedStreamingClass(Components[i]).NameExistsSomewhere(proposedName,me); if Result=true then break; end; end; end; procedure TIntrospectedStreamingClass.ensureCorrectName(proposedName: string; aowner: TComponent); var FullName: string; i: Integer; begin FullName:=proposedName; if assigned(aowner) then begin i:=0; // while aowner.FindComponent(FullName)<>nil do begin while (aowner as TIntrospectedStreamingClass).NameExistsSomewhere(FullName,self) do begin FullName:=proposedName+IntToStr(i); inc(i); end; //нужен вариант проверки и компонентах, принадлежащих Owner, end; Name:=FullName; end; procedure TIntrospectedStreamingClass.RecursiveEnsure(our_root,aowner: TIntrospectedStreamingClass); var i: Integer; fullName: string; begin i:=0; fullName:=Name; while aowner.NameExistsSomewhere(FullName,self) or our_root.NameExistsSomewhere(FullName,self) do begin fullName:=Name+IntToStr(i); inc(i); end; Name:=FullName; //себя переименовали for i:=0 to ComponentCount-1 do if Components[i] is TIntrospectedStreamingClass then TIntrospectedStreamingClass(Components[i]).RecursiveEnsure(our_root,aowner); end; procedure TIntrospectedStreamingClass.ensureCorrectNames(aowner: TIntrospectedStreamingClass); begin RecursiveEnsure(self,aowner); end; procedure TIntrospectedStreamingClass.myGetPropInfo(propPath: string; out Instance: TPersistent; out fPropInfo: PPropInfo); var i,j,L: Integer; PropValue: TObject; fPropName: string; begin i := 1; L := Length(propPath); Instance := FindOwner; while True do begin j := i; while (i <= L) and (PropPath[i] <> '.') do Inc(i); FPropName := Copy(PropPath, j, i - j); if i > l then Break; fPropInfo := GetPropInfo(Instance.ClassInfo, FPropName); if fPropInfo = nil then begin if (Instance is TComponent) then begin Instance:=TComponent(Instance).FindComponent(fPropName) as TPersistent; if Instance=nil then Exception.Create('Property '+FPropName+' not found'); end else Raise Exception.Create('Property '+FPropName+' not found'); end else begin PropValue := nil; if fPropInfo^.PropType^.Kind = tkClass then PropValue := TObject(GetOrdProp(Instance, fPropInfo)); if not (PropValue is TPersistent) then Raise Exception.Create('Wrong property path'); Instance := TPersistent(PropValue); end; Inc(I); end; fPropInfo := GetPropInfo(Instance.ClassInfo, FPropName); end; function TIntrospectedStreamingClass.GetFloatProperty(aPath: string): Real; var instance: TPersistent; fPropInfo: PPropInfo; begin myGetPropInfo(aPath,instance,fPropInfo); if fPropInfo.PropType^.Kind<>tkFloat then Raise Exception.Create('error: property is not float number'); Result:=GetFloatProp(instance,fPropInfo); end; function TIntrospectedStreamingClass.OwnedBy(Component, Owner: TComponent): Boolean; begin Result := True; while Component <> nil do if Component = Owner then Exit else Component := Component.Owner; Result := False; end; function TIntrospectedStreamingClass.GetComponentValue(Component,LookUpRoot: TComponent): string; begin if Component.Owner = LookupRoot then Result := Component.Name else if Component = LookupRoot then Result := 'Owner' { Do not translate } else if (Component.Owner <> nil) and (Component.Owner.Name <> '') and (Component.Name <> '') then if OwnedBy(Component.Owner, LookupRoot) then Result := GetComponentValue(Component.Owner,LookUpRoot) + '.' + Component.Name else Result := Component.Owner.Name + '.' + Component.Name else if Component.Name <> '' then Result := Component.Name + '.Owner' { Do not translate } else Result := ''; end; end.
// AKTools. akStrUtils unit. // Модуль, содержащий функции по работе со строками. //============================================================================= unit akStrUtils; interface uses Classes, SysUtils, Windows; type TChars = set of char; ECryptError = class(Exception); // *********************** Работа со строками ********************************** // Добавляет к строке Org строку add. Работает быстрее org := org + add; procedure FastAddString(var Org: string; add: string); // Возвращает сегмент с порядковым номером N (считая с нуля), // Если сегмента с номером N нет, то функция вернет SegSep. // Например, если Str = "tos\pax\file\dir\sux\sux.htm", SegSep = "\", а // N = 2, то резултатом будет строка "sux". function GetRightSegment(N: Integer; Str: string; SegSep: Char): string; function GetLeftSegment(N: Integer; Str: string; SegSep: Char): string; // Криптует строку Str function CryptString(Str: string): string; // Дешифрует криптованную строку Str function UnCryptString(Str: string): string; // Проверяет, что в строке нет символов с кодом больше #127 function IsLat(Str: string): boolean; // Преобразует OEM->ANSI function StrOEMToANSI(St: string): string; // Преобразует ANSI->OEM function StrANSItoOEM(St: string): string; // Возвращает строку, разделенную по словам procedure GetStrWords(St: string; List: TStringList; latonly: boolean = true); // Возвращает true, если слова, перечисленные через пробел // в Words находятся в строке St, причем расстояние между // ними не более 10 символов (использовать для поиска по фразе) function WordsIsNear(St: string; Words: string): boolean; // Проверяет, что все слова, перечисленные через пробел в Words существуют // в строке St. function WordsIn(St: string; Words: string): boolean; // Удаляет указанные символы из строки function TrimIn(St: string; rchars: TChars): string; // Перобразует текст в строку, путем удаления из него всех символов #13, #10, // #9 (если необходимо добавляет "пробел"). function TextToLine(St: string): string; // Возвращает инициалы имени, указанного в Name function GetNameLT(Name: string): string; // Возвращает позицию первого символа, отличного от Ch. // В StartFrom указывается с какого символа начинать проверку // Если символа с кодом отличным от ch не найдено, то возвращается 0. function NotCharPos(St: string; ch: Char; StartFrom: Integer = 1): Integer; // Возвращает строку, в которой все символы c1 заменены на // c2. (работает много быстрее StringReplace) function ReplaceChar(st: string; c1, c2: char): string; // Разбивает строку на подстроки, длина каждой из которых // не превышает len символов. Разбивка производится только // на стыках слов, однако если слово слишком длинное, то оно // разобьется "как есть". Строки отделяются друг от друга // последовательностью символов #13#10. first и next указывают // отступы с левого края в первой и следующих строках. function WordWrapStr(st: string; len: Integer; first: Integer = 0; next: Integer = 0): string; // Возвращает позицию Nой (начиная с нуля) подстроки SubStr в строке S // Если таковая не обнаружена, то вернется 0. (Проверка идет справа налево) function PosR(Substr: string; S: string; N: Integer = 0; IgnoreCase: Boolean = false; from: Integer = 0): Integer; function PosL(StartFrom: Integer; Substr: string; S: string; N: Integer = 0; IgnoreCase: Boolean = false): Integer; // Возвращает непустую строку, если Src = "" function CodeEmptyString(src: string): string; // Делает обратное EmptyQtString действие: function DecodeEmptyString(src: string): string; // Сравнение по маске function IsWild(InputStr, Wilds: string; IgnoreCase: Boolean): Boolean; // Расширеное сравнение : // Wilds может содержать следующие специальные символы : // ? - любой символ // * - любая последовательность символов // | - логическое "или" function IsWildEx(InputStr: string; Wilds: string; IgnoreCase: Boolean): Boolean; // Функция ищет подстроку, находящуюся дальше "from" в строке S между // сепараторами SepStart и SepEnd и заменяет в этой подстроке все // OldPattern на NewPattern. Если OldPattern = "*", то любая подстрока // заменится на NewPattern. function StringReplaceIn(from: Integer; const S, SepStart, SepEnd, OldPattern, NewPattern: string; Flags: TReplaceFlags; RemoveSeps: Boolean = true; InsertNew: Boolean = false): string; // Функция быстрой замены в InStr строки FindStr на ReplaceStr function FastStringReplace(InStr: string; FindStr, ReplaceStr: string): string; // преобразовывает все символы с кодом меньше 33 и "/", "\" в %xx function UrlEncode(url: string): string; type TStringsCounterData = record Str: string[200]; Hash: LongWord; Count: Integer; Data: Integer; end; PStringsCounterData = ^TStringsCounterData; // Обычный TStringList, элементы которого не повторяются, а в Data хранится количество // добавленных строк с данным имененм. Используйте только Add для пополнения списка TStringsCounterList = class(TList) private function GetCounts(Index: Integer): Integer; procedure SetCounts(Index: Integer; const Value: Integer); function GetItems(Index: Integer): PStringsCounterData; public destructor Destroy; override; function IndexOf(const S: string): Integer; function Add(const S: string; Data: Integer; IncCount: Integer = 1): Integer; property Counts[Index: Integer]: Integer read GetCounts write SetCounts; property Items[Index: Integer]: PStringsCounterData read GetItems; default; procedure Clear; override; procedure SortByCounts; end; TStringBtwInfo = record PosStart: Integer; // позиция первого сепаратора в строке PosEnd: Integer; // позиция начала последнего сепаратора TotalLen: Integer; // общая длина строки, заключенной в сепараторы (вместе с ними) SepString: string; // собственно сюда сохраняется строка. Params: string; // если useparams = true, то сюда вернется то, что было указано // в стартовом теге после ":" ("%project:3s%" - "3s"). SearchOk: Boolean; // данные стурктуры имеют смысл только если SearchOk = true end; // Возвращает подстроку, находяющуюся дальше from и расположенную между // сепараторами SepStart и SepEnd. (<td>mytext</td>, вернет "mytext") // если SepEnd не указан, то он считается равным SepStart function GetStringBetween(from: Integer; str: string; SepStart: string; SepEnd: string = ''): TStringBtwInfo; procedure PrepareTextToXML(var buffer: string); function NormalizeXML(str: string): string; var csCryptFirst, csCryptSecond: Integer; csCryptHeader: string; implementation uses akDataUtils; function NormalizeXML(str: string): string; begin Result := FastStringReplace(str, '<', '&lt;'); Result := FastStringReplace(Result, '>', '&gt;'); Result := FastStringReplace(Result, '&', '&amp;'); Result := FastStringReplace(Result, '''', '&apos;'); Result := FastStringReplace(Result, '"', '&quot;'); end; function FastStringReplace(InStr: string; FindStr, ReplaceStr: string): string; var LenFindStr, LenReplaceStr, LenInStr: integer; PtrInStr, PtrOutStr, // pointers to incremental reading and writing PInStr, POutStr: PChar; // pointer to start of output string Res: Integer; begin if (FindStr = '') or (InStr = '') then begin Result := InStr; exit; end; Result := ''; LenInStr := Length(InStr); LenFindStr := Length(FindStr); LenReplaceStr := Length(ReplaceStr); Res := 0; PInStr := PChar(InStr); PtrInStr := PInStr; {find number of occurences to allocate output memory in one chunk} while PtrInStr < (PInStr + LenInStr) do begin if StrLIComp(PtrInStr, PChar(FindStr), LenFindStr) = 0 then inc(Res); inc(PtrInStr); end; {reset pointer} PtrInStr := PInStr; {allocate the output memory - calculating what is needed} GetMem(POutStr, Length(InStr) + (Res * (LenReplaceStr - LenFindStr)) + 1); try {find and replace the strings} PtrOutStr := POutStr; while PtrInStr < (PInStr + LenInStr) do begin if (StrLIComp(PtrInStr, PChar(FindStr), LenFindStr) = 0) then begin if (LenReplaceStr > 0) then begin StrLCopy(PtrOutStr, PChar(ReplaceStr), LenReplaceStr); inc(PtrOutStr, LenReplaceStr); // increment output pointer end; inc(PtrInStr, LenFindStr); // increment input pointer end else begin {write one char to the output string} StrLCopy(PtrOutStr, PtrInStr, 1); // copy character inc(PtrInStr); inc(PtrOutStr); end; end; {copy the output string memory to the provided output string} Result := StrPas(POutStr); finally FreeMem(POutStr); end; end; procedure PrepareTextToXML(var buffer: string); var i: Integer; begin for i := 1 to Length(Buffer) do if (Buffer[i] in [#0..#32, #10, #13, '&', '"']) then Buffer[i] := #32; end; procedure FastAddString(var Org: string; add: string); var addln, orgln: Integer; begin orgln := Length(org); addln := Length(add); SetLength(Org, Length(Org) + addln); Move(add[1], Org[orgln + 1], addln); end; function GetStringBetween(from: Integer; str: string; SepStart: string; SepEnd: string): TStringBtwInfo; var i, ps: Integer; sepen: string; begin with Result do begin SearchOk := false; posStart := PosL(from, SepStart, str); if posStart = 0 then exit; if SepEnd = '' then SepEn := SepStart else SepEn := SepEnd; posEnd := PosL(posStart + Length(SepStart), SepEn, str); if posEnd = 0 then exit; ps := posStart + Length(SepStart); SepString := Copy(str, ps, posEnd - ps); i := Pos(':', SepString); if i = 0 then Params := '' else begin Params := Copy(SepString, i + 1, maxInt); SepString := Copy(SepString, 1, i - 1); end; TotalLen := posEnd - ps + Length(SepStart) + Length(SepEn); SearchOk := True; end; end; function StringReplaceIn(from: Integer; const S, SepStart, SepEnd, OldPattern, NewPattern: string; Flags: TReplaceFlags; RemoveSeps: Boolean = true; InsertNew: Boolean = false): string; var SPs, EPs: Integer; old, newStr: string; begin Result := S; SPs := PosL(from, SepStart, S, 0, rfIgnoreCase in Flags); if SPs = 0 then exit; SPs := SPs + Length(SepStart); EPs := PosL(SPs, SepEnd, S, 0, rfIgnoreCase in Flags); if EPs = 0 then exit; if OldPattern <> '*' then newStr := StringReplace(Copy(S, SPs, EPs - SPs), OldPattern, NewPattern, Flags) else if NewPattern = '*' then newStr := Copy(S, SPs, EPs - SPs) else newStr := NewPattern; // Если не нужно удалять сепараторы, то добавляем их к строке. if not RemoveSeps then newStr := SepStart + newStr + SepEnd; // Если добавляем новую строку, то сохраняем старую в "old". if InsertNew then old := SepStart + Copy(S, SPs, EPs - SPs) + SepEnd else old := ''; Result := Copy(S, 1, SPs - Length(SepStart) - 1) + old + newStr + Copy(S, EPs + Length(SepEnd), MaxInt); end; function IsWild(InputStr, Wilds: string; IgnoreCase: Boolean): Boolean; function FindPart(const HelpWilds, InputStr: string): Integer; var I, J: Integer; Diff: Integer; begin I := Pos('?', HelpWilds); if I = 0 then begin { if no '?' in HelpWilds } Result := Pos(HelpWilds, InputStr); Exit; end; { '?' in HelpWilds } Diff := Length(InputStr) - Length(HelpWilds); if Diff < 0 then begin Result := 0; Exit; end; { now move HelpWilds over InputStr } for I := 0 to Diff do begin for J := 1 to Length(HelpWilds) do begin if (InputStr[I + J] = HelpWilds[J]) or (HelpWilds[J] = '?') then begin if J = Length(HelpWilds) then begin Result := I + 1; Exit; end; end else Break; end; end; Result := 0; end; function SearchNext(var Wilds: string): Integer; { looking for next *, returns position and string until position } begin Result := Pos('*', Wilds); if Result > 0 then Wilds := Copy(Wilds, 1, Result - 1); end; var CWild, CInputWord: Integer; { counter for positions } I, LenHelpWilds: Integer; MaxInputWord, MaxWilds: Integer; { Length of InputStr and Wilds } HelpWilds: string; begin if Wilds = InputStr then begin Result := True; Exit; end; repeat { delete '**', because '**' = '*' } I := Pos('**', Wilds); if I > 0 then Wilds := Copy(Wilds, 1, I - 1) + '*' + Copy(Wilds, I + 2, MaxInt); until I = 0; if Wilds = '*' then begin { for fast end, if Wilds only '*' } Result := True; Exit; end; MaxInputWord := Length(InputStr); MaxWilds := Length(Wilds); if IgnoreCase then begin { upcase all letters } InputStr := AnsiUpperCase(InputStr); Wilds := AnsiUpperCase(Wilds); end; if (MaxWilds = 0) or (MaxInputWord = 0) then begin Result := False; Exit; end; CInputWord := 1; CWild := 1; Result := True; repeat if InputStr[CInputWord] = Wilds[CWild] then begin { equal letters } { goto next letter } Inc(CWild); Inc(CInputWord); Continue; end; if Wilds[CWild] = '?' then begin { equal to '?' } { goto next letter } Inc(CWild); Inc(CInputWord); Continue; end; if Wilds[CWild] = '*' then begin { handling of '*' } HelpWilds := Copy(Wilds, CWild + 1, MaxWilds); I := SearchNext(HelpWilds); LenHelpWilds := Length(HelpWilds); if I = 0 then begin { no '*' in the rest, compare the ends } if HelpWilds = '' then Exit; { '*' is the last letter } { check the rest for equal Length and no '?' } for I := 0 to LenHelpWilds - 1 do begin if (HelpWilds[LenHelpWilds - I] <> InputStr[MaxInputWord - I]) and (HelpWilds[LenHelpWilds - I] <> '?') then begin Result := False; Exit; end; end; Exit; end; { handle all to the next '*' } Inc(CWild, 1 + LenHelpWilds); I := FindPart(HelpWilds, Copy(InputStr, CInputWord, MaxInt)); if I = 0 then begin Result := False; Exit; end; CInputWord := I + LenHelpWilds; Continue; end; Result := False; Exit; until (CInputWord > MaxInputWord) or (CWild > MaxWilds); { no completed evaluation } if CInputWord <= MaxInputWord then Result := False; if (CWild <= MaxWilds) and (Wilds[MaxWilds] <> '*') then Result := False; end; function IsWildEx(InputStr: string; Wilds: string; IgnoreCase: Boolean): Boolean; var i: Integer; seg: string; begin Result := False; for i := 0 to maxInt do begin Seg := GetLeftSegment(i, Wilds, '|'); if Seg = '|' then break; if IsWild(InputStr, Seg, IgnoreCase) then begin Result := True; break; end; end; end; function GetRightSegment(N: Integer; Str: string; SegSep: Char): string; var i: Integer; ResPos, SecPos, SecN: Integer; begin SecN := 0; ResPos := -1; SecPos := Length(Str); for i := Length(Str) downto 1 do begin if (Str[i] = SegSep) then begin if SecN = N then begin ResPos := i + 1; // левый SegSep break; end; SecPos := i - 1; // правый SegSep Inc(SecN); end; end; if (ResPos = -1) and (N = SecN) then ResPos := 1; if ResPos = -1 then Result := SegSep else Result := Copy(Str, ResPos, SecPos - ResPos + 1); end; function GetLeftSegment(N: Integer; Str: string; SegSep: Char): string; var i: Integer; ResPos, SecPos, SecN: Integer; begin SecN := 0; ResPos := -1; SecPos := 1; for i := 1 to Length(Str) do begin if Str[i] = SegSep then begin if SecN = N then begin ResPos := i - 1; // левый SegSep break; end; SecPos := i + 1; // правый SegSep Inc(SecN); end; end; if (ResPos = -1) and (N = SecN) then ResPos := Length(Str); if ResPos = -1 then Result := SegSep else Result := Copy(Str, SecPos, ResPos - SecPos + 1); end; function CryptString(Str: string): string; var i, clen: Integer; begin clen := Length(csCryptHeader); SetLength(Result, Length(Str) + clen); Move(csCryptHeader[1], Result[1], clen); for i := 1 to Length(Str) do begin if i mod 2 = 0 then Result[i + clen] := Chr(Ord(Str[i]) xor csCryptSecond) else Result[i + clen] := Chr(Ord(Str[i]) xor csCryptFirst); end; end; function UnCryptString(Str: string): string; var i, clen: Integer; begin clen := Length(csCryptHeader); SetLength(Result, Length(Str) - clen); if Copy(Str, 1, clen) <> csCryptHeader then raise ECryptError.Create('UnCryptString failed'); for i := 1 to Length(Str) - clen do begin if (i) mod 2 = 0 then Result[i] := Chr(Ord(Str[i + clen]) xor csCryptSecond) else Result[i] := Chr(Ord(Str[i + clen]) xor csCryptFirst); end; end; function IsLat(Str: string): boolean; var i: Integer; begin Result := True; for i := 1 to Length(Str) do if Str[i] > #127 then begin Result := False; exit; end; end; function StrOEMToANSI(St: string): string; begin Result := ''; if st = '' then exit; SetLength(Result, Length(St)); OemToChar(PChar(St), PChar(Result)); end; function StrANSItoOEM(St: string): string; begin Result := ''; if st = '' then exit; SetLength(Result, Length(St)); CharToOEM(PChar(St), PChar(Result)); end; function CodeEmptyString(src: string): string; begin Result := Trim(src); if Result = '' then Result := '!null!value'; end; function DecodeEmptyString(src: string): string; begin Result := Trim(src); if Result = '!null!value' then Result := ''; end; procedure GetStrWords(St: string; List: TStringList; latonly: boolean = true); var i: Integer; Start: Integer; Wrd: string; str: string; begin List.Clear; str := st + ' '; Wrd := ''; Start := 1; for i := 1 to Length(str) do begin if str[i] in [#13, #10, #9, #32..#64, #91..#96, #123..#191] then begin Wrd := Trim(Copy(str, Start, i - Start)); if ((not IsLat(Wrd)) or (not latonly)) and (Wrd <> '') then List.Add(Wrd); Start := i + 1; end; end; end; // Возвращает true, если фраза wrds 100% присутствует. // Возвращает false, если фраза пока не найдена, но первое слово // уже обнаружено. Первый символ этого слова возвращается в Res. // Если Res = 0, то фраза 100% отсутствует в строке. function FirstWordsIsNear(St: string; wrds: TStringList; var Res: Integer): Boolean; var prevLen, prev, psr, w: Integer; tt: string; begin Res := 0; Result := True; if Wrds.Count = 0 then exit; prevLen := 0; Prev := 0; tt := CharLower(PChar(st)); for w := 0 to Wrds.Count - 1 do begin psr := Pos(wrds[w], tt); if w = 0 then begin Res := psr; prev := psr; FillChar(tt[1], psr, #32); end; if (psr = 0) or (psr - prev - prevLen > 10) then begin Result := False; Break; end; prev := psr; prevLen := Length(wrds[w]); end; end; function WordsIsNear(St: string; Words: string): boolean; var sl: TStringList; Offset, psf: Integer; str: string; begin Result := False; if Trim(Words) = '' then begin Result := True; exit; end; sl := TStringList.Create; try psf := 0; Offset := 1; GetStrWords(AnsiLowerCase(Words), sl, false); repeat str := Copy(st, offset, maxint); if FirstWordsIsNear(str, sl, psf) then begin Result := True; break; end; inc(offset, psf); until (str = '') or (psf = 0); finally sl.Free; end; end; function TrimIn(St: string; rchars: TChars): string; var f, s: Integer; begin SetLength(Result, Length(St)); s := 0; for f := 1 to Length(St) do begin if not (St[f] in rchars) then begin inc(s); Result[s] := st[f]; end; end; SetLength(Result, s); end; function TextToLine(St: string): string; var f, s: Integer; PrevDeleted: boolean; begin SetLength(Result, Length(St)); s := 0; PrevDeleted := False; for f := 1 to Length(St) do begin if not (St[f] in [#13, #10, #9]) then begin inc(s); Result[s] := st[f]; PrevDeleted := False; end else begin if not PrevDeleted then begin inc(s); Result[s] := ' '; end; PrevDeleted := True; end; end; SetLength(Result, s); end; function GetNameLT(Name: string): string; var p, l, i: Integer; begin Result := Copy(Name, 1, 1); // первый символ p := Pos(' ', Name); // символ после первого пробела if p <> 0 then Result := Result + Copy(Name, p + 1, 1); l := p; for i := Length(Name) downto 1 do if Name[i] = ' ' then begin l := i; break; end; if p <> l then Result := Result + Copy(Name, l + 1, 1); end; function NotCharPos(St: string; ch: Char; StartFrom: Integer = 1): Integer; var i: Integer; begin Result := 0; for i := StartFrom to Length(st) do if st[i] <> ch then begin Result := i; Break; end; end; function WordWrapStr; var i: Integer; ln, crStart, crLastSp, crlen: Integer; sta: string; begin Result := StringOfChar(' ', first); crLastSp := Len; crlen := 0; crStart := 1; ln := 0; for i := 1 to Length(st) do begin inc(crLen); if (crLen > len + 1) or (i = Length(st)) then begin if i = Length(st) then crLastSp := MaxInt; inc(ln); if ln > 1 then Sta := StringOfChar(' ', next) else Sta := ''; Result := Result + Sta + Trim(Copy(st, crStart, crLastSp)); if i <> Length(st) then Result := Result + #13#10; crLen := i - (crStart + crLastSp); crStart := crStart + crLastSp; crLastSp := Len; end else if (st[i] in [' ']) then begin crLastSp := crLen; end; end; end; function WordsIn(St: string; Words: string): boolean; var sl: TStringList; i: Integer; lw1, lw2: string; begin Result := True; if Trim(Words) = '' then begin Result := True; exit; end; sl := TStringList.Create; try lw2 := AnsiLowerCase(st); GetStrWords(Words, sl, false); for i := 0 to sl.Count - 1 do begin lw1 := AnsiLowerCase(sl[i]); if Pos(lw1, lw2) = 0 then begin Result := False; break; end; end; finally sl.Free; end; end; function ReplaceChar(st: string; c1, c2: char): string; var i: Integer; begin Result := st; for i := 1 to Length(st) do if Result[i] = c1 then Result[i] := c2; end; function PosL(StartFrom: Integer; Substr: string; S: string; N: Integer = 0; IgnoreCase: Boolean = false): Integer; var i, slen, okcnt, sfrom: Integer; begin okcnt := 0; Result := 0; slen := Length(SubStr); if slen = 0 then exit; sfrom := iifs(StartFrom <= 0, 1, StartFrom); for i := sfrom to Length(s) do begin if ((IgnoreCase) and ((upcase(s[i]) = upcase(SubStr[1])) and (CompareText(Copy(s, i, slen), SubStr) = 0))) or ((not IgnoreCase) and ((s[i] = SubStr[1]) and (CompareStr(Copy(s, i, slen), SubStr) = 0))) then inc(okcnt); if okcnt = N + 1 then begin Result := i; break; end; end; end; function PosR(Substr: string; S: string; N: Integer; IgnoreCase: Boolean; from: Integer): Integer; var fr, i, slen, okcnt: Integer; begin okcnt := 0; Result := 0; slen := Length(SubStr); if slen = 0 then exit; if from = 0 then fr := Length(s) else fr := from; if fr > Length(s) then fr := Length(s); for i := fr downto 1 do begin if ((IgnoreCase) and ((upcase(s[i]) = upcase(SubStr[1])) and (CompareText(Copy(s, i, slen), SubStr) = 0))) or ((not IgnoreCase) and ((s[i] = SubStr[1]) and (CompareStr(Copy(s, i, slen), SubStr) = 0))) then { if ((IgnoreCase) and (AnsiCompareText(Copy(s, i, slen), SubStr) = 0)) or ((not IgnoreCase) and (AnsiCompareStr(Copy(s, i, slen), SubStr) = 0)) then} inc(okcnt); if okcnt = N + 1 then begin Result := i; break; end; end; end; function PosRP(Substr: string; S: string; from: Integer; IgnoreCase: Boolean = false): Integer; var fr, i, slen {, okcnt}: Integer; begin {okcnt := 0;}Result := 0; slen := Length(SubStr); if from > Length(s) then fr := from else fr := Length(s); for i := fr downto 1 do begin if ((IgnoreCase) and (AnsiCompareText(Copy(s, i, slen), SubStr) = 0)) or ((not IgnoreCase) and (AnsiCompareStr(Copy(s, i, slen), SubStr) = 0)) then // inc(okcnt); begin Result := i; break; end; end; end; { TStringsCounterList } function TStringsCounterList.Add(const S: string; Data: Integer; IncCount: Integer): Integer; var fnd: Integer; ptr: PStringsCounterData; begin fnd := IndexOf(s); if fnd = -1 then begin New(ptr); ptr^.Hash := GetStringCRC(s, false); ptr^.Count := IncCount; ptr^.Str := S; ptr^.Data := Data; inherited Add(ptr); end else begin Counts[fnd] := Counts[fnd] + IncCount; end; Result := fnd; end; procedure TStringsCounterList.Clear; var i: Integer; begin for i := 0 to Count - 1 do Dispose(PStringsCounterData(Items[i])); inherited; end; destructor TStringsCounterList.Destroy; begin Clear; inherited; end; function TStringsCounterList.GetCounts(Index: Integer): Integer; begin Result := Items[Index]^.Count; end; function TStringsCounterList.GetItems(Index: Integer): PStringsCounterData; begin Result := inherited Items[Index]; end; function TStringsCounterList.IndexOf(const S: string): Integer; var i: Integer; sh: LongWord; dt: PStringsCounterData; begin Result := -1; sh := GetStringCRC(S, false); for i := 0 to Count - 1 do begin dt := PStringsCounterData(Items[i]); if (dt^.Hash = sh) and (dt^.Str = S) then begin // Нашли запись: Result := i; break; end; end; end; procedure TStringsCounterList.SetCounts(Index: Integer; const Value: Integer); begin PStringsCounterData(Items[Index])^.Count := Value; end; function CompareFunc(Item1, Item2: Pointer): Integer; var Cnt1, Cnt2: Integer; begin Cnt1 := PStringsCounterData(Item1)^.Count; Cnt2 := PStringsCounterData(Item2)^.Count; if Cnt1 < Cnt2 then Result := -1 else if Cnt1 > Cnt2 then Result := 1 else Result := 0; end; procedure TStringsCounterList.SortByCounts; begin Sort(CompareFunc); end; function UrlEncode(url: string): string; var i, ps: Integer; ch: string; begin SetLength(result, Length(url) * 3); ps := 1; for i := 1 to Length(url) do begin if url[i] in [#0..#32, '/', '\'] then begin ch := '%' + IntToHex(Ord(url[i]), 2); Move(ch[1], result[ps], 3); inc(ps, 3); end else begin result[ps] := url[i]; inc(ps); end; end; SetLength(Result, ps - 1); end; initialization csCryptFirst := 28; csCryptSecond := 235; csCryptHeader := ''; end.
{ Subroutine SST_FLAG_USED_ROUT (PROC) * * Flag all the symbols as used that are eventually referenced by the routine * descriptor PROC. } module sst_FLAG_USED_ROUT; define sst_flag_used_rout; %include 'sst2.ins.pas'; procedure sst_flag_used_rout ( {flag symbols eventually used from rout call} in proc: sst_proc_t); {routine descriptor} var arg_p: sst_proc_arg_p_t; {points to current routine argument descriptor} begin if proc.sym_p <> nil then begin {do routine name symbol, if any} sst_flag_used_symbol (proc.sym_p^); end; if proc.dtype_func_p <> nil then begin {do function return data type, if any} sst_flag_used_dtype (proc.dtype_func_p^); end; arg_p := proc.first_arg_p; {init current call argument to first} while arg_p <> nil do begin {once for each call argument} if arg_p^.sym_p <> nil then begin {do dummy arg name, if any} sst_flag_used_symbol (arg_p^.sym_p^); end; if arg_p^.exp_p <> nil then begin {do expression for passed arg value, if any} sst_flag_used_exp (arg_p^.exp_p^); end; sst_flag_used_dtype (arg_p^.dtype_p^); {do data type of this argument} arg_p := arg_p^.next_p; {advance to next argument of this routine} end; {back and process next call argument} end;
// islip - IneQuation's Simple LOLCODE Interpreter in Pascal // Written by Leszek "IneQuation" Godlewski <leszgod081@student.polsl.pl> // Language parser and bytecode compiler unit // Sorry for the spaghetti code but can't be arsed to improve it! unit compiler; // uncomment the following to enable debug printouts //{$DEFINE DEBUG} {$IFDEF fpc} {$MODE objfpc} {$ENDIF} interface uses typedefs, parser, bytecode, variable, convert, SysUtils; type // variable linked list element pislip_cmp_var = ^islip_cmp_var; islip_cmp_var = record next : pislip_cmp_var; id : string; v : pislip_var; end; // variable container islip_cmp_var_cont = class public m_head : pislip_cmp_var; m_tail : pislip_cmp_var; m_index : size_t; constructor create; destructor destroy; override; // appends the new variable to the list and returns its index function append(v : pislip_var; id : string) : size_t; // finds the index of the given variable by its ID; returns // ARG_NULL if not found function get_var_index(id : string) : size_t; // finds the given variable by its ID; returns nil on failure function get_var(id : string) : pislip_cmp_var; end; // instruction linked list element pislip_cmp_inst = ^islip_cmp_inst; islip_cmp_inst = record next : pislip_cmp_inst; i : byte; arg : int; end; // instruction container islip_cmp_code_cont = class public m_head : pislip_cmp_inst; m_tail : pislip_cmp_inst; m_count : size_t; constructor create; destructor destroy; override; // appends the new instruction to the list and returns its pointer function append(i : byte; arg : size_t) : pislip_cmp_inst; // removes the last element from the list procedure chop_tail; end; // list element for ipcont pislip_cmp_ip = ^islip_cmp_ip; islip_cmp_ip = record i : pislip_cmp_inst; next : pislip_cmp_ip; end; pislip_cmp_ipcont = ^islip_cmp_ipcont; // helper class to manage a linked list of instruction pointers to simplify // jumping out of success blocks to after the non-linear code block islip_cmp_ipcont = class public constructor create; // fills the arguments of all elements with ofs procedure fill(ofs : int); // adds a pointer to an instruction to list procedure add(i : pislip_cmp_inst); private m_head : pislip_cmp_ip; m_tail : pislip_cmp_ip; end; islip_compiler = class public constructor create(var input : cfile); destructor destroy; override; // returns false on compilation failure function compile : boolean; procedure get_products(var c : islip_bytecode; var d : islip_data); private m_parser : islip_parser; m_vars : islip_cmp_var_cont; m_code : islip_cmp_code_cont; m_done : boolean; // evaluates the upcoming statement function eval_statement(gtfo : pislip_cmp_ipcont) : boolean; // evaluates the upcoming expression function eval_expr : boolean; // parses a number or boolean literal function literal(token : string) : boolean; // parses a variable assignment R-value function variable_rvalue(id : string) : boolean; // checks if the given string is a valid LOLCODE identifier function is_valid_ident(s : string) : boolean; // optimizes some instruction combinations procedure optimize(start : pislip_cmp_inst); end; implementation const LOLCODE_VERSION = '1.2'; // supported LOLCODE version type islip_cmp_state = ( CS_UNDEF, // undefined state, before reading the first token CS_START, // just had HAI, expecting version number or line break CS_STATEMENT // program body, expecting a statement ); islip_flowstate = ( FS_LINEAR, // we're reading a normal, linear code block FS_IF, // we're reading an "if" block FS_ELSEIF, // we're reading an "else if" block FS_ELSE, // we're reading an "else" block FS_SWITCH, // we're reading a switch block FS_LOOP // we're reading a loop block ); // ==================================================== // compiler implementation // ==================================================== constructor islip_compiler.create(var input : cfile); begin m_parser := islip_parser.create(input); m_vars := islip_cmp_var_cont.create; m_code := islip_cmp_code_cont.create; m_done := false; end; destructor islip_compiler.destroy; begin m_parser.destroy; m_vars.destroy; m_code.destroy; end; function islip_compiler.literal(token : string) : boolean; var floatmath : boolean; sr, sc : size_t; f : float; i : int; pv : pislip_var; begin literal := false; // we can detect number literals by the first character if not ((token[1] in ['0'..'9']) or (token[1] = '-')) then begin // it can only be either a boolean literal or a syntax error now if token = 'WIN' then begin {$IFDEF DEBUG} writeln('DEBUG: boolean literal'); {$ENDIF} new(pv); pv^ := islip_var.create(true); m_code.append(OP_PUSH, m_vars.append(pv, '')); literal := true; end else if token = 'FAIL' then begin {$IFDEF DEBUG} writeln('DEBUG: boolean literal'); {$ENDIF} new(pv); pv^ := islip_var.create(false); m_code.append(OP_PUSH, m_vars.append(pv, '')); literal := true; end; exit; end; {$IFDEF DEBUG} writeln('DEBUG: number literal'); {$ENDIF} floatmath := false; // don't switch to floating point math unless we find a radix for i := 2 to length(token) do begin if token[i] = '.' then begin if floatmath then begin m_parser.get_pos(sr, sc); writeln('ERROR: Multiple radix characters in number literal at', ' line ', sr, ', column ', sc); exit; end; floatmath := true; end else if not (token[i] in ['0'..'9']) then begin m_parser.get_pos(sr, sc); writeln('ERROR: Invalid number literal at line ', sr, ', column ', sc); exit; end; end; new(pv); if floatmath then begin if not atof(token, @f) then begin m_parser.get_pos(sr, sc); writeln('ERROR: Invalid number literal at line ', sr, ', column ', sc); exit; end; pv^ := islip_var.create(f); end else begin try i := StrToInt(token); except on E : Exception do begin m_parser.get_pos(sr, sc); writeln('ERROR: Invalid number literal at line ', sr, ', column ', sc); exit; end; end; pv^ := islip_var.create(i); end; // generate the instructions m_code.append(OP_PUSH, m_vars.append(pv, '')); literal := true; end; function islip_compiler.variable_rvalue(id : string) : boolean; var token : string; toktype : islip_parser_token_type; pv : pislip_var; v : pislip_cmp_var; sr, sc : size_t; begin variable_rvalue := false; // try to fetch an existing variable v := m_vars.get_var(id); // fetch next token if not m_parser.get_token(token, toktype) then begin writeln('ERROR: Unexpected end of file'); exit; end; // check if this is a literal if toktype = TT_STRING then begin new(pv); pv^ := islip_var.create(token); m_vars.append(pv, id); // if the variable already exists, it's been initialized // somewhere else already, so just pop the nev value into it; // otherwise it's a constant and doesn't even need to be put onto // the stack if v <> nil then begin // nullify the variable ID m_vars.m_tail^.id := ''; // the last one in the list will be the one we need m_code.append(OP_PUSH, m_vars.m_index); // FIXME: put index into islip_cmp_var m_code.append(OP_POP, m_vars.get_var_index(v^.id)); end; end else if literal(token) then begin // if the variable already exists, it's been initialized // somewhere else already, so just pop the top of the stack // into it if v = nil then begin // remove the last OP_PUSH and set variable identifier m_code.chop_tail; m_vars.m_tail^.id := id; end else // FIXME: put index into islip_cmp_var m_code.append(OP_POP, m_vars.get_var_index(v^.id)); end else begin m_parser.unget_token; // evaluate the expression if not eval_expr() then begin m_parser.get_pos(sr, sc); writeln('ERROR: Unable to evaluate expression at ', 'line ', sr, ', column ', sc); exit; end; // if the variable already exists, it's been initialized // somewhere else already, so just pop the top of the stack // into it if v <> nil then // FIXME: put index into islip_cmp_var m_code.append(OP_POP, m_vars.get_var_index(v^.id)) else begin new(pv); pv^ := islip_var.create; m_code.append(OP_POP, m_vars.append(pv, id)); end; end; variable_rvalue := true; end; function islip_compiler.is_valid_ident(s : string) : boolean; var i : size_t; begin if length(s) < 1 then begin is_valid_ident := false; exit; end; is_valid_ident := true; for i := 1 to length(s) do if not (s[i] in ['a'..'z', 'A'..'Z']) then begin is_valid_ident := false; exit; end; end; // ==================================================== // recursive expression evaluator // ==================================================== function islip_compiler.eval_expr : boolean; var token : string; toktype : islip_parser_token_type; sr, sc, op : size_t; v : pislip_var; mo : boolean; i : int; begin eval_expr := false; // i.e. expression is invalid if not (m_parser.get_token(token, toktype) and (length(token) > 0)) then begin writeln('ERROR: Unexpected end of file'); exit; end; {$IFDEF DEBUG} writeln('DEBUG: eval_expr: Token: "', token, '", token type: ', integer(toktype)); {$ENDIF} // basic math binary ops: +-*/% min max if (token = 'SUM') or (token = 'DIFF') or (token = 'PRODUKT') or (token = 'QUOSHUNT') or (token = 'MOD') or (token = 'BIGGR') or (token = 'SMALLR') then begin {$IFDEF DEBUG} writeln('DEBUG: eval_expr: basic math op'); {$ENDIF} // choose the opcode if token = 'SUM' then op := OP_ADD else if token = 'DIFF' then op := OP_SUB else if token = 'PRODUKT' then op := OP_MUL else if token = 'QUOSHUNT' then op := OP_DIV else if token = 'MOD' then op := OP_MOD else if token = 'BIGGR' then op := OP_MAX else //if token = 'SMALLR' then op := OP_MIN; if not m_parser.get_token(token, toktype) then begin writeln('ERROR: Unexpected end of file'); exit; end; if token <> 'OF' then begin m_parser.get_pos(sr, sc); writeln('ERROR: "OF" expected, but got "', token, '" at line ', sr, ', column ', sc); exit; end; // evaluate the first operand if not eval_expr() then exit; // read the "AN" keyword if not m_parser.get_token(token, toktype) then begin writeln('ERROR: Unexpected end of file'); exit; end; if token <> 'AN' then begin m_parser.get_pos(sr, sc); writeln('ERROR: "AN" expected, but got "', token, '" at line ', sr, ', column ', sc); exit; end; // evaluate the second operand if not eval_expr() then exit; // add the instruction m_code.append(op, ARG_NULL); // basic boolean ops: && == // oops! the BOTH keyword can start both an AND and an equality check, // thus the separate code block end else if token = 'BOTH' then begin {$IFDEF DEBUG} writeln('DEBUG: eval_expr: BOTH'); {$ENDIF} if not m_parser.get_token(token, toktype) then begin writeln('ERROR: Unexpected end of file'); exit; end; // boolean AND if token = 'OF' then begin // evaluate first operand if not eval_expr() then exit; // read the "AN" keyword if not m_parser.get_token(token, toktype) then begin writeln('ERROR: Unexpected end of file'); exit; end; if token <> 'AN' then begin m_parser.get_pos(sr, sc); writeln('ERROR: "AN" expected, but got "', token, '" at line ', sr, ', column ', sc); exit; end; // evaluate second operand if not eval_expr() then exit; // add the instruction m_code.append(OP_AND, ARG_NULL); // equality check end else if token = 'SAEM' then begin // evaluate first operand if not eval_expr() then exit; // read the "AN" keyword if not m_parser.get_token(token, toktype) then begin writeln('ERROR: Unexpected end of file'); exit; end; if token <> 'AN' then begin m_parser.get_pos(sr, sc); writeln('ERROR: "AN" expected, but got "', token, '" at line ', sr, ', column ', sc); exit; end; // evaluate second operand if not eval_expr() then exit; // add the instruction m_code.append(OP_EQ, ARG_NULL); end else begin m_parser.get_pos(sr, sc); writeln('ERROR: "OF" or "SAEM" expected, but got "', token, '" at line ', sr, ', column ', sc); exit; end; // basic boolean binary ops: || ^ end else if (token = 'EITHER') or (token = 'WON') then begin {$IFDEF DEBUG} writeln('DEBUG: eval_expr: basic boolean op'); {$ENDIF} // choose the opcode if token = 'EITHER' then op := OP_OR else //if token = 'WON' then op := OP_XOR; if not m_parser.get_token(token, toktype) then begin writeln('ERROR: Unexpected end of file'); exit; end; if token <> 'OF' then begin m_parser.get_pos(sr, sc); writeln('ERROR: "OF" expected, but got "', token, '" at line ', sr, ', column ', sc); exit; end; // evaluate the first operand if not eval_expr() then exit; // read the "AN" keyword if not m_parser.get_token(token, toktype) then begin writeln('ERROR: Unexpected end of file'); exit; end; if token <> 'AN' then begin m_parser.get_pos(sr, sc); writeln('ERROR: "AN" expected, but got "', token, '" at line ', sr, ', column ', sc); exit; end; // evaluate the second operand if not eval_expr() then exit; // add the instruction m_code.append(op, ARG_NULL); // inequation end else if token = 'DIFFRINT' then begin {$IFDEF DEBUG} writeln('DEBUG: eval_expr: inequation'); {$ENDIF} // evaluate the first operand if not eval_expr() then exit; // read the "AN" keyword if not m_parser.get_token(token, toktype) then begin writeln('ERROR: Unexpected end of file'); exit; end; if token <> 'AN' then begin m_parser.get_pos(sr, sc); writeln('ERROR: "AN" expected, but got "', token, '" at line ', sr, ', column ', sc); exit; end; // evaluate the second operand if not eval_expr() then exit; // add the instruction m_code.append(OP_NEQ, ARG_NULL); // negation end else if token = 'NOT' then begin {$IFDEF DEBUG} writeln('DEBUG: eval_expr: negation'); {$ENDIF} // evaluate the operand if not eval_expr() then exit; m_code.append(OP_NEG, ARG_NULL); // string concatenation end else if token = 'SMOOSH' then begin {$IFDEF DEBUG} writeln('DEBUG: eval_expr: string concatenation'); {$ENDIF} // do we have more than 1 operand? mo := false; while true do begin if not m_parser.get_token(token, toktype) then begin writeln('ERROR: Unexpected end of file'); exit; end; if ((toktype = TT_EXPR) and (token = 'MKAY')) or ((length(token) = 1) and (token[1] in [chr(10), chr(13)])) then break; m_parser.unget_token; if not eval_expr() then exit; // only append the instruction if have anything to concat if mo then m_code.append(OP_CONCAT, ARG_NULL) else mo := true; end; // string constant end else if toktype = TT_STRING then begin {$IFDEF DEBUG} writeln('DEBUG: eval_expr: string constant'); {$ENDIF} // create a new var and get it into the list new(v); v^ := islip_var.create(token); // generate the instructions m_code.append(OP_PUSH, m_vars.append(v, '')); // either a variable identifier, or a number or boolean literal end else if not literal(token) then begin // check for illegal characters if not is_valid_ident(token) then begin m_parser.get_pos(sr, sc); writeln('ERROR: Invalid characters in identifier at line ', sr, ', column ', sc); exit; end; {$IFDEF DEBUG} writeln('DEBUG: eval_expr: identifier ', token); {$ENDIF} // FIXME: search for functions, too // FIXME: implement them first! i := m_vars.get_var_index(token); if i = 0 then begin m_parser.get_pos(sr, sc); writeln('ERROR: Unknown identifier "', token, '" at line ', sr, ', column ', sc); exit; end; // generate the instruction m_code.append(OP_PUSH, i); end; eval_expr := true; end; // ==================================================== // recursive statement evaluator // ==================================================== function islip_compiler.eval_statement(gtfo : pislip_cmp_ipcont) : boolean; var token, id : string; toktype : islip_parser_token_type; sr, sc, tmp : size_t; pv : pislip_var; v : pislip_cmp_var; i : pislip_cmp_inst; flowstate : islip_flowstate; ipcont : islip_cmp_ipcont; begin eval_statement := false; if not (m_parser.get_token(token, toktype) and (length(token) > 0)) then begin writeln('ERROR: Unexpected end of file'); exit; end; // skip newlines if (length(token) = 1) and (token[1] in [chr(10), chr(13)]) then begin eval_statement := true; exit; end; {$IFDEF DEBUG} writeln('DEBUG: eval_statement: Token: "', token, '", type: ', int(toktype)); {$ENDIF} if token = 'CAN' then begin // fetch next token if not m_parser.get_token(token, toktype) then begin writeln('ERROR: Unexpected end of file'); exit; end; if token <> 'HAS' then begin m_parser.get_pos(sr, sc); writeln('ERROR: "HAS" expected, but got "', token, '" at line ', sr, ', column ', sc); exit; end; // fetch next token if not m_parser.get_token(token, toktype) then begin writeln('ERROR: Unexpected end of file'); exit; end; if token[length(token)] = '?' then begin // remove the question mark delete(token, length(token), 1); // see if we recognize the library // FIXME: allow inlcusion of third-party files if (token <> 'STDIO') and (token <> 'MAHZ') then begin writeln('ERROR: Unknown module "', token, '"'); exit; end else {$IFDEF DEBUG} writeln('DEBUG: Including module "', token, '"'); {$ENDIF} end; // conditional end else if token = 'O' then begin // fetch next token if not m_parser.get_token(token, toktype) then begin writeln('ERROR: Unexpected end of file'); exit; end; if token <> 'RLY?' then begin m_parser.get_pos(sr, sc); writeln('ERROR: "RLY?" expected, but got "', token, '" at ', 'line ', sr, ', column ', sc); exit; end; // fetch next token; there may be newlines before it while true do begin if not m_parser.get_token(token, toktype) then begin writeln('ERROR: Unexpected end of file'); exit; end; if (length(token) = 1) and (token[1] in [chr(10), chr(13)]) then continue else if token <> 'YA' then begin m_parser.get_pos(sr, sc); writeln('ERROR: "YA" expected, but got "', token, '" at ', 'line ', sr, ', column ', sc); exit; end else break; end; // fetch next token if not m_parser.get_token(token, toktype) then begin writeln('ERROR: Unexpected end of file'); exit; end; if token <> 'RLY' then begin m_parser.get_pos(sr, sc); writeln('ERROR: "RLY" expected, but got "', token, '" at ', 'line ', sr, ', column ', sc); exit; end; // create an instruction container ipcont := islip_cmp_ipcont.create; // push IT onto the stack m_code.append(OP_PUSH, 1); // save off the instruction information; jump offset will be updated // later on i := m_code.append(OP_CNDJMP, ARG_NULL); // evaluate statements until we hit another flow control statement flowstate := FS_IF; while m_parser.get_token(token, toktype) do begin // check for the end of the block if token = 'OIC' then begin if flowstate <> FS_ELSE then i^.arg := m_code.m_count + 1; flowstate := FS_LINEAR; end; // this is intentional - there SHOULD NOT be an "else" here! if flowstate = FS_LINEAR then begin // optimize code and update jump offset optimize(i); break; // end of conditional block altogether end else if flowstate in [FS_IF, FS_ELSEIF] then begin // elseif if token = 'MEBBE' then begin // optimize the code so far and update the jump offset; the // +2 accounts for the jump we're about to add optimize(i); i^.arg := m_code.m_count + 2; // add the jump to after the block on success ipcont.add(m_code.append(OP_JMP, ARG_NULL)); // set next state flowstate := FS_ELSEIF; // evaluate the condition if not eval_expr() then begin m_parser.get_pos(sr, sc); writeln('ERROR: Unable to evaluate expression at ', 'line ', sr, ', column ', sc); exit; end; // save off the instruction information; jump offset will // be updated later on i := m_code.append(OP_CNDJMP, ARG_NULL); continue; // else end else if (toktype = TT_EXPR) and (token = 'NO') then begin // fetch next token if not m_parser.get_token(token, toktype) then begin writeln('ERROR: Unexpected end of file'); exit; end; if token <> 'WAI' then begin m_parser.get_pos(sr, sc); writeln('ERROR: "WAI" expected, but got "', token, '" at line ', sr, ', column ', sc); exit; end; // optimize the code so far and update the jump offset; the // +2 accounts for the jump we're about to add; it's there // to skip the "else" block and we absolutely need it // because there's no condition that can be checked optimize(i); i^.arg := m_code.m_count + 2; // set next state flowstate := FS_ELSE; ipcont.add(m_code.append(OP_JMP, ARG_NULL)); continue; end; end; // otherwise just parse the statement m_parser.unget_token; if not eval_statement(gtfo) then exit; // the recursive instance will have raised an error end; if flowstate <> FS_LINEAR then begin writeln('ERROR: Unexpected end of file'); exit; end; // fill the arguments of the saved instructions and clean up the mess ipcont.fill(m_code.m_count + 1); ipcont.destroy; // switch end else if token = 'WTF?' then begin flowstate := FS_LINEAR; // create an instruction container ipcont := islip_cmp_ipcont.create; while m_parser.get_token(token, toktype) do begin // check for the end of the block if token = 'OIC' then begin // if we haven't entered a switch statement yet, the pointer i // will be invalid if flowstate <> FS_LINEAR then begin // optimize code and update jump offset optimize(i); if i^.arg = ARG_NULL then i^.arg := m_code.m_count + 1; flowstate := FS_LINEAR; end; break; // end of block end; if flowstate in [FS_LINEAR, FS_SWITCH] then begin if token = 'OMG' then begin // if we've come here from a switch block, finish it up and // make a jump over the condition check; we only leave the // block on GTFO if flowstate = FS_SWITCH then begin // optimize the code so far and update the jump offset optimize(i); // so that it points on OP_PUSH i^.arg := m_code.m_count + 2; // so that it points on after the check m_code.append(OP_JMP, m_code.m_count + 5); end else // set new state flowstate := FS_SWITCH; // push IT onto the stack m_code.append(OP_PUSH, 1); // read literal if not m_parser.get_token(token, toktype) then begin writeln('ERROR: Unexpected end of file'); exit; end; if toktype = TT_STRING then begin new(pv); pv^ := islip_var.create(token); m_code.append(OP_PUSH, m_vars.append(pv, '')); end else if not literal(token) then begin m_parser.get_pos(sr, sc); writeln('ERROR: Literal expected, but got "', token, '" at line ', sr, ', column ', sc); exit; end; // condition check m_code.append(OP_EQ, ARG_NULL); // save off the instruction information; jump offset will // be updated later on i := m_code.append(OP_CNDJMP, ARG_NULL); continue; end else if (flowstate = FS_SWITCH) and (token = 'OMGWTF') then begin // optimize the code so far and update the jump offset // the +2 accounts for the unconditional jump we're about // to add; it's there to skip the "else" block and we // absolutely need it because there's no condition that can // be checked optimize(i); i^.arg := m_code.m_count + 2; // set next state flowstate := FS_ELSE; // save off the instruction information; jump offset will // be updated later on ipcont.add(m_code.append(OP_JMP, ARG_NULL)); continue; end else if (flowstate = FS_SWITCH) and (token = 'GTFO') then begin // just add a jump out of the block ipcont.add(m_code.append(OP_JMP, ARG_NULL)); continue; end; end; // just parse the statement m_parser.unget_token; if not eval_statement(nil) then exit; // the recursive instance will have raised an error end; if flowstate <> FS_LINEAR then begin writeln('ERROR: Unexpected end of file'); exit; end; // fill the arguments of the saved instructions and clean up the mess ipcont.fill(m_code.m_count + 1); ipcont.destroy; // loop end else if token = 'IM' then begin // fetch next token if not m_parser.get_token(token, toktype) then begin writeln('ERROR: Unexpected end of file'); exit; end; if token <> 'IN' then begin m_parser.get_pos(sr, sc); writeln('ERROR: "IN" expected, but got "', token, '" at ', 'line ', sr, ', column ', sc); exit; end; // fetch next token if not m_parser.get_token(token, toktype) then begin writeln('ERROR: Unexpected end of file'); exit; end; if token <> 'YR' then begin m_parser.get_pos(sr, sc); writeln('ERROR: "YR" expected, but got "', token, '" at ', 'line ', sr, ', column ', sc); exit; end; // read loop label if not m_parser.get_token(token, toktype) then begin writeln('ERROR: Unexpected end of file'); exit; end; id := token; // mark the beginning of the loop sr := m_code.m_count + 1; // read loop operation flowstate := FS_LOOP; // fetch next token if not m_parser.get_token(token, toktype) then begin writeln('ERROR: Unexpected end of file'); exit; end; ipcont := islip_cmp_ipcont.create;; if (token = 'UPPIN') or (token = 'NERFIN') then begin // reuse the variable to mark the operation if token[1] = 'U' then sc := 1 else sc := 2; // fetch next token if not m_parser.get_token(token, toktype) then begin writeln('ERROR: Unexpected end of file'); exit; end; if token <> 'YR' then begin m_parser.get_pos(sr, sc); writeln('ERROR: "YR" expected, but got "', token, '" at ', 'line ', sr, ', column ', sc); exit; end; // fetch next token if not m_parser.get_token(token, toktype) then begin writeln('ERROR: Unexpected end of file'); exit; end; // check for illegal characters if not is_valid_ident(token) then begin m_parser.get_pos(sr, sc); writeln('ERROR: Invalid characters in identifier at line ', sr, ', column ', sc); exit; end; // FIXME: search for functions, too // FIXME: implement them first! tmp := m_vars.get_var_index(token); if tmp = 0 then begin m_parser.get_pos(sr, sc); writeln('ERROR: Unknown identifier "', token, '" at line ', sr, ', column ', sc); exit; end; // check if we have a loop condition if not m_parser.get_token(token, toktype) then begin writeln('ERROR: Unexpected end of file'); exit; end; if (token = 'TIL') or (token = 'WILE') then begin // evaluate the expression if not eval_expr() then begin m_parser.get_pos(sr, sc); writeln('ERROR: Unable to evaluate expression at ', 'line ', sr, ', column ', sc); exit; end; // TIL will keep the loop running if the condition is false, // while WILE will do so when it's true, so add a negation for // TIL if token[1] = 'T' then m_code.append(OP_NEG, ARG_NULL); // add a conditional jump out of the loop ipcont.add(m_code.append(OP_CNDJMP, ARG_NULL)); end else begin m_parser.get_pos(sr, sc); writeln('ERROR: "TIL" or "WILE" expected, but got "', token, '" at line ', sr, ', column ', sc); exit; end; end else begin // else it's an infinite loop sc := 0; m_parser.unget_token; end; while true do begin // look for the loop closing statement // fetch next token if not m_parser.get_token(token, toktype) then begin writeln('ERROR: Unexpected end of file'); exit; end; if token = 'IM' then begin // fetch next token if not m_parser.get_token(token, toktype) then begin writeln('ERROR: Unexpected end of file'); exit; end; if token = 'OUTTA' then begin // fetch next token if not m_parser.get_token(token, toktype) then begin writeln('ERROR: Unexpected end of file'); exit; end; if token <> 'YR' then begin m_parser.get_pos(sr, sc); writeln('ERROR: "YR" expected, but got "', token, '" at line ', sr, ', column ', sc); exit; end; // fetch next token if not m_parser.get_token(token, toktype) then begin writeln('ERROR: Unexpected end of file'); exit; end; if token = id then begin // add incrementation/decrementation, if relevant if sc = 1 then begin m_code.append(OP_PUSH, tmp); m_code.append(OP_INCR, 1); m_code.append(OP_POP, tmp); end else if sc = 2 then begin m_code.append(OP_PUSH, tmp); m_code.append(OP_INCR, 0); m_code.append(OP_POP, tmp); end; // add a jump to the beginning of the loop m_code.append(OP_JMP, sr); flowstate := FS_LINEAR; break; end else begin // need to unget 3 tokens (loop label, YR and OUTTA) // IM will be taken care of later on m_parser.unget_token; m_parser.unget_token; m_parser.unget_token; end; end; m_parser.unget_token; end; // just parse the statement m_parser.unget_token; if not eval_statement(@ipcont) then exit; // the recursive instance will have raised an error end; if flowstate <> FS_LINEAR then begin writeln('ERROR: Unexpected end of file'); exit; end; ipcont.fill(m_code.m_count + 1); ipcont.destroy; // variable creation (and optionally assignment) end else if token = 'I' then begin // fetch next token if not m_parser.get_token(token, toktype) then begin writeln('ERROR: Unexpected end of file'); exit; end; if token <> 'HAS' then begin m_parser.get_pos(sr, sc); writeln('ERROR: "HAS" expected, but got "', token, '" at line ', sr, ', column ', sc); exit; end; // fetch next token if not m_parser.get_token(token, toktype) then begin writeln('ERROR: Unexpected end of file'); exit; end; if token <> 'A' then begin m_parser.get_pos(sr, sc); writeln('ERROR: "A" expected, but got "', token, '" at line ', sr, ', column ', sc); exit; end; // fetch next token if not m_parser.get_token(token, toktype) then begin writeln('ERROR: Unexpected end of file'); exit; end; // check if it's a valid identifier if not is_valid_ident(token) then begin m_parser.get_pos(sr, sc); writeln('ERROR: Invalid characters in identifier at ', 'line ', sr, ', column ', sc); exit; end; // save off the identifier id := token; // read the next part of the assignment statement if not m_parser.get_token(token, toktype) then begin writeln('ERROR: Unexpected end of file'); exit; end; if token <> 'ITZ' then begin // unget the token for reevaluation m_parser.unget_token; // add an untyped var new(pv); pv^ := islip_var.create; m_vars.append(pv, id); // else try reading the R-value end else if not variable_rvalue(id) then exit; // we rely on variable_rvalue to raise errors end else if token = 'MAEK' then begin if not m_parser.get_token(token, toktype) then begin writeln('ERROR: Unexpected end of file'); exit; end; // check for illegal characters if not is_valid_ident(token) then begin m_parser.get_pos(sr, sc); writeln('ERROR: Invalid characters in identifier at line ', sr, ', column ', sc); exit; end; // fail if the variable doesn't exist sr := m_vars.get_var_index(token); if sr = 0 then begin m_parser.get_pos(sr, sc); writeln('ERROR: Unknown identifier "', token, '" at line ', sr, ', column ', sc); exit; end; // check for "A" if not m_parser.get_token(token, toktype) then begin writeln('ERROR: Unexpected end of file'); exit; end; if token <> 'A' then begin m_parser.get_pos(sr, sc); writeln('ERROR: "A" expected, but got "', token, '" at line ', sr, ', column ', sc); exit; end; // check for type if not m_parser.get_token(token, toktype) then begin writeln('ERROR: Unexpected end of file'); exit; end; m_code.append(OP_PUSH, sr); if token = 'NOOB' then m_code.append(OP_CAST, int(VT_UNTYPED)) else if token = 'TROOF' then m_code.append(OP_CAST, int(VT_BOOL)) else if token = 'NUMBR' then m_code.append(OP_CAST, int(VT_INT)) else if token = 'NUMBAR' then m_code.append(OP_CAST, int(VT_FLOAT)) else if token = 'YARN' then m_code.append(OP_CAST, int(VT_STRING)) else begin m_parser.get_pos(sr, sc); writeln('ERROR: Expected a type name, but got "', token, '" at line ', sr, ', column ', sc); exit; end; m_code.append(OP_POP, sr); end else if (token = 'VISIBLE') or (token = 'INVISIBLE') then begin // put the value on the stack and print it if not eval_expr() then begin m_parser.get_pos(sr, sc); writeln('ERROR: Unable to evaluate expression at ', 'line ', sr, ', column ', sc); exit; end; // differentiate between stdio and stderr if token[1] = 'I' then m_code.append(OP_PRINT, 1) else m_code.append(OP_PRINT, ARG_NULL); end else if token = 'GIMMEH' then begin if not m_parser.get_token(token, toktype) then begin writeln('ERROR: Unexpected end of file'); exit; end; // check for illegal characters if not is_valid_ident(token) then begin m_parser.get_pos(sr, sc); writeln('ERROR: Invalid characters in identifier at line ', sr, ', column ', sc); exit; end; // if the variable doesn't exist, create it sr := m_vars.get_var_index(token); if sr = ARG_NULL then begin new(pv); pv^ := islip_var.create; sr := m_vars.append(pv, token); end; m_code.append(OP_READ, ARG_NULL); m_code.append(OP_POP, sr); // HACK HACK HACK!!! a not-so-ellegant way of catching loop breaks end else if (gtfo <> nil) and (token = 'GTFO') then gtfo^.add(m_code.append(OP_JMP, ARG_NULL)) // exit from program // NOTE: a custom extension, not included in the spec else if token = 'KTHX' then m_code.append(OP_STOP, ARG_NULL) else begin // look for a variable first v := m_vars.get_var(token); if v <> nil then begin // fetch next token if not m_parser.get_token(token, toktype) then begin writeln('ERROR: Unexpected end of file'); exit; end; if token = 'R' then begin // we have an assignation here if not variable_rvalue(v^.id) then exit; // rely on variable_rvalue to raise errors // manual exit w/success eval_statement := true; exit; end else m_parser.unget_token; end; m_parser.unget_token; // try to evaluate the "IT" implied variable, which is // always on slot #1 if eval_expr then begin m_code.append(OP_POP, 1); end else begin m_parser.get_pos(sr, sc); writeln('ERROR: Unknown keyword "', token, '" at line ', sr, ', column ', sc); exit; end; end; eval_statement := true; end; function islip_compiler.compile : boolean; var token : string; toktype : islip_parser_token_type; state : islip_cmp_state; sr, sc : size_t; pv : pislip_var; bye : boolean; begin compile := false; bye := false; // initialization state := CS_UNDEF; // create the implied "IT" variable new(pv); pv^ := islip_var.create; m_vars.append(pv, 'IT'); while m_parser.get_token(token, toktype) and (length(token) > 0) do begin {$IFDEF DEBUG} writeln('DEBUG: compile: Token: "', token, '" type ', int(toktype), ', state: ', int(state)); {$ENDIF} case state of CS_UNDEF: begin if token <> 'HAI' then begin m_parser.get_pos(sr, sc); writeln('ERROR: Unknown token "', token, '" at line ', sr, ', column ', sc); exit; end; if not m_parser.get_token(token, toktype) then begin writeln('ERROR: Unexpected end of file'); exit; end; // the version number might've been omitted if (length(token) = 1) and (token[1] in [chr(10), chr(13)]) then begin state := CS_STATEMENT; continue; end; if token <> LOLCODE_VERSION then begin m_parser.get_pos(sr, sc); writeln('ERROR: Unsupported language version "', token, '" at line ', sr, ', column ', sc); exit; end; state := CS_STATEMENT; end; CS_STATEMENT: begin // end of program if token = 'KTHXBYE' then begin m_code.append(OP_STOP, ARG_NULL); token := ''; bye := true; break; end; // unget token for reevaluation m_parser.unget_token; if not eval_statement(nil) then begin //writeln('ERROR: Unable to parse script'); compile := false; exit; end; end; end; end; if not bye then begin writeln('ERROR: Script is missing termination ("KTHXBYE")'); compile := false; exit; end; // run optimizations optimize(m_code.m_head); m_done := true; compile := true; end; // FIXME: try to make it context-sensitive so that it doesn't break code procedure islip_compiler.optimize(start : pislip_cmp_inst); {var prev, temp : pislip_cmp_inst;} begin {prev := nil; repeat // unlink contiguous pops and pushes of the same variable if (start^.next <> nil) and (start^.i = OP_POP) and (start^.next^.i = OP_PUSH) and (start^.arg = start^.next^.arg) then begin // unlink the instructions if prev <> nil then prev^.next := start^.next^.next else m_code.m_head := start^.next^.next; temp := start; start := start^.next^.next; dispose(temp^.next); dispose(temp); dec(m_code.m_count, 2); end else begin prev := start; start := start^.next; end; until start = nil;} end; procedure islip_compiler.get_products(var c : islip_bytecode; var d : islip_data); var pi : pislip_cmp_inst; pv : pislip_cmp_var; i : int; begin if not m_done then begin writeln('ERROR: Attempted to retrieve compilation products before ', 'compilation'); exit; end; // resize the arrays accordingly setlength(c, integer(m_code.m_count)); setlength(d, integer(m_vars.m_index)); // copy the stuff from the lists to the arrays i := 1; pv := m_vars.m_head; while pv <> nil do begin d[i] := pv^.v^; pv := pv^.next; inc(i); end; i := 1; pi := m_code.m_head; while pi <> nil do begin c[i].inst := pi^.i; c[i].arg := pi^.arg; pi := pi^.next; inc(i); end; end; // ==================================================== // variable container implementation // ==================================================== constructor islip_cmp_var_cont.create; begin m_head := nil; m_tail := nil; m_index := 0; end; destructor islip_cmp_var_cont.destroy; var p1, p2 : pislip_cmp_var; begin p1 := m_head; while p1 <> nil do begin p2 := p1; p1 := p1^.next; //p2^.v^.destroy; dispose(p2^.v); dispose(p2); end; end; function islip_cmp_var_cont.append(v : pislip_var; id : string) : size_t; var p : pislip_cmp_var; begin inc(m_index); append := m_index; new(p); p^.v := v; p^.id := id; p^.next := nil; if m_head = nil then begin m_head := p; m_tail := p; end else begin m_tail^.next := p; m_tail := p; end; end; function islip_cmp_var_cont.get_var_index(id : string) : size_t; var p : pislip_cmp_var; i : size_t; begin get_var_index := ARG_NULL; i := 1; p := m_head; while p <> nil do begin if p^.id = id then begin get_var_index := i; exit; end; p := p^.next; inc(i); end; end; function islip_cmp_var_cont.get_var(id : string) : pislip_cmp_var; var p : pislip_cmp_var; i : size_t; begin get_var := nil; i := 0; p := m_head; while p <> nil do begin if p^.id = id then begin get_var := p; exit; end; p := p^.next; inc(i); end; get_var := nil; end; // ==================================================== // instruction container implementation // ==================================================== constructor islip_cmp_code_cont.create; begin m_head := nil; m_tail := nil; m_count := 0; end; destructor islip_cmp_code_cont.destroy; var p1, p2 : pislip_cmp_inst; begin p1 := m_head; while p1 <> nil do begin p2 := p1; p1 := p1^.next; dispose(p2); end; end; function islip_cmp_code_cont.append(i : byte; arg : size_t) : pislip_cmp_inst; var p : pislip_cmp_inst; begin inc(m_count); new(p); p^.i := i; p^.arg := arg; p^.next := nil; if m_head = nil then begin m_head := p; m_tail := p; end else begin m_tail^.next := p; m_tail := p; end; append := p; end; procedure islip_cmp_code_cont.chop_tail; var p : pislip_cmp_inst; begin if m_tail = nil then exit; dec(m_count); if m_head = m_tail then begin m_head := nil; dispose(m_tail); m_tail := nil; exit; end; p := m_head; while p^.next <> m_tail do p := p^.next; dispose(p^.next); m_tail := p; end; // ==================================================== // jump instruction container implementation // ==================================================== constructor islip_cmp_ipcont.create; begin m_head := nil; m_tail := nil; end; procedure islip_cmp_ipcont.fill(ofs : int); var p1, p2 : pislip_cmp_ip; begin p1 := m_head; while p1 <> nil do begin p1^.i^.arg := ofs; p2 := p1; p1 := p1^.next; dispose(p2); end; m_head := nil; m_tail := nil; end; procedure islip_cmp_ipcont.add(i : pislip_cmp_inst); var p : pislip_cmp_ip; begin new(p); p^.i := i; p^.next := nil; if m_tail <> nil then m_tail^.next := p else m_head := p; m_tail := p; end; end.
unit dbx_FB_no_ini; (* How to deploy a database application without a DBXDrivers.ini file. XE2 + Firebird 2.x port, with some tweaks. Original: http://andy.jgknet.de/blog/2010/11/dbx-without-deploying-dbxdrivers-ini/ Now: https://www.idefixpack.de/blog/2010/11/dbx-without-deploying-dbxdrivers-ini/ Quote: If you want to connect to an other database vendor, you have to adjust the string literals in TDBXInternalProperties.Create and the driver name in the RegisterDriverClass(СMySQLТ, ..) call. I could not override DBX "Interbase" driver with this trick, perhaps dbx4 FB driver has some extra checks inside. So moving the dbx3 project to dbx4 requires driver name change. One can also use this as a sample to load Firebird Embedded DLL into dbExpress 4 based application without dirty tricks like renaming Firebird DLLs. *) interface implementation uses DBXCommon, DBXDynalinkNative, Data.DBXFirebird {required for connection!!!}; type TDBXInternalDriver = class(TDBXDynalinkDriverNative) public constructor Create(DriverDef: TDBXDriverDef); override; end; TDBXInternalProperties = class(TDBXProperties) public constructor Create(DBXContext: TDBXContext); override; end; { TDBXInternalDriver } constructor TDBXInternalDriver.Create(DriverDef: TDBXDriverDef); begin inherited Create(DriverDef, TDBXDynalinkDriverLoader); InitDriverProperties(TDBXInternalProperties.Create(DriverDef.FDBXContext)); end; { TDBXInternalProperties } constructor TDBXInternalProperties.Create(DBXContext: TDBXContext); begin inherited Create(DBXContext); (* DriverUnit=Data.DBXFirebird DriverPackageLoader=TDBXDynalinkDriverLoader,DbxCommonDriver160.bpl DriverAssemblyLoader=Borland.Data.TDBXDynalinkDriverLoader,Borland.Data.DbxCommonDriver,Version=16.0.0.0,Culture=neutral,PublicKeyToken=91d62ebb5b0d1b1b MetaDataPackageLoader=TDBXFirebirdMetaDataCommandFactory,DbxFirebirdDriver160.bpl MetaDataAssemblyLoader=Borland.Data.TDBXFirebirdMetaDataCommandFactory,Borland.Data.DbxFirebirdDriver,Version=16.0.0.0,Culture=neutral,PublicKeyToken=91d62ebb5b0d1b1b GetDriverFunc=getSQLDriverINTERBASE LibraryName=dbxfb.dll LibraryNameOsx=libsqlfb.dylib VendorLib=fbclient.dll VendorLibWin64=fbclient.dll VendorLibOsx=/Library/Frameworks/Firebird.framework/Firebird BlobSize=-1 CommitRetain=False Database=database.fdb ErrorResourceFile= LocaleCode=0000 Password=masterkey RoleName=RoleName ServerCharSet= SQLDialect=3 IsolationLevel=ReadCommitted User_Name=sysdba WaitOnLocks=True Trim Char=False *) Values[TDBXPropertyNames.DriverUnit] := ''; // This is for the IDE only Values[TDBXPropertyNames.GetDriverFunc] := 'getSQLDriverINTERBASE'; Values[TDBXPropertyNames.LibraryName] := 'dbxfb.dll'; Values[TDBXPropertyNames.VendorLib] := 'fbclient.dll'; // Values[TDBXPropertyNames.VendorLibWin64] := 'fbclient.dll'; Values[TDBXPropertyNames.Database] := 'DatabaseName.fdb'; Values[TDBXPropertyNames.UserName] := 'sysdba'; Values[TDBXPropertyNames.Password] := 'masterkey'; Values[TDBXPropertyNames.MaxBlobSize] := '-1'; Values['WaitOnLocks'] := 'True'; Values['Trim Char'] := 'False'; Values['SQLDialect'] := '3'; Values['CommitRetain'] := 'False'; Values['DriverUnit'] := 'Data.DBXFirebird'; // Values['DriverPackageLoader'] := 'TDBXDynalinkDriverLoader,DbxCommonDriver160.bpl'; // Values['DriverAssemblyLoader'] := 'Borland.Data.TDBXDynalinkDriverLoader,Borland.Data.DbxCommonDriver,Version=16.0.0.0,Culture=neutral,PublicKeyToken=91d62ebb5b0d1b1b'; // Values['MetaDataPackageLoader'] := 'TDBXFirebirdMetaDataCommandFactory,DbxFirebirdDriver160.bpl'; // Values['MetaDataAssemblyLoader'] := 'Borland.Data.TDBXFirebirdMetaDataCommandFactory,Borland.Data.DbxFirebirdDriver,Version=16.0.0.0,Culture=neutral,PublicKeyToken=91d62ebb5b0d1b1b'; end; var InternalConnectionFactory: TDBXMemoryConnectionFactory; initialization TDBXDriverRegistry.RegisterDriverClass('Firebird', TDBXInternalDriver); // TDBXDriverRegistry.RegisterDriverClass('Interbase', TDBXInternalDriver); // не помогает, надо править параметры TSQLConnection // this does not work, one has to override driver name in TSQLConnection InternalConnectionFactory := TDBXMemoryConnectionFactory.Create; InternalConnectionFactory.Open; TDBXConnectionFactory.SetConnectionFactory(InternalConnectionFactory); end.
unit WpcStatementProperties; {$mode objfpc}{$H+} interface uses Classes, SysUtils, WpcCommonTypes, WpcExceptions; type { TWpcDelayStatementProperty } TWpcDelayStatementProperty = class(TObject) public const MAX_DELAY_VALUE = 1000 * 60 * 60 * 24 * 32; private FDelay: LongWord; // milliseconds public procedure SetDelay(PDelay : LongWord); procedure SetDelay(PDelay : LongWord; MeasurementUnit : TWpcTimeMeasurementUnits); public property Delay : LongWord read FDelay write SetDelay default 0; public class function ConvertToMilliseconds(PDelay : LongWord; MeasurementUnit : TWpcTimeMeasurementUnits) : LongWord; end; { TWpcProbabilityStatementProperty } TWpcProbabilityStatementProperty = class(TObject) private FProbability: Byte; // percents procedure SetProbability(Probability: Byte); public property Probability : Byte read FProbability write SetProbability default 100; end; { TWpcTimesStatementProperty } TWpcTimesStatementProperty = class(TObject) private FTimes: LongWord; procedure SetTimes(Times: LongWord); public property Times : LongWord read FTimes write SetTimes default 1; end; { TWpcWeightStatementProperty } TWpcWeightStatementProperty = class(TObject) private FWeight: LongWord; procedure SetWeight(Weight: LongWord); public property Weight : LongWord read FWeight write SetWeight default 1; end; implementation { TWpcDelayStatementProperty } procedure TWpcDelayStatementProperty.SetDelay(PDelay: LongWord); begin if (PDelay > MAX_DELAY_VALUE) then raise TWpcIllegalArgumentException.Create('Too long wait time.'); FDelay := PDelay; end; procedure TWpcDelayStatementProperty.SetDelay(PDelay : LongWord; MeasurementUnit : TWpcTimeMeasurementUnits); begin FDelay := ConvertToMilliseconds(PDelay, MeasurementUnit); end; {$Q+} class function TWpcDelayStatementProperty.ConvertToMilliseconds(PDelay: LongWord; MeasurementUnit: TWpcTimeMeasurementUnits): LongWord; begin try case MeasurementUnit of MILLISECONDS: Result := PDelay; SECONDS: Result := PDelay * 1000; MINUTES: Result := PDelay * 1000 * 60; HOURS: Result := PDelay * 1000 * 60 * 60; DAYS: Result := PDelay * 1000 * 60 * 60 * 24; else raise TWpcIllegalArgumentException.Create('Wrong wait time measurement unit.'); end; except on EIntOverflow do raise TWpcIllegalArgumentException.Create('Delay is too big.'); end; end; {$Q-} { TWpcProbabilityStatementProperty } procedure TWpcProbabilityStatementProperty.SetProbability(Probability: Byte); begin if ((Probability < 0) or (Probability > 100)) then raise TWpcIllegalArgumentException.Create('Probability should be in percents.'); FProbability := Probability; end; { TWpcTimesStatementProperty } procedure TWpcTimesStatementProperty.SetTimes(Times: LongWord); begin if (Times < 1 ) then raise TWpcIllegalArgumentException.Create('Times should be positive number.'); FTimes:=Times; end; { TWpcWeightStatementProperty } procedure TWpcWeightStatementProperty.SetWeight(Weight: LongWord); begin if (Weight < 1) then raise TWpcIllegalArgumentException.Create('Weight value should be positive.'); FWeight := Weight; end; end.
{ Copyright (C) <2005> <Andrew Haines> chmfilewriter.pas This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } { See the file COPYING.FPC, included in this distribution, for details about the copyright. } unit chmfilewriter; {$mode objfpc}{$H+} interface uses Classes, SysUtils, chmwriter; type TChmProject = class; TChmProgressCB = procedure (Project: TChmProject; CurrentFile: String) of object; { TChmProject } TChmProject = class private FAutoFollowLinks: Boolean; FDefaultFont: String; FDefaultPage: String; FFiles: TStrings; FIndexFileName: String; FMakeBinaryTOC: Boolean; FMakeBinaryIndex: Boolean; FMakeSearchable: Boolean; FFileName: String; FOnProgress: TChmProgressCB; FOutputFileName: String; FTableOfContentsFileName: String; FTitle: String; protected function GetData(const DataName: String; out PathInChm: String; out FileName: String; var Stream: TStream): Boolean; procedure LastFileAdded(Sender: TObject); public constructor Create; destructor Destroy; override; procedure LoadFromFile(AFileName: String); procedure SaveToFile(AFileName: String); procedure WriteChm(AOutStream: TStream); function ProjectDir: String; // though stored in the project file, it is only there for the program that uses the unit // since we actually write to a stream property OutputFileName: String read FOutputFileName write FOutputFileName; property FileName: String read FFileName write FFileName; property Files: TStrings read FFiles write FFiles; property AutoFollowLinks: Boolean read FAutoFollowLinks write FAutoFollowLinks; property TableOfContentsFileName: String read FTableOfContentsFileName write FTableOfContentsFileName; property MakeBinaryTOC: Boolean read FMakeBinaryTOC write FMakeBinaryTOC; property MakeBinaryIndex: Boolean read FMakeBinaryIndex write FMakeBinaryIndex; property Title: String read FTitle write FTitle; property IndexFileName: String read FIndexFileName write FIndexFileName; property MakeSearchable: Boolean read FMakeSearchable write FMakeSearchable; property DefaultPage: String read FDefaultPage write FDefaultPage; property DefaultFont: String read FDefaultFont write FDefaultFont; property OnProgress: TChmProgressCB read FOnProgress write FOnProgress; end; implementation uses XmlCfg, chmsitemap; { TChmProject } function TChmProject.GetData(const DataName: String; out PathInChm: String; out FileName: String; var Stream: TStream): Boolean; begin Result := False; // Return true to abort compressing files TMemoryStream(Stream).LoadFromFile(ProjectDir+DataName); // clean up the filename FileName := StringReplace(ExtractFileName(DataName), '\', '/', [rfReplaceAll]); FileName := StringReplace(FileName, '//', '/', [rfReplaceAll]); PathInChm := '/'+ExtractFilePath(DataName); if Assigned(FOnProgress) then FOnProgress(Self, DataName); end; procedure TChmProject.LastFileAdded(Sender: TObject); var IndexStream: TFileStream; TOCStream: TFileStream; Writer: TChmWriter; TOCSitemap : TChmSiteMap; IndexSiteMap: TChmSiteMap; begin // Assign the TOC and index files Writer := TChmWriter(Sender); {$ifdef chmindex} Writeln('binindex filename ',IndexFileName); {$endif} if (IndexFileName <> '') and FileExists(IndexFileName) then begin IndexStream := TFileStream.Create(IndexFileName, fmOpenRead); Writer.AppendIndex(IndexStream); if MakeBinaryIndex then begin {$ifdef chmindex} Writeln('into binindex '); {$endif} IndexStream.Position := 0; IndexSitemap := TChmSiteMap.Create(stIndex); indexSitemap.LoadFromStream(IndexStream); Writer.AppendBinaryIndexFromSiteMap(IndexSitemap,False); IndexSitemap.Free; end; IndexStream.Free; end; if (TableOfContentsFileName <> '') and FileExists(TableOfContentsFileName) then begin TOCStream := TFileStream.Create(TableOfContentsFileName, fmOpenRead); Writer.AppendTOC(TOCStream); if MakeBinaryTOC then begin TOCStream.Position := 0; TOCSitemap := TChmSiteMap.Create(stTOC); TOCSitemap.LoadFromStream(TOCStream); Writer.AppendBinaryTOCFromSiteMap(TOCSitemap); TOCSitemap.Free; end; TOCStream.Free; end; end; constructor TChmProject.Create; begin FFiles := TStringList.Create; end; destructor TChmProject.Destroy; begin FFIles.Free; inherited Destroy; end; procedure TChmProject.LoadFromFile(AFileName: String); var Cfg: TXMLConfig; FileCount: Integer; I: Integer; begin Cfg := TXMLConfig.Create(nil); Cfg.Filename := AFileName; FileName := AFileName; Files.Clear; FileCount := Cfg.GetValue('Files/Count/Value', 0); for I := 0 to FileCount-1 do begin Files.Add(Cfg.GetValue('Files/FileName'+IntToStr(I)+'/Value','')); end; IndexFileName := Cfg.GetValue('Files/IndexFile/Value',''); TableOfContentsFileName := Cfg.GetValue('Files/TOCFile/Value',''); // For chm file merging, bintoc must be false and binindex true. Change defaults in time? MakeBinaryTOC := Cfg.GetValue('Files/MakeBinaryTOC/Value', True); MakeBinaryIndex:= Cfg.GetValue('Files/MakeBinaryIndex/Value', False); AutoFollowLinks := Cfg.GetValue('Settings/AutoFollowLinks/Value', False); MakeSearchable := Cfg.GetValue('Settings/MakeSearchable/Value', False); DefaultPage := Cfg.GetValue('Settings/DefaultPage/Value', ''); Title := Cfg.GetValue('Settings/Title/Value', ''); OutputFileName := Cfg.GetValue('Settings/OutputFileName/Value', ''); DefaultFont := Cfg.GetValue('Settings/DefaultFont/Value', ''); Cfg.Free; end; procedure TChmProject.SaveToFile(AFileName: String); var Cfg: TXMLConfig; I: Integer; begin Cfg := TXMLConfig.Create(nil); Cfg.StartEmpty := True; Cfg.Filename := FileName; Cfg.Clear; Cfg.SetValue('Files/Count/Value', Files.Count); for I := 0 to Files.Count-1 do begin Cfg.SetValue('Files/FileName'+IntToStr(I)+'/Value', Files.Strings[I]); end; Cfg.SetValue('Files/IndexFile/Value', IndexFileName); Cfg.SetValue('Files/TOCFile/Value', TableOfContentsFileName); Cfg.SetValue('Files/MakeBinaryTOC/Value',MakeBinaryTOC); Cfg.SetValue('Files/MakeBinaryIndex/Value',MakeBinaryIndex); Cfg.SetValue('Settings/AutoFollowLinks/Value', AutoFollowLinks); Cfg.SetValue('Settings/MakeSearchable/Value', MakeSearchable); Cfg.SetValue('Settings/DefaultPage/Value', DefaultPage); Cfg.SetValue('Settings/Title/Value', Title); Cfg.SetValue('Settings/OutputFileName/Value', OutputFileName); Cfg.SetValue('Settings/DefaultFont/Value', DefaultFont); Cfg.Flush; Cfg.Free; end; function TChmProject.ProjectDir: String; begin Result := ExtractFilePath(FileName); end; procedure TChmProject.WriteChm(AOutStream: TStream); var Writer: TChmWriter; TOCStream, IndexStream: TFileStream; begin IndexStream := nil; TOCStream := nil; Writer := TChmWriter.Create(AOutStream, False); // our callback to get data Writer.OnGetFileData := @GetData; Writer.OnLastFile := @LastFileAdded; // give it the list of files Writer.FilesToCompress.AddStrings(Files); // now some settings in the chm Writer.DefaultPage := DefaultPage; Writer.Title := Title; Writer.DefaultFont := DefaultFont; Writer.FullTextSearch := MakeSearchable; Writer.HasBinaryTOC := MakeBinaryTOC; Writer.HasBinaryIndex := MakeBinaryIndex; // and write! Writer.Execute; if Assigned(TOCStream) then TOCStream.Free; if Assigned(IndexStream) then IndexStream.Free; end; end.
unit ChemicalStorage; interface uses Warehouses, Kernel, Surfaces, WorkCenterBlock, BackupInterfaces, CacheAgent; type TMetaChemicalStorage = class(TMetaWarehouse) public constructor Create(anId : string; aCapacities : array of TFluidValue; aChemicalsMax : TFluidValue; aOilMax : TFluidValue; aGasolineMax : TFluidValue; theOverPrice : TPercent; aBlockClass : CBlock); end; TChemicalStorage = class(TWarehouse) private fChemicalsIn : TInputData; fChemicalsOut : TOutputData; fOilIn : TInputData; fOilOut : TOutputData; fGasolineIn : TInputData; fGasolineOut : TOutputData; end; procedure RegisterBackup; implementation uses ClassStorage, StdFluids; // TMetaChemicalStorage constructor TMetaChemicalStorage.Create(anId : string; aCapacities : array of TFluidValue; aChemicalsMax : TFluidValue; aOilMax : TFluidValue; aGasolineMax : TFluidValue; theOverPrice : TPercent; aBlockClass : CBlock); var Sample : TChemicalStorage; begin inherited Create(anId, aCapacities, aBlockClass); Sample := nil; // Inputs NewMetaInput( tidGate_Chemicals, tidFluid_Chemicals, aChemicalsMax, sizeof(Sample.fChemicalsIn), Sample.Offset(Sample.fChemicalsIn)); // Outputs NewMetaOutput( tidGate_Chemicals, tidFluid_Chemicals, aChemicalsMax, sizeof(Sample.fChemicalsOut), Sample.Offset(Sample.fChemicalsOut)); // Inputs NewMetaInput( tidGate_Oil, tidFluid_Oil, aOilMax, sizeof(Sample.fOilIn), Sample.Offset(Sample.fOilIn)); // Outputs NewMetaOutput( tidGate_Oil, tidFluid_Oil, aOilMax, sizeof(Sample.fOilOut), Sample.Offset(Sample.fOilOut)); // Inputs NewMetaInput( tidGate_Gasoline, tidFluid_Gasoline, aGasolineMax, sizeof(Sample.fGasolineIn), Sample.Offset(Sample.fGasolineIn)); // Outputs NewMetaOutput( tidGate_Gasoline, tidFluid_Gasoline, aGasolineMax, sizeof(Sample.fGasolineOut), Sample.Offset(Sample.fGasolineOut)); // Wares RegisterWare(tidGate_Chemicals, 100, 0, theOverPrice, aChemicalsMax); RegisterWare(tidGate_Oil, 100, 0, theOverPrice, aOilMax); RegisterWare(tidGate_Gasoline, 100, 0, theOverPrice, aGasolineMax); end; // Register backup procedure RegisterBackup; begin BackupInterfaces.RegisterClass(TChemicalStorage); end; end.
unit RttiUtils; {*************************************************************************} { } { This unit contains TRttiEnabled utils and is not used other modules } { of ÕmlHit library } { } { } { Copyright (c) 2000-2008 Hitsoft LLC. } { } {*************************************************************************} {*************************************************************************} { } { Hitsoft Xml Object Library } { } { Copyright (C) 2009 Hitsoft LLC. (http://opensource.hitsoft-it.com) } { } { This program is free software: you can redistribute it and/or modify } { it under the terms of the GNU General Public License as published by } { the Free Software Foundation, either version 3 of the License, or } { (at your option) any later version. } { } { This program is distributed in the hope that it will be useful, } { but WITHOUT ANY WARRANTY; without even the implied warranty of } { MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the } { GNU General Public License for more details. } { } { You should have received a copy of the GNU General Public License } { along with this program. If not, see <http://www.gnu.org/licenses/>. } { } {*************************************************************************} interface uses RttiClasses; function CloneRttiEnabled(Origin: TRttiEnabled): TRttiEnabled; procedure FreeRttiArray(Origin: TRttiEnabledArray); implementation uses Classes, SAX, SAX2Rtti, SysUtils, SAXCustomWriter, BSAX, SAXAdapters; function CloneRttiEnabled(Origin: TRttiEnabled): TRttiEnabled; var Writer: IXMLWriter; Stream: TStringStream; XMLReader : IXMLReader; XMLBufReader: IBufferedXMLReader; Vendor: TSAXVendor; ContentHandler: IContentHandler; begin Stream := TStringStream.Create(''); Writer := CreateWriter; Writer.Stream := Stream; Writer.IncludeProlog := True; Writer.Standalone := True; Writer.Indent := False; Writer.StartDocument; WriteRttiObject(Writer, Origin, 'clone'); Writer.EndDocument; Result := TRttiEnabled(TRttiClass(Origin.ClassType).Create); Vendor:= GetSAXVendor; ContentHandler := RttiContentHandler(Result, nil); if Vendor is TBufferedSAXVendor then begin XMLBufReader:= TBufferedSAXVendor(Vendor).BufferedXMLReader; XMLBufReader.setContentHandler(Adapt(ContentHandler, XMLBufReader)); XMLBufReader.setErrorHandler(RttiErrorHandler); XMLBufReader.parse(TStreamInputSource.Create(Stream, soReference) as IInputSource); XMLBufReader:= nil; end else begin XMLReader:= Vendor.XMLReader; XMLReader.setContentHandler(ContentHandler); XMLReader.setErrorHandler(RttiErrorHandler); XMLReader.parse(TStreamInputSource.Create(Stream, soReference) as IInputSource); XMLReader:= nil; end; Stream.Free; end; procedure FreeRttiArray(Origin: TRttiEnabledArray); var I: Integer; begin for I := 0 to High(Origin) do if Assigned(Origin[I]) then FreeAndNil(Origin[I]); end; end.
unit uSolicitacaoCronogramaVO; interface uses System.SysUtils, uUsuarioVO; type TSolicitacaoCronogramaVO = class private FId: Integer; FIdUsuarioOperacional: Integer; FHoraFim: string; FIdSolicitacao: Integer; FHoraInicio: string; FData: TDate; FUsuarioOperacional: TUsuarioVO; procedure SetData(const Value: TDate); procedure SetHoraFim(const Value: string); procedure SetHoraInicio(const Value: string); procedure SetId(const Value: Integer); procedure SetIdSolicitacao(const Value: Integer); procedure SetIdUsuarioOperacional(const Value: Integer); procedure SetUsuarioOperacional(const Value: TUsuarioVO); public property Id: Integer read FId write SetId; property IdSolicitacao: Integer read FIdSolicitacao write SetIdSolicitacao; property IdUsuarioOperacional: Integer read FIdUsuarioOperacional write SetIdUsuarioOperacional; property Data: TDate read FData write SetData; property HoraInicio: string read FHoraInicio write SetHoraInicio; property HoraFim: string read FHoraFim write SetHoraFim; property UsuarioOperacional: TUsuarioVO read FUsuarioOperacional write SetUsuarioOperacional; constructor Create(); overload; destructor Destroy; override; end; implementation { TSolicitacaoCronogramaVO } constructor TSolicitacaoCronogramaVO.Create; begin inherited Create; FUsuarioOperacional := TUsuarioVO.Create; end; destructor TSolicitacaoCronogramaVO.Destroy; begin FreeAndNil(FUsuarioOperacional); inherited; end; procedure TSolicitacaoCronogramaVO.SetData(const Value: TDate); begin FData := Value; end; procedure TSolicitacaoCronogramaVO.SetHoraFim(const Value: string); begin FHoraFim := Value; end; procedure TSolicitacaoCronogramaVO.SetHoraInicio(const Value: string); begin FHoraInicio := Value; end; procedure TSolicitacaoCronogramaVO.SetId(const Value: Integer); begin FId := Value; end; procedure TSolicitacaoCronogramaVO.SetIdSolicitacao(const Value: Integer); begin FIdSolicitacao := Value; end; procedure TSolicitacaoCronogramaVO.SetIdUsuarioOperacional( const Value: Integer); begin FIdUsuarioOperacional := Value; end; procedure TSolicitacaoCronogramaVO.SetUsuarioOperacional( const Value: TUsuarioVO); begin FUsuarioOperacional := Value; end; end.
unit GX_MultilineHost; // Original Author: Stefan Hoffmeister <Stefan.Hoffmeister@econos.de> {$I GX_CondDefine.inc} interface uses Classes, Controls; type TGxMultiLineTabDockHostsManager = class(TObject) private FSqueezingCode: Pointer; FDockableFormClass: TClass; FNotificationVmtIndex: Integer; protected procedure DisableHooking; procedure EnableHooking; function DetermineNotificationVmtIndex: Integer; function GetTabDockHostFormClass: TClass; public constructor Create; destructor Destroy; override; end; var DefaultToMultiLine: Boolean = False; implementation uses {$IFOPT D+} GX_DbugIntf, {$ENDIF} SysUtils, Windows, Forms, Menus, ComCtrls, ImgList, GX_VerDepConst, GX_ClassHacks; type TNotificationSignature = procedure(Self: TObject; AComponent: TComponent; Operation: TOperation); register; var ReplacedNotification: TNotificationSignature; const AddedMultiLineMenuItemName = 'mnuGxMultiLineTab'; type TGxSqueezedInClass = class(TComponent) // We cannot have any data members, since the class may never be instantiated... // Therefore, "Self" in the context of this class isn't exactly // what might be expected. private procedure InsertMultiLineControls(TabDockHost: TWinControl); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; public procedure PopupMenuPopup(Sender: TObject); procedure MultiLineClick(Sender: TObject); end; procedure TGxSqueezedInClass.InsertMultiLineControls(TabDockHost: TWinControl); resourcestring SMultiLine = 'MultiLine'; var MenuItem: TMenuItem; FoundPopupMenu: TPopupMenu; FoundPageControl: TComponent; APageControl: TPageControl; i: Integer; begin for i := 0 to TabDockHost.ComponentCount-1 do begin if TabDockHost.Components[i] is TPopupMenu then begin FoundPopupMenu := TPopupMenu(TabDockHost.Components[i]); if FoundPopupMenu.FindComponent(AddedMultiLineMenuItemName) <> nil then Break; FoundPopupMenu.OnPopup := PopupMenuPopup; // Add a break line MenuItem := TMenuItem.Create(FoundPopupMenu); MenuItem.Caption := '-'; FoundPopupMenu.Items.Insert(0, MenuItem); // Our multi-line entry MenuItem := TMenuItem.Create(FoundPopupMenu); MenuItem.Name := AddedMultiLineMenuItemName; MenuItem.Checked := DefaultToMultiLine; MenuItem.Caption := SMultiLine; MenuItem.OnClick := MultiLineClick; FoundPopupMenu.Items.Insert(0, MenuItem); // Done looping Break; end; end; for i := 0 to TabDockHost.ComponentCount-1 do begin FoundPageControl := TabDockHost.Components[i]; if FoundPageControl is TPageControl then begin APageControl := TPageControl(FoundPageControl); if DefaultToMultiLine then APageControl.MultiLine := True; end; end; end; procedure TGxSqueezedInClass.Notification(AComponent: TComponent; Operation: TOperation); begin // Warning: Handle "Self" with care... Assert(@ReplacedNotification <> nil); ReplacedNotification(Self, AComponent, Operation); // Essentially call "inherited;" Assert(TComponent(Self) is TWinControl); InsertMultiLineControls(TWinControl(Self)); end; procedure TGxSqueezedInClass.MultiLineClick(Sender: TObject); var i: Integer; IsMultiLine: Boolean; PageControl: TComponent; begin // Warning: Handle "Self" with care... with Sender as TMenuItem do begin Checked := not Checked; IsMultiLine := Checked; end; for i := 0 to ComponentCount-1 do begin PageControl := Components[i]; if PageControl is TPageControl then begin TPageControl(PageControl).MultiLine := IsMultiLine; end; end; end; procedure TGxSqueezedInClass.PopupMenuPopup(Sender: TObject); var TabDockForm: TCustomForm; FoundPageControl: TPageControl; MenuItem: TMenuItem; i: Integer; begin // Warning: Handle "Self" with care... TabDockForm := (Sender as TPopupMenu).Owner as TCustomForm; for i := 0 to TabDockForm.ComponentCount-1 do begin if TabDockForm.Components[i] is TPageControl then begin FoundPageControl := TPageControl(TabDockForm.Components[i]); MenuItem := (Sender as TPopupMenu).FindComponent(AddedMultiLineMenuItemName) as TMenuItem; Assert(MenuItem <> nil); MenuItem.Enabled := not (FoundPageControl.TabPosition in [tpLeft, tpRight]); MenuItem.Checked := FoundPageControl.MultiLine; end; end; end; { TGxMultiLineTabDockHostsManager } constructor TGxMultiLineTabDockHostsManager.Create; (* var i: Integer; TabDockHostForm: TComponent; *) begin inherited Create; FSqueezingCode := @TGxSqueezedInClass.Notification; FDockableFormClass := GetTabDockHostFormClass; FNotificationVmtIndex := DetermineNotificationVmtIndex; EnableHooking; (* // Scan for tab dock hosts that are already present // and add ourselves to those forms that are already // present. // The order is important - first we must enable // hooking, since this is tested (implicitly) in // the squeezing class for i := 0 to Screen.FormCount-1 do begin if SameText(Screen.Forms[i].ClassName, TTabDockHostFormName) then begin TabDockHostForm := Screen.Forms[i]; with TGxSqueezedInClass.Create(TabDockHostForm) do InsertMultiLineControls(TabDockHostForm); end; end; *) end; destructor TGxMultiLineTabDockHostsManager.Destroy; begin DisableHooking; FDockableFormClass := nil; FNotificationVmtIndex := -1; FSqueezingCode := nil; inherited Destroy; end; function GetVirtualMethodPointer(AClass: TClass; const Index: Cardinal): Pointer; type PPointer = ^Pointer; begin Result := PPointer(Cardinal(AClass) + Index * SizeOf(Pointer))^; end; procedure SetVirtualMethodPointer(AClass: TClass; const Index: Cardinal; const Method: Pointer); var PatchAddress: Pointer; DummyProtection: DWORD; OldProtection: DWORD; begin PatchAddress := Pointer(Cardinal(AClass) + Index * SizeOf(Pointer)); // Set memory access rights so that we can write into this page if not VirtualProtect(PatchAddress, SizeOf(Pointer), PAGE_READWRITE, @OldProtection) then RaiseLastOsError; try // Write method into VMT Pointer(PatchAddress^) := Method; finally // Restore memory access rights if not VirtualProtect(PatchAddress, SizeOf(Pointer), OldProtection, @DummyProtection) then RaiseLastOsError; end; // Make sure that everything keeps working in a dual processor setting FlushInstructionCache(GetCurrentProcess, PatchAddress, SizeOf(Pointer)); end; procedure TGxMultiLineTabDockHostsManager.DisableHooking; begin if FDockableFormClass = nil then Exit; Assert(@ReplacedNotification <> nil); if FNotificationVmtIndex < 0 then Exit; Assert(FSqueezingCode = GetVirtualMethodPointer(FDockableFormClass, FNotificationVmtIndex)); SetVirtualMethodPointer(FDockableFormClass, FNotificationVmtIndex, @ReplacedNotification); @ReplacedNotification := nil; end; procedure TGxMultiLineTabDockHostsManager.EnableHooking; begin if FDockableFormClass = nil then begin {$IFOPT D+} SendDebugError('Unable to locate IDE tab dock host form class'); {$ENDIF} Exit; end; Assert(@ReplacedNotification = nil); if FNotificationVmtIndex < 0 then Exit; @ReplacedNotification := GetVirtualMethodPointer(FDockableFormClass, FNotificationVmtIndex); SetVirtualMethodPointer(FDockableFormClass, FNotificationVmtIndex, FSqueezingCode); end; function TGxMultiLineTabDockHostsManager.GetTabDockHostFormClass: TClass; begin Result := GetClassReference(TTabDockHostFormName, TTabDockHostFormClassContainer); end; function TGxMultiLineTabDockHostsManager.DetermineNotificationVmtIndex: Integer; type PPointer = ^Pointer; const MaxIndex = 500; var VmtScanner: PPointer; Index: Integer; begin Result := -1; if FDockableFormClass = nil then Exit; // We need to "find" the index of the Notification virtual function; // theoretically hard-coding the index would work, too, but that // breaks as soon as the VCL changes somewhere deep down. // Accomplish this by finding the index in our squeezing class // (TGxSqueezedInClass) and simply use that index for our target // class - it is guaranteed to be the same index by virtue of // virtual method tables (and not compiler version dependent). VmtScanner := PPointer(TGxSqueezedInClass); Index := -1; // MaxIndex is just a sanity checker in order to // scan at most MaxIndex VMT entries. while Index < MaxIndex do begin Inc(Index); if VmtScanner^ = FSqueezingCode then Break; Inc(VmtScanner); end; if Index = MaxIndex then Exit; Result := Index; end; end.
unit PE.Parser.TLS; interface uses System.SysUtils, PE.Common, PE.Types, PE.Types.Directories, PE.Types.TLS, PE.TLS; type TPETLSParser = class(TPEParser) public function Parse: TParserResult; override; end; implementation uses PE.Image; { TPETLSParser } function TPETLSParser.Parse: TParserResult; var PE: TPEImage; var Dir: TImageDataDirectory; TLSDir: TTLSDirectory; AddressofCallbacks: TVA; CurRVA, CallbackVA: uint64; bRead: boolean; begin PE := TPEImage(FPE); if not PE.DataDirectories.Get(DDIR_TLS, @Dir) then exit(PR_OK); if Dir.IsEmpty then exit(PR_OK); if not PE.SeekRVA(Dir.VirtualAddress) then begin PE.Msg.Write(SCategoryTLS, 'Incorrect directory RVA.'); exit(PR_ERROR); end; case PE.ImageBits of 32: begin bRead := PE.ReadEx(TLSDir.tls32, SizeOf(TLSDir.tls32)); AddressofCallbacks := TLSDir.tls32.AddressofCallbacks; end; 64: begin bRead := PE.ReadEx(TLSDir.tls64, SizeOf(TLSDir.tls64)); AddressofCallbacks := TLSDir.tls64.AddressofCallbacks; end; else exit(PR_ERROR); end; if not bRead then begin PE.Msg.Write(SCategoryTLS, 'Failed to read directory.'); exit(PR_ERROR); end; // Assign dir. PE.TLS.Dir := TLSDir; // Try to read callback addresses if available. // It's ok if there's no callbacks. if AddressofCallbacks = 0 then exit(PR_OK); if not PE.SeekVA(AddressofCallbacks) then begin PE.Msg.Write(SCategoryTLS, 'Incorrect address of callbacks.'); exit(PR_OK); end; while True do begin CurRVA := PE.PositionRVA; // Try to read callback address. if not PE.ReadWordEx(0, @CallbackVA) then begin PE.Msg.Write(SCategoryTLS, 'Failed to read callback address at RVA: 0x%x. Probably malformed data.', [CurRVA]); break; end; // Is it terminator? if CallbackVA = 0 then break; // Does the address exist? if not PE.VAExists(CallbackVA) then begin PE.Msg.Write(SCategoryTLS, 'Bad callback address (0x%x) at RVA: 0x%x', [CallbackVA, CurRVA]); break; end; // Add existing address. PE.TLS.CallbackRVAs.Add(PE.VAToRVA(CallbackVA)) end; exit(PR_OK); end; end.
unit ddExportFilerDispatcher; // Модуль: "w:\common\components\rtl\Garant\dd\PipeOut\ddExportFilerDispatcher.pas" // Стереотип: "SimpleClass" // Элемент модели: "TddExportFilerDispatcher" MUID: (5603F0890069) {$Include w:\common\components\rtl\Garant\dd\ddDefine.inc} interface uses l3IntfUses , l3ProtoObject , l3Interfaces , ddExportFilerMap , ddPipeOutInterfaces , l3Filer , dt_Types ; type TddFileMaskArray = array [TddExportDocPart] of Il3CString; TddExportDivideByArray = array [TddExportDocPart] of TddExportDivideBySet; TddCurrentFilesArray = array [TddExportDocPart] of IUnknown; TddExportFilerDispatcher = class(Tl3ProtoObject) private f_FileMask: TddFileMaskArray; f_Map: TddExportFilerMap; f_DivideBy: TddExportDivideByArray; f_SingleFiler: Tl3CustomFiler; f_CurrentFiles: TddCurrentFilesArray; f_CurrentTopic: TDocID; f_CodePage: LongInt; f_ExportDate: TDateTime; f_FilePartSize: Integer; f_TargetFolder: AnsiString; f_FileExt: AnsiString; f_LowcaseFilenames: Boolean; f_IsDirByMain: Boolean; f_UpdateFiles: Boolean; private procedure DropCurrentFilesData; protected function pm_GetFileMask(aPart: TddExportDocPart): Il3CString; virtual; procedure pm_SetFileMask(aPart: TddExportDocPart; const aValue: Il3CString); virtual; function pm_GetDivideBy(aPart: TddExportDocPart): TddExportDivideBySet; virtual; procedure pm_SetDivideBy(aPart: TddExportDocPart; aValue: TddExportDivideBySet); virtual; procedure Cleanup; override; {* Функция очистки полей объекта. } procedure ClearFields; override; public constructor Create; reintroduce; function GetFiler(aTopic: TDocID; aPart: TddExportDocPart; const aAccGroup: Il3CString): Tl3CustomFiler; procedure Start; {* Корректирует маски файлов и DivideBy, обнуляет файлеры } procedure Finish; {* Закрывает все открытые файлеры } procedure RollBack; {* Удаляет уже вылитые данные текущего топика (случай аварийного отката) } function GetActualDir(const aMain: AnsiString): AnsiString; public property CodePage: LongInt read f_CodePage write f_CodePage; property FileMask[aPart: TddExportDocPart]: Il3CString read pm_GetFileMask write pm_SetFileMask; property DivideBy[aPart: TddExportDocPart]: TddExportDivideBySet read pm_GetDivideBy write pm_SetDivideBy; property ExportDate: TDateTime read f_ExportDate write f_ExportDate; property FilePartSize: Integer read f_FilePartSize write f_FilePartSize; property TargetFolder: AnsiString read f_TargetFolder write f_TargetFolder; property FileExt: AnsiString read f_FileExt write f_FileExt; property LowcaseFilenames: Boolean read f_LowcaseFilenames write f_LowcaseFilenames; property IsDirByMain: Boolean read f_IsDirByMain; property UpdateFiles: Boolean read f_UpdateFiles write f_UpdateFiles; end;//TddExportFilerDispatcher implementation uses l3ImplUses , SysUtils , l3Chars , ddExportFilerDispatcherElem , l3FileUtils , l3Types , ddUtils , l3String , l3Const , l3Base , Classes //#UC START# *5603F0890069impl_uses* //#UC END# *5603F0890069impl_uses* ; function TddExportFilerDispatcher.pm_GetFileMask(aPart: TddExportDocPart): Il3CString; //#UC START# *5603FBF902CB_5603F0890069get_var* //#UC END# *5603FBF902CB_5603F0890069get_var* begin //#UC START# *5603FBF902CB_5603F0890069get_impl* Result := f_FileMask[aPart]; //#UC END# *5603FBF902CB_5603F0890069get_impl* end;//TddExportFilerDispatcher.pm_GetFileMask procedure TddExportFilerDispatcher.pm_SetFileMask(aPart: TddExportDocPart; const aValue: Il3CString); //#UC START# *5603FBF902CB_5603F0890069set_var* //#UC END# *5603FBF902CB_5603F0890069set_var* begin //#UC START# *5603FBF902CB_5603F0890069set_impl* f_FileMask[aPart] := aValue; //#UC END# *5603FBF902CB_5603F0890069set_impl* end;//TddExportFilerDispatcher.pm_SetFileMask function TddExportFilerDispatcher.pm_GetDivideBy(aPart: TddExportDocPart): TddExportDivideBySet; //#UC START# *560A4EE9011B_5603F0890069get_var* //#UC END# *560A4EE9011B_5603F0890069get_var* begin //#UC START# *560A4EE9011B_5603F0890069get_impl* Result := f_DivideBy[aPart]; //#UC END# *560A4EE9011B_5603F0890069get_impl* end;//TddExportFilerDispatcher.pm_GetDivideBy procedure TddExportFilerDispatcher.pm_SetDivideBy(aPart: TddExportDocPart; aValue: TddExportDivideBySet); //#UC START# *560A4EE9011B_5603F0890069set_var* //#UC END# *560A4EE9011B_5603F0890069set_var* begin //#UC START# *560A4EE9011B_5603F0890069set_impl* f_DivideBy[aPart] := aValue; //#UC END# *560A4EE9011B_5603F0890069set_impl* end;//TddExportFilerDispatcher.pm_SetDivideBy constructor TddExportFilerDispatcher.Create; //#UC START# *560A4BA903C9_5603F0890069_var* //#UC END# *560A4BA903C9_5603F0890069_var* begin //#UC START# *560A4BA903C9_5603F0890069_impl* inherited; f_Map := TddExportFilerMap.Create; f_CodePage := CP_OEMLite; //#UC END# *560A4BA903C9_5603F0890069_impl* end;//TddExportFilerDispatcher.Create function TddExportFilerDispatcher.GetFiler(aTopic: TDocID; aPart: TddExportDocPart; const aAccGroup: Il3CString): Tl3CustomFiler; //#UC START# *560A4C0F00CA_5603F0890069_var* var l_FileName: AnsiString; l_Folder: AnsiString; l_IFileName: Il3CString; l_Index: TddFilerDispatcherMapKeyRecord; l_FilerHolder: IddExportFilerDispatcherElem; l_DateStr: AnsiString; l_FilePartSize: Integer; //#UC END# *560A4C0F00CA_5603F0890069_var* begin //#UC START# *560A4C0F00CA_5603F0890069_impl* if (aTopic <> f_CurrentTopic) and (aPart in [edpDocument, edpAnnotation]) then begin DropCurrentFilesData; f_CurrentTopic := aTopic; end; l_Folder := GetActualDir(l3Str(aAccGroup)); ForceDirectories(l_Folder); if edbTopic in DivideBy[aPart] then begin // делим по топикам, маска и другое просто не имеет значения l_FileName := IntToStr(aTopic); if aPart = edpAnnotation then l_FileName := l_FileName + 'a'; l_FileName := ConcatDirName(l_Folder, l_FileName + f_FileExt); FreeAndNil(f_SingleFiler); try f_SingleFiler := Tl3DOSFiler.Make(l_FileName, l3_fmWrite); f_SingleFiler.Open; f_SingleFiler.CodePage := f_CodePage; except on E: Exception do l3System.Msg2Log(cFilerOpenErrorMsg, [E.Message, l_FileName]); end; f_CurrentFiles[aPart] := l3CStr(l_FileName); Result := f_SingleFiler; end else begin l_Index.rPart := aPart; if (edbAccGroup in DivideBy[aPart]) or f_IsDirByMain then l_Index.rAccGroup := aAccGroup else l_Index.rAccGroup := l3CStr(''); // если мейнов в маске нет, то незачем плодить файлеры if f_Map.Has(l_Index) then l_FilerHolder := f_Map.ValueByKey(l_Index) else begin l_IFileName := l3StringReplace(FileMask[aPart], cExportFileMaskPatterns[eptAccGroup], aAccGroup.AsWStr, [rfReplaceAll, rfIgnoreCase]); l_DateStr := ddUtils.DateToString(f_ExportDate); l_IFileName := l3StringReplace(l_IFileName, cExportFileMaskPatterns[eptExportDate], l3PCharLen(l_DateStr), [rfReplaceAll, rfIgnoreCase]); l_FileName := ConcatDirName(l_Folder, ChangeFileExt(l3Str(l_IFileName), f_FileExt)); l_IFileName := l3CStr(l_FileName); if f_LowcaseFilenames then l_IFileName := l3Lower(l_IFileName); if edbSize in DivideBy[aPart] then l_FilePartSize := f_FilePartSize else l_FilePartSize := 0; l_FilerHolder := TddExportFilerDispatcherElem.Make(l_IFileName, f_CodePage, l_FilePartSize, f_UpdateFiles); f_Map.Add(l_Index, l_FilerHolder); end; f_CurrentFiles[aPart] := l_FilerHolder; Result := l_FilerHolder.Filer; end; //#UC END# *560A4C0F00CA_5603F0890069_impl* end;//TddExportFilerDispatcher.GetFiler procedure TddExportFilerDispatcher.Start; {* Корректирует маски файлов и DivideBy, обнуляет файлеры } //#UC START# *560A5979037E_5603F0890069_var* var l_DocPart: TddExportDocPart; procedure CorrectByPattern(aDocPart: TddExportDocPart; aPattern: TddExportFileMaskPatternType; aDivideBy: TddExportDivideBySet); begin if l3Pos(FileMask[aDocPart], cExportFileMaskPatterns[aPattern], False) <> l3NotFound then DivideBy[aDocPart] := DivideBy[aDocPart] + aDivideBy; end; procedure CorrectByDivideBy(aDocPart: TddExportDocPart; aDivideBy: TddExportDivideBy; aPattern: TddExportFileMaskPatternType); var l_Ext: AnsiString; l_FilePart: Il3CString; begin if (aDivideBy in DivideBy[aDocPart]) and (l3Pos(FileMask[aDocPart], cExportFileMaskPatterns[aPattern], False) = l3NotFound) then begin l_Ext := ExtractFileExt(l3Str(FileMask[aDocPart])); l_FilePart := l3Copy(FileMask[aDocPart], 0, FileMask[aDocPart].AsWStr.SLen - Length(l_Ext)); FileMask[aDocPart] := l3Cat([l_FilePart, l3CStr('_'), l3CStr(cExportFileMaskPatterns[aPattern]), l3CStr(l_Ext)]); end; end; //#UC END# *560A5979037E_5603F0890069_var* begin //#UC START# *560A5979037E_5603F0890069_impl* f_Map.Clear; // на всякий случай FreeAndNil(f_SingleFiler); Assert(f_TargetFolder <> '', 'Пустое имя папки экспорта'); for l_DocPart := edpDocument to edpAnnotation do begin if l3IsNil(FileMask[l_DocPart]) then FileMask[l_DocPart] := l3CStr(cDefaultFileMask[l_DocPart]) else begin CorrectByPattern(l_DocPart, eptAccGroup, [edbAccGroup]); CorrectByPattern(l_DocPart, eptPartNum, [edbSize]); end; CorrectByDivideBy(l_DocPart, edbAccGroup, eptAccGroup); CorrectByDivideBy(l_DocPart, edbSize, eptPartNum); if edbSize in DivideBy[l_DocPart] then Assert(FilePartSize > 0, 'Ошибка! Требуется разделение по размеру, но не указан требуемый размер!'); end; f_IsDirByMain := l3Pos(l3CStr(f_TargetFolder), cExportFileMaskPatterns[eptAccGroup], False) <> l3NotFound; DropCurrentFilesData; //#UC END# *560A5979037E_5603F0890069_impl* end;//TddExportFilerDispatcher.Start procedure TddExportFilerDispatcher.Finish; {* Закрывает все открытые файлеры } //#UC START# *560BA6EA03BC_5603F0890069_var* //#UC END# *560BA6EA03BC_5603F0890069_var* begin //#UC START# *560BA6EA03BC_5603F0890069_impl* f_Map.Clear; FreeAndNil(f_SingleFiler); DropCurrentFilesData; //#UC END# *560BA6EA03BC_5603F0890069_impl* end;//TddExportFilerDispatcher.Finish procedure TddExportFilerDispatcher.RollBack; {* Удаляет уже вылитые данные текущего топика (случай аварийного отката) } //#UC START# *5617725803A8_5603F0890069_var* var l_Part: TddExportDocPart; l_Str: Il3CString; l_Elem: IddExportFilerDispatcherElem; //#UC END# *5617725803A8_5603F0890069_var* begin //#UC START# *5617725803A8_5603F0890069_impl* for l_Part := edpDocument to edpAnnotation do begin FreeAndNil(f_SingleFiler); if f_CurrentFiles[l_Part] <> nil then begin if Supports(f_CurrentFiles[l_Part], IddExportFilerDispatcherElem, l_Elem) then l_Elem.RollBack else if Supports(f_CurrentFiles[l_Part], Il3CString, l_Str) then begin DeleteFile(l3Str(l_Str)); end else Assert(False, 'Что-то непонятное в данных о текущем топике!'); end; end; //#UC END# *5617725803A8_5603F0890069_impl* end;//TddExportFilerDispatcher.RollBack procedure TddExportFilerDispatcher.DropCurrentFilesData; //#UC START# *5617897D0210_5603F0890069_var* var l_Part: TddExportDocPart; //#UC END# *5617897D0210_5603F0890069_var* begin //#UC START# *5617897D0210_5603F0890069_impl* for l_Part := edpDocument to edpAnnotation do f_CurrentFiles[l_Part] := nil; //#UC END# *5617897D0210_5603F0890069_impl* end;//TddExportFilerDispatcher.DropCurrentFilesData function TddExportFilerDispatcher.GetActualDir(const aMain: AnsiString): AnsiString; //#UC START# *561BA41E0388_5603F0890069_var* //#UC END# *561BA41E0388_5603F0890069_var* begin //#UC START# *561BA41E0388_5603F0890069_impl* if f_IsDirByMain then Result := l3Str(l3StringReplace(l3CStr(f_TargetFolder), cExportFileMaskPatterns[eptAccGroup], l3CStr(aMain).AsWStr, [rfReplaceAll, rfIgnoreCase])) else Result := f_TargetFolder; //#UC END# *561BA41E0388_5603F0890069_impl* end;//TddExportFilerDispatcher.GetActualDir procedure TddExportFilerDispatcher.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_5603F0890069_var* //#UC END# *479731C50290_5603F0890069_var* begin //#UC START# *479731C50290_5603F0890069_impl* FreeAndNil(f_Map); inherited; //#UC END# *479731C50290_5603F0890069_impl* end;//TddExportFilerDispatcher.Cleanup procedure TddExportFilerDispatcher.ClearFields; begin TargetFolder := ''; FileExt := ''; inherited; end;//TddExportFilerDispatcher.ClearFields end.
{ Double Commander ------------------------------------------------------------------------- Manager that maintains a list of running file source operations and manages queues of operations. Copyright (C) 2010-2012 Przemys³aw Nagay (cobines@gmail.com) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. } unit uOperationsManager; {$mode objfpc}{$H+} interface uses Classes, SysUtils, uOperationThread, uFileSourceOperation; type {en Handle to OperationsManager's operation.} TOperationHandle = type Longint; {en Identifier of OperationsManager's queue.} TOperationsManagerQueueIdentifier = type Longint; const InvalidOperationHandle = TOperationHandle(0); FreeOperationsQueueId = 0; ModalQueueId = Pred(FreeOperationsQueueId); SingleQueueId = Succ(FreeOperationsQueueId); type TOperationsManagerQueue = class; { TOperationsManagerItem } TOperationsManagerItem = class strict private FHandle : TOperationHandle; FOperation : TFileSourceOperation; FQueue : TOperationsManagerQueue; FThread : TOperationThread; private function RemoveFromQueue: Boolean; {en Inserts the item into new queue at specific position. @param(NewQueue To which queue to insert the item. If it is the same queue in which the item is currently nothing is performed.) @param(TargetOperation Handle to another operation in NewQueue near which the item should be placed.) @param(PlaceBefore If @true then places item before TargetOperation. If @false then places item after TargetOperation.) } procedure SetQueue(NewQueue: TOperationsManagerQueue; TargetOperation: TOperationHandle; PlaceBefore: Boolean); public constructor Create(AHandle: TOperationHandle; AOperation: TFileSourceOperation; AThread: TOperationThread); destructor Destroy; override; {en Moves the item and places it before or after another operation. @param(TargetOperation Handle to another operation where item should be moved. If handle belongs to operation from a different queue then the item is moved to that queue and placed before or after the operation.) @param(PlaceBefore If @true then places item before TargetOperation. If @false then places item after TargetOperation.) } procedure Move(TargetOperation: TOperationHandle; PlaceBefore: Boolean); procedure MoveToBottom; function MoveToNewQueue: TOperationsManagerQueueIdentifier; procedure MoveToTop; procedure SetQueue(NewQueue: TOperationsManagerQueue; InsertAtFront: Boolean = False); property Handle: TOperationHandle read FHandle; property Operation: TFileSourceOperation read FOperation; property Queue: TOperationsManagerQueue read FQueue; property Thread: TOperationThread read FThread; end; { TOperationsManagerQueue } TOperationsManagerQueue = class strict private FIdentifier: TOperationsManagerQueueIdentifier; FList: TFPList; FPaused: Boolean; function GetIndexByHandle(Handle: TOperationHandle): Integer; function GetItem(Index: Integer): TOperationsManagerItem; function GetItemByHandle(Handle: TOperationHandle): TOperationsManagerItem; function GetOperationsCount: Integer; private {en Inserts new item into the queue. @param(InsertAt If -1 (default) it adds to the back of the queue. If 0 inserts at the front. If 0 < InsertAt < Count it inserts at specific position.) } function Insert(Item: TOperationsManagerItem; InsertAt: Integer = -1): Integer; {en Inserts new item into the queue. @param(InsertAtFront If @true then inserts at the front, if @false then inserts at the back.) } function Insert(Item: TOperationsManagerItem; TargetOperation: TOperationHandle; PlaceBefore: Boolean): Integer; {en Moves item within the queue. @param(SourceItem Which item should be moved.) @param(TargetItem SourceItem is moved placed either before or after TargetItem. If TargetItem is @nil then SourceItem is moved to the front if PlaceBefore is @true and to the back if PlaceBefore is @false.) @param(PlaceBefore If @true then SourceItem is placed before TargetItem. If @false then SourceItem is placed after TargetItem.) } procedure Move(SourceItem, TargetItem: TOperationsManagerItem; PlaceBefore: Boolean); function Remove(Item: TOperationsManagerItem): Boolean; public constructor Create(AIdentifier: TOperationsManagerQueueIdentifier); destructor Destroy; override; function GetDescription(IncludeCount: Boolean): String; {en Returns @true if this queue is a free operations queue. } function IsFree: Boolean; inline; procedure Pause; procedure Stop; procedure TogglePause; procedure UnPause; property Count: Integer read GetOperationsCount; property Identifier: TOperationsManagerQueueIdentifier read FIdentifier; property Items[Index: Integer]: TOperationsManagerItem read GetItem; property ItemByHandle[Handle: TOperationHandle]: TOperationsManagerItem read GetItemByHandle; property Paused: Boolean read FPaused; end; TOperationManagerEvent = (omevOperationAdded, omevOperationRemoved, omevOperationMoved); TOperationManagerEvents = set of TOperationManagerEvent; TOperationManagerEventNotify = procedure(Item: TOperationsManagerItem; Event: TOperationManagerEvent) of object; {en Manages file source operations. Executes them, stores threads, allows querying active operations (meaning operations being executed). } { TOperationsManager } TOperationsManager = class private FLastUsedHandle: TOperationHandle; FEventsListeners: array[TOperationManagerEvent] of TFPList; FQueues: TFPList; procedure ThreadTerminatedEvent(Sender: TObject); function GetItemByOperation(Operation: TFileSourceOperation): TOperationsManagerItem; function GetItemByIndex(Index: Integer): TOperationsManagerItem; function GetOperationsCount: Integer; function GetNextUnusedHandle: TOperationHandle; function GetQueueByIndex(Index: Integer): TOperationsManagerQueue; function GetQueueByIdentifier(Identifier: TOperationsManagerQueueIdentifier): TOperationsManagerQueue; function GetQueuesCount: Integer; function MoveToNewQueue(Item: TOperationsManagerItem): TOperationsManagerQueueIdentifier; procedure MoveToQueue(Item: TOperationsManagerItem; QueueIdentifier: TOperationsManagerQueueIdentifier); {en Notifies all listeners that an event has occurred (or multiple events). } procedure NotifyEvents(Item: TOperationsManagerItem; Events: TOperationManagerEvents); public constructor Create; destructor Destroy; override; {en Adds an operation to the manager. @param(ShowProgress If @true automatically shows progress window.) } function AddOperation(Operation: TFileSourceOperation; ShowProgress: Boolean = True): TOperationHandle; {en Adds an operation to the manager. @param(QueueIdentifier Specifies to which queue to put the operation.) @param(InsertAtFrontOfQueue If @true inserts the operation at the front of the queue, if @false inserts at the back of the queue.) @param(ShowProgress If @true automatically shows progress window.) } function AddOperation(Operation: TFileSourceOperation; QueueIdentifier: TOperationsManagerQueueIdentifier; InsertAtFrontOfQueue: Boolean; ShowProgress: Boolean = True): TOperationHandle; {en Adds an operation to the manager. Execute operation in the main thread and show progress in modal window. } function AddOperationModal(Operation: TFileSourceOperation): TOperationHandle; {en Operations retrieved this way can be safely used from the main GUI thread. But they should not be stored for longer use, because they may be destroyed by the Operations Manager when they finish. Operation handle can always be used to query OperationsManager if the operation item is still alive. } function GetItemByHandle(Handle: TOperationHandle): TOperationsManagerItem; function GetOrCreateQueue(Identifier: TOperationsManagerQueueIdentifier): TOperationsManagerQueue; function GetNewQueueIdentifier: TOperationsManagerQueueIdentifier; procedure PauseAll; procedure StopAll; procedure UnPauseAll; function AllProgressPoint: Double; {en Adds a function to call on specific events. } procedure AddEventsListener(Events: TOperationManagerEvents; FunctionToCall: TOperationManagerEventNotify); {en Removes a registered function callback for events. } procedure RemoveEventsListener(Events: TOperationManagerEvents; FunctionToCall: TOperationManagerEventNotify); property OperationsCount: Integer read GetOperationsCount; property QueuesCount: Integer read GetQueuesCount; property QueueByIndex[Index: Integer]: TOperationsManagerQueue read GetQueueByIndex; property QueueByIdentifier[Identifier: TOperationsManagerQueueIdentifier]: TOperationsManagerQueue read GetQueueByIdentifier; end; var OperationsManager: TOperationsManager = nil; implementation uses uDebug, uLng, uFileSourceOperationMisc, uFileSourceProperty, uFileSource; type PEventsListItem = ^TEventsListItem; TEventsListItem = record EventFunction: TOperationManagerEventNotify; end; { TOperationsManagerItem } constructor TOperationsManagerItem.Create(AHandle: TOperationHandle; AOperation: TFileSourceOperation; AThread: TOperationThread); begin FHandle := AHandle; FOperation := AOperation; FThread := AThread; end; destructor TOperationsManagerItem.Destroy; begin inherited Destroy; FOperation.Free; end; procedure TOperationsManagerItem.Move(TargetOperation: TOperationHandle; PlaceBefore: Boolean); var TargetItem: TOperationsManagerItem; begin TargetItem := OperationsManager.GetItemByHandle(TargetOperation); if Assigned(TargetItem) then begin if Queue = TargetItem.Queue then Queue.Move(Self, TargetItem, PlaceBefore) else SetQueue(TargetItem.Queue, TargetOperation, PlaceBefore); end; end; procedure TOperationsManagerItem.MoveToBottom; begin Queue.Move(Self, nil, False); end; function TOperationsManagerItem.MoveToNewQueue: TOperationsManagerQueueIdentifier; begin Result := OperationsManager.MoveToNewQueue(Self); end; procedure TOperationsManagerItem.MoveToTop; begin Queue.Move(Self, nil, True); end; function TOperationsManagerItem.RemoveFromQueue: Boolean; begin Result := Queue.Remove(Self); if Queue.Count = 0 then begin OperationsManager.FQueues.Remove(Queue); Queue.Free; end; FQueue := nil; end; procedure TOperationsManagerItem.SetQueue(NewQueue: TOperationsManagerQueue; InsertAtFront: Boolean); begin if (Queue <> NewQueue) and Assigned(NewQueue) then begin if not Assigned(Queue) or RemoveFromQueue then begin FQueue := NewQueue; if InsertAtFront then NewQueue.Insert(Self, 0) // Insert at the front of the queue. else NewQueue.Insert(Self); // Add at the back of the queue. OperationsManager.NotifyEvents(Self, [omevOperationMoved]); end; end; end; procedure TOperationsManagerItem.SetQueue(NewQueue: TOperationsManagerQueue; TargetOperation: TOperationHandle; PlaceBefore: Boolean); begin if (Queue <> NewQueue) and Assigned(NewQueue) then begin if not Assigned(Queue) or RemoveFromQueue then begin FQueue := NewQueue; NewQueue.Insert(Self, TargetOperation, PlaceBefore); OperationsManager.NotifyEvents(Self, [omevOperationMoved]); end; end; end; { TOperationsManagerQueue } function TOperationsManagerQueue.GetIndexByHandle(Handle: TOperationHandle): Integer; begin for Result := 0 to Count - 1 do begin if TOperationsManagerItem(Items[Result]).Handle = Handle then Exit; end; Result := -1; end; function TOperationsManagerQueue.GetItem(Index: Integer): TOperationsManagerItem; begin Result := TOperationsManagerItem(FList.Items[Index]); end; function TOperationsManagerQueue.GetItemByHandle(Handle: TOperationHandle): TOperationsManagerItem; var Index: Integer; begin for Index := 0 to Count - 1 do begin Result := Items[Index]; if Result.Handle = Handle then Exit; end; Result := nil; end; function TOperationsManagerQueue.GetOperationsCount: Integer; begin Result := FList.Count; end; constructor TOperationsManagerQueue.Create(AIdentifier: TOperationsManagerQueueIdentifier); begin FList := TFPList.Create; FIdentifier := AIdentifier; end; destructor TOperationsManagerQueue.Destroy; var i: Integer; begin inherited Destroy; for i := 0 to FList.Count - 1 do Items[i].Free; FList.Free; end; function TOperationsManagerQueue.GetDescription(IncludeCount: Boolean): String; begin Result := rsDlgQueue + ' #' + IntToStr(Identifier); if IncludeCount then Result := Result + ' [' + IntToStr(Count) + ']'; end; procedure TOperationsManagerQueue.Move(SourceItem, TargetItem: TOperationsManagerItem; PlaceBefore: Boolean); var FromIndex, ToIndex: Integer; ShouldMove: Boolean = False; begin FromIndex := GetIndexByHandle(SourceItem.Handle); if FromIndex >= 0 then begin if not Assigned(TargetItem) then begin if PlaceBefore then ToIndex := 0 else ToIndex := FList.Count - 1; ShouldMove := True; end else begin ToIndex := GetIndexByHandle(TargetItem.Handle); if ToIndex >= 0 then begin if PlaceBefore then begin if FromIndex < ToIndex then Dec(ToIndex); end else begin if FromIndex > ToIndex then Inc(ToIndex); end; ShouldMove := True; end; end; end; if ShouldMove and (FromIndex <> ToIndex) then begin if (not Paused) and ((FromIndex = 0) or (ToIndex = 0)) and not IsFree then Items[0].Operation.Pause; FList.Move(FromIndex, ToIndex); if (not Paused) and ((FromIndex = 0) or (ToIndex = 0)) and not IsFree then Items[0].Operation.Start; OperationsManager.NotifyEvents(SourceItem, [omevOperationMoved]); end; end; function TOperationsManagerQueue.Insert(Item: TOperationsManagerItem; InsertAt: Integer): Integer; begin if InsertAt = -1 then InsertAt := FList.Count else begin if (not Paused) and (InsertAt = 0) and not IsFree then Items[0].Operation.Pause; end; FList.Insert(InsertAt, Item); Result := InsertAt; if (not Paused) and (IsFree or (InsertAt = 0)) then begin Item.Operation.Start; end else Item.Operation.Pause; end; function TOperationsManagerQueue.Insert(Item: TOperationsManagerItem; TargetOperation: TOperationHandle; PlaceBefore: Boolean): Integer; begin Result := GetIndexByHandle(TargetOperation); if Result >= 0 then begin if not PlaceBefore then Inc(Result); Insert(Item, Result); end; end; function TOperationsManagerQueue.IsFree: Boolean; begin Result := (FIdentifier = FreeOperationsQueueId) or (FIdentifier = ModalQueueId); end; procedure TOperationsManagerQueue.Pause; var Index: Integer; begin if IsFree then begin for Index := 0 to Count - 1 do Items[Index].Operation.Pause; end else begin FPaused := True; if Count > 0 then Items[0].Operation.Pause; end; end; function TOperationsManagerQueue.Remove(Item: TOperationsManagerItem): Boolean; var Index: Integer; begin Index := FList.Remove(Item); Result := Index <> -1; if Result and (not Paused) and (not IsFree) and (Index = 0) and (Count > 0) then begin Items[0].Operation.Start; end; end; procedure TOperationsManagerQueue.Stop; var i: Integer; begin for i := 0 to Count - 1 do Items[i].Operation.Stop; end; procedure TOperationsManagerQueue.TogglePause; begin if Paused then UnPause else Pause; end; procedure TOperationsManagerQueue.UnPause; var Index: Integer; begin if IsFree then begin for Index := 0 to Count - 1 do Items[Index].Operation.Start; end else begin if Count > 0 then Items[0].Operation.Start; FPaused := False; end; end; { TOperationsManager } constructor TOperationsManager.Create; var Event: TOperationManagerEvent; begin FQueues := TFPList.Create; FLastUsedHandle := InvalidOperationHandle; for Event := Low(FEventsListeners) to High(FEventsListeners) do FEventsListeners[Event] := TFPList.Create; inherited Create; end; destructor TOperationsManager.Destroy; var i: Integer; Event: TOperationManagerEvent; begin inherited Destroy; for Event := Low(FEventsListeners) to High(FEventsListeners) do begin for i := 0 to FEventsListeners[Event].Count - 1 do Dispose(PEventsListItem(FEventsListeners[Event].Items[i])); FreeAndNil(FEventsListeners[Event]); end; if QueuesCount > 0 then DCDebug('Warning: Destroying Operations Manager with active operations!'); FreeAndNil(FQueues); end; function TOperationsManager.AddOperation(Operation: TFileSourceOperation; ShowProgress: Boolean): TOperationHandle; begin if fspListOnMainThread in (Operation.FileSource as IFileSource).Properties then Result := AddOperationModal(Operation) else begin Result := AddOperation(Operation, FreeOperationsQueueId, False, ShowProgress); end; end; function TOperationsManager.AddOperation( Operation: TFileSourceOperation; QueueIdentifier: TOperationsManagerQueueIdentifier; InsertAtFrontOfQueue: Boolean; ShowProgress: Boolean = True): TOperationHandle; var Thread: TOperationThread; Item: TOperationsManagerItem; begin if QueueIdentifier = ModalQueueId then begin Result:= AddOperationModal(Operation); Exit; end; Result := InvalidOperationHandle; if Assigned(Operation) then begin Thread := TOperationThread.Create(True, Operation); if Assigned(Thread) then begin if Assigned(Thread.FatalException) then raise Thread.FatalException; Item := TOperationsManagerItem.Create(GetNextUnusedHandle, Operation, Thread); if Assigned(Item) then try Operation.PreventStart; Result := Item.Handle; // Set OnTerminate event so that we can cleanup when thread finishes. // Or instead of this create a timer for each thread and do: // Thread.WaitFor (or WaitForThreadTerminate(Thread.ThreadID)) Thread.OnTerminate := @ThreadTerminatedEvent; Item.SetQueue(GetOrCreateQueue(QueueIdentifier), InsertAtFrontOfQueue); NotifyEvents(Item, [omevOperationAdded]); if ShowProgress then ShowOperation(Item); Thread.Start; except Item.Free; end; end; end; end; function TOperationsManager.AddOperationModal(Operation: TFileSourceOperation): TOperationHandle; var Thread: TOperationThread; Item: TOperationsManagerItem; begin Result := InvalidOperationHandle; if Assigned(Operation) then begin Thread := TOperationThread.Create(True, Operation); if Assigned(Thread) then begin if Assigned(Thread.FatalException) then raise Thread.FatalException; Item := TOperationsManagerItem.Create(GetNextUnusedHandle, Operation, Thread); if Assigned(Item) then try Operation.PreventStart; Result := Item.Handle; Item.SetQueue(GetOrCreateQueue(ModalQueueId), False); NotifyEvents(Item, [omevOperationAdded]); ShowOperationModal(Item); ThreadTerminatedEvent(Thread); except Item.Free; end; end; end; end; function TOperationsManager.GetOperationsCount: Integer; var QueueIndex: Integer; Queue: TOperationsManagerQueue; begin Result := 0; for QueueIndex := 0 to QueuesCount - 1 do begin Queue := QueueByIndex[QueueIndex]; Inc(Result, Queue.Count); end; end; function TOperationsManager.GetQueuesCount: Integer; begin Result := FQueues.Count; end; function TOperationsManager.MoveToNewQueue(Item: TOperationsManagerItem): TOperationsManagerQueueIdentifier; var NewQueueId: TOperationsManagerQueueIdentifier; NewQueue: TOperationsManagerQueue; begin for NewQueueId := Succ(FreeOperationsQueueId) to MaxInt do begin if not Assigned(QueueByIdentifier[NewQueueId]) then begin NewQueue := GetOrCreateQueue(NewQueueId); Item.SetQueue(NewQueue); Exit(NewQueueId); end; end; end; function TOperationsManager.GetItemByHandle(Handle: TOperationHandle): TOperationsManagerItem; var QueueIndex: Integer; Queue: TOperationsManagerQueue; begin if Handle <> InvalidOperationHandle then begin for QueueIndex := 0 to QueuesCount - 1 do begin Queue := QueueByIndex[QueueIndex]; Result := Queue.ItemByHandle[Handle]; if Assigned(Result) then Exit; end; end; Result := nil; end; function TOperationsManager.GetItemByOperation(Operation: TFileSourceOperation): TOperationsManagerItem; var OperIndex, QueueIndex: Integer; Item: TOperationsManagerItem; Queue: TOperationsManagerQueue; begin for QueueIndex := 0 to QueuesCount - 1 do begin Queue := QueueByIndex[QueueIndex]; for OperIndex := 0 to Queue.Count - 1 do begin Item := Queue.Items[OperIndex]; if Item.Operation = Operation then Exit(Item); end; end; Result := nil; end; function TOperationsManager.GetItemByIndex(Index: Integer): TOperationsManagerItem; var OperIndex, QueueIndex: Integer; Queue: TOperationsManagerQueue; Counter: Integer; begin Counter := 0; for QueueIndex := 0 to QueuesCount - 1 do begin Queue := QueueByIndex[QueueIndex]; for OperIndex := 0 to Queue.Count - 1 do begin if Counter = Index then Exit(Queue.Items[OperIndex]); Inc(Counter); end; end; Result := nil; end; function TOperationsManager.GetOrCreateQueue(Identifier: TOperationsManagerQueueIdentifier): TOperationsManagerQueue; begin Result := QueueByIdentifier[Identifier]; if not Assigned(Result) then begin Result := TOperationsManagerQueue.Create(Identifier); FQueues.Add(Result); end; end; function TOperationsManager.GetNewQueueIdentifier: TOperationsManagerQueueIdentifier; var NewQueueId: TOperationsManagerQueueIdentifier; begin for NewQueueId := Succ(FreeOperationsQueueId) to MaxInt do begin if not Assigned(QueueByIdentifier[NewQueueId]) then begin Exit(NewQueueId); end; end; end; procedure TOperationsManager.MoveToQueue(Item: TOperationsManagerItem; QueueIdentifier: TOperationsManagerQueueIdentifier); var Queue: TOperationsManagerQueue; begin Queue := GetOrCreateQueue(QueueIdentifier); Item.SetQueue(Queue); end; function TOperationsManager.GetNextUnusedHandle: TOperationHandle; begin // Handles are consecutively incremented. // Even if they overflow there is little probability that // there will be that many operations. Result := InterLockedIncrement(FLastUsedHandle); if Result = InvalidOperationHandle then Result := InterLockedIncrement(FLastUsedHandle); end; function TOperationsManager.GetQueueByIndex(Index: Integer): TOperationsManagerQueue; begin if (Index >= 0) and (Index < FQueues.Count) then Result := TOperationsManagerQueue(FQueues.Items[Index]) else Result := nil; end; function TOperationsManager.GetQueueByIdentifier(Identifier: TOperationsManagerQueueIdentifier): TOperationsManagerQueue; var i: Integer; Queue: TOperationsManagerQueue; begin for i := 0 to FQueues.Count - 1 do begin Queue := QueueByIndex[i]; if Queue.Identifier = Identifier then Exit(Queue); end; Result := nil; end; procedure TOperationsManager.ThreadTerminatedEvent(Sender: TObject); var Thread: TOperationThread; Item: TOperationsManagerItem; OperIndex, QueueIndex: Integer; Queue: TOperationsManagerQueue; begin // This function is executed from the GUI thread (through Synchronize). Thread := Sender as TOperationThread; // Search the terminated thread in the operations list. for QueueIndex := 0 to QueuesCount - 1 do begin Queue := QueueByIndex[QueueIndex]; for OperIndex := 0 to Queue.Count - 1 do begin Item := TOperationsManagerItem(Queue.Items[OperIndex]); if Item.Thread = Thread then begin Item.RemoveFromQueue; NotifyEvents(Item, [omevOperationRemoved]); // Here the operation should not be used anymore // (by the thread and by any operations viewer). Item.Free; Exit; end; end; end; end; procedure TOperationsManager.PauseAll; var i: Integer; begin for i := 0 to QueuesCount - 1 do OperationsManager.QueueByIndex[i].Pause; end; procedure TOperationsManager.StopAll; var i: Integer; begin for i := 0 to QueuesCount - 1 do OperationsManager.QueueByIndex[i].Stop; end; procedure TOperationsManager.UnPauseAll; var i: Integer; begin for i := 0 to QueuesCount - 1 do OperationsManager.QueueByIndex[i].UnPause; end; function TOperationsManager.AllProgressPoint: Double; var Item: TOperationsManagerItem; i: Integer; begin Result := 0; if OperationsManager.OperationsCount <> 0 then begin for i := 0 to OperationsCount - 1 do begin Item := OperationsManager.GetItemByIndex(i); if Assigned(Item) then Result := Result + Item.Operation.Progress; // calculate allProgressBar end; Result := Result / OperationsManager.OperationsCount; // Ïîêàçûâàåì ñðåäíèé ïðîãðåññ end; end; procedure TOperationsManager.AddEventsListener(Events: TOperationManagerEvents; FunctionToCall: TOperationManagerEventNotify); var Item: PEventsListItem; Event: TOperationManagerEvent; begin for Event := Low(TOperationManagerEvent) to High(TOperationManagerEvent) do begin if Event in Events then begin Item := New(PEventsListItem); Item^.EventFunction := FunctionToCall; FEventsListeners[Event].Add(Item); end; end; end; procedure TOperationsManager.RemoveEventsListener(Events: TOperationManagerEvents; FunctionToCall: TOperationManagerEventNotify); var Item: PEventsListItem; Event: TOperationManagerEvent; i: Integer; begin for Event := Low(TOperationManagerEvent) to High(TOperationManagerEvent) do begin if Event in Events then begin for i := 0 to FEventsListeners[Event].Count - 1 do begin Item := PEventsListItem(FEventsListeners[Event].Items[i]); if Item^.EventFunction = FunctionToCall then begin FEventsListeners[Event].Delete(i); Dispose(Item); break; // break from one for only end; end; end; end; end; procedure TOperationsManager.NotifyEvents(Item: TOperationsManagerItem; Events: TOperationManagerEvents); var EventItem: PEventsListItem; Event: TOperationManagerEvent; i: Integer; begin for Event := Low(TOperationManagerEvent) to High(TOperationManagerEvent) do begin if Event in Events then begin // Call each listener function. for i := 0 to FEventsListeners[Event].Count - 1 do begin EventItem := PEventsListItem(FEventsListeners[Event].Items[i]); EventItem^.EventFunction(Item, Event); end; end; end; end; initialization OperationsManager := TOperationsManager.Create; finalization FreeAndNil(OperationsManager); end.
unit DocumentEditor; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, GsDocument, DocumentViewer, Vcl.Menus, VirtualTrees, ActiveX, Vcl.ImgList, System.Actions, Vcl.ActnList, System.ImageList, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls, MdiChilds.ElementEditor, FmItemsEditor, Vcl.Grids, Vcl.CheckLst, CommCtrl, Generics.Collections, Vcl.ToolWin, System.UITypes, FmFilterSelect, GlobalData, JvPageList, JvExControls, JvExComCtrls, JvPageListTreeView; type TNodeAction = procedure(Node: PVirtualNode) of object; TListViewDragMode = (ddCoefs, ddMaterials, ddMachines, ddWorkers, ddMachinist); PResourceData = ^TResourceData; TResourceData = record Kind: TGsResourceKind; Code: string; Caption: string; Measure: string; Mass: Real; WorkClass: Real; Price1: Real; Price2: Real; IsResource: Boolean; Hash: string; procedure UpdateHash; end; TfrmDocumentEditor = class(TfrmDocumentViewer, IDataRowIterator) AL: TActionList; acCopy: TAction; acCut: TAction; acPaste: TAction; pcEditors: TPageControl; tsContainer: TTabSheet; tsChapter: TTabSheet; tsRow: TTabSheet; edtContainerCaption: TLabeledEdit; pnlSmartEditor: TPanel; Splitter: TSplitter; btnConfirm: TButton; btnNext: TButton; btnPrev: TButton; btnEdit: TButton; edtChapterCode: TLabeledEdit; edtChapterCaption: TLabeledEdit; edtCode: TLabeledEdit; edtCaption: TLabeledEdit; edtMeasure: TLabeledEdit; acSearch: TAction; CheckListBox1: TCheckListBox; pcBulletin: TPageControl; TabSheet1: TTabSheet; Splitter1: TSplitter; lvCoefs: TListView; acListViewAdd: TAction; acListViewRemove: TAction; acListViewUpdate: TAction; N2: TMenuItem; PopupMenuBookMarks: TPopupMenu; N3: TMenuItem; N4: TMenuItem; MICalculateRows: TMenuItem; N5: TMenuItem; FilterOZP: TMenuItem; FilterMT: TMenuItem; FilterEM: TMenuItem; FilterZM: TMenuItem; acSortByCode: TAction; N1: TMenuItem; acLoadPrices: TAction; TabSheet7: TTabSheet; edtTypeName: TLabeledEdit; edtDocNumber: TLabeledEdit; edtDocTitle: TLabeledEdit; cbDocType: TComboBox; Label1: TLabel; acExcludePositions: TAction; N6: TMenuItem; tsResources: TTabSheet; VSTResources: TVirtualStringTree; tvBulletin: TJvPageListTreeView; Splitter2: TSplitter; plBulletin: TJvPageList; JvStandardPage1: TJvStandardPage; JvStandardPage2: TJvStandardPage; procedure N4Click(Sender: TObject); procedure N5Click(Sender: TObject); procedure N1Click(Sender: TObject); procedure VSTDragDrop(Sender: TBaseVirtualTree; Source: TObject; DataObject: IDataObject; Formats: TFormatArray; Shift: TShiftState; Pt: TPoint; var Effect: Integer; Mode: TDropMode); procedure VSTDragOver(Sender: TBaseVirtualTree; Source: TObject; Shift: TShiftState; State: TDragState; Pt: TPoint; Mode: TDropMode; var Effect: Integer; var Accept: Boolean); procedure VSTKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FilterOZPClick(Sender: TObject); procedure N7Click(Sender: TObject); procedure N8Click(Sender: TObject); procedure N10Click(Sender: TObject); procedure N11Click(Sender: TObject); procedure acCopyExecute(Sender: TObject); procedure acCutExecute(Sender: TObject); procedure acPasteExecute(Sender: TObject); procedure acCopyUpdate(Sender: TObject); procedure acPasteUpdate(Sender: TObject); procedure VSTNodeClick(Sender: TBaseVirtualTree; const HitInfo: THitInfo); procedure btnPrevClick(Sender: TObject); procedure btnNextClick(Sender: TObject); procedure btnConfirmClick(Sender: TObject); procedure VSTAfterItemPaint(Sender: TBaseVirtualTree; TargetCanvas: TCanvas; Node: PVirtualNode; ItemRect: TRect); procedure btnEditClick(Sender: TObject); procedure VSTNodeDblClick(Sender: TBaseVirtualTree; const HitInfo: THitInfo); procedure acSearchExecute(Sender: TObject); procedure CheckListBox1DblClick(Sender: TObject); procedure CheckListBox1DragDrop(Sender, Source: TObject; X, Y: Integer); procedure CheckListBox1DragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); procedure CheckListBox1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); // procedure lvMaterialsMouseDown(Sender: TObject; Button: TMouseButton; // Shift: TShiftState; X, Y: Integer); procedure ZonesClick(Sender: TObject); procedure N2Click(Sender: TObject); procedure N3Click(Sender: TObject); procedure MICalculateRowClick(Sender: TObject); procedure MICalculateRowsClick(Sender: TObject); procedure FilterMTClick(Sender: TObject); procedure FilterEMClick(Sender: TObject); procedure FilterZMClick(Sender: TObject); procedure N6Click(Sender: TObject); procedure acSortByCodeExecute(Sender: TObject); // procedure acLoadPricesExecute(Sender: TObject); procedure edtTypeNameChange(Sender: TObject); procedure edtDocNumberChange(Sender: TObject); procedure edtDocTitleChange(Sender: TObject); procedure cbDocTypeChange(Sender: TObject); procedure acExcludePositionsExecute(Sender: TObject); procedure VSTResourcesGetNodeDataSize(Sender: TBaseVirtualTree; var NodeDataSize: Integer); procedure VSTResourcesFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode); procedure VSTResourcesGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); procedure VSTResourcesBeforeItemErase(Sender: TBaseVirtualTree; TargetCanvas: TCanvas; Node: PVirtualNode; ItemRect: TRect; var ItemColor: TColor; var EraseAction: TItemEraseAction); procedure VSTResourcesNewText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; NewText: string); procedure VSTResourcesNodeDblClick(Sender: TBaseVirtualTree; const HitInfo: THitInfo); procedure VSTResourcesDragOver(Sender: TBaseVirtualTree; Source: TObject; Shift: TShiftState; State: TDragState; Pt: TPoint; Mode: TDropMode; var Effect: Integer; var Accept: Boolean); private //удалить ненужные методы... FEditorForm: TFmElementEditor; FEdit: TEdit; procedure UpdateItem; procedure SetExpanded(Value: Boolean); // procedure SetEditText; function GetSmartEditor: Boolean; procedure SetSmartEditor(AValue: Boolean); procedure UpdateSmartViewer(Item: TGsAbstractItem); // procedure EditKeyPress(Sender: TObject; var Key: Char); // procedure editExit(Sender: TObject); // procedure RemoveCoefByCode(Code: string); // procedure RemoveResourceByCode(Code: string); procedure FilterRows(Cost: TGsCostKind); protected procedure DoEditItem(Sender: TObject; Item: TGsAbstractItem); override; procedure SetDocument(ADocument: TGsDocument); override; // procedure UpdateMaterials; procedure UpdateCoefs; procedure UpdateCoefsInRow(Row: TGsRow; ListItem: TListItem); procedure DragDropFromLV(Tree: TBaseVirtualTree; LV: TBaseVirtualTree; Mode: TListViewDragMode); procedure LoadPrices(Source: TGsDocument); procedure DoUpdateZoneData(); override; procedure UpdateResourceTree; procedure UpdateResources(Data: PResourceData); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; { Методы для привзяки к панели управления } procedure EditSelectedPositions; procedure Copy(Node: PVirtualNode); procedure UpdateBulletinContent; procedure Cut(Node: PVirtualNode); procedure Paste(Node: PVirtualNode); procedure CreateElement(ANode: PVirtualNode); procedure EditElement(Node: PVirtualNode); procedure DeleteElement(Node: PVirtualNode); procedure CreateChapter(Node: PVirtualNode); procedure CreateSubChapter(Node: PVirtualNode); procedure EditAttributes(Node: PVirtualNode); procedure SelectPositions; procedure SelectPositionsFilter; { Если делали процедуру VST.ClearSelection то лучше вызывать методы через этот: } //хер знает почему я так сделал, надо бы переделать. procedure TryExecute(NodeAction: TNodeAction); procedure RemoveElement; overload; procedure RemoveElement(Node: PVirtualNode); overload; procedure UpdateItemData(Data: TGsAbstractItem); procedure SelectNodes(ChapterType: TGsChapterType); procedure Next; procedure Prev; property ExpandedTree: Boolean write SetExpanded; property SmartEditorEnabled: Boolean read GetSmartEditor write SetSmartEditor; end; implementation // uses uses FmTreeSearch, FmResourceCountEditor, FmEditSelection; // ElementEditor; {$R *.dfm} procedure TfrmDocumentEditor.acCopyExecute(Sender: TObject); begin TryExecute(Self.Copy); end; procedure TfrmDocumentEditor.acCopyUpdate(Sender: TObject); begin acCopy.Enabled := Document <> nil; end; procedure TfrmDocumentEditor.acCutExecute(Sender: TObject); begin TryExecute(Self.Cut); end; procedure TfrmDocumentEditor.acExcludePositionsExecute(Sender: TObject); var Node: PVirtualNode; Data: PVSTDocument; List: TList; I: Integer; Item: TGsAbstractItem; begin for Node in VST.SelectedNodes do begin Data := VST.GetNodeData(Node); if Data.Item is TGsAbstractContainer then begin List := TList.Create; try case Document.DocumentType of dtPrice: TGsAbstractContainer(Data.Item) .EnumItems(List, TGsPriceElement, True); dtIndex: TGsAbstractContainer(Data.Item) .EnumItems(List, TGsIndexElement, True); dtBaseData: TGsAbstractContainer(Data.Item).EnumItems(List, TGsRow, True); end; for I := 0 to List.Count - 1 do begin Item := TGsAbstractItem(List[I]); Data.Item.Add(Item.Parent.Extract(Item)); end; finally List.Free; end; end else ShowMessage ('Для извлечения позиций необходимо выбрать раздел, в котором стоят данные позиции.'); end; UpdateContent; end; //procedure TfrmDocumentEditor.acListViewUpdateExecute(Sender: TObject); //begin // UpdateBulletinContent; //end; //procedure TfrmDocumentEditor.acLoadPricesExecute(Sender: TObject); //var // OD: TOpenDialog; // ADocument: TGsDocument; //begin // OD := TOpenDialog.Create(Self); // try // OD.Filter := 'XML | *.xml'; // if OD.Execute then // begin // Cursor := crHourGlass; // ADocument := TGsDocument.Create; // try // ADocument.LoadFromFile(OD.FileName); // LoadPrices(ADocument); // UpdateMaterials; // ShowMessage('Цены обновлены'); // finally // Cursor := crDefault; // ADocument.Free; // end; // end; // finally // OD.Free; // end; //end; procedure TfrmDocumentEditor.acPasteExecute(Sender: TObject); begin TryExecute(Self.Paste); end; procedure TfrmDocumentEditor.acPasteUpdate(Sender: TObject); begin acPaste.Enabled := (Document <> nil) and (GsDocument.Paste <> nil); end; procedure TfrmDocumentEditor.acSearchExecute(Sender: TObject); var Fm: TFmVirtualTreeSearch; begin Fm := TFmVirtualTreeSearch.Create(Self); try Fm.Tree := Self.VST; Fm.ShowModal; finally Fm.Free; end; end; procedure TfrmDocumentEditor.acSortByCodeExecute(Sender: TObject); var Node: PVirtualNode; Data: PVSTDocument; begin Node := VST.GetFirstSelected; if Node <> nil then begin Data := VST.GetNodeData(Node); if Data.Item is TGsAbstractContainer then begin TGsAbstractContainer(Data.Item).SortByCode; UpdateContent; end; end; end; procedure TfrmDocumentEditor.btnConfirmClick(Sender: TObject); var Node: PVirtualNode; Data: PVSTDocument; begin Node := VST.GetFirstSelected; if Node <> nil then begin Data := VST.GetNodeData(Node); UpdateItemData(Data.Item); VST.InvalidateNode(Node); end; end; procedure TfrmDocumentEditor.btnEditClick(Sender: TObject); begin TryExecute(EditElement); end; procedure TfrmDocumentEditor.btnNextClick(Sender: TObject); begin Next; end; procedure TfrmDocumentEditor.btnPrevClick(Sender: TObject); begin Prev; end; procedure TfrmDocumentEditor.CheckListBox1DblClick(Sender: TObject); var Node: PVirtualNode; Index: Integer; begin Index := TCheckListBox(Sender).ItemIndex; if Index <> -1 then begin VST.ClearSelection; Node := PVirtualNode(TObject(TCheckListBox(Sender).Items.Objects[Index])); VST.FocusedNode := Node; VST.Selected[Node] := True; end; end; procedure TfrmDocumentEditor.CheckListBox1DragDrop(Sender, Source: TObject; X, Y: Integer); var Node: PVirtualNode; Str: string; begin if Source is TVirtualStringTree then begin for Node in TVirtualStringTree(Source).SelectedNodes do begin Str := TVirtualStringTree(Source).Text[Node, 0] + ' ' + TVirtualStringTree(Source).Text[Node, 1]; if TCheckListBox(Sender).Items.IndexOf(Str) = -1 then TCheckListBox(Sender).Items.AddObject(Str, TObject(Node)); end; end; end; procedure TfrmDocumentEditor.CheckListBox1DragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); begin Accept := True; end; procedure TfrmDocumentEditor.CheckListBox1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = vk_delete then CheckListBox1.DeleteSelected; end; procedure TfrmDocumentEditor.cbDocTypeChange(Sender: TObject); begin case cbDocType.ItemIndex of 0: Document.BaseDataType := bdtMachine; 1: Document.BaseDataType := bdtMaterial; 2: Document.BaseDataType := bdtERs; 3: Document.BaseDataType := bdtESNs; 4: Document.BaseDataType := bdtWorkerScale; 5: Document.BaseDataType := bdtCargo; 6: Document.BaseDataType := bdtProject; end; UpdateContent; // UpdateBulletinContent; { Машины Материалы Расценки Нормы Рабочие Перевозки Проектный } end; procedure TfrmDocumentEditor.Copy(Node: PVirtualNode); var AData: PVSTDocument; begin AData := VST.GetNodeData(Node); if AData.Item is TGsResource then GsDocument.Copy(AData.Item.Parent) else if (AData.Item.Parent <> nil) then GsDocument.Copy(AData.Item); end; constructor TfrmDocumentEditor.Create(AOwner: TComponent); begin inherited Create(AOwner); FEditorForm := TFmElementEditor.Create(Application); FEditorForm.Item := nil; FEditorForm.RowIterator := Self; SmartEditorEnabled := False; // FEdit := TEdit.Create(Self); // FEdit.OnKeyPress := EditKeyPress; // FEdit.OnExit := editExit; // FEdit.Visible := False; end; procedure TfrmDocumentEditor.CreateChapter(Node: PVirtualNode); var AData: PVSTDocument; AContainer: TGsAbstractContainer; ContainerClass: TGsAbstractItemClass; begin if Node <> nil then begin AData := VST.GetNodeData(Node); ContainerClass := TGsAbstractContainer; if Document.DocumentType = dtBaseData then ContainerClass := TGsChapter; if (AData.Item is TGsAbstractContainer) and (AData.Item.Parent.Parent <> nil) then begin AContainer := ContainerClass.Create(Document) as TGsAbstractContainer; AData.Item.Parent.Add(AContainer); AddItem(AContainer, Node.Parent); end; end; end; procedure TfrmDocumentEditor.CreateElement(ANode: PVirtualNode); var Data: PVSTDocument; Item: TGsAbstractItem; AObject: TGsAbstractItem; begin ANode := VST.GetFirstSelected; Item := nil; if ANode <> nil then begin case Document.DocumentType of dtBaseData: begin Item := TGsRow.Create(Document); TGsRow(Item).Code := '<code>'; TGsRow(Item).Caption := '<caption>'; TGsRow(Item).Measure := '<measure>'; end; dtPrice: begin Item := TGsPriceElement.Create(Document); TGsPriceElement(Item).Code := '<code>'; TGsPriceElement(Item).Caption := '<caption>'; TGsPriceElement(Item).Measure := '<measure>'; end; dtIndex: begin Item := TGsIndexElement.Create(Document); TGsIndexElement(Item).Code := '<code>'; TGsIndexElement(Item).Caption := '<caption>'; end; end; Data := VST.GetNodeData(ANode); AObject := Data.Item; while (ANode <> nil) and (AObject <> nil) and not(AObject is TGsAbstractContainer) do begin ANode := ANode.Parent; Data := VST.GetNodeData(ANode); AObject := Data.Item; end; if AObject <> nil then begin AObject.Add(Item); AddItem(Item, ANode); end; end; end; procedure TfrmDocumentEditor.CreateSubChapter(Node: PVirtualNode); var AData: PVSTDocument; AContainer: TGsAbstractContainer; ContainerClass: TGsAbstractItemClass; begin if Node <> nil then begin AData := VST.GetNodeData(Node); ContainerClass := TGsAbstractContainer; if Document.DocumentType = dtBaseData then ContainerClass := TGsChapter; if (AData.Item is TGsAbstractContainer) then begin AContainer := ContainerClass.Create(Document) as TGsAbstractContainer; AData.Item.Add(AContainer); AddItem(AContainer, Node); end; end; end; procedure TfrmDocumentEditor.Cut(Node: PVirtualNode); var AData: PVSTDocument; CanCut: Boolean; begin CanCut := True; AData := VST.GetNodeData(Node); if AData.Item is TGsResource then GsDocument.Cut(AData.Item.Parent) else if AData.Item.Parent.Parent = nil then begin GsDocument.Cut(nil); CanCut := False; end else GsDocument.Cut(AData.Item); if CanCut then VST.DeleteNode(Node); end; procedure TfrmDocumentEditor.DeleteElement(Node: PVirtualNode); begin TryExecute(Self.DeleteElement); end; destructor TfrmDocumentEditor.Destroy; begin FEdit.Free; FEditorForm.Free; inherited Destroy; end; procedure TfrmDocumentEditor.DoEditItem(Sender: TObject; Item: TGsAbstractItem); begin if FEditorForm.Item <> nil then FEditorForm.Show; end; procedure TfrmDocumentEditor.DoUpdateZoneData; begin UpdateBulletinContent; end; procedure TfrmDocumentEditor.DragDropFromLV(Tree: TBaseVirtualTree; LV: TBaseVirtualTree; Mode: TListViewDragMode); var // TargetNode: PVirtualNode; // TargetData: PVSTDocument; // Row: TGsRow; // ListItem: TListItem; // List: TList<TGsRow>; // Resource: TGsResource; // O: TGsOutlay; NodeFrom: PVirtualNode; NodeTo: PVirtualNode; DataFrom: PResourceData; DataTo: PVSTDocument; Resource: TGsResource; Row: TGsRow; O: TGsOutlay; begin NodeFrom := LV.FocusedNode; if NodeFrom = nil then Exit; NodeTo := Tree.DropTargetNode; if NodeTo = nil then Exit; DataTo := Tree.GetNodeData(NodeTo); DataFrom := LV.GetNodeData(NodeFrom); if (DataTo.Item is TGsRow) and (DataFrom.IsResource) then begin Row := TGsRow(DataTo.Item); Resource := Row.ResourceByCode(DataFrom.Code); if Resource = nil then begin O := TGsOutlay.Create(Document); Resource := TGsResource.Create(Document); O.Add(Resource); case DataFrom.Kind of rkMaterial: Row.MaterialList.Add(O); rkWorker: Row.WorkerList.Add(O); rkMashinist: Row.MachinistList.Add(O); rkMashine: Row.MachineList.Add(O); end; Resource.Kind := DataFrom.Kind; Resource.Code := DataFrom.Code; Resource.Caption := DataFrom.Caption; Resource.Measure := DataFrom.Measure; Resource.SetCostValue(cstPrice, DataFrom.Price1, CurrentZone); if DataFrom.Kind = rkMaterial then begin Resource.SetCostValue(cstWSP, DataFrom.Price2, CurrentZone); Resource.SetCostValue(cstMass, DataFrom.Mass, CurrentZone); end else if DataFrom.Kind = rkMashine then Resource.SetCostValue(cstZM, DataFrom.Price2, CurrentZone) else if DataFrom.Kind = rkWorker then Resource.Attributes[Ord(raWorkerClass)] := DataFrom.WorkClass; AddItem(Resource, NodeTo); end else O := Resource.Outlay; with TFmSetResourceCount.Create(Application) do begin Outlay := O; ShowModal; Free; end; VST.RepaintNode(NodeTo); end; // TargetNode := Tree.DropTargetNode; // if TargetNode = nil then // Exit; // // TargetData := Tree.GetNodeData(TargetNode); // ListItem := LV.Selected; // // if Mode = ddCoefs then // begin // if TargetData.Item is TGsRow then // begin // Row := TGsRow(TargetData.Item); // if MessageDlg('Применить (обновить) данный коэффициент к расценке?', // mtConfirmation, mbYesNo, 0) = mrYes then // UpdateCoefsInRow(Row, ListItem); // end // else // // if TargetData.Item is TGsChapter then // begin // if MessageDlg // ('Применить (обновить) данный коэффициент на группу расценок?', // mtConfirmation, mbYesNo, 0) = mrYes then // begin // List := TargetData.Item.Iterate<TGsRow>; // try // for Row in List do // UpdateCoefsInRow(Row, ListItem); // finally // List.Free // end; // end; // end; // // end // else // begin // if TargetData.Item is TGsRow then // begin // Row := TGsRow(TargetData.Item); // Resource := Row.ResourceByCode(ListItem.Caption); // if Resource = nil then // begin // O := TGsOutlay.Create(Document); // Resource := TGsResource.Create(Document); // O.Add(Resource); // Resource.Code := ListItem.Caption; // Resource.Caption := ListItem.SubItems[0]; // Resource.Measure := ListItem.SubItems[1]; // Resource.SetCostValue(cstPrice, ConvertToFloat(ListItem.SubItems[2]), // CurrentZone); // // case Mode of // ddMaterials: // begin // Resource.Kind := rkMaterial; // Row.MaterialList.Add(O); // Resource.SetCostValue(cstWSP, ConvertToFloat(ListItem.SubItems[3] // ), CurrentZone); // Resource.SetCostValue(cstMass, ConvertToFloat(ListItem.SubItems[4] // ), CurrentZone); // end; // ddMachines: // begin // Resource.Kind := rkMashine; // Row.MachineList.Add(O); // Resource.SetCostValue(cstZM, ConvertToFloat(ListItem.SubItems[3]), // CurrentZone); // end; // ddWorkers: // begin // Resource.Kind := rkWorker; // Row.WorkerList.Add(O); // Resource.Attributes[Ord(raWorkerClass)] := // ConvertToFloat(ListItem.SubItems[3]); // end; // ddMachinist: // begin // Resource.Kind := rkMashinist; // Row.MachinistList.Add(O); // // end; // end; // // AddItem(Resource, TargetNode); // end // else // O := Resource.Outlay; // // with TFmSetResourceCount.Create(Self) do // begin // Outlay := O; // ShowModal; // Free; // end; // // end; // end; // // Tree.RepaintNode(TargetNode); end; procedure TfrmDocumentEditor.EditAttributes(Node: PVirtualNode); var ItemsEditor: TItemsEditorForm; Data: PVSTDocument; NewChapter: TGsAbstractContainer; ANode: PVirtualNode; NeedToRestoreParent: Boolean; begin NeedToRestoreParent := False; Data := VST.GetNodeData(Node); if not(Data.Item is TGsAbstractContainer) then begin NewChapter := nil; case Document.DocumentType of dtPrice, dtIndex: NewChapter := TGsAbstractContainer.Create(Document); dtBaseData: NewChapter := TGsChapter.Create(Document); end; for ANode in VST.SelectedNodes do begin Data := VST.GetNodeData(ANode); if (Data.Item is TGsRow) or (Data.Item is TGsIndexElement) or (Data.Item is TGsPriceElement) then begin Data.Item.IntTag := Integer(Data.Item.Parent); NewChapter.Add(Data.Item); NeedToRestoreParent := True; end; end; end else NewChapter := Data.Item as TGsAbstractContainer; ItemsEditor := TItemsEditorForm.Create(Self); ItemsEditor.Chapter := NewChapter; ItemsEditor.ShowModal; if NeedToRestoreParent then begin while NewChapter.Count > 0 do begin NewChapter.Items[0].Parent := TGsAbstractItem(NewChapter.Items[0].IntTag); NewChapter.Extract(NewChapter.Items[0]); end; NewChapter.Free; end; end; procedure TfrmDocumentEditor.EditElement(Node: PVirtualNode); var Data: PVSTDocument; begin Data := VST.GetNodeData(Node); DoEditItem(VST, Data.Item); VST.InvalidateNode(Node) end; //procedure TfrmDocumentEditor.editExit(Sender: TObject); //begin // SetEditText; //end; // //procedure TfrmDocumentEditor.EditKeyPress(Sender: TObject; var Key: Char); //begin // if Key = #13 then // begin // SetEditText; // Key := #0; // end; //end; procedure TfrmDocumentEditor.EditSelectedPositions; begin with TFmEditSelections.Create(Application) do begin ParentTree := Self; ShowModal; Free; end; end; procedure TfrmDocumentEditor.edtDocNumberChange(Sender: TObject); begin Document.Number := edtDocNumber.Text; end; procedure TfrmDocumentEditor.edtDocTitleChange(Sender: TObject); begin Document.Title := edtDocTitle.Text; end; procedure TfrmDocumentEditor.edtTypeNameChange(Sender: TObject); begin Document.TypeName := edtTypeName.Text; end; procedure TfrmDocumentEditor.FilterRows(Cost: TGsCostKind); var Node: PVirtualNode; Data: PVSTDocument; PZ: Real; begin Self.CheckListBox1.Clear; for Node in VST.Nodes do begin Data := VST.GetNodeData(Node); if (Data.Item is TGsRow) and (Document.CheckRowCost(TGsRow(Data.Item), Cost, PZ, CurrentZone)) then begin // CheckListBox1.AddItem(VST.Text[Node, 0] + ' расхождение стоимости ПЗ: ' + // FloatToStr(Round(PZ * 100) / 100) + ' руб.', TObject(Node)); VST.Selected[Node] := True; end; end; end; procedure TfrmDocumentEditor.FilterZMClick(Sender: TObject); begin FilterRows(cstZM); end; function TfrmDocumentEditor.GetSmartEditor: Boolean; begin Result := pnlSmartEditor.Visible; end; procedure TfrmDocumentEditor.LoadPrices(Source: TGsDocument); var List: TList<TGsResource>; Resource: TGsResource; S: TStringList; SourceList: TList; I: Integer; Index: Integer; Row: TGsRow; begin if Source.Zones.Count <> Document.Zones.Count then Exit; SourceList := TList.Create; try Source.Chapters.EnumItems(SourceList, TGsRow, True); if SourceList.Count <> 0 then begin S := TStringList.Create; try for I := 0 to SourceList.Count - 1 do S.AddObject(TGsRow(SourceList[I]).Code, TGsRow(SourceList[I])); List := (Document.Chapters as TGsAbstractItem).Iterate<TGsResource>; try for Resource in List do begin Index := S.IndexOf(Resource.Code); if Index <> -1 then begin Row := TGsRow(S.Objects[Index]); Resource.SetCostValue(cstPrice, Row.GetCostValue(cstPrice, CurrentZone), CurrentZone); case Resource.Kind of rkMaterial: Resource.SetCostValue(cstWSP, Row.GetCostValue(cstPriceBT, CurrentZone), CurrentZone); rkMashine: Resource.SetCostValue(cstZM, Row.GetCostValue(cstZM, CurrentZone), CurrentZone); end; end; end; finally List.Free; end; finally S.Free; end; end; finally SourceList.Free; end; end; //procedure TfrmDocumentEditor.lvMaterialsMouseDown(Sender: TObject; // Button: TMouseButton; Shift: TShiftState; X, Y: Integer); //var // R: TRect; // ht: TLVHitTestInfo; //begin // FEditedLV := TListView(Sender); // FEdit.Parent := TListView(Sender); // FEdit.OnKeyPress := EditKeyPress; // ListItem := TListView(Sender).GetItemAt(2, Y); // if ListItem = nil then // Exit; // FillChar(ht, SizeOf(ht), 0); // ht.Pt.X := X; // ht.Pt.Y := Y; // SendMessage(TListView(Sender).Handle, LVM_SUBITEMHITTEST, 0, Integer(@ht)); // FSub := ht.iSubItem; // // Caption := inttostr(FSub); // if FSub > 0 then // begin // ListView_GetSubItemRect(TListView(Sender).Handle, ListItem.Index, FSub, // LVIR_BOUNDS, @R); // // Offsetrect(R, TListView(Sender).Left, TListView(Sender).Top); // FEdit.SetBounds(R.Left, R.Top, R.Right - R.Left, R.Bottom - R.Top); // Dec(FSub); // FEdit.Text := ListItem.SubItems[FSub]; // FEdit.Visible := True; // FEdit.SetFocus; // end; //end; procedure TfrmDocumentEditor.MICalculateRowClick(Sender: TObject); var Node: PVirtualNode; Data: PVSTDocument; begin Node := VST.GetFirstSelected; if Node <> nil then begin Data := VST.GetNodeData(Node); if Data.Item is TGsRow then TGsRow(Data.Item).Calculate; end; end; procedure TfrmDocumentEditor.MICalculateRowsClick(Sender: TObject); var Node: PVirtualNode; Data: PVSTDocument; begin for Node in VST.SelectedNodes do begin Data := VST.GetNodeData(Node); if Data.Item is TGsRow then TGsRow(Data.Item).Calculate; end; end; procedure TfrmDocumentEditor.N10Click(Sender: TObject); begin TryExecute(Self.CreateElement); end; procedure TfrmDocumentEditor.N11Click(Sender: TObject); begin RemoveElement; end; procedure TfrmDocumentEditor.N1Click(Sender: TObject); var ANode: PVirtualNode; Data: PVSTDocument; begin ANode := VST.GetFirstSelected; if ANode <> nil then begin Data := VST.GetNodeData(ANode); DoEditItem(VST, Data.Item); end; end; procedure TfrmDocumentEditor.N2Click(Sender: TObject); begin FilterRows(cstPZ); end; procedure TfrmDocumentEditor.N3Click(Sender: TObject); var d: TSaveDialog; begin d := TSaveDialog.Create(Self); try d.Filter := 'Text document | *.txt'; d.DefaultExt := 'txt'; d.FileName := ChangeFileExt(Document.FileName, '.txt'); if d.Execute then CheckListBox1.Items.SaveToFile(d.FileName); finally d.Free; end; end; procedure TfrmDocumentEditor.N4Click(Sender: TObject); begin SetExpanded(True); end; procedure TfrmDocumentEditor.N5Click(Sender: TObject); begin SetExpanded(False); end; procedure TfrmDocumentEditor.N6Click(Sender: TObject); var Node: PVirtualNode; Data: PVSTDocument; begin Node := VST.GetFirstSelected; if Node <> nil then begin Data := VST.GetNodeData(Node); if Data.Item is TGsAbstractContainer then begin TGsAbstractContainer(Data.Item).SortByCode; UpdateContent; end; end; end; procedure TfrmDocumentEditor.FilterEMClick(Sender: TObject); begin FilterRows(cstEM); end; procedure TfrmDocumentEditor.FilterMTClick(Sender: TObject); begin FilterRows(cstMT); end; procedure TfrmDocumentEditor.FilterOZPClick(Sender: TObject); begin FilterRows(cstOZ); end; procedure TfrmDocumentEditor.N7Click(Sender: TObject); begin TryExecute(Self.Cut); end; procedure TfrmDocumentEditor.N8Click(Sender: TObject); begin TryExecute(Self.Paste); end; procedure TfrmDocumentEditor.Next; begin SendMessage(VST.Handle, WM_KEYDOWN, VK_DOWN, 0); UpdateItem; end; procedure TfrmDocumentEditor.Paste(Node: PVirtualNode); var InsertedNode: PVirtualNode; Data: PVSTDocument; AObject, InsertingObj: TGsAbstractItem; PasteItem: TGsAbstractItem; begin Node := VST.GetFirstSelected; if Node = nil then Exit; Data := VST.GetNodeData(Node); AObject := Data.Item; PasteItem := GsDocument.Paste; if (PasteItem = nil) or (PasteItem is TGsOutlay) then Exit; while (Node <> nil) and (AObject <> nil) and not(AObject is TGsAbstractContainer) do begin Node := Node.Parent; Data := VST.GetNodeData(Node); AObject := Data.Item; end; if not(AObject = nil) then begin Screen.Cursor := crHourGlass; try InsertingObj := TGsAbstractItem.CreateCompatibleObject(PasteItem); InsertingObj.Assign(PasteItem); (AObject as TGsAbstractContainer).Add(InsertingObj); if InsertingObj is TGsAbstractContainer then begin InsertedNode := AddItem(InsertingObj, Node); AddContainer(InsertingObj as TGsAbstractContainer, InsertedNode); end else PriceToVST(InsertingObj, Node); finally Screen.Cursor := crDefault; end; end; GsDocument.Copy(nil); end; procedure TfrmDocumentEditor.Prev; begin SendMessage(VST.Handle, WM_KEYDOWN, VK_UP, 0); UpdateItem; end; //procedure TfrmDocumentEditor.RemoveCoefByCode(Code: string); //var // Row: TGsRow; // List: TList<TGsRow>; // Item: TGsAbstractItem; //begin // List := Document.GetAll<TGsRow>; // try // for Row in List do // begin // Item := Row.FactorList.ItemByAttribute(Ord(dtaNumber), Code, TGsFactor); // if Item <> nil then // Row.FactorList.Remove(Item); // end; // finally // List.Free // end; //end; procedure TfrmDocumentEditor.RemoveElement(Node: PVirtualNode); var Data: PVSTDocument; AObject: TGsAbstractItem; aOutlay: TGsOutlay; aObjectParent: TGsAbstractContainer; begin if Node = nil then Exit; Data := VST.GetNodeData(Node); if Data.Item.Parent is TGsAbstractContainer then begin AObject := Data.Item; VST.DeleteNode(Node); aObjectParent := TGsAbstractContainer(AObject.Parent); aObjectParent.Extract(AObject); FreeAndNil(AObject); end else if Data.Item.Parent is TGsOutlay then begin // Это ресурс aOutlay := Data.Item.Parent as TGsOutlay; VST.DeleteNode(Node); TGsAbstractContainer(aOutlay.Parent).Extract(aOutlay); FreeAndNil(aOutlay); end else if Data.Item is TGsIndexAddOn then begin AObject := Data.Item.Parent; AObject.Extract(Data.Item).Free; VST.DeleteNode(Node); end; VST.UpdateScrollBars(True); end; procedure TfrmDocumentEditor.RemoveElement; var Node: PVirtualNode; begin Node := VST.GetFirstSelected; RemoveElement(Node); end; //procedure TfrmDocumentEditor.RemoveResourceByCode(Code: string); //var // Node: PVirtualNode; // Data: PVSTDocument; // List: TList<PVirtualNode>; //begin // List := TList<PVirtualNode>.Create; // try // for Node in VST.Nodes do // begin // Data := VST.GetNodeData(Node); // if (Data.Item is TGsResource) and (TGsResource(Data.Item).Code = Code) // then // List.Add(Node); // end; // // while List.Count > 0 do // begin // RemoveElement(List[0]); // List.Delete(0); // end; // finally // List.Free; // end; //end; procedure TfrmDocumentEditor.SelectNodes(ChapterType: TGsChapterType); var Node: PVirtualNode; Data: PVSTDocument; begin VST.ClearSelection; for Node in VST.Nodes do begin Data := VST.GetNodeData(Node); if (Data.Item is TGsChapter) and (TGsChapter(Data.Item).ChapterType = ChapterType) then VST.Selected[Node] := True; end; end; procedure TfrmDocumentEditor.SelectPositions; var Node: PVirtualNode; Data: PVSTDocument; begin VST.ClearSelection; for Node in VST.Nodes do begin Data := VST.GetNodeData(Node); if (Data.Item is TGsIndexElement) or (Data.Item is TGsPriceElement) or (Data.Item is TGsRow) then VST.Selected[Node] := True; end; end; procedure TfrmDocumentEditor.SelectPositionsFilter; begin with TFmSelelectFilter.Create(Application) do begin Tree := Self.VST; ShowModal; Free; end; end; procedure TfrmDocumentEditor.SetDocument(ADocument: TGsDocument); begin inherited SetDocument(ADocument); ExpandedTree := False; UpdateBulletinContent; UpdateResourceTree; end; procedure TfrmDocumentEditor.SetExpanded(Value: Boolean); var Node: PVirtualNode; Data: PVSTDocument; begin for Node in VST.Nodes do begin Data := VST.GetNodeData(Node); if Data.Item is TGsAbstractContainer then VST.Expanded[Node] := Value; end; VST.ScrollIntoView(VST.GetFirst, False, False); end; procedure TfrmDocumentEditor.SetSmartEditor(AValue: Boolean); begin pnlSmartEditor.Visible := AValue; end; procedure TfrmDocumentEditor.TryExecute(NodeAction: TNodeAction); var Node: PVirtualNode; begin Node := VST.GetFirstSelected; if Node <> nil then NodeAction(Node); end; procedure TfrmDocumentEditor.UpdateItemData(Data: TGsAbstractItem); begin if Data.ClassType = TGsAbstractContainer then begin TGsAbstractContainer(Data).Caption := edtContainerCaption.Text; end else if Data.ClassType = TGsChapter then begin TGsChapter(Data).Caption := edtChapterCaption.Text; TGsChapter(Data).Code := edtChapterCode.Text; end else if Data.ClassType = TGsIndexElement then begin TGsIndexElement(Data).Code := edtCode.Text; TGsIndexElement(Data).Caption := edtCaption.Text; end else if Data.ClassType = TGsPriceElement then begin TGsPriceElement(Data).Code := edtCode.Text; TGsPriceElement(Data).Caption := edtCaption.Text; TGsPriceElement(Data).Measure := edtMeasure.Text; end else if Data is TGsRow then begin TGsRow(Data).Code := edtCode.Text; TGsRow(Data).Caption := edtCaption.Text; TGsRow(Data).Measure := edtMeasure.Text; end else if Data is TGsResource then begin TGsResource(Data).Code := edtCode.Text; TGsResource(Data).Caption := edtCaption.Text; TGsResource(Data).Measure := edtMeasure.Text; end; end; procedure TfrmDocumentEditor.UpdateResources(Data: PResourceData); var L: TList<TGsResource>; Resource: TGsResource; begin L := TGsAbstractItem(Document.Chapters).Iterate<TGsResource>; try for Resource in L do begin if Resource.Code + Resource.Caption + Resource.Measure = Data.Hash then begin Resource.Code := Data.Code; Resource.Caption := Data.Caption; Resource.Measure := Data.Measure; Resource.SetCostValue(cstPrice, Data.Price1); if Data.Kind = rkMaterial then begin Resource.SetCostValue(cstWSP, Data.Price2); Resource.SetCostValue(cstMass, Data.Mass); end else if Data.Kind = rkMashine then Resource.SetCostValue(cstZM, Data.Price2) else if Data.Kind = rkWorker then Resource.Attributes[Ord(raWorkerClass)] := Data.WorkClass; end; end; finally L.Free; end; end; procedure TfrmDocumentEditor.UpdateResourceTree; var MaterialsNode: PVirtualNode; MachinesNode: PVirtualNode; WorkersNode: PVirtualNode; MachinistNode: PVirtualNode; ResourceNode: PVirtualNode; Resource: TGsResource; ResourceList: TList<TGsResource>; NodeData: PResourceData; Hash: TStringList; begin if Document.DocumentType <> dtBaseData then Exit; VSTResources.Clear; VSTResources.BeginUpdate; Hash := TStringList.Create; ResourceNode := nil; try MaterialsNode := VSTResources.AddChild(nil); PResourceData(VSTResources.GetNodeData(MaterialsNode)).Code := 'Материалы'; PResourceData(VSTResources.GetNodeData(MaterialsNode)).IsResource := False; MachinesNode := VSTResources.AddChild(nil); PResourceData(VSTResources.GetNodeData(MachinesNode)).Code := 'Машины'; PResourceData(VSTResources.GetNodeData(MachinesNode)).IsResource := False; WorkersNode := VSTResources.AddChild(nil); PResourceData(VSTResources.GetNodeData(WorkersNode)).Code := 'Рабочие'; PResourceData(VSTResources.GetNodeData(WorkersNode)).IsResource := False; MachinistNode := VSTResources.AddChild(nil); PResourceData(VSTResources.GetNodeData(MachinistNode)).Code := 'Машинисты'; PResourceData(VSTResources.GetNodeData(MachinistNode)).IsResource := False; ResourceList := TGsAbstractItem(Document.Chapters).Iterate<TGsResource>; try for Resource in ResourceList do begin if Hash.IndexOf(Resource.Code + Resource.Caption + Resource.Measure) <> -1 then Continue; Hash.Add(Resource.Code + Resource.Caption + Resource.Measure); case Resource.Kind of rkMaterial: ResourceNode := VSTResources.AddChild(MaterialsNode); rkWorker: ResourceNode := VSTResources.AddChild(WorkersNode); rkMashinist: ResourceNode := VSTResources.AddChild(MachinistNode); rkMashine: ResourceNode := VSTResources.AddChild(MachinesNode); end; NodeData := VSTResources.GetNodeData(ResourceNode); NodeData.Kind := Resource.Kind; NodeData.Code := Resource.Code; NodeData.Caption := Resource.Caption; NodeData.Measure := Resource.Measure; NodeData.IsResource := True; NodeData.UpdateHash; if Resource.Kind = rkMaterial then NodeData.Mass := Resource.GetCostValue(cstMass, CurrentZone) else NodeData.Mass := 0; if Resource.Kind = rkWorker then NodeData.WorkClass := Resource.Attributes[Ord(raWorkerClass)] else NodeData.WorkClass := 0; NodeData.Price1 := Resource.GetCostValue(cstPrice, CurrentZone); if Resource.Kind = rkMaterial then NodeData.Price2 := Resource.GetCostValue(cstWSP, CurrentZone) else if Resource.Kind = rkMashine then NodeData.Price2 := Resource.GetCostValue(cstZM, CurrentZone) else NodeData.Price2 := 0; end; VSTResources.SortTree(0, sdAscending); finally ResourceList.Free; end; finally Hash.Free; end; VSTResources.EndUpdate; end; procedure TfrmDocumentEditor.UpdateBulletinContent; begin if (Document <> nil) and (Document.DocumentType = dtBaseData) and (Document.BaseDataType in [bdtERs, bdtRows, bdtESNs, bdtCargo, bdtProject, bdtMachine, bdtMaterial]) then begin edtTypeName.Text := Document.TypeName; edtDocNumber.Text := Document.Number; edtDocTitle.Text := Document.Title; case Document.BaseDataType of bdtMachine: cbDocType.ItemHeight := 0; bdtMaterial: cbDocType.ItemHeight := 1; bdtERs: cbDocType.ItemHeight := 2; bdtRows: cbDocType.ItemHeight := 2; bdtESNs: cbDocType.ItemHeight := 3; bdtWorkerScale: cbDocType.ItemHeight := 4; bdtCargo: cbDocType.ItemHeight := 5; bdtProject: cbDocType.ItemHeight := 6; end; //UpdateMaterials; UpdateCoefs; ExpandedTree := True; end else begin pcBulletin.Visible := False; N2.Visible := False; end; end; procedure TfrmDocumentEditor.UpdateCoefs; var Factor: TGsFactor; Item: TListItem; Hash: TStringList; HashStr: string; List: TList<TGsFactor>; begin lvCoefs.Clear; Hash := TStringList.Create; try //lvMaterials.Items.BeginUpdate; List := Document.GetAll<TGsFactor>; try for Factor in List do begin HashStr := VarToStr(Factor.Attributes[Ord(dtaNumber)]) + VarToStr(Factor.Attributes[Ord(dtaCaption)]); if Hash.IndexOf(HashStr) <> -1 then Continue; Hash.Add(HashStr); begin Item := lvCoefs.Items.Add; Item.Caption := VarToStr(Factor.Attributes[Ord(dtaNumber)]); Item.SubItems.Add(VarToStr(Factor.Attributes[Ord(dtaCaption)])); Item.SubItems.Add(VarToStr(Factor.Attributes[Ord(dtaPZ)])); Item.SubItems.Add(VarToStr(Factor.Attributes[Ord(dtaOZ)])); Item.SubItems.Add(VarToStr(Factor.Attributes[Ord(dtaEM)])); Item.SubItems.Add(VarToStr(Factor.Attributes[Ord(dtaZM)])); Item.SubItems.Add(VarToStr(Factor.Attributes[Ord(dtaMT)])); Item.SubItems.Add(VarToStr(Factor.Attributes[Ord(dtaFlags)])); end; end; finally List.Free; end; finally Hash.Free; end; // lvMaterials.Items.EndUpdate; end; procedure TfrmDocumentEditor.UpdateCoefsInRow(Row: TGsRow; ListItem: TListItem); var Factor: TGsFactor; Item: TGsAbstractItem; begin Item := Row.FactorList.ItemByAttribute(Ord(dtaNumber), ListItem.Caption, TGsFactor); if Item = nil then begin Factor := TGsFactor.Create(Document); Row.FactorList.Add(Factor); end else Factor := TGsFactor(Item); Factor.Attributes[Ord(dtaNumber)] := ListItem.Caption; Factor.Attributes[Ord(dtaCaption)] := ListItem.SubItems[0]; if ListItem.SubItems[1] <> '' then Factor.Attributes[Ord(dtaPZ)] := StrToFloat(ListItem.SubItems[1]) else Factor.Attributes[Ord(dtaPZ)] := Unassigned; if ListItem.SubItems[2] <> '' then Factor.Attributes[Ord(dtaOZ)] := StrToFloat(ListItem.SubItems[2]) else Factor.Attributes[Ord(dtaOZ)] := Unassigned; if ListItem.SubItems[3] <> '' then Factor.Attributes[Ord(dtaEM)] := StrToFloat(ListItem.SubItems[3]) else Factor.Attributes[Ord(dtaEM)] := Unassigned; if ListItem.SubItems[4] <> '' then Factor.Attributes[Ord(dtaZM)] := StrToFloat(ListItem.SubItems[4]) else Factor.Attributes[Ord(dtaZM)] := Unassigned; if ListItem.SubItems[5] <> '' then Factor.Attributes[Ord(dtaMT)] := StrToFloat(ListItem.SubItems[5]) else Factor.Attributes[Ord(dtaMT)] := Unassigned; if ListItem.SubItems[6] <> '' then Factor.Attributes[Ord(dtaFlags)] := StrToFloat(ListItem.SubItems[6]) else Factor.Attributes[Ord(dtaFlags)] := Unassigned; end; procedure TfrmDocumentEditor.UpdateItem; var ANode: PVirtualNode; Data: PVSTDocument; begin ANode := VST.GetFirstSelected; if ANode <> nil then begin Data := VST.GetNodeData(ANode); FEditorForm.Item := Data.Item; UpdateSmartViewer(Data.Item); end; end; procedure TfrmDocumentEditor.UpdateSmartViewer(Item: TGsAbstractItem); begin if Item.ClassType = TGsRow then begin pcEditors.ActivePage := tsRow; edtCode.Text := TGsRow(Item).Code; edtCaption.Text := TGsRow(Item).Caption; edtMeasure.Text := TGsRow(Item).Measure; end else if Item.ClassType = TGsIndexElement then begin pcEditors.ActivePage := tsRow; edtCode.Text := TGsIndexElement(Item).Code; edtCaption.Text := TGsIndexElement(Item).Caption; edtMeasure.Text := ''; end else if Item.ClassType = TGsPriceElement then begin pcEditors.ActivePage := tsRow; edtCode.Text := TGsPriceElement(Item).Code; edtCaption.Text := TGsPriceElement(Item).Caption; edtMeasure.Text := TGsPriceElement(Item).Measure; end else if Item.ClassType = TGsChapter then begin pcEditors.ActivePage := tsChapter; edtChapterCode.Text := TGsChapter(Item).Code; edtChapterCaption.Text := TGsChapter(Item).Caption; end else if Item.ClassType = TGsAbstractContainer then begin pcEditors.ActivePage := tsContainer; edtContainerCaption.Text := TGsAbstractContainer(Item).Caption; end else if Item.ClassType = TGsResource then begin pcEditors.ActivePage := tsRow; edtCode.Text := TGsResource(Item).Code; edtCaption.Text := TGsResource(Item).Caption; edtMeasure.Text := TGsResource(Item).Measure; end; end; procedure TfrmDocumentEditor.VSTResourcesBeforeItemErase (Sender: TBaseVirtualTree; TargetCanvas: TCanvas; Node: PVirtualNode; ItemRect: TRect; var ItemColor: TColor; var EraseAction: TItemEraseAction); begin if PResourceData(Sender.GetNodeData(Node)).IsResource then ItemColor := RGB(255, 251, 242); end; procedure TfrmDocumentEditor.VSTResourcesDragOver(Sender: TBaseVirtualTree; Source: TObject; Shift: TShiftState; State: TDragState; Pt: TPoint; Mode: TDropMode; var Effect: Integer; var Accept: Boolean); begin Accept := True; end; procedure TfrmDocumentEditor.VSTResourcesFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode); var Data: PResourceData; begin Data := VSTResources.GetNodeData(Node); Finalize(Data^); end; procedure TfrmDocumentEditor.VSTResourcesGetNodeDataSize (Sender: TBaseVirtualTree; var NodeDataSize: Integer); begin NodeDataSize := SizeOf(TResourceData); end; procedure TfrmDocumentEditor.VSTResourcesGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); var Data: PResourceData; begin Data := VSTResources.GetNodeData(Node); if Data.IsResource then CellText := '-' else CellText := ''; case Column of 0: CellText := Data.Code; 1: CellText := Data.Caption; 2: CellText := Data.Measure; 3: if Data.Price1 <> 0 then CellText := FloatToStr(Data.Price1); 4: if Data.Price2 <> 0 then CellText := FloatToStr(Data.Price2); 6: if Data.Mass <> 0 then CellText := FloatToStr(Data.Mass); 5: if Data.WorkClass <> 0 then CellText := FloatToStr(Data.WorkClass); end; end; procedure TfrmDocumentEditor.VSTResourcesNewText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; NewText: string); var Data: PResourceData; tmp: Real; begin Data := VSTResources.GetNodeData(Node); tmp := 0; case Column of 0: Data.Code := NewText; 1: Data.Caption := NewText; 2: Data.Measure := NewText; 3: try tmp := Data.Price1; Data.Price1 := GlobalData.ConvertToFloat(NewText); except Data.Price1 := tmp; end; 4: if Data.Kind in [rkMaterial, rkMashine] then try tmp := Data.Price2; Data.Price2 := GlobalData.ConvertToFloat(NewText); except Data.Price2 := tmp; end; 5: if Data.Kind = rkWorker then try tmp := Data.WorkClass; Data.WorkClass := GlobalData.ConvertToFloat(NewText); except Data.WorkClass := tmp; end; 6: if Data.Kind = rkMaterial then try tmp := Data.Mass; Data.Mass := GlobalData.ConvertToFloat(NewText); except Data.Mass := tmp; end; end; UpdateResources(Data); Data.UpdateHash; end; procedure TfrmDocumentEditor.VSTResourcesNodeDblClick(Sender: TBaseVirtualTree; const HitInfo: THitInfo); begin VSTResources.EditNode(HitInfo.HitNode, HitInfo.HitColumn); end; procedure TfrmDocumentEditor.VSTAfterItemPaint(Sender: TBaseVirtualTree; TargetCanvas: TCanvas; Node: PVirtualNode; ItemRect: TRect); begin UpdateItem; end; procedure TfrmDocumentEditor.VSTDragDrop(Sender: TBaseVirtualTree; Source: TObject; DataObject: IDataObject; Formats: TFormatArray; Shift: TShiftState; Pt: TPoint; var Effect: Integer; Mode: TDropMode); var I, ItemIndex: Integer; DropArray: TNodeArray; TargetNode // , Node : PVirtualNode; TargetData, Data: PVSTDocument; aItem: TGsAbstractItem; aCntItem: TGsAbstractContainer; DragMode: TListViewDragMode; begin DragMode := TListViewDragMode(-1); if (Source is TBaseVirtualTree) and (Source <> Sender) then begin // if Source = lvCoefs then // DragMode := ddCoefs // else // // if Source = lvMachinist then // DragMode := ddMachinist // else // // if Source = lvMachines then // DragMode := ddMachines // else // // if Source = lvMaterials then // DragMode := ddMaterials // else // // if Source = lvWorkers then // DragMode := ddWorkers; // DragDropFromLV(Sender, Source as TBaseVirtualTree, DragMode); end else begin // TargetNode := TBaseVirtualTree(Source).DropTargetNode; TargetNode := Sender.DropTargetNode; if TargetNode = nil then Exit; DropArray := Sender.GetSortedSelection(True); // DropArray := TBaseVirtualTree(SourcE).GetSortedSelection(True); for I := 0 to Length(DropArray) - 1 do if TargetNode = DropArray[I] then Exit; TargetData := Sender.GetNodeData(TargetNode); case Mode of dmOnNode: if (TargetData.Item is TGsAbstractContainer) then for I := 0 to Length(DropArray) - 1 do begin Data := Sender.GetNodeData(DropArray[I]); if Data.Item.Parent is TGsAbstractContainer then begin aCntItem := TGsAbstractContainer(Data.Item.Parent); aItem := aCntItem.Extract(Data.Item); TGsAbstractContainer(TargetData.Item).Add(aItem); Sender.MoveTo(DropArray[I], TargetNode, amAddChildLast, False) end; end; dmAbove, dmBelow: if TargetData.Item.Parent is TGsAbstractContainer then for I := 0 to Length(DropArray) - 1 do begin Data := Sender.GetNodeData(DropArray[I]); if not(Data.Item.Parent is TGsOutlay) then begin aCntItem := TGsAbstractContainer(Data.Item.Parent); aItem := Data.Item; aItem := aCntItem.Extract(aItem); ItemIndex := TGsAbstractContainer(TargetData.Item.Parent) .IndexOf(TargetData.Item); if Mode = dmAbove then begin TGsAbstractContainer(TargetData.Item.Parent) .Insert(aItem, ItemIndex); Sender.MoveTo(DropArray[I], TargetNode, amInsertBefore, False) end else begin TGsAbstractContainer(TargetData.Item.Parent) .Insert(aItem, ItemIndex + 1); Sender.MoveTo(DropArray[I], TargetNode, amInsertAfter, False) end; end; end; end; end; end; procedure TfrmDocumentEditor.VSTDragOver(Sender: TBaseVirtualTree; Source: TObject; Shift: TShiftState; State: TDragState; Pt: TPoint; Mode: TDropMode; var Effect: Integer; var Accept: Boolean); begin Accept := (Source = Sender) or (Source is TBaseVirtualTree); if Accept then Accept := TVirtualStringTree(Sender).DropTargetNode <> nil; end; procedure TfrmDocumentEditor.VSTKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = vk_delete then RemoveElement; end; procedure TfrmDocumentEditor.VSTNodeClick(Sender: TBaseVirtualTree; const HitInfo: THitInfo); begin UpdateItem; end; procedure TfrmDocumentEditor.VSTNodeDblClick(Sender: TBaseVirtualTree; const HitInfo: THitInfo); begin Sender.Expanded[HitInfo.HitNode] := not Sender.Expanded[HitInfo.HitNode]; inherited; end; procedure TfrmDocumentEditor.ZonesClick(Sender: TObject); begin inherited; // UpdateBulletinContent; end; { TResourceData } procedure TResourceData.UpdateHash; begin Hash := Code + Caption + Measure; end; end.
unit PositionRecord; interface type TPositionRecord = record private fFractionalX : double; fFractionalY : double; public X : integer; Y : integer; procedure ClearFraction(); procedure AddFraction(aX : double; aY : double); class function Create(aX : Integer; aY : Integer) : TPositionRecord; static; function Distance(destination : TPositionRecord) : Double; function DestinationReached(destination : TPositionRecord; limit : Integer = 25) : Boolean; end; implementation { TPositionRecord } procedure TPositionRecord.ClearFraction; begin fFractionalX := 0; fFractionalY := 0; end; class function TPositionRecord.Create(aX, aY: Integer): TPositionRecord; begin Result.X := aX; Result.Y := aY; Result.fFractionalX := 0; Result.fFractionalY := 0; end; function TPositionRecord.DestinationReached(destination: TPositionRecord; limit : Integer): Boolean; begin Result := (Distance(destination) < limit); end; function TPositionRecord.Distance(destination: TPositionRecord): Double; begin Result := Sqrt( Sqr(destination.X - X) + Sqr(destination.Y - Y)); end; procedure TPositionRecord.AddFraction(aX : double; aY : double); var truncX : integer; truncY : integer; begin fFractionalX := fFractionalX + aX; truncX := Trunc(fFractionalX); X := X + truncX; fFractionalX := fFractionalX - truncX; fFractionalY := fFractionalY + aY; truncY := Trunc(fFractionalY); Y := Y + truncY; fFractionalY := fFractionalY - truncY; end; end.
unit ShellObjects; interface uses Windows, ComObj, SysUtils, {RegistryStr, NetTypes, }ShellGUID, CommCtrl, ShellApi; //=========================================================================== // // Object identifiers in the explorer's name space (ItemID and IDList) // // All the items that the user can browse with the explorer (such as files, // directories, servers, work-groups, etc.) has an identifier which is unique // among items within the parent folder. Those identifiers are called item // IDs (SHITEMID). Since all its parent folders have their own item IDs, // any items can be uniquely identified by a list of item IDs, which is called // an ID list (ITEMIDLIST). // // ID lists are almost always allocated by the task allocator (see some // description below as well as OLE 2.0 SDK) and may be passed across // some of shell interfaces (such as IShellFolder). Each item ID in an ID list // is only meaningful to its parent folder (which has generated it), and all // the clients must treat it as an opaque binary data except the first two // bytes, which indicates the size of the item ID. // // When a shell extension -- which implements the IShellFolder interace -- // generates an item ID, it may put any information in it, not only the data // with that it needs to identifies the item, but also some additional // information, which would help implementing some other functions efficiently. // For example, the shell's IShellFolder implementation of file system items // stores the primary (long) name of a file or a directory as the item // identifier, but it also stores its alternative (short) name, size and date // etc. // // When an ID list is passed to one of shell APIs (such as SHGetPathFromIDList), // it is always an absolute path -- relative from the root of the name space, // which is the desktop folder. When an ID list is passed to one of IShellFolder // member function, it is always a relative path from the folder (unless it // is explicitly specified). // //=========================================================================== // // SHITEMID -- Item ID // const IID_IContextMenu: TGUID = ( D1:$000214E4;D2: $0000;D3:$0000;D4:($C0, $00, $00, $00, $00, $00, $00, $46)); type PShellItemID = ^TShellItemID; TShellItemID = record Count : word; // Size of the ID (including cb itself) Data : array[0..1] of byte; end; // // ITEMIDLIST -- List if item IDs (combined with 0-terminator) // type PItemIDList = ^TItemIDList; TItemIDList = record ID : TShellItemID; end; //=========================================================================== // // Task allocator API // // All the shell extensions MUST use the task allocator (see OLE 2.0 // programming guild for its definition) when they allocate or free // memory objects (mostly ITEMIDLIST) that are returned across any // shell interfaces. There are two ways to access the task allocator // from a shell extension depending on whether or not it is linked with // OLE32.DLL or not ( stdcall; virtual; abstract;ly for efficiency). // // (1) A shell extension which calls any OLE API (i.e., linked with // OLE32.DLL) should call OLE's task allocator (by retrieving // the task allocator by calling CoGetMalloc API). // // (2) A shell extension which does not call any OLE API (i.e., not linked // with OLE32.DLL) should call the shell task allocator API (defined // below), so that the shell can quickly loads it when OLE32.DLL is not // loaded by any application at that point. // // Notes: // In next version of Windowso release, SHGetMalloc will be replaced by // the following macro. // // SHGetMalloc(ppmem) CoGetMalloc(MEMCTX_TASK, ppmem) // //=========================================================================== function SHGetMalloc( var Malloc : IMAlloc ) : HRESULT; stdcall; external 'Shell32.dll'; //=========================================================================== // // IContextMenu interface // // [OverView] // // The shell uses the IContextMenu interface in following three cases. // // case-1: The shell is loading context menu extensions. // // When the user clicks the right mouse button on an item within the shell's // name space (i.g., file, directory, server, work-group, etc.), it creates // the default context menu for its type, then loads context menu extensions // that are registered for that type (and its base type) so that they can // add extra menu items. Those context menu extensions are registered at // HKCR\{ProgID}\shellex\ContextMenuHandlers. // // case-2: The shell is retrieving a context menu of sub-folders in extended // name-space. // // When the explorer's name space is extended by name space extensions, // the shell calls their IShellFolder::GetUIObjectOf to get the IContextMenu // objects when it creates context menus for folders under those extended // name spaces. // // case-3: The shell is loading non-default drag and drop handler for directories. // // When the user performed a non-default drag and drop onto one of file // system folders (i.e., directories), it loads shell extensions that are // registered at HKCR\{ProgID}\DragDropHandlers. // // // [Member functions] // // // IContextMenu::QueryContextMenu // // This member function may insert one or more menuitems to the specified // menu (hmenu) at the specified location (indexMenu which is never be -1). // The IDs of those menuitem must be in the specified range (idCmdFirst and // idCmdLast). It returns the maximum menuitem ID offset (ushort) in the // 'code' field (low word) of the scode. // // The uFlags specify the context. It may have one or more of following // flags. // // CMF_DEFAULTONLY: This flag is passed if the user is invoking the default // action (typically by double-clicking, case 1 and 2 only). Context menu // extensions (case 1) should not add any menu items, and returns NOERROR. // // CMF_VERBSONLY: The explorer passes this flag if it is constructing // a context menu for a short-cut object (case 1 and case 2 only). If this // flag is passed, it should not add any menu-items that is not appropriate // from a short-cut. // A good example is the "Delete" menuitem, which confuses the user // because it is not clear whether it deletes the link source item or the // link itself. // // CMF_EXPLORER: The explorer passes this flag if it has the left-side pane // (case 1 and 2 only). Context menu extensions should ignore this flag. // // High word (16-bit) are reserved for context specific communications // and the rest of flags (13-bit) are reserved by the system. // // // IContextMenu::InvokeCommand // // This member is called when the user has selected one of menuitems that // are inserted by previous QueryContextMenu member. In this case, the // LOWORD(lpici->lpVerb) contains the menuitem ID offset (menuitem ID - // idCmdFirst). // // This member function may also be called programmatically. In such a case, // lpici->lpVerb specifies the canonical name of the command to be invoked, // which is typically retrieved by GetCommandString member previously. // // Parameters in lpci: // cbSize -- Specifies the size of this structure (sizeof(*lpci)) // hwnd -- Specifies the owner window for any message/dialog box. // fMask -- Specifies whether or not dwHotkey/hIcon paramter is valid. // lpVerb -- Specifies the command to be invoked. // lpParameters -- Parameters (optional) // lpDirectory -- Working directory (optional) // nShow -- Specifies the flag to be passed to ShowWindow (SW_*). // dwHotKey -- Hot key to be assigned to the app after invoked (optional). // hIcon -- Specifies the icon (optional). // // // IContextMenu::GetCommandString // // This member function is called by the explorer either to get the // canonical (language independent) command name (uFlags == GCS_VERB) or // the help text ((uFlags & GCS_HELPTEXT) != 0) for the specified command. // The retrieved canonical string may be passed to its InvokeCommand // member function to invoke a command programmatically. The explorer // displays the help texts in its status bar; therefore, the length of // the help text should be reasonably short (<40 characters). // // Parameters: // idCmd -- Specifies menuitem ID offset (from idCmdFirst) // uFlags -- Either GCS_VERB or GCS_HELPTEXT // pwReserved -- Reserved (must pass NULL when calling, must ignore when called) // pszName -- Specifies the string buffer. // cchMax -- Specifies the size of the string buffer. // //=========================================================================== // QueryContextMenu uFlags const CMF_NORMAL = $00000000; CMF_DEFAULTONLY = $00000001; CMF_VERBSONLY = $00000002; CMF_EXPLORE = $00000004; CMF_RESERVED = $ffff0000; // View specific // GetCommandString uFlags GCS_VERB = $00000000; // canonical verb GCS_HELPTEXT = $00000001; // help text (for status bar) GCS_VALIDATE = $00000002; // validate command exists CMDSTR_NEWFOLDER = 'NewFolder'; CMDSTR_VIEWLIST = 'ViewList'; CMDSTR_VIEWDETAILS = 'ViewDetails'; { CMIC_MASK_HOTKEY = SEE_MASK_HOTKEY; CMIC_MASK_ICON = SEE_MASK_ICON; CMIC_MASK_FLAG_NO_UI = SEE_MASK_FLAG_NO_UI; CMIC_MASK_MODAL = $80000000; // Internal CMIC_VALID_SEE_FLAGS = SEE_VALID_CMIC_FLAGS; // Internal } type PInvokeCommandInfo = ^TInvokeCommandInfo; TInvokeCommandInfo = record Size : DWORD; // must be sizeof(CMINVOKECOMMANDINFO) Mask : DWORD; // any combination of CMIC_MASK_* hwnd : THandle; // might be NULL (indicating no owner window) Verb : pchar; // either a string of MAKEINTRESOURCE(idOffset) Parameters : pchar; // might be NULL (indicating no parameter) Directory : pchar; // might be NULL (indicating no specific directory) Show : integer; // one of SW_ values for ShowWindow() API HotKey : DWORD; hIcon : THandle; end; type PInvokeCommandInfoEx = ^TInvokeCommandInfoEx; TInvokeCommandInfoEx = packed record Size : DWORD; // must be sizeof(CMINVOKECOMMANDINFOEX) Mask : DWORD; // any combination of CMIC_MASK_* wnd : HWND; // might be NULL (indicating no owner window) Verb : pchar; // either a string or MAKEINTRESOURCE(idOffset) Parameters : pchar; // might be NULL (indicating no parameter) Directory : pchar; // might be NULL (indicating no specific directory) Show : integer; // one of SW_ values for ShowWindow() API HotKey : DWORD; hIcon : HICON; Title : pchar; // For CreateProcess-StartupInfo.lpTitle VerbW : pwidechar; // Unicode verb (for those who can use it) ParametersW : pwidechar; // Unicode parameters (for those who can use it) DirectoryW : pwidechar; // Unicode directory (for those who can use it) TitleW : pwidechar; // Unicode title (for those who can use it) end; type IContextMenu = class( IUnknown ) function QueryContextMenu ( Menu : THandle; MenuIndex : UINT; CmdFirst : UINT; CmdLast : UINT; Flags : UINT ) : HRESULT; virtual; stdcall; abstract; function InvokeCommand( Info : PInvokeCommandInfo ) : HRESULT ; virtual; stdcall; abstract; function GetCommandString ( Command : UINT; uType : UINT; Reserved : pointer; Name : pchar; Max : UINT ) : HRESULT; virtual; stdcall; abstract; end; // // IContextMenu2 (IContextMenu with one new member) // // IContextMenu2::HandleMenuMsg // // This function is called, if the client of IContextMenu is aware of // IContextMenu2 interface and receives one of following messages while // it is calling TrackPopupMenu (in the window proc of hwndOwner): // WM_INITPOPUP, WM_DRAWITEM and WM_MEASUREITEM // The callee may handle these messages to draw owner draw menuitems. // type IContextMenu2 = class( IUnknown ) function QueryContextMenu( Menu : HMENU; indexMenu : UINT; CmdFirst, CmdLast : UINT; Flags : integer ) : HResult; virtual; stdcall; abstract; function InvokeCommand( lpici : PInvokeCommandInfo ) : HResult; virtual; stdcall; abstract; function GetCommandString( Cmd : UINT; uType : UINT; pwReserved : PInteger; pszName : pchar; cchMax : UINT ) : HResult; virtual; stdcall; abstract; function HandleMenuMsg( Msg : UINT; WParameter : WPARAM; lParameter : LPARAM ) : HResult; virtual; stdcall; abstract; end; //=========================================================================== // // Interface: IShellExtInit // // The IShellExtInit interface is used by the explorer to initialize shell // extension objects. The explorer (1) calls CoCreateInstance (or equivalent) // with the registered CLSID and IID_IShellExtInit, (2) calls its Initialize // member, then (3) calls its QueryInterface to a particular interface (such // as IContextMenu or IPropSheetExt and (4) performs the rest of operation. // // // [Member functions] // // IShellExtInit::Initialize // // This member function is called when the explorer is initializing either // context menu extension, property sheet extension or non-default drag-drop // extension. // // Parameters: (context menu or property sheet extension) // pidlFolder -- Specifies the parent folder // lpdobj -- Spefifies the set of items selected in that folder. // hkeyProgID -- Specifies the type of the focused item in the selection. // // Parameters: (non-default drag-and-drop extension) // pidlFolder -- Specifies the target (destination) folder // lpdobj -- Specifies the items that are dropped (see the description // about shell's clipboard below for clipboard formats). // hkeyProgID -- Specifies the folder type. // //=========================================================================== type IShellExtInit = class( IUnknown ) function Initialize ( FolderPIDL : PItemIDList; lpdobj : pointer; ProgID : HKEY ) : HRESULT; virtual; stdcall; abstract; end; //=========================================================================== // // Interface: IShellPropSheetExt // // The explorer uses the IShellPropSheetExt to allow property sheet // extensions or control panel extensions to add additional property // sheet pages. // // // [Member functions] // // IShellPropSheetExt::AddPages // // The explorer calls this member function when it finds a registered // property sheet extension for a particular type of object. For each // additional page, the extension creates a page object by calling // CreatePropertySheetPage API and calls lpfnAddPage. // // Parameters: // lpfnAddPage -- Specifies the callback function. // lParam -- Specifies the opaque handle to be passed to the callback function. // // // IShellPropSheetExt::ReplacePage // // The explorer never calls this member of property sheet extensions. The // explorer calls this member of control panel extensions, so that they // can replace some of default control panel pages (such as a page of // mouse control panel). // // Parameters: // uPageID -- Specifies the page to be replaced. // lpfnReplace Specifies the callback function. // lParam -- Specifies the opaque handle to be passed to the callback function. // //=========================================================================== type IShellPropSheetExt = class( IUnknown ) function AddPages( AddPage : TFNAddPropSheetPage; lParameter : LPARAM ) : HResult; virtual; stdcall; abstract; function ReplacePage( uPageID : UINT; ReplaceWith : TFNAddPropSheetPage; lParameter : LPARAM ) : HResult; virtual; stdcall; abstract; end; //=========================================================================== // // IPersistFolder Interface // // The IPersistFolder interface is used by the file system implementation of // IShellFolder::BindToObject when it is initializing a shell folder object. // // // [Member functions] // // IPersistFolder::Initialize // // This member function is called when the explorer is initializing a // shell folder object. // // Parameters: // pidl -- Specifies the absolute location of the folder. // //=========================================================================== type IPersistFolder = class( IPersist ) function Initialize( pidl : PItemIdList ) : HResult; virtual; stdcall; abstract; end; //=========================================================================== // // IShellIcon Interface // // used to get a icon index for a IShellFolder object. // // this interface can be implemented by a IShellFolder, as a quick way to // return the icon for a object in the folder. // // a instance of this interface is only created once for the folder, unlike // IExtractIcon witch is created once for each object. // // if a ShellFolder does not implement this interface, the standard // GetUIObject(....IExtractIcon) method will be used to get a icon // for all objects. // // the following standard imagelist indexs can be returned: // // 0 document (blank page) (not associated) // 1 document (with stuff on the page) // 2 application (exe, com, bat) // 3 folder (plain) // 4 folder (open) // // IShellIcon:GetIconOf(pidl, flags, lpIconIndex) // // pidl object to get icon for. // flags GIL_* input flags (GIL_OPEN, ...) // lpIconIndex place to return icon index. // // returns: // NOERROR, if lpIconIndex contains the correct system imagelist index. // S_FALSE, if unable to get icon for this object, go through // GetUIObject, IExtractIcon, methods. // //=========================================================================== type IShellIcon = class( IUnknown ) function GetIconOf( pidl : PItemIdList; flags : UINT; var IconIndex : UINT ) : HResult; virtual; stdcall; abstract; end; //=========================================================================== // // IShellLink Interface // //=========================================================================== // IShellLink::Resolve fFlags const SLR_NO_UI = $0001; SLR_ANY_MATCH = $0002; SLR_UPDATE = $0004; // IShellLink::GetPath fFlags SLGP_SHORTPATH = $0001; SLGP_UNCPRIORITY = $0002; type IShellLink = class( IUnknown ) function GetPath ( FileName : pchar; MaxPath : integer; var FindData : TWin32FindDataA; Flags : DWORD ) : HRESULT; virtual; stdcall; abstract; function GetIDList( var ppidl : PItemIDList ) : HRESULT; virtual; stdcall; abstract; function SetIDList( pidl : PItemIDList ) : HRESULT; virtual; stdcall; abstract; function GetDescription( Name : pchar; MaxName : integer ) : HRESULT; virtual; stdcall; abstract; function SetDescription( Name : pchar ) : HRESULT; virtual; stdcall; abstract; function GetWorkingDirectory( Dir : pchar; MaxPath : integer ) : HRESULT; virtual; stdcall; abstract; function SetWorkingDirectory( Dir : pchar) : HRESULT; virtual; stdcall; abstract; function GetArguments( Args : pchar; MaxPath : integer ) : HRESULT; virtual; stdcall; abstract; function SetArguments( Args : pchar ) : HRESULT; virtual; stdcall; abstract; function GetHotkey( var Hotkey : word ) : HRESULT; virtual; stdcall; abstract; function SetHotkey( Hotkey : word ) : HRESULT; virtual; stdcall; abstract; function GetShowCmd( var ShowCmd : integer ) : HRESULT; virtual; stdcall; abstract; function SetShowCmd( ShowCmd : integer ) : HRESULT; virtual; stdcall; abstract; function GetIconLocation ( IconPath : pchar; PathLength : integer; var IconIndex : integer ) : HRESULT; virtual; stdcall; abstract; function SetIconLocation ( IconPath : pchar; IconIndex : integer ) : HRESULT; virtual; stdcall; abstract; function SetRelativePath( PathRel : pchar; Reserved : DWORD ) : HRESULT; virtual; stdcall; abstract; function Resolve( hwnd : THandle; Flags : DWORD ) : HRESULT; virtual; stdcall; abstract; function SetPath( FileName : pchar ) : HRESULT; virtual; stdcall; abstract; end; //=========================================================================== // // IShellExecuteHook Interface // //=========================================================================== type IShellExecuteHookA = class( IUnknown ) function Execute( pei : TShellExecuteInfoA ) : HResult; virtual; stdcall; abstract; end; type IShellExecuteHookW = class( IUnknown ) function Execute( pei : TShellExecuteInfoW ) : HResult; virtual; stdcall; abstract; end; //=========================================================================== // // INewShortcutHook Interface // //=========================================================================== type INewShortcutHookA = class( IUnknown ) function SetReferent( Referent : pchar; wnd : HWND ) : HResult; virtual; stdcall; abstract; function GetReferent( Referent : pchar; cchReferent : integer ) : HResult; virtual; stdcall; abstract; function SetFolder( Folder : pchar ) : HResult; virtual; stdcall; abstract; function GetFolder( Folder : pchar; cchFolder : integer ) : HResult; virtual; stdcall; abstract; function GetName( Name : pchar; cchName : integer) : HResult; virtual; stdcall; abstract; function GetExtension( Extension : pchar; cchExtension : integer ) : HResult; virtual; stdcall; abstract; end; type INewShortcutHookW = class( IUnknown ) function SetReferent( Referent : pwidechar; wnd : HWND ) : HResult; virtual; stdcall; abstract; function GetReferent( Referent : pwidechar; cchReferent : integer ) : HResult; virtual; stdcall; abstract; function SetFolder( Folder : pwidechar ) : HResult; virtual; stdcall; abstract; function GetFolder( Folder : pwidechar; cchFolder : integer ) : HResult; virtual; stdcall; abstract; function GetName( Name : pwidechar; cchName : integer) : HResult; virtual; stdcall; abstract; function GetExtension( Extension : pwidechar; cchExtension : integer ) : HResult; virtual; stdcall; abstract; end; //=========================================================================== // // ICopyHook Interface // // // The copy hook is called whenever file system directories are // copy/moved/deleted/renamed via the shell. It is also called by the shell // on changes of status of printers. // // Clients register their id under STRREG_SHEX_COPYHOOK for file system hooks // and STRREG_SHEx_PRNCOPYHOOK for printer hooks. // the CopyCallback is called prior to the action, so the hook has the chance // to allow, deny or cancel the operation by returning the falues: // IDYES - means allow the operation // IDNO - means disallow the operation on this file, but continue with // any other operations (eg. batch copy) // IDCANCEL - means disallow the current operation and cancel any pending // operations // // arguments to the CopyCallback // hwnd - window to use for any UI // wFunc - what operation is being done // wFlags - and flags (FOF_*) set in the initial call to the file operation // pszSrcFile - name of the source file // dwSrcAttribs - file attributes of the source file // pszDestFile - name of the destiation file (for move and renames) // dwDestAttribs - file attributes of the destination file // // //=========================================================================== // file operations const FO_MOVE = $0001; FO_COPY = $0002; FO_DELETE = $0003; FO_RENAME = $0004; FOF_MULTIDESTFILES = $0001; FOF_CONFIRMMOUSE = $0002; FOF_SILENT = $0004; // don't create progress/report FOF_RENAMEONCOLLISION = $0008; FOF_NOCONFIRMATION = $0010; // Don't prompt the user. FOF_WANTMAPPINGHANDLE = $0020; // Fill in SHFILEOPSTRUCT.hNameMappings // Must be freed using SHFreeNameMappings FOF_ALLOWUNDO = $0040; FOF_FILESONLY = $0080; // on *.*, do only files FOF_SIMPLEPROGRESS = $0100; // means don't show names of files FOF_NOCONFIRMMKDIR = $0200; // don't confirm making any needed dirs type FILEOP_FLAGS = UINT; // printer operations const PO_DELETE = $0013; // printer is being deleted PO_RENAME = $0014; // printer is being renamed PO_PORTCHANGE = $0020; // port this printer connected to is being changed // if this id is set, the strings received by // the copyhook are a doubly-null terminated // list of strings. The first is the printer // name and the second is the printer port. PO_REN_PORT = $0034; // PO_RENAME and PO_PORTCHANGE at same time. // no POF_ flags currently defined type PRINTEROP_FLAGS = UINT; type ICopyHook = class( IUnknown ) function CopyCallback ( hwnd : THandle; Func : UINT; Flags : UINT; SrcFile : pchar; SrcAttribs : DWORD; DestFile : pchar; DestAttribs : DWORD ) : UINT; virtual; stdcall; abstract; end; //=========================================================================== // // IFileViewerSite Interface // //=========================================================================== type IFileViewerSite = class function QueryInterface(const iid: TIID; var obj): HResult; virtual; stdcall; abstract; function AddRef : ULONG; virtual; stdcall; abstract; function Release : ULONG; virtual; stdcall; abstract; function SetPinnedWindow( hwnd : THandle ) : HResult; virtual; stdcall; abstract; function GetPinnedWindow( var hwnd : THandle ) : HResult; virtual; stdcall; abstract; end; //=========================================================================== // // IFileViewer Interface // // Implemented in a FileViewer component object. Used to tell a // FileViewer to PrintTo or to view, the latter happening though // ShowInitialize and Show. The filename is always given to the // viewer through IPersistFile. // //=========================================================================== type PFileViwerShowInfo = ^TFileViwerShowInfo; TFileViwerShowInfo = record // Stuff passed into viewer (in) Size : DWORD; // Size of structure for future expansion... Owner : THandle; // who is the owner window. Show : integer; // The show command // Passed in and updated (in/Out) Flags : DWORD; // flags Rect : TRect; // Where to create the window may have defaults Rel : IUnknown; // Relese this interface when window is visible // Stuff that might be returned from viewer (out) NewFile : POleStr; // New File to view. end; // Define File View Show Info Flags. const FVSIF_RECT = $00000001; // The rect variable has valid data. FVSIF_PINNED = $00000002; // We should Initialize pinned FVSIF_NEWFAILED = $08000000; // The new file passed back failed // to be viewed. FVSIF_NEWFILE = $80000000; // A new file to view has been returned FVSIF_CANVIEWIT = $40000000; // The viewer can view it. type IFileViewer = class function QueryInterface(const iid: TIID; var obj): HResult; virtual; stdcall; abstract; function AddRef : ULONG; virtual; stdcall; abstract; function Release : ULONG; virtual; stdcall; abstract; function ShowInitialize( FileSite : IFileViewerSite ) : HResult; virtual; stdcall; abstract; function Show( Info : PFileViwerShowInfo ) : HResult; virtual; stdcall; abstract; function PrintTo( Driver : pchar; SuppressUI : BOOL ) : HResult; virtual; stdcall; abstract; end; //------------------------------------------------------------------------- // // struct STRRET // // structure for returning strings from IShellFolder member functions // //------------------------------------------------------------------------- const STRRET_WSTR = $0000; STRRET_OFFSET = $0001; STRRET_CSTR = $0002; type PStrRet = ^TStrRet; TStrRet = record case uType : UINT of // One of the STRRET_* values 0 : (OleStr : POleStr); // OLESTR that will be freed 1 : (Offset : UINT); // Offset into SHITEMID (ANSI) 2 : (Str : array[0..MAX_PATH - 1] of char); // Buffer to fill in end; (* typedef struct _STRRET { UINT uType; // One of the STRRET_* values union { LPWSTR pOleStr; // OLESTR that will be freed UINT uOffset; // Offset into SHITEMID (ANSI) char cStr[MAX_PATH]; // Buffer to fill in } DUMMYUNIONNAME; } STRRET, *LPSTRRET; *) //------------------------------------------------------------------------- // // SHGetPathFromIDList // // This function assumes the size of the buffer (MAX_PATH). The pidl // should point to a file system object. // //------------------------------------------------------------------------- function SHGetPathFromIDList( pidl : PItemIDList; Path : pchar ) : BOOL; stdcall; external 'Shell32.dll' //------------------------------------------------------------------------- // // SHGetSpecialFolderLocation // // Returns a pidl to a predefined shell folder. The caller must free the // pidl. Use SHGetMalloc to obtain an allocator that can free the pidl. // //------------------------------------------------------------------------- // // registry entries for special paths are kept in : const REGSTR_PATH_EXPLORER = 'Software\\Microsoft\\Windows\\CurrentVersion\\Explorer'; REGSTR_PATH_SPECIAL_FOLDERS = REGSTR_PATH_EXPLORER + '\\Shell Folders'; CSIDL_DESKTOP = $0000; CSIDL_PROGRAMS = $0002; CSIDL_CONTROLS = $0003; CSIDL_PRINTERS = $0004; CSIDL_PERSONAL = $0005; CSIDL_FAVORITES = $0006; CSIDL_STARTUP = $0007; CSIDL_RECENT = $0008; CSIDL_SENDTO = $0009; CSIDL_BITBUCKET = $000a; CSIDL_STARTMENU = $000b; CSIDL_DESKTOPDIRECTORY = $0010; CSIDL_DRIVES = $0011; CSIDL_NETWORK = $0012; CSIDL_NETHOOD = $0013; CSIDL_FONTS = $0014; CSIDL_TEMPLATES = $0015; function SHGetSpecialFolderLocation( Owner : THandle; Folder : integer; var pidl : PItemIDList ) : HResult; stdcall; external 'Shell32.dll'; //------------------------------------------------------------------------- // // SHBrowseForFolder API // //------------------------------------------------------------------------- type TBFFCallBack = function( hwnd : THandle; Msg : UINT; lParam : LPARAM; lpData : LPARAM ) : integer; //typedef int (CALLBACK* BFFCALLBACK)(HWND hwnd, UINT uMsg, LPARAM lParam, LPARAM lpData); PBrowseInfo = ^TBrowseInfo; TBrowseInfo = record Owner : THandle; Root : PItemIDList; DisplayName : pchar; // Return display name of item selected. Title : pchar; // text to go in the banner over the tree. Flags : UINT; // Flags that control the return stuff funct : TBFFCallBack; Param : LPARAM; // extra info that's passed back in callbacks Image : integer; // output var: where to return the Image index. end; // Browsing for directory. const WM_USER = $0400; const BIF_RETURNONLYFSDIRS = $0001; // For finding a folder to start document searching BIF_DONTGOBELOWDOMAIN = $0002; // For starting the Find Computer BIF_STATUSTEXT = $0004; BIF_RETURNFSANCESTORS = $0008; BIF_BROWSEFORCOMPUTER = $1000; // Browsing for Computers. BIF_BROWSEFORPRINTER = $2000; // Browsing for Printers // message from browser BFFM_INITIALIZED = 1; BFFM_SELCHANGED = 2; // messages to browser BFFM_SETSTATUSTEXT = (WM_USER + 100); BFFM_ENABLEOK = (WM_USER + 101); BFFM_SETSELECTION = (WM_USER + 102); function SHBrowseForFolder( lpbi : PBrowseInfo ) : PItemIDList; stdcall; external 'Shell32.dll'; //------------------------------------------------------------------------- // // SHLoadInProc // // When this function is called, the shell calls CoCreateInstance // (or equivalent) with CLSCTX_INPROC_SERVER and the specified CLSID // from within the shell's process and release it immediately. // //------------------------------------------------------------------------- function SHLoadInProc( const rclsid : TCLSID ) : HRESULT; stdcall; external 'Shell32.dll'; //------------------------------------------------------------------------- // // IEnumIDList interface // // IShellFolder::EnumObjects member returns an IEnumIDList object. // //------------------------------------------------------------------------- type IEnumIDList = class( IUnknown ) function Next ( celt : ULONG; var rgelt : PItemIDList; var Fetched : ULONG ) : HRESULT; virtual; stdcall; abstract; function Skip( celt : ULONG ) : HRESULT; virtual; stdcall; abstract; function Reset : HRESULT; virtual; stdcall; abstract; function Clone( var Enum : IEnumIDList ) : HRESULT; virtual; stdcall; abstract; end; //------------------------------------------------------------------------- // // IShellFolder interface // // // [Member functions] // // IShellFolder::BindToObject(pidl, pbc, riid, ppvOut) // This function returns an instance of a sub-folder which is specified // by the IDList (pidl). // // IShellFolder::BindToStorage(pidl, pbc, riid, ppvObj) // This function returns a storage instance of a sub-folder which is // specified by the IDList (pidl). The shell never calls this member // function in the first release of Win95. // // IShellFolder::CompareIDs(lParam, pidl1, pidl2) // This function compares two IDLists and returns the result. The shell // explorer always passes 0 as lParam, which indicates "sort by name". // It should return 0 (as CODE of the scode), if two id indicates the // same object; negative value if pidl1 should be placed before pidl2; // positive value if pidl2 should be placed before pidl1. // // IShellFolder::CreateViewObject(hwndOwner, riid, ppvOut) // This function creates a view object of the folder itself. The view // object is a difference instance from the shell folder object. // // IShellFolder::GetAttributesOf(cidl, apidl, prgfInOut) // This function returns the attributes of specified objects in that // folder. "cidl" and "apidl" specifies objects. "apidl" contains only // simple IDLists. The explorer initializes *prgfInOut with a set of // flags to be evaluated. The shell folder may optimize the operation // by not returning unspecified flags. // // IShellFolder::GetUIObjectOf(hwndOwner, cidl, apidl, riid, prgfInOut, ppvOut) // This function creates a UI object to be used for specified objects. // The shell explorer passes either IID_IDataObject (for transfer operation) // or IID_IContextMenu (for context menu operation) as riid. // // IShellFolder::GetDisplayNameOf // This function returns the display name of the specified object. // If the ID contains the display name (in the locale character set), // it returns the offset to the name. Otherwise, it returns a pointer // to the display name string (UNICODE), which is allocated by the // task allocator, or fills in a buffer. // // IShellFolder::SetNameOf // This function sets the display name of the specified object. // If it changes the ID as well, it returns the new ID which is // alocated by the task allocator. // //------------------------------------------------------------------------- // IShellFolder::EnumObjects const SHCONTF_FOLDERS = 32; // for shell browser SHCONTF_NONFOLDERS = 64; // for default view SHCONTF_INCLUDEHIDDEN = 128; // for hidden/system objects // IShellFolder::GetDisplayNameOf/SetNameOf uFlags const SHGDN_NORMAL = 0; // default (display purpose) SHGDN_INFOLDER = 1; // displayed under a folder (relative) SHGDN_FORPARSING = $8000; // for ParseDisplayName or path // IShellFolder::GetAttributesOf flags const DROPEFFECT_COPY = 1; //Size is 4 DROPEFFECT_MOVE = 2; //Size is 4 DROPEFFECT_LINK = 4; //Size is 4 DROPEFFECT_SCROLL = $80000000; //Size is 4 const SFGAO_CANCOPY = DROPEFFECT_COPY; // Objects can be copied SFGAO_CANMOVE = DROPEFFECT_MOVE; // Objects can be moved SFGAO_CANLINK = DROPEFFECT_LINK; // Objects can be linked SFGAO_CANRENAME = $00000010; // Objects can be renamed SFGAO_CANDELETE = $00000020; // Objects can be deleted SFGAO_HASPROPSHEET = $00000040; // Objects have property sheets SFGAO_DROPTARGET = $00000100; // Objects are drop target SFGAO_CAPABILITYMASK = $00000177; SFGAO_LINK = $00010000; // Shortcut (link) SFGAO_SHARE = $00020000; // shared SFGAO_READONLY = $00040000; // read-only SFGAO_GHOSTED = $00080000; // ghosted icon SFGAO_DISPLAYATTRMASK = $000F0000; SFGAO_FILESYSANCESTOR = $10000000; // It contains file system folder SFGAO_FOLDER = $20000000; // It's a folder. SFGAO_FILESYSTEM = $40000000; // is a file system thing (file/folder/root) SFGAO_HASSUBFOLDER = $80000000; // Expandable in the map pane SFGAO_CONTENTSMASK = $80000000; SFGAO_VALIDATE = $01000000; // invalidate cached information SFGAO_REMOVABLE = $02000000; // is this removeable media? SFGAO_ALL = $FFFFFFFF; // All attributes type IShellFolder = class( IUnknown ) function ParseDisplayName ( Owner : THandle; Reserved : pointer; DisplayName : POleStr; var Eaten : ULONG; var pidl : PItemIDList; var Attributes : ULONG ) : HRESULT; virtual; stdcall; abstract; function EnumObjects ( Owner : THandle; Flags : DWORD; var EnumIDList : IEnumIDList ) : HRESULT; virtual; stdcall; abstract; function BindToObject ( pidl : PItemIDList; Reserved : pointer; const iid : TIID; var Out : IShellFolder //pointer ) : HRESULT; virtual; stdcall; abstract; function BindToStorage ( pidl : PItemIDList; Reserved : pointer; const iid : TIID; var Obj : pointer ) : HRESULT; virtual; stdcall; abstract; //Check it out function CompareIDs ( lParam : LPARAM; pidl1 : PItemIDList; pidl2 : PItemIDList ) : HRESULT; virtual; stdcall; abstract; function CreateViewObject ( Owner : THandle; const iid : TIID; var Out : pointer ) : HRESULT; virtual; stdcall; abstract; function GetAttributesOf ( cidl : UINT; var apidl : PItemIDList; var InOut : ULONG ) : HRESULT; virtual; stdcall; abstract; function GetUIObjectOf ( Owner : THandle; cidl : UINT; var apidl : PItemIDList; const iid : TGUID; var InOut : UINT; var Out : pointer ) : HRESULT; virtual; stdcall; abstract; function GetDisplayNameOf ( pidl : PItemIDList; Flags : DWORD; var Name : TSTRRET ) : HRESULT; virtual; stdcall; abstract; function SetNameOf ( Owner : THandle; pidl : PItemIDList; Name : POleStr; Flags : DWORD; var PidlOut : PItemIDList ) : HRESULT; virtual; stdcall; abstract; end; // // Helper function which returns a IShellFolder interface to the desktop // folder. This is equivalent to call CoCreateInstance with CLSID_ShellDesktop. // // CoCreateInstance(CLSID_Desktop, NULL, // CLSCTX_INPROC, IID_IShellFolder, &pshf); // function SHGetDesktopFolder( var ShellFolder : IShellFolder ) : HRESULT; stdcall; external 'Shell32.dll'; //========================================================================== // Clipboard format which may be supported by IDataObject from system // defined shell folders (such as directories, network, ...). //========================================================================== const CFSTR_SHELLIDLIST = 'Shell IDList Array'; // CF_IDLIST CFSTR_SHELLIDLISTOFFSET = 'Shell Object Offsets'; // CF_OBJECTPOSITIONS CFSTR_NETRESOURCES = 'Net Resource'; // CF_NETRESOURCE CFSTR_FILEDESCRIPTOR = 'FileGroupDescriptor'; // CF_FILEGROUPDESCRIPTOR CFSTR_FILECONTENTS = 'FileContents'; // CF_FILECONTENTS CFSTR_FILENAME = 'FileName'; // CF_FILENAME CFSTR_PRINTERGROUP = 'PrinterFriendlyName'; // CF_PRINTERS CFSTR_FILENAMEMAP = 'FileNameMap'; // CF_FILENAMEMAP // // CF_OBJECTPOSITIONS // // const DVASPECT_SHORTNAME = 2; // use for CF_HDROP to get short name version // // format of CF_NETRESOURCE // type PNetResArray = ^TNetResArray; TNetResArray = record Items : UINT; nr : array[0..1] of TNetResource; end; // // format of CF_IDLIST // PCIDA = ^TCIDA; TCIDA = record cidl : UINT; // number of relative IDList offset : array[0..1] of UINT ; // [0]: folder IDList, [1]-[cidl]: item IDList end; // // FILEDESCRIPTOR.dwFlags field indicate which fields are to be used // const FD_CLSID = $0001; FD_SIZEPOINT = $0002; FD_ATTRIBUTES = $0004; FD_CREATETIME = $0008; FD_ACCESSTIME = $0010; FD_WRITESTIME = $0020; FD_FILESIZE = $0040; FD_LINKUI = $8000; // 'link' UI is prefered type LONG = integer; SIZEL = LONG; FILETIME = record LowDateTime : DWORD; HighDateTime : DWORD; end; POINTL = record x : LONG; y : LONG; end; type PFileDescriptor = ^TFileDescriptor; TFileDescriptor = record Flags : DWORD; clsid : TCLSID; size : SIZEL; point : POINTL; FileAttributes : DWORD; CreationTime : FILETIME; LastAccessTime : FILETIME; LastWriteTime : FILETIME; FileSizeHigh : DWORD; FileSizeLow : DWORD; FileName : pchar; end; // // format of CF_FILEGROUPDESCRIPTOR // type TFileGroupDescriptor = record Items : UINT; fgd : array [0..1] of TFileDescriptor; end; // // format of CF_HDROP and CF_PRINTERS, in the HDROP case the data that follows // is a double null terinated list of file names, for printers they are printer // friendly names // type PDropFiles = ^TDropFiles; TDropFiles = record Files : DWORD; // offset of file list pt : TPoint; // drop point (client coords) NC : BOOL; // is it on NonClient area // and pt is in screen coords Wide : BOOL; // WIDE character switch end; //====== File System Notification APIs =============================== // // // File System Notification flags // const SHCNE_RENAMEITEM = $00000001; SHCNE_CREATE = $00000002; SHCNE_DELETE = $00000004; SHCNE_MKDIR = $00000008; SHCNE_RMDIR = $00000010; SHCNE_MEDIAINSERTED = $00000020; SHCNE_MEDIAREMOVED = $00000040; SHCNE_DRIVEREMOVED = $00000080; SHCNE_DRIVEADD = $00000100; SHCNE_NETSHARE = $00000200; SHCNE_NETUNSHARE = $00000400; SHCNE_ATTRIBUTES = $00000800; SHCNE_UPDATEDIR = $00001000; SHCNE_UPDATEITEM = $00002000; SHCNE_SERVERDISCONNECT = $00004000; SHCNE_UPDATEIMAGE = $00008000; SHCNE_DRIVEADDGUI = $00010000; SHCNE_RENAMEFOLDER = $00020000; SHCNE_FREESPACE = $00040000; SHCNE_ASSOCCHANGED = $08000000; SHCNE_DISKEVENTS = $0002381F; SHCNE_GLOBALEVENTS = $0C0581E0; // Events that dont match pidls first SHCNE_ALLEVENTS = $7FFFFFFF; SHCNE_INTERRUPT = $80000000; // The presence of this flag indicates // that the event was generated by an // interrupt. It is stripped out before // the clients of SHCNNotify_ see it. // Flags // uFlags & SHCNF_TYPE is an ID which indicates what dwItem1 and dwItem2 mean const SHCNF_IDLIST = $0000; // LPITEMIDLIST SHCNF_PATH = $0001; // path name SHCNF_PRINTER = $0002; // printer friendly name SHCNF_DWORD = $0003; // DWORD SHCNF_TYPE = $00FF; SHCNF_FLUSH = $1000; SHCNF_FLUSHNOWAIT = $2000; // // APIs // procedure SHChangeNotify( EventId : LONG; Flags : UINT; dwItem1, dwItem2 : pointer ); stdcall; external 'Shell32.dll'; // // SHAddToRecentDocs // const SHARD_PIDL = $00000001; SHARD_PATH = $00000002; procedure SHAddToRecentDocs( Flags : UINT; pv : pointer ); stdcall; external 'Shell32.dll'; function SHGetInstanceExplorer( var ppunk : IUnknown ): HRESULT; stdcall; external 'Shell32.dll'; //=========================================================================== // // IExtractIcon interface // // This interface is used in two different places in the shell. // // Case-1: Icons of sub-folders for the scope-pane of the explorer. // // It is used by the explorer to get the "icon location" of // sub-folders from each shell folders. When the user expands a folder // in the scope pane of the explorer, the explorer does following: // (1) binds to the folder (gets IShellFolder), // (2) enumerates its sub-folders by calling its EnumObjects member, // (3) calls its GetUIObjectOf member to get IExtractIcon interface // for each sub-folders. // In this case, the explorer uses only IExtractIcon::GetIconLocation // member to get the location of the appropriate icon. An icon location // always consists of a file name (typically DLL or EXE) and either an icon // resource or an icon index. // // // Case-2: Extracting an icon image from a file // // It is used by the shell when it extracts an icon image // from a file. When the shell is extracting an icon from a file, // it does following: // (1) creates the icon extraction handler object (by getting its CLSID // under the {ProgID}\shell\ExtractIconHanler key and calling // CoCreateInstance requesting for IExtractIcon interface). // (2) Calls IExtractIcon::GetIconLocation. // (3) Then, calls IExtractIcon::Extract with the location/index pair. // (4) If (3) returns NOERROR, it uses the returned icon. // (5) Otherwise, it recursively calls this logic with new location // assuming that the location string contains a fully qualified path name. // // From extension programmer's point of view, there are only two cases // where they provide implementations of IExtractIcon: // Case-1) providing explorer extensions (i.e., IShellFolder). // Case-2) providing per-instance icons for some types of files. // // Because Case-1 is described above, we'll explain only Case-2 here. // // When the shell is about display an icon for a file, it does following: // (1) Finds its ProgID and ClassID. // (2) If the file has a ClassID, it gets the icon location string from the // "DefaultIcon" key under it. The string indicates either per-class // icon (e.g., "FOOBAR.DLL,2") or per-instance icon (e.g., "%1,1"). // (3) If a per-instance icon is specified, the shell creates an icon // extraction handler object for it, and extracts the icon from it // (which is described above). // // It is important to note that the shell calls IExtractIcon::GetIconLocation // first, then calls IExtractIcon::Extract. Most application programs // that support per-instance icons will probably store an icon location // (DLL/EXE name and index/id) rather than an icon image in each file. // In those cases, a programmer needs to implement only the GetIconLocation // member and it Extract member simply returns S_FALSE. They need to // implement Extract member only if they decided to store the icon images // within files themselved or some other database (which is very rare). // // // // [Member functions] // // // IExtractIcon::GetIconLocation // // This function returns an icon location. // // Parameters: // uFlags [in] -- Specifies if it is opened or not (GIL_OPENICON or 0) // szIconFile [out] -- Specifies the string buffer buffer for a location name. // cchMax [in] -- Specifies the size of szIconFile (almost always MAX_PATH) // piIndex [out] -- Sepcifies the address of UINT for the index. // pwFlags [out] -- Returns GIL_* flags // Returns: // NOERROR, if it returns a valid location; S_FALSE, if the shell use a // default icon. // // Notes: The location may or may not be a path to a file. The caller can // not assume anything unless the subsequent Extract member call returns // S_FALSE. // // if the returned location is not a path to a file, GIL_NOTFILENAME should // be set in the returned flags. // // IExtractIcon::Extract // // This function extracts an icon image from a specified file. // // Parameters: // pszFile [in] -- Specifies the icon location (typically a path to a file). // nIconIndex [in] -- Specifies the icon index. // phiconLarge [out] -- Specifies the HICON variable for large icon. // phiconSmall [out] -- Specifies the HICON variable for small icon. // nIconSize [in] -- Specifies the size icon required (size of large icon) // LOWORD is the requested large icon size // HIWORD is the requested small icon size // Returns: // NOERROR, if it extracted the from the file. // S_FALSE, if the caller should extract from the file specified in the // location. // //=========================================================================== // GetIconLocation() input flags const GIL_OPENICON = $0001; // allows containers to specify an "open" look GIL_FORSHELL = $0002; // icon is to be displayed in a ShellFolder // GetIconLocation() return flags const GIL_SIMULATEDOC = $0001; // simulate this document icon for this GIL_PERINSTANCE = $0002; // icons from this class are per instance (each file has its own) GIL_PERCLASS = $0004; // icons from this class per class (shared for all files of this type) GIL_NOTFILENAME = $0008; // location is not a filename, must call ::Extract GIL_DONTCACHE = $0010; // this icon should not be cached type IExtractIcon = class(IUnknown) function GetIconLocation ( Flags : UINT; IconFile : pchar; cchMax : UINT; var index : integer; var pwFlags : UINT ) : HRESULT; virtual; stdcall; abstract; function Extract ( FileName : pchar; Index : UINT; var LargeIcon : HIcon; var SmallIcon : HIcon; IconSize : UINT ) : HRESULT; virtual; stdcall; abstract; end; //========================================================================== // // IShellBrowser/IShellView/IShellFolder interface // // These three interfaces are used when the shell communicates with // name space extensions. The shell (explorer) provides IShellBrowser // interface, and extensions implements IShellFolder and IShellView // interfaces. // //========================================================================== //-------------------------------------------------------------------------- // // Command/menuitem IDs // // The explorer dispatches WM_COMMAND messages based on the range of // command/menuitem IDs. All the IDs of menuitems that the view (right // pane) inserts must be in FCIDM_SHVIEWFIRST/LAST (otherwise, the explorer // won't dispatch them). The view should not deal with any menuitems // in FCIDM_BROWSERFIRST/LAST (otherwise; it won't work with the future // version of the shell). // // FCIDM_SHVIEWFIRST/LAST for the right pane (IShellView) // FCIDM_BROWSERFIRST/LAST for the explorer frame (IShellBrowser) // FCIDM_GLOBAL/LAST for the explorer's submenu IDs // //-------------------------------------------------------------------------- const FCIDM_SHVIEWFIRST = $0000; FCIDM_SHVIEWLAST = $7fff; FCIDM_BROWSERFIRST = $a000; FCIDM_BROWSERLAST = $bf00; FCIDM_GLOBALFIRST = $8000; FCIDM_GLOBALLAST = $9fff; // // Global submenu IDs and separator IDs // const FCIDM_MENU_FILE = (FCIDM_GLOBALFIRST + $0000); FCIDM_MENU_EDIT = (FCIDM_GLOBALFIRST + $0040); FCIDM_MENU_VIEW = (FCIDM_GLOBALFIRST + $0080); FCIDM_MENU_VIEW_SEP_OPTIONS = (FCIDM_GLOBALFIRST + $0081); FCIDM_MENU_TOOLS = (FCIDM_GLOBALFIRST + $00c0); FCIDM_MENU_TOOLS_SEP_GOTO = (FCIDM_GLOBALFIRST + $00c1); FCIDM_MENU_HELP = (FCIDM_GLOBALFIRST + $0100); FCIDM_MENU_FIND = (FCIDM_GLOBALFIRST + $0140); FCIDM_MENU_EXPLORE = (FCIDM_GLOBALFIRST + $0150); FCIDM_MENU_FAVORITES = (FCIDM_GLOBALFIRST + $0170); //-------------------------------------------------------------------------- // control IDs known to the view //-------------------------------------------------------------------------- FCIDM_TOOLBAR = (FCIDM_BROWSERFIRST + 0); FCIDM_STATUS = (FCIDM_BROWSERFIRST + 1); //-------------------------------------------------------------------------- // // FOLDERSETTINGS // // FOLDERSETTINGS is a data structure that explorer passes from one folder // view to another; when the user is browsing. It calls ISV::GetCurrentInfo // member to get the current settings and pass it to ISV::CreateViewWindow // to allow the next folder view "inherit" it. These settings assumes a // particular UI (which the shell's folder view has); and shell extensions // may or may not use those settings. // //-------------------------------------------------------------------------- type PViewSettings = PByte; // NB Bitfields. // FWF_DESKTOP implies FWF_TRANSPARENT/NOCLIENTEDGE/NOSCROLL const FWF_AUTOARRANGE = $0001; FWF_ABBREVIATEDNAMES = $0002; FWF_SNAPTOGRID = $0004; FWF_OWNERDATA = $0008; FWF_BESTFITWINDOW = $0010; FWF_DESKTOP = $0020; FWF_SINGLESEL = $0040; FWF_NOSUBFOLDERS = $0080; FWF_TRANSPARENT = $0100; FWF_NOCLIENTEDGE = $0200; FWF_NOSCROLL = $0400; FWF_ALIGNLEFT = $0800; FWF_SINGLECLICKACTIVATE = $8000; // TEMPORARY -- NO UI FOR THIS const FVM_ICON = 1; FVM_SMALLICON = 2; FVM_LIST = 3; FVM_DETAILS = 4; type PFolderSettings = ^TFolderSettings; TFolderSettings = packed record ViewMode : UINT; // View mode (FOLDERVIEWMODE values) Flags : UINT; // View options (FOLDERFLAGS bits) end; //-------------------------------------------------------------------------- // // Interface: IShellBrowser // // IShellBrowser interface is the interface that is provided by the shell // explorer/folder frame window. When it creates the "contents pane" of // a shell folder (which provides IShellFolder interface); it calls its // CreateViewObject member function to create an IShellView object. Then; // it calls its CreateViewWindow member to create the "contents pane" // window. The pointer to the IShellBrowser interface is passed to // the IShellView object as a parameter to this CreateViewWindow member // function call. // // +--------------------------+ <-- Explorer window // | [] Explorer | // |--------------------------+ IShellBrowser // | File Edit View .. | // |--------------------------| // | | | // | | <-------- Content pane // | | | // | | | IShellView // | | | // | | | // +--------------------------+ // // // // [Member functions] // // // IShellBrowser::GetWindow(phwnd) // // Inherited from IOleWindow::GetWindow. // // // IShellBrowser::ContextSensitiveHelp(fEnterMode) // // Inherited from IOleWindow::ContextSensitiveHelp. // // // IShellBrowser::InsertMenusSB(hmenuShared; lpMenuWidths) // // Similar to the IOleInPlaceFrame::InsertMenus. The explorer will put // "File" and "Edit" pulldown in the File menu group; "View" and "Tools" // in the Container menu group and "Help" in the Window menu group. Each // pulldown menu will have a uniqu ID; FCIDM_MENU_FILE/EDIT/VIEW/TOOLS/HELP. // The view is allowed to insert menuitems into those sub-menus by those // IDs must be between FCIDM_SHVIEWFIRST and FCIDM_SHVIEWLAST. // // // IShellBrowser::SetMenuSB(hmenuShared; holemenu; hwndActiveObject) // // Similar to the IOleInPlaceFrame::SetMenu. The explorer ignores the // holemenu parameter (reserved for future enhancement) and performs // menu-dispatch based on the menuitem IDs (see the description above). // It is important to note that the explorer will add different // set of menuitems depending on whether the view has a focus or not. // Therefore; it is very important to call ISB::OnViewWindowActivate // whenever the view window (or its children) gets the focus. // // // IShellBrowser::RemoveMenusSB(hmenuShared) // // Same as the IOleInPlaceFrame::RemoveMenus. // // // IShellBrowser::SetStatusTextSB(lpszStatusText) // // Same as the IOleInPlaceFrame::SetStatusText. It is also possible to // send messages directly to the status window via SendControlMsg. // // // IShellBrowser::EnableModelessSB(fEnable) // // Same as the IOleInPlaceFrame::EnableModeless. // // // IShellBrowser::TranslateAcceleratorSB(lpmsg; wID) // // Same as the IOleInPlaceFrame::TranslateAccelerator; but will be // never called because we don't support EXEs (i.e.; the explorer has // the message loop). This member function is defined here for possible // future enhancement. // // // IShellBrowser::BrowseObject(pidl; wFlags) // // The view calls this member to let shell explorer browse to another // folder. The pidl and wFlags specifies the folder to be browsed. // // Following three flags specifies whether it creates another window or not. // SBSP_SAMEBROWSER -- Browse to another folder with the same window. // SBSP_NEWBROWSER -- Creates another window for the specified folder. // SBSP_DEFBROWSER -- Default behavior (respects the view option). // // Following three flags specifies open; explore; or default mode. These . // are ignored if SBSP_SAMEBROWSER or (SBSP_DEFBROWSER && (single window . // browser || explorer)). . // SBSP_OPENMODE -- Use a normal folder window // SBSP_EXPLOREMODE -- Use an explorer window // SBSP_DEFMODE -- Use the same as the current window // // Following three flags specifies the pidl. // SBSP_ABSOLUTE -- pidl is an absolute pidl (relative from desktop) // SBSP_RELATIVE -- pidl is relative from the current folder. // SBSP_PARENT -- Browse the parent folder (ignores the pidl) // // // IShellBrowser::GetViewStateStream(grfMode; ppstm) // // The browser returns an IStream interface as the storage for view // specific state information. // // grfMode -- Specifies the read/write access (STGM_READ/WRITE/READWRITE) // ppstm -- Specifies the LPSTREAM variable to be filled. // // // IShellBrowser::GetControlWindow(id; phwnd) // // The shell view may call this member function to get the window handle // of Explorer controls (toolbar or status winodw -- FCW_TOOLBAR or // FCW_STATUS). // // // IShellBrowser::SendControlMsg(id; uMsg; wParam; lParam; pret) // // The shell view calls this member function to send control messages to // one of Explorer controls (toolbar or status window -- FCW_TOOLBAR or // FCW_STATUS). // // // IShellBrowser::QueryActiveShellView(IShellView * ppshv) // // This member returns currently activated (displayed) shellview object. // A shellview never need to call this member function. // // // IShellBrowser::OnViewWindowActive(pshv) // // The shell view window calls this member function when the view window // (or one of its children) got the focus. It MUST call this member before // calling IShellBrowser::InsertMenus; because it will insert different // set of menu items depending on whether the view has the focus or not. // // // IShellBrowser::SetToolbarItems(lpButtons; nButtons; uFlags) // // The view calls this function to add toolbar items to the exporer's // toolbar. "lpButtons" and "nButtons" specifies the array of toolbar // items. "uFlags" must be one of FCT_MERGE; FCT_CONFIGABLE; FCT_ADDTOEND. // //------------------------------------------------------------------------- // // Values for wFlags parameter of ISB::BrowseObject() member. // const SBSP_DEFBROWSER = $0000; SBSP_SAMEBROWSER = $0001; SBSP_NEWBROWSER = $0002; SBSP_DEFMODE = $0000; SBSP_OPENMODE = $0010; SBSP_EXPLOREMODE = $0020; SBSP_ABSOLUTE = $0000; SBSP_RELATIVE = $1000; SBSP_PARENT = $2000; SBSP_INITIATEDBYHLINKFRAME = $80000000; SBSP_REDIRECT = $40000000; // // Values for id parameter of ISB::GetWindow/SendControlMsg members. // // WARNING: // Any shell extensions which sends messages to those control windows // might not work in the future version of windows. If you really need // to send messages to them; (1) don't assume that those control window // always exist (i.e. GetControlWindow may fail) and (2) verify the window // class of the window before sending any messages. // const FCW_STATUS = $0001; FCW_TOOLBAR = $0002; FCW_TREE = $0003; // // Values for uFlags paremeter of ISB::SetToolbarItems member. // const FCT_MERGE = $0001; FCT_CONFIGABLE = $0002; FCT_ADDTOEND = $0004; const SBSC_HIDE = 0; SBSC_SHOW = 1; SBSC_TOGGLE = 2; SBSC_QUERY = 3; // CommandTarget ids. const SBCMDID_ENABLESHOWTREE = 0; SBCMDID_SHOWCONTROL = 1; // variant vt_i4 = loword = FCW_* hiword = SBSC_* SBCMDID_CANCELNAVIGATION = 2; // cancel last navigation SBCMDID_MAYSAVECHANGES = 3; // about to close and may save changes SBCMDID_SETHLINKFRAME = 4; // variant vt_i4 = phlinkframe SBCMDID_ENABLESTOP = 5; // variant vt_bool = fEnable SBCMDID_OPTIONS = 6; // the view.options page const CDBOSC_SETFOCUS = $00000000; CDBOSC_KILLFOCUS = $00000001; CDBOSC_SELCHANGE = $00000002; CDBOSC_RENAME = $00000003; // // shellview select item flags // const SVSI_DESELECT = $0000; SVSI_SELECT = $0001; SVSI_EDIT = $0003; // includes select SVSI_DESELECTOTHERS = $0004; SVSI_ENSUREVISIBLE = $0008; SVSI_FOCUSED = $0010; // // shellview get item object flags // const SVGIO_BACKGROUND = $00000000; SVGIO_SELECTION = $00000001; SVGIO_ALLVIEW = $00000002; // // uState values for IShellView::UIActivate // const SVUIA_DEACTIVATE = 0; SVUIA_ACTIVATE_NOFOCUS = 1; SVUIA_ACTIVATE_FOCUS = 2; SVUIA_INPLACEACTIVATE = 3; // new flag for IShellView2 type IShellView = class; IShellBrowser = class( IOleWindow ) function InsertMenusSB( hmenuShared : HMENU; MenuWidths : POleMenuGroupWidths ) : HResult; virtual; stdcall; abstract; function SetMenuSB( hmenuShared : HMENU; holemenuReserved : HMENU; hwndActiveObject : HWND ) : HResult; virtual; stdcall; abstract; function RemoveMenusSB( hmenuShared : HMENU ) : HResult; virtual; stdcall; abstract; function SetStatusTextSB( lpszStatusText : POleStr ) : HResult; virtual; stdcall; abstract; function EnableModelessSB( fEnable : BOOL ) : HResult; virtual; stdcall; abstract; function TranslateAcceleratorSB( var msg : TMsg; wID : WORD ) : HResult; virtual; stdcall; abstract; function BrowseObject( pidl : PitemIdList; wFlags : UINT ) : HResult; virtual; stdcall; abstract; function GetViewStateStream( grfMode : DWORD; var ppStrm : IStream ) : HResult; virtual; stdcall; abstract; function GetControlWindow( id : UINT; var wnd : HWND ) : HResult; virtual; stdcall; abstract; function SendControlMsg( id : UINT; uMsg : UINT; wParameter : WPARAM; lParameter : LPARAM; var ret : LRESULT ) : HResult; virtual; stdcall; abstract; function QueryActiveShellView( var shv : IShellView ) : HResult; virtual; stdcall; abstract; function OnViewWindowActive( shv : IShellView ) : HResult; virtual; stdcall; abstract; function SetToolbarItems( Buttons : PTBBUTTON; nButtons : UINT; Flags : UINT ) : HResult; virtual; stdcall; abstract; end; //------------------------------------------------------------------------- // ICommDlgBrowser interface // // ICommDlgBrowser interface is the interface that is provided by the new // common dialog window to hook and modify the behavior of IShellView. When // a default view is created; it queries its parent IShellBrowser for the // ICommDlgBrowser interface. If supported; it calls out to that interface // in several cases that need to behave differently in a dialog. // // Member functions: // // ICommDlgBrowser::OnDefaultCommand() // Called when the user double-clicks in the view or presses Enter. The // browser should return S_OK if it processed the action itself; S_FALSE // to let the view perform the default action. // // ICommDlgBrowser::OnStateChange(ULONG uChange) // Called when some states in the view change. 'uChange' is one of the // CDBOSC_* values. This call is made after the state (selection; focus; // etc) has changed. There is no return value. // // ICommDlgBrowser::IncludeObject(LPCITEMIDLIST pidl) // Called when the view is enumerating objects. 'pidl' is a relative // IDLIST. The browser should return S_OK to include the object in the // view; S_FALSE to hide it // //------------------------------------------------------------------------- ICommDlgBrowser = class( IUnknown ) function OnDefaultCommand( shv : IShellView ) : HResult; virtual; stdcall; abstract; function OnStateChange( shv : IShellView; uChange : ULONG) : HResult; virtual; stdcall; abstract; function IncludeObject( shv : IShellView; pidl : PItemIdList ) : HResult; virtual; stdcall; abstract; end; //========================================================================== // // Interface: IShellView // // IShellView::GetWindow(phwnd) // // Inherited from IOleWindow::GetWindow. // // // IShellView::ContextSensitiveHelp(fEnterMode) // // Inherited from IOleWindow::ContextSensitiveHelp. // // // IShellView::TranslateAccelerator(lpmsg) // // Similar to IOleInPlaceActiveObject::TranlateAccelerator. The explorer // calls this function BEFORE any other translation. Returning S_OK // indicates that the message was translated (eaten) and should not be // translated or dispatched by the explorer. // // // IShellView::EnableModeless(fEnable) // Similar to IOleInPlaceActiveObject::EnableModeless. // // // IShellView::UIActivate(uState) // // The explorer calls this member function whenever the activation // state of the view window is changed by a certain event that is // NOT caused by the shell view itself. // // SVUIA_DEACTIVATE will be passed when the explorer is about to // destroy the shell view window; the shell view is supposed to remove // all the extended UIs (typically merged menu and modeless popup windows). // // SVUIA_ACTIVATE_NOFOCUS will be passsed when the shell view is losing // the input focus or the shell view has been just created without the // input focus; the shell view is supposed to set menuitems appropriate // for non-focused state (no selection specific items should be added). // // SVUIA_ACTIVATE_FOCUS will be passed when the explorer has just // created the view window with the input focus; the shell view is // supposed to set menuitems appropriate for focused state. // // SVUIA_INPLACEACTIVATE(new) will be passed when the shell view is opened // within an ActiveX control; which is not a UI active. In this case; // the shell view should not merge menus or put toolbas. To be compatible // with Win95 client; we don't pass this value unless the view supports // IShellView2. // // The shell view should not change focus within this member function. // The shell view should not hook the WM_KILLFOCUS message to remerge // menuitems. However; the shell view typically hook the WM_SETFOCUS // message; and re-merge the menu after calling IShellBrowser:: // OnViewWindowActivated. // // // IShellView::Refresh() // // The explorer calls this member when the view needs to refresh its // contents (such as when the user hits F5 key). // // // IShellView::CreateViewWindow // // This member creates the view window (right-pane of the explorer or the // client window of the folder window). // // // IShellView::DestroyViewWindow // // This member destroys the view window. // // // IShellView::GetCurrentInfo // // This member returns the folder settings. // // // IShellView::AddPropertySHeetPages // // The explorer calls this member when it is opening the option property // sheet. This allows the view to add additional pages to it. // // // IShellView::SaveViewState() // // The explorer calls this member when the shell view is supposed to // store its view settings. The shell view is supposed to get a view // stream by calling IShellBrowser::GetViewStateStream and store the // current view state into that stream. // // // IShellView::SelectItem(pidlItem; uFlags) // // The explorer calls this member to change the selection state of // item(s) within the shell view window. If pidlItem is NULL and uFlags // is SVSI_DESELECTOTHERS; all items should be deselected. // //------------------------------------------------------------------------- IShellView = class( IOleWindow ) function TranslateAccelerator( var msg : TMsg ) : HResult; virtual; stdcall; abstract; function EnableModeless( fEnable : BOOL ) : HResult; virtual; stdcall; abstract; function UIActivate( uState : UINT ) : HResult; virtual; stdcall; abstract; function Refresh : HResult; virtual; stdcall; abstract; function CreateViewWindow( PrevView : IShellView; var fs : TFolderSettings; psb : IShellBrowser; var prcView : TRect; var Wnd : HWnd ) : HResult; virtual; stdcall; abstract; function DestroyViewWindow : HResult; virtual; stdcall; abstract; function GetCurrentInfo( var fs : TFolderSettings ) : HResult; virtual; stdcall; abstract; function AddPropertySheetPages( dwReserved : DWORD; lpfn : TFNAddPropSheetPage; lparameter : LPARAM ) : HResult; virtual; stdcall; abstract; function SaveViewState : HResult; virtual; stdcall; abstract; function SelectItem( pidlItem : PItemIdList; uFlags : UINT ) : HResult; virtual; stdcall; abstract; function GetItemObject( uItem : UINT; riid : TIID; var ppv : pointer ) : HResult; virtual; stdcall; abstract; end; PSV2CVW2_PARAMS = ^TSV2CVW2_PARAMS; TSV2CVW2_PARAMS = packed record cbSize : DWORD; Prev : IShellView; pfs : PFolderSettings; Owner : IShellBrowser; rView : PRect; pvid : TIID; hwndView : HWND; end; IShellView2 = class( IShellView ) function GetView( pvid : PIID; uView : ULONG ) : HResult; virtual; stdcall; abstract; function CreateViewWindow2( lpParams : PSV2CVW2_PARAMS ) : HResult; virtual; stdcall; abstract; end; implementation end.
{------------------------------------------------------------------------------ TDam component Developed by Rodrigo Depine Dalpiaz (digao dalpiaz) Non visual component to manage message dialogs https://github.com/digao-dalpiaz/Dam Please, read the documentation at GitHub link. ------------------------------------------------------------------------------} unit DamUnit; {$IFDEF FPC}{$mode delphi}{$ENDIF} interface uses {$IFDEF FPC} Classes, SysUtils, Graphics, ImgList; {$ELSE} System.Classes, System.SysUtils, Vcl.Graphics, Vcl.ImgList; {$ENDIF} const DAM_PARAM_EXCEPTION = '{except}'; DAM_PARAM_IDENT = '%p'; type TDamLanguage = (dgEnglish, dgPortuguese, dgSpanish, dgGerman, dgItalian, dgChinese, dgJapanese, dgGreek, dgRussian, dgFrench, dgPolish, dgDutch, dgTurkish); TDamDlgPosition = (dpScreenCenter, dpActiveFormCenter, dpMainFormCenter); TDamMsgRes = 1..3; TDamMsgTitle = (dtApp, dtParentForm, dtMainForm, dtByIcon, dtCustom); TDamMsgIcon = (diApp, diInfo, diQuest, diWarn, diError, diCustom); TDamMsgButtons = (dbOK, dbYesNo, dbOne, dbTwo, dbThree); TDamParams = TArray<Variant>; TDamMsg = class; TDamShowEvent = procedure(Sender: TObject; Msg: TDamMsg; var MsgText: string; var Handled: Boolean; var MsgResult: TDamMsgRes) of object; TDamLinkClickEvent = procedure(Sender: TObject; Msg: TDamMsg; const Target: string; var Handled: Boolean; var CloseMsg: Boolean; var MsgResult: TDamMsgRes) of object; TDam = class(TComponent) private FAbout: string; FLanguage: TDamLanguage; FRaises: Boolean; FSounds: Boolean; FImages: TCustomImageList; FFont: TFont; FDefault: Boolean; FUnit: string; FColorMsg, FColorBtn: TColor; FCenterButtons: Boolean; FDialogPosition: TDamDlgPosition; FDialogBorder: Boolean; FShowEvent: TDamShowEvent; FLinkClick: TDamLinkClickEvent; procedure SetImages(const Value: TCustomImageList); procedure SetFont(const Value: TFont); function GetFontStored: Boolean; function ShowDialog(Msg: TDamMsg; const Text: string): TDamMsgRes; procedure OnError(Sender: TObject; E: Exception); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; protected procedure GetChildren(Proc: TGetChildProc; Root: TComponent); override; procedure Loaded; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; published property About: string read FAbout; property Language: TDamLanguage read FLanguage write FLanguage; property HandleExceptions: Boolean read FRaises write FRaises default False; property Images: TCustomImageList read FImages write SetImages; property MessageFont: TFont read FFont write SetFont stored GetFontStored; property DamDefault: Boolean read FDefault write FDefault default False; property DamUnitName: string read FUnit write FUnit; property PlaySounds: Boolean read FSounds write FSounds default True; property MessageColor: TColor read FColorMsg write FColorMsg default clWhite; property ButtonsColor: TColor read FColorBtn write FColorBtn default clBtnFace; property CenterButtons: Boolean read FCenterButtons write FCenterButtons default False; property DialogPosition: TDamDlgPosition read FDialogPosition write FDialogPosition default dpScreenCenter; property DialogBorder: Boolean read FDialogBorder write FDialogBorder default True; property OnShowMessage: TDamShowEvent read FShowEvent write FShowEvent; property OnLinkClick: TDamLinkClickEvent read FLinkClick write FLinkClick; end; TDamMsg = class(TComponent) private FCustomTitle: string; FCustomIcon: TIcon; FTitle: TDamMsgTitle; FIcon: TDamMsgIcon; FMessage: string; FButton1: string; FButton2: string; FButton3: string; FButtons: TDamMsgButtons; FSwapFocus: Boolean; FRaise: Boolean; FFixedWidth: Integer; FHelpContext: THelpContext; FHelpKeyword: string; FDam: TDam; procedure SetIcon(const Value: TIcon); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Preview; function Run(const Params: TDamParams = nil): TDamMsgRes; function RunAsBool(const Params: TDamParams = nil): Boolean; function GetParentComponent: TComponent; override; function HasParent: Boolean; override; procedure Assign(Source: TPersistent); override; protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; published property CustomTitle: string read FCustomTitle write FCustomTitle; property CustomIcon: TIcon read FCustomIcon write SetIcon; property Title: TDamMsgTitle read FTitle write FTitle default dtByIcon; property Icon: TDamMsgIcon read FIcon write FIcon default diInfo; property Message: string read FMessage write FMessage; property Button1: string read FButton1 write FButton1; property Button2: string read FButton2 write FButton2; property Button3: string read FButton3 write FButton3; property Buttons: TDamMsgButtons read FButtons write FButtons default dbOK; property SwapFocus: Boolean read FSwapFocus write FSwapFocus default False; property RaiseExcept: Boolean read FRaise write FRaise default False; property FixedWidth: Integer read FFixedWidth write FFixedWidth default 0; property HelpContext: THelpContext read FHelpContext write FHelpContext default 0; property HelpKeyword: string read FHelpKeyword write FHelpKeyword; property Dam: TDam read FDam write FDam; end; EDam = class(Exception) private FDamMsg: TDamMsg; public property DamMsg: TDamMsg read FDamMsg; constructor Create(const Msg: string; const Params: TDamParams = nil); overload; constructor Create(DamMsg: TDamMsg; const Params: TDamParams = nil); overload; end; procedure MsgInfo(const Msg: string; const Params: TDamParams = nil); procedure MsgWarn(const Msg: string; const Params: TDamParams = nil); procedure MsgError(const Msg: string; const Params: TDamParams = nil); function MsgQuest(const Msg: string; const Params: TDamParams = nil): Boolean; procedure ShowErrorMsg; function CaptureErrorMsg: string; procedure MsgRaise(const Msg: string; const Params: TDamParams = nil); function DamParams(const Params: array of Variant): TDamParams; //compatibility with old dynamic array implementation uses DamDialog, DamLanguage, Vcl.DzHTMLText, {$IFDEF FPC} Forms, Windows; {$ELSE} Vcl.Forms, Winapi.Windows, System.UITypes; {$ENDIF} const STR_VERSION = '5.1'; var ObjDefault: TDam = nil; procedure CheckExceptObject; begin if ExceptObject=nil then raise Exception.Create('DAM: ExceptObject nil'); end; procedure CheckDamDefault; begin if ObjDefault=nil then raise Exception.Create('DAM: Default TDam not found'); end; function CaptureErrorMsg: string; begin CheckExceptObject; Result := Exception(ExceptObject).Message; end; procedure ShowErrorMsg; begin CheckExceptObject; CheckDamDefault; ObjDefault.OnError(nil, Exception(ExceptObject)); end; function DamParams(const Params: array of Variant): TDamParams; var I: Integer; begin SetLength(Result, Length(Params)); for I := Low(Params) to High(Params) do Result[I] := Params[I]; end; function QuickMsg(const Msg: string; const Params: TDamParams; Kind: TDamMsgIcon): Boolean; var M: TDamMsg; begin CheckDamDefault; M := TDamMsg.Create(nil); try M.Dam := ObjDefault; M.Message := Msg; M.Icon := Kind; if Kind = diQuest then M.Buttons := dbYesNo; Result := M.RunAsBool(Params); finally M.Free; end; end; procedure MsgInfo(const Msg: string; const Params: TDamParams); begin QuickMsg(Msg, Params, diInfo); end; procedure MsgWarn(const Msg: string; const Params: TDamParams); begin QuickMsg(Msg, Params, diWarn); end; procedure MsgError(const Msg: string; const Params: TDamParams); begin QuickMsg(Msg, Params, diError); end; function MsgQuest(const Msg: string; const Params: TDamParams): Boolean; begin Result := QuickMsg(Msg, Params, diQuest); end; procedure MsgRaise(const Msg: string; const Params: TDamParams); begin raise EDam.Create(Msg, Params); end; // function PosOfAnyString(const Args: array of string; const Text: string; Offset: Integer; out ArgIdx: Integer; out iPos: Integer): Boolean; var I, J: Integer; begin for I := Offset to Length(Text) do begin for J := Low(Args) to High(Args) do begin if Copy(Text, I, Length(Args[J]))=Args[J] then begin ArgIdx := J; iPos := I; Exit(True); end; end; end; Exit(False); end; function ParseParams(const Msg: string; const Params: TDamParams): string; const ARGS: array[0..1] of string = (DAM_PARAM_IDENT, DAM_PARAM_EXCEPTION); var A, aPar: string; I, Offset, IdxPar, ArgIdx: Integer; begin A := Msg; IdxPar := -1; Offset := 1; while PosOfAnyString(ARGS, A, Offset, ArgIdx, I) do begin if ArgIdx=0 then begin Inc(IdxPar); if IdxPar>High(Params) then raise Exception.CreateFmt('DAM: Parameter index %d not found', [IdxPar]); end; Delete(A, I, Length(ARGS[ArgIdx])); case ArgIdx of 0: aPar := Params[IdxPar]; 1: aPar := CaptureErrorMsg; end; aPar := TDzHTMLText.EscapeTextToHTML(aPar); Insert(aPar, A, I); Offset := I+Length(aPar); end; Result := A; end; // -- TDamMsg constructor TDamMsg.Create(AOwner: TComponent); begin inherited; FCustomIcon := TIcon.Create; FTitle := dtByIcon; FIcon := diInfo; FButtons := dbOK; end; destructor TDamMsg.Destroy; begin FCustomIcon.Free; FDam := nil; inherited; end; procedure TDamMsg.Preview; begin RunDamDialog(Self, FMessage); end; function TDamMsg.Run(const Params: TDamParams): TDamMsgRes; begin if FRaise then raise EDam.Create(Self, Params); //else Result := Dam.ShowDialog(Self, ParseParams(FMessage, Params)); end; function TDamMsg.RunAsBool(const Params: TDamParams): Boolean; begin Result := Run(Params)=1; end; procedure TDamMsg.Assign(Source: TPersistent); var SourceMsg: TDamMsg; begin if Source is TDamMsg then begin SourceMsg := TDamMsg(Source); FCustomTitle := SourceMsg.FCustomTitle; FCustomIcon.Assign(SourceMsg.FCustomIcon); FTitle := SourceMsg.FTitle; FIcon := SourceMsg.FIcon; FMessage := SourceMsg.FMessage; FButton1 := SourceMsg.FButton1; FButton2 := SourceMsg.FButton2; FButton3 := SourceMsg.FButton3; FButtons := SourceMsg.FButtons; FSwapFocus := SourceMsg.FSwapFocus; FRaise := SourceMsg.FRaise; end else raise Exception.Create('Source must be TDamMsg'); end; function TDamMsg.HasParent: Boolean; begin Result := True; end; function TDamMsg.GetParentComponent: TComponent; begin Result := FDam; end; procedure TDamMsg.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) then if (AComponent = FDam) then Free; end; procedure TDamMsg.SetIcon(const Value: TIcon); begin FCustomIcon.Assign(Value); end; // -- TDam constructor TDam.Create(AOwner: TComponent); begin inherited; FAbout := 'Digao Dalpiaz / Version '+STR_VERSION; FFont := TFont.Create; FFont.Name := 'Segoe UI'; FFont.Size := 10; FSounds := True; FColorMsg := clWhite; FColorBtn := clBtnFace; FDialogBorder := True; SetDamLangBySysLang(FLanguage); end; destructor TDam.Destroy; begin FFont.Free; if not (csDesigning in ComponentState) then begin if FRaises then Application.OnException := nil; //avoid AV end; inherited; end; procedure TDam.GetChildren(Proc: TGetChildProc; Root: TComponent); var C: TComponent; begin for C in Owner do if C.GetParentComponent = Self then Proc(C); end; procedure TDam.Loaded; begin inherited; if not (csDesigning in ComponentState) then begin if FRaises then Application.OnException := OnError; if FDefault then ObjDefault := Self; end; end; procedure TDam.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if Operation = opRemove then begin if AComponent = FImages then FImages := nil; end; end; procedure TDam.SetImages(const Value: TCustomImageList); begin if Value <> FImages then begin FImages := Value; if FImages <> nil then FImages.FreeNotification(Self); end; end; procedure TDam.SetFont(const Value: TFont); begin FFont.Assign(Value); end; function TDam.GetFontStored: Boolean; begin Result := not ( (FFont.Charset = DEFAULT_CHARSET) and (FFont.Color = clWindowText) and (FFont.Name = 'Segoe UI') and (FFont.Orientation = 0) and (FFont.Pitch = fpDefault) and (FFont.Size = 10) and (FFont.Style = []) and (FFont.Quality = fqDefault) ); end; function TDam.ShowDialog(Msg: TDamMsg; const Text: string): TDamMsgRes; var newMsg: string; Handled: Boolean; HndRes: TDamMsgRes; begin newMsg := Text; if Assigned(FShowEvent) then begin Handled := False; HndRes := 1; //default FShowEvent(Self, Msg, newMsg, Handled, HndRes); if Handled then Exit(HndRes); end; Result := RunDamDialog(Msg, newMsg); end; procedure TDam.OnError(Sender: TObject; E: Exception); var Msg: TDamMsg; Text: string; begin if (E is EDam) and (EDam(E).DamMsg<>nil) then begin ShowDialog(EDam(E).DamMsg, E.Message); end else begin if E is EDam then Text := E.Message else Text := TDzHTMLText.EscapeTextToHTML(E.Message); Msg := TDamMsg.Create(nil); try Msg.Dam := Self; Msg.Icon := diError; ShowDialog(Msg, Text); finally Msg.Free; end; end; end; constructor EDam.Create(const Msg: string; const Params: TDamParams); begin inherited Create(ParseParams(Msg, Params)); end; constructor EDam.Create(DamMsg: TDamMsg; const Params: TDamParams); begin inherited Create(ParseParams(DamMsg.Message, Params)); FDamMsg := DamMsg; end; initialization {$IFNDEF FPC}System.{$ENDIF}Classes.RegisterClass(TDamMsg); if DZHTMLTEXT_INTERNAL_VERSION <> 706 then raise Exception.Create('Please, update DzHTMLText component.'); end.
{ view.pas View class of the texteditor example. Creates the user interface. This example project is released under public domain AUTHORS: Felipe Monteiro de Carvalho } unit view; {$mode objfpc}{$H+} interface uses Classes, SysUtils, MacOSAll, appkit, foundation, objc, mytoolbar; type { TMyView } TMyView = class private { Other helper functions } procedure AddToMenubar(menu: NSMenu); function CreateAppleMenu(): NSMenu; function CreateFileMenu(): NSMenu; procedure CreateMainMenu(); function CreateMenuItem(ATitle: shortstring; ACallback: string; ATarget: objc.id): NSMenuItem; function CreateToolbar(AOwnerView: NSView; AX, AY, AWidth, AHeight: Double): NSToolbar; function CreateTextField(): NSTextField; public { classes } MainWindow: NSWindow; MainWindowView: NSView; Toolbar: NSToolbar; TextField: NSTextField; MainMenu, AppleMenu, ServicesMenu, FileMenu: NSMenu; OpenItem, SaveItem, SaveAsItem, ExitItem: NSMenuItem; { strings and sizes} CFWindowTitle, CFEmptyString: CFStringRef; MainWindowRect: NSRect; { methods } procedure CreateUserInterface(); end; const Str_Window_Title = 'Text Editor'; var MyView: TMyView = nil; implementation uses controller, model; {@@ } procedure TMyView.CreateUserInterface(); begin CFEmptyString := CFStringCreateWithPascalString(nil, '', kCFStringEncodingUTF8); { Creates the main window } MainWindowRect.origin.x := 300.0; MainWindowRect.origin.y := 300.0; MainWindowRect.size.width := 300.0; MainWindowRect.size.height := 500.0; MainWindow := NSWindow.initWithContentRect_styleMask_backing_defer(MainWindowRect, NSTitledWindowMask or NSClosableWindowMask or NSMiniaturizableWindowMask or NSResizableWindowMask, NSBackingStoreBuffered, LongBool(NO)); MainWindowView := NSView.CreateWithHandle(MainWindow.contentView); CFWindowTitle := CFStringCreateWithPascalString(nil, Str_Window_Title, kCFStringEncodingUTF8); MainWindow.setTitle(CFWindowTitle); { Adds the toolbar and it's buttons } Toolbar := CreateToolbar(MainWindowView, 0, MainWindowRect.size.height - 50, MainWindowRect.size.width, 50); MainWindow.setToolbar(Toolbar.Handle); { Add the text area } TextField := CreateTextField(); { Add the main menu } CreateMainMenu(); end; {@@ Creates the Apple submenu } function TMyView.CreateAppleMenu(): NSMenu; var AppleMenuTitle, ServicesMenuTitle: CFStringRef; begin AppleMenuTitle := CFStringCreateWithPascalString(nil, 'Apple Menu', kCFStringEncodingUTF8); ServicesMenuTitle := CFStringCreateWithPascalString(nil, 'Services', kCFStringEncodingUTF8); { Creates the Apple menu } Result := NSMenu.initWithTitle(AppleMenuTitle); { Add the services submenu } ServicesMenu := NSMenu.initWithTitle(ServicesMenuTitle); NSApp.setServicesMenu(ServicesMenu.Handle); end; {@@ Creates the File submenu } function TMyView.CreateFileMenu(): NSMenu; var MenuTitle: CFStringRef; begin MenuTitle := CFStringCreateWithPascalString(nil, 'File', kCFStringEncodingUTF8); { Creates the file menu } Result := NSMenu.initWithTitle(MenuTitle); { Adds items to it } OpenItem := CreateMenuItem('Open', 'doOpenFile:', myController.Handle); Result.addItem(OpenItem.Handle); SaveItem := CreateMenuItem('Save', 'doSaveFile:', myController.Handle); Result.addItem(SaveItem.Handle); SaveAsItem := CreateMenuItem('Save As', 'doSaveAsFile:', myController.Handle); Result.addItem(SaveAsItem.Handle); Result.addItem(NSMenuItem.separatorItem.Handle); ExitItem := CreateMenuItem('Exit', 'doClose:', myController.Handle); Result.addItem(ExitItem.Handle); end; {@@ Adds a submenu to the main menu } procedure TMyView.AddToMenubar(menu: NSMenu); var dummyItem: NSMenuItem; begin dummyItem := NSMenuItem.initWithTitle_action_keyEquivalent(CFEmptyString, nil, CFEmptyString); dummyItem.setSubmenu(menu.Handle); MainMenu.addItem(dummyItem.Handle); dummyItem.Free; end; {@@ Creates the toolbar object. Setting the items is done in the controller. } function TMyView.CreateToolbar(AOwnerView: NSView; AX, AY, AWidth, AHeight: Double): NSToolbar; begin Result := NSToolbar.initWithIdentifier(CFEmptyString); myToolbarController := TMyToolbarController.Create; Result.setDelegate(myToolbarController.Handle); end; {@@ Creates the main menu } procedure TMyView.CreateMainMenu(); begin MainMenu := NSMenu.initWithTitle(CFEmptyString); NSApp.setMainMenu(MainMenu.Handle); AppleMenu := CreateAppleMenu(); NSApp.setAppleMenu(AppleMenu.Handle); AddToMenubar(AppleMenu); FileMenu := CreateFileMenu(); AddToMenubar(FileMenu); end; {@@ Creates a new menu item from a title } function TMyView.CreateMenuItem(ATitle: shortstring; ACallback: string; ATarget: objc.id): NSMenuItem; var ItemText: CFStringRef; KeyText: CFStringRef; begin KeyText := CFStringCreateWithPascalString(nil, '', kCFStringEncodingUTF8); ItemText := CFStringCreateWithPascalString(nil, ATitle, kCFStringEncodingUTF8); WriteLn(' ItemText: ', IntToHex(Int64(ItemText), 8), ' ATitle: ', ATitle); Result := NSMenuItem.initWithTitle_action_keyEquivalent( ItemText, nil, KeyText); Result.setTarget(ATarget); Result.setAction(sel_registerName(PChar(ACallback))); end; {@@ Creates an autosized NSTextField } function TMyView.CreateTextField(): NSTextField; var ClientRect: NSRect; begin ClientRect.origin.x := 0.0; ClientRect.origin.y := 0.0; ClientRect.size.width := 300.0; ClientRect.size.height := 500.0; Result := NSTextField.initWithFrame(ClientRect); Result.setAutoresizingMask(NSViewWidthSizable or NSViewHeightSizable); MainWindowView.addSubview(Result.Handle); end; end.
unit kwInclude; {* Зарезервированное слово: INCLUDE Пример: [code] INCLUDE 'Included.script' [code] } // Модуль: "w:\common\components\rtl\Garant\ScriptEngine\kwInclude.pas" // Стереотип: "ScriptKeyword" // Элемент модели: "Include" MUID: (4DC1949F00E1) // Имя типа: "TkwInclude" {$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc} interface {$If NOT Defined(NoScripts)} uses l3IntfUses , tfwIncludeLike , tfwScriptingInterfaces ; type TkwInclude = class(TtfwIncludeLike) {* Зарезервированное слово: INCLUDE Пример: [code] INCLUDE 'Included.script' [code] } protected function EndBracket(const aContext: TtfwContext; aSilent: Boolean): RtfwWord; override; class function GetWordNameForRegister: AnsiString; override; function AfterWordMaxCount(const aCtx: TtfwContext): Integer; override; end;//TkwInclude {$IfEnd} // NOT Defined(NoScripts) implementation {$If NOT Defined(NoScripts)} uses l3ImplUses , kwIncluded , l3String //#UC START# *4DC1949F00E1impl_uses* //#UC END# *4DC1949F00E1impl_uses* ; function TkwInclude.EndBracket(const aContext: TtfwContext; aSilent: Boolean): RtfwWord; //#UC START# *4DB6C99F026E_4DC1949F00E1_var* //#UC END# *4DB6C99F026E_4DC1949F00E1_var* begin //#UC START# *4DB6C99F026E_4DC1949F00E1_impl* Result := DisabledEndBracket(aContext, aSilent); //#UC END# *4DB6C99F026E_4DC1949F00E1_impl* end;//TkwInclude.EndBracket class function TkwInclude.GetWordNameForRegister: AnsiString; begin Result := 'INCLUDE'; end;//TkwInclude.GetWordNameForRegister function TkwInclude.AfterWordMaxCount(const aCtx: TtfwContext): Integer; //#UC START# *4DB9B446039A_4DC1949F00E1_var* //#UC END# *4DB9B446039A_4DC1949F00E1_var* begin //#UC START# *4DB9B446039A_4DC1949F00E1_impl* Result := -1; //#UC END# *4DB9B446039A_4DC1949F00E1_impl* end;//TkwInclude.AfterWordMaxCount initialization TkwInclude.RegisterInEngine; {* Регистрация Include } {$IfEnd} // NOT Defined(NoScripts) end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.5 2004.10.27 9:17:46 AM czhower For TIdStrings Rev 1.4 7/28/04 11:43:32 PM RLebeau Bug fix for CleanupCookieList() Rev 1.3 2004.02.03 5:45:02 PM czhower Name changes Rev 1.2 1/22/2004 7:10:02 AM JPMugaas Tried to fix AnsiSameText depreciation. Rev 1.1 2004.01.21 1:04:54 PM czhower InitComponenet Rev 1.0 11/14/2002 02:16:26 PM JPMugaas 2001-Mar-31 Doychin Bondzhev - Added new method AddCookie2 that is called when we have Set-Cookie2 as response - The common code in AddCookie and AddCookie2 is now in DoAdd 2001-Mar-24 Doychin Bondzhev - Added OnNewCookie event This event is called for every new cookie. Can be used to ask the user program do we have to store this cookie in the cookie collection - Added new method AddCookie This calls the OnNewCookie event and if the result is true it adds the new cookie in the collection } unit IdCookieManager; { Implementation of the HTTP State Management Mechanism as specified in RFC 6265. Author: Remy Lebeau (remy@lebeausoftware.org) Copyright: (c) Chad Z. Hower and The Indy Team. } interface {$i IdCompilerDefines.inc} uses Classes, IdBaseComponent, IdCookie, IdHeaderList, IdURI; Type TOnNewCookieEvent = procedure(ASender: TObject; ACookie: TIdCookie; var VAccept: Boolean) of object; TOnCookieManagerEvent = procedure(ASender: TObject; ACookieCollection: TIdCookies) of object; TOnCookieCreateEvent = TOnCookieManagerEvent; TOnCookieDestroyEvent = TOnCookieManagerEvent; TIdCookieManager = class(TIdBaseComponent) protected FOnCreate: TOnCookieCreateEvent; FOnDestroy: TOnCookieDestroyEvent; FOnNewCookie: TOnNewCookieEvent; FCookieCollection: TIdCookies; procedure CleanupCookieList; procedure DoOnCreate; virtual; procedure DoOnDestroy; virtual; function DoOnNewCookie(ACookie: TIdCookie): Boolean; virtual; procedure InitComponent; override; public destructor Destroy; override; // procedure AddServerCookie(const ACookie: String; AURL: TIdURI); procedure AddServerCookies(const ACookies: TStrings; AURL: TIdURI); procedure AddCookies(ASource: TIdCookieManager); procedure CopyCookie(ACookie: TIdCookie); // procedure GenerateClientCookies(AURL: TIdURI; SecureOnly: Boolean; Headers: TIdHeaderList); // property CookieCollection: TIdCookies read FCookieCollection; published property OnCreate: TOnCookieCreateEvent read FOnCreate write FOnCreate; property OnDestroy: TOnCookieDestroyEvent read FOnDestroy write FOnDestroy; property OnNewCookie: TOnNewCookieEvent read FOnNewCookie write FOnNewCookie; end; //procedure SplitCookies(const ACookie: String; ACookies: TStrings); implementation uses IdAssignedNumbers, IdException, IdGlobal, IdGlobalProtocols, SysUtils; { TIdCookieManager } destructor TIdCookieManager.Destroy; begin CleanupCookieList; DoOnDestroy; FreeAndNil(FCookieCollection); inherited Destroy; end; function SortCookiesFunc(Item1, Item2: TIdCookie): Integer; begin // using the algorithm defined in RFC 6265 section 5.4 if Item1 = Item2 then begin Result := 0; end else if Length(Item2.Path) > Length(Item1.Path) then begin Result := 1; end else if Length(Item1.Path) = Length(Item2.Path) then begin if Item2.CreatedAt < Item1.CreatedAt then begin Result := 1; end else begin Result := -1; end; end else begin Result := -1; end; end; procedure TIdCookieManager.GenerateClientCookies(AURL: TIdURI; SecureOnly: Boolean; Headers: TIdHeaderList); var I: Integer; LCookieList: TIdCookieList; LResultList: TList; LCookie: TIdCookie; LCookiesToSend: String; LNow: TDateTime; begin // check for expired cookies first... CleanupCookieList; LCookieList := CookieCollection.LockCookieList(caRead); try if LCookieList.Count > 0 then begin LResultList := TList.Create; try // Search for cookies for this domain and URI for I := 0 to LCookieList.Count-1 do begin LCookie := LCookieList.Cookies[I]; if LCookie.IsAllowed(AURL, SecureOnly) then begin LResultList.Add(LCookie); end; end; if LResultList.Count > 0 then begin if LResultList.Count > 1 then begin LResultList.Sort(TListSortCompare(@SortCookiesFunc)); end; LNow := Now; for I := 0 to LResultList.Count-1 do begin TIdCookie(LResultList.Items[I]).LastAccessed := LNow; end; LCookiesToSend := TIdCookie(LResultList.Items[0]).ClientCookie; for I := 1 to LResultList.Count-1 do begin LCookiesToSend := LCookiesToSend + '; ' + TIdCookie(LResultList.Items[I]).ClientCookie; {Do not Localize} end; Headers.AddValue('Cookie', LCookiesToSend); {Do not Localize} end; finally LResultList.Free; end; end; finally CookieCollection.UnlockCookieList(caRead); end; end; procedure TIdCookieManager.AddServerCookie(const ACookie: String; AURL: TIdURI); var LCookie: TIdCookie; begin // TODO: use TIdCookies.AddServerCookie() after adding // a way for it to query the manager for rejections... // //FCookieCollection.AddServerCookie(ACookie, AURI); LCookie := FCookieCollection.Add; try if LCookie.ParseServerCookie(ACookie, AURL) then begin if DoOnNewCookie(LCookie) then begin if FCookieCollection.AddCookie(LCookie, AURL) then begin LCookie := nil; Exit; end; end; end; finally if LCookie <> nil then begin LCookie.Collection := nil; LCookie.Free; end; end; end; procedure TIdCookieManager.AddCookies(ASource: TIdCookieManager); begin if (ASource <> nil) and (ASource <> Self) then begin FCookieCollection.AddCookies(ASource.CookieCollection); end; end; procedure TIdCookieManager.AddServerCookies(const ACookies: TStrings; AURL: TIdURI); var I: Integer; begin for I := 0 to ACookies.Count-1 do begin AddServerCookie(ACookies[I], AURL); end; end; procedure TIdCookieManager.CopyCookie(ACookie: TIdCookie); var LCookie: TIdCookie; begin LCookie := TIdCookieClass(ACookie.ClassType).Create(FCookieCollection); try LCookie.Assign(ACookie); if LCookie.Domain <> '' then begin if DoOnNewCookie(LCookie) then begin if FCookieCollection.AddCookie(LCookie, nil) then begin LCookie := nil; end; end; end; finally if LCookie <> nil then begin LCookie.Collection := nil; LCookie.Free; end; end; end; function TIdCookieManager.DoOnNewCookie(ACookie: TIdCookie): Boolean; begin Result := True; if Assigned(FOnNewCookie) then begin OnNewCookie(Self, ACookie, Result); end; end; procedure TIdCookieManager.DoOnCreate; begin if Assigned(FOnCreate) then begin OnCreate(Self, FCookieCollection); end; end; procedure TIdCookieManager.DoOnDestroy; begin if Assigned(FOnDestroy) then begin OnDestroy(Self, FCookieCollection); end; end; procedure TIdCookieManager.CleanupCookieList; var i: Integer; LCookieList: TIdCookieList; LCookie: TIdCookie; begin LCookieList := FCookieCollection.LockCookieList(caReadWrite); try for i := LCookieList.Count-1 downto 0 do begin LCookie := LCookieList.Cookies[i]; if LCookie.IsExpired then begin // The Cookie has expired. It has to be removed from the collection LCookieList.Delete(i); LCookie.Collection := nil; LCookie.Free; end; end; finally FCookieCollection.UnlockCookieList(caReadWrite); end; end; procedure TIdCookieManager.InitComponent; begin inherited InitComponent; FCookieCollection := TIdCookies.Create(Self); DoOnCreate; end; end.
unit SmartThreads; interface uses Windows, Classes, SysUtils; type TSmartThread = class( TThread ) public constructor Create( CreateSuspended : boolean ); destructor Destroy; override; public procedure CallSync( ExtMethod : TThreadMethod ); end; procedure CallSync( ExtMethod : TThreadMethod ); type ESmartSyncFault = class( Exception ); var MainThreadId : DWORD; procedure InitThreadRegistry; procedure DoneThreadRegistry; {$IFNDEF LIBRARY} function FindThread( ThreadId : dword ) : TThread; {$ENDIF} implementation {$IFDEF LIBRARY} uses SmartThreadRegistry; procedure InitThreadRegistry; begin SmartThreadRegistry.InitThreadRegistry; end; procedure DoneThreadRegistry; begin SmartThreadRegistry.DoneThreadRegistry; end; {$ELSE} procedure RegisterThread( Thread : TThread ); external 'ThreadRegistry.dll'; procedure UnregisterThread( Thread : TThread ); external 'ThreadRegistry.dll'; function FindThread( ThreadId : dword ) : TThread; external 'ThreadRegistry.dll'; procedure InitThreadRegistry; external 'ThreadRegistry.dll'; procedure DoneThreadRegistry; external 'ThreadRegistry.dll'; {$ENDIF} // TSmartThread constructor TSmartThread.Create( CreateSuspended : boolean ); begin inherited Create( true ); RegisterThread( self ); if not CreateSuspended then Resume; end; destructor TSmartThread.Destroy; begin UnregisterThread( self ); inherited; end; procedure TSmartThread.CallSync( ExtMethod : TThreadMethod ); begin Synchronize( ExtMethod ); end; // CallSync procedure CallSync( ExtMethod : TThreadMethod ); var CurrentThreadId : DWORD; CurrentThread : TThread; begin CurrentThreadId := GetCurrentThreadId; if CurrentThreadId <> MainThreadId then begin CurrentThread := FindThread( CurrentThreadId ); if (CurrentThread <> nil) and (CurrentThread is TSmartThread) then TSmartThread(CurrentThread).CallSync( ExtMethod ) else raise ESmartSyncFault.Create( 'Attemp to synchronize in a non smart thread' ) end else ExtMethod; end; initialization MainThreadId := GetCurrentThreadId; end.
unit HGM.Controls.ListBoxDraw; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, System.Generics.Collections, Vcl.ExtCtrls, System.UITypes, Vcl.Grids, HGM.Common; type TGetDataProc = procedure(Index:Integer; var Value:string) of object; TItemClick = procedure(Sender:TObject; MouseButton:TMouseButton; const Index:Integer) of object; TListBoxEx = class(TCustomDrawGrid) private FItemDowned:Boolean; FItemIndex:Integer; FCordHot:TGridCoord; FGetDataProc:TGetDataProc; FWheelDown:TMouseWheelUpDownEvent; FWheelUp:TMouseWheelUpDownEvent; FOnMouseMove:TMouseMoveEvent; FOnMouseLeave: TNotifyEvent; FOnMouseDown: TMouseEvent; FOnItemClick:TItemClick; FOnDrawCell:TDrawCellEvent; FDefDrawing: Boolean; procedure FDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State:TGridDrawState); procedure FMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure FMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure FMouseLeave(Sender: TObject); procedure FMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure SetRowCount(Value: Integer); function GetRowCount: Longint; procedure SetColumnWidth; procedure SetWidth(const Value: Integer); function GetWidth: Integer; procedure SetItemIndex(const Value: Integer); procedure SetShowScrollBar(const Value: Boolean); function GetShowScrollBar: Boolean; procedure SetDefDrawing(const Value: Boolean); public function DoMouseWheelDown(Shift: TShiftState; MousePos: TPoint): Boolean; override; function DoMouseWheelUp(Shift: TShiftState; MousePos: TPoint): Boolean; override; constructor Create(AOwner: TComponent); override; published property Align; property Anchors; property BevelEdges; property BevelInner; property BevelKind; property BevelOuter; property BevelWidth; property BiDiMode; property BorderStyle; property Color; property Constraints; property Ctl3D; property DefaultRowHeight; property DoubleBuffered; property DragCursor; property DragKind; property DragMode; property Enabled; property Font; property ParentBiDiMode; property ParentColor; property ParentCtl3D; property ParentDoubleBuffered; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property Touch; property Visible; property StyleElements; property OnClick; property OnContextPopup; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnGesture; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseActivate; property OnMouseUp; property OnSetEditText; property OnStartDock; property OnStartDrag; property OnTopLeftChanged; property OnMouseEnter; property ShowScrollBar:Boolean read GetShowScrollBar write SetShowScrollBar default True; property DefaultDataDrawing:Boolean read FDefDrawing write SetDefDrawing default True; property OnDrawCellData:TDrawCellEvent read FOnDrawCell write FOnDrawCell; property Width:Integer read GetWidth write SetWidth; property ItemIndex:Integer read FItemIndex write SetItemIndex; property ItemCount:Longint read GetRowCount write SetRowCount default 5; property OnMouseDown:TMouseEvent read FOnMouseDown write FOnMouseDown; property OnMouseLeave:TNotifyEvent read FOnMouseLeave write FOnMouseLeave; property OnMouseMove:TMouseMoveEvent read FOnMouseMove write FOnMouseMove; property OnItemClick:TItemClick read FOnItemClick write FOnItemClick; property GetData:TGetDataProc read FGetDataProc write FGetDataProc; property OnMouseWheelDown:TMouseWheelUpDownEvent read FWheelDown write FWheelDown; property OnMouseWheelUp:TMouseWheelUpDownEvent read FWheelUp write FWheelUp; end; procedure Register; implementation uses Math; function MixColors(Color1, Color2:TColor; Alpha:Byte):TColor; var C1, C2:LongInt; R, G, B, V1, V2:Byte; begin Alpha:=Round(2.55 * Alpha); C1:=ColorToRGB(Color1); C2:=ColorToRGB(Color2); V1:=Byte(C1); V2:=Byte(C2); R:=Alpha * (V1 - V2) shr 8 + V2; V1:=Byte(C1 shr 8); V2:=Byte(C2 shr 8); G:=Alpha * (V1 - V2) shr 8 + V2; V1:=Byte(C1 shr 16); V2:=Byte(C2 shr 16); B:=Alpha * (V1 - V2) shr 8 + V2; Result:=(B shl 16) + (G shl 8) + R; end; procedure Register; begin RegisterComponents(PackageName, [TListBoxEx]); end; function Between(FMin, FValue, FMax:Integer):Boolean; begin Result:=(FValue >= FMin) and (FValue <= FMax); end; function ScaledRect(const Src:TRect; Delta:Integer):TRect; begin Result:=Src; //Rect(1, 1, 4, 4) Result.Left:=Result.Left - Delta; //Scale 1 = Rect(0, 0, 5, 5) Result.Top:=Result.Top - Delta; Result.Right:=Result.Right + Delta; Result.Bottom:=Result.Bottom + Delta; end; function ColorDarker(Color:TColor; Percent:Byte = 40):TColor; var R, G, B:Byte; begin if Percent > 100 then Percent:=100; Color:=ColorToRGB(Color); R:=GetRValue(Color); G:=GetGValue(Color); B:=GetBValue(Color); R:=R - MulDiv(R, Percent, 100); G:=G - MulDiv(G, Percent, 100); B:=B - MulDiv(B, Percent, 100); Result:=RGB(R, G, B); end; function ColorLighter(Color:TColor; Percent:Byte = 40):TColor; var R, G, B:Byte; begin Color:=ColorToRGB(Color); R:=GetRValue(Color); G:=GetGValue(Color); B:=GetBValue(Color); R:=R + MulDiv(255-R, Percent, 100); G:=G + MulDiv(255-G, Percent, 100); B:=B + MulDiv(255-B, Percent, 100); Result:=RGB(R, G, B); end; function DrawTextCentered(Canvas: TCanvas; const R: TRect; S: String; FDrawFlags:Cardinal = DT_CENTER): Integer; var DrawRect: TRect; DrawFlags: Cardinal; DrawParams: TDrawTextParams; begin DrawRect:= R; DrawFlags:= DT_END_ELLIPSIS or DT_NOPREFIX or DT_WORDBREAK or DT_EDITCONTROL or FDrawFlags; DrawText(Canvas.Handle, PChar(S), -1, DrawRect, DrawFlags or DT_CALCRECT); DrawRect.Right:= R.Right; if DrawRect.Bottom < R.Bottom then OffsetRect(DrawRect, 0, (R.Bottom - DrawRect.Bottom) div 2) else DrawRect.Bottom:= R.Bottom; ZeroMemory(@DrawParams, SizeOf(DrawParams)); DrawParams.cbSize:= SizeOf(DrawParams); DrawTextEx(Canvas.Handle, PChar(S), -1, DrawRect, DrawFlags, @DrawParams); Result:= DrawParams.uiLengthDrawn; end; { TListBoxEx } procedure TListBoxEx.SetRowCount(Value: Longint); begin inherited RowCount:=Max(1, Value); SetColumnWidth; end; procedure TListBoxEx.SetShowScrollBar(const Value: Boolean); begin case Value of True:ScrollBars:=ssVertical; False:ScrollBars:=ssNone; end; SetColumnWidth; end; procedure TListBoxEx.SetWidth(const Value: Integer); begin inherited Width:=Value; SetColumnWidth; end; procedure TListBoxEx.SetColumnWidth; var ColWidth:Integer; begin if Width > 0 then begin if not Assigned(Parent) then begin DefaultColWidth:=Width-20; end else begin ColWidth:=ClientWidth; if ColWidth < 1 then ColWidth:= 1; DefaultColWidth:=ColWidth; end; end; end; procedure TListBoxEx.SetDefDrawing(const Value: Boolean); begin FDefDrawing:= Value; Repaint; end; procedure TListBoxEx.SetItemIndex(const Value: Integer); begin FItemIndex:= Value; if Value >= 0 then Row:=Value; Repaint; end; constructor TListBoxEx.Create(AOwner: TComponent); begin inherited; inherited OnMouseMove:=FMouseMove; inherited OnMouseUp:=FMouseUp; inherited OnMouseDown:=FMouseDown; inherited OnMouseLeave:=FMouseLeave; inherited OnDrawCell:=FDrawCell; DefaultColWidth:=140; DrawingStyle:=gdsGradient; FDefDrawing:=True; Width:=160; FItemIndex:=-1; FItemDowned:=False; FCordHot.X:=-1; FCordHot.Y:=-1; ColCount:=1; FixedCols:=0; FixedRows:=0; inherited DefaultDrawing:=False; Options:=[goRowSelect, goThumbTracking]; ScrollBars:=ssVertical; end; function TListBoxEx.DoMouseWheelDown(Shift: TShiftState; MousePos: TPoint): Boolean; begin Result:=True; Perform(WM_VSCROLL, SB_LINEDOWN, 0); Repaint; end; function TListBoxEx.DoMouseWheelUp(Shift: TShiftState; MousePos: TPoint): Boolean; begin Result:=True; Perform(WM_VSCROLL, SB_LINEUP, 0); Repaint; end; procedure TListBoxEx.FDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); var BColor:TColor; ID:Integer; TextValue:string; procedure DrawText(Value:string; Offset:Integer = 0); var RText:TRect; begin with Canvas do begin RText:=Rect; RText.Left:=RText.Left + 1 + Offset; RText.Top:=RText.Top + 1; RText.Right:=RText.Right - 1; RText.Bottom:=RText.Bottom - 1; DrawTextCentered(Canvas, RText, Value, DT_LEFT); end; end; begin with Canvas do begin TextValue:='?'; Brush.Style:=bsSolid; Pen.Style:=psSolid; Brush.Color:=Color; Pen.Color:=Brush.Color; Rectangle(Rect); Brush.Color:=$00F1F2F2; Pen.Color:=Brush.Color; Rectangle(Rect); Pen.Color:=ColorDarker(Brush.Color); MoveTo(Rect.Left, Rect.Bottom-1); LineTo(Rect.Right, Rect.Bottom-1); if ARow mod 2 = 0 then Brush.Color:=$00E7E8E8 else Brush.Color:=$00F1F2F2; //if ARow = FItemIndex then Brush.Color:=ColorDarker($00E7E8E8); if ARow = Row then begin Brush.Color:=ColorDarker($00E7E8E8); Font.Color:=clWhite; end else begin Font.Color:=$00282828; end; Pen.Color:=Brush.Color; Rectangle(Rect); if (FCordHot.Y = ARow) and (ARow <> Row) then begin if FItemDowned then BColor:=ColorDarker($00DCDCDC, 20) else BColor:=$00DCDCDC; Brush.Color:=MixColors(BColor, Canvas.Brush.Color, 150); Pen.Color:=Brush.Color; Brush.Style:=bsSolid; Pen.Style:=psSolid; Rectangle(Rect); end; if not FDefDrawing then begin if Assigned(FOnDrawCell) then FOnDrawCell(Sender, ACol, ARow, Rect, State); Exit; end; Brush.Style:=bsClear; ID:=ARow; if Assigned(FGetDataProc) then FGetDataProc(ID, TextValue); DrawText(TextValue); end; end; procedure TListBoxEx.FMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin FItemDowned:=True; end; procedure TListBoxEx.FMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if Row >= 0 then begin if FItemDowned then begin FItemIndex:=Row; if Assigned(FOnItemClick) then FOnItemClick(Sender, Button, FItemIndex); end; end; FItemDowned:=False; end; procedure TListBoxEx.FMouseLeave(Sender: TObject); begin FCordHot.X:=-1; FCordHot.Y:=-1; FItemDowned:=False; Repaint; end; procedure TListBoxEx.FMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if not Focused then SetFocus; FCordHot:=MouseCoord(X, Y); if Between(0, FCordHot.Y, RowCount-1) then begin Cursor:=crHandPoint; end else Cursor:=crDefault; Repaint; if Assigned(FOnMouseMove) then FOnMouseMove(Sender, Shift, X, Y); end; function TListBoxEx.GetRowCount:Longint; begin Result:=RowCount; end; function TListBoxEx.GetShowScrollBar:Boolean; begin Result:=ScrollBars <> ssNone; end; function TListBoxEx.GetWidth: Integer; begin Result:=inherited Width; end; end.
unit atOpenRedactionsOperation; // Модуль: "w:\quality\test\garant6x\AdapterTest\Operations\atOpenRedactionsOperation.pas" // Стереотип: "SimpleClass" // Элемент модели: "TatOpenRedactionsOperation" MUID: (48B560B601B8) interface uses l3IntfUses , atOperationBase , atLoadDocumentsByIDFromListOperation ; type TatOpenRedactionsOperation = class(TatOperationBase) private f_LoadDocumentByIDFromListOperation: TatLoadDocumentsByIDFromListOperation; protected procedure ExecuteSelf; override; procedure Cleanup; override; {* Функция очистки полей объекта. } procedure InitFields; override; procedure ExecuteChilds; override; end;//TatOpenRedactionsOperation implementation uses l3ImplUses , DocumentUnit , atLogger , atStringHelper , SysUtils //#UC START# *48B560B601B8impl_uses* //#UC END# *48B560B601B8impl_uses* ; procedure TatOpenRedactionsOperation.ExecuteSelf; //#UC START# *48089F460352_48B560B601B8_var* var l_RedactionsList : IRedactionInfoList; l_Redaction : TRedactionInfo; i : integer; //#UC END# *48089F460352_48B560B601B8_var* begin //#UC START# *48089F460352_48B560B601B8_impl* inherited; // получаем список редакций with ExecutionContext.UserWorkContext do begin Assert(CurrDoc <> nil, 'CurrDoc <> nil'); Logger.Info('Получаем спиок редакций...'); CurrDoc.GetRedactionsList(l_RedactionsList); end; Assert(l_RedactionsList <> nil, 'l_RedactionsList <> nil'); if (l_RedactionsList.Count = 0) then begin Logger.Info('Список редакций пуст.'); Exit; end; // перебираем редакции for i := 0 to l_RedactionsList.Count-1 do begin l_RedactionsList.pm_GetItem(i, l_Redaction); // открываем редакцию Logger.Info('Название редакции: "%s". Номер: %d.', [TatStringHelper.AStr2DStr(l_Redaction.rName), l_Redaction.rId]); with f_LoadDocumentByIDFromListOperation do begin Logger.Info('Теперь воспользуемся операцией %s для открытия документа', [ClassName]); Parameters['documents_list'].AsStr := IntToStr(l_Redaction.rId); Execute(ExecutionContext); end; // выполняем детей inherited ExecuteChilds; end; //#UC END# *48089F460352_48B560B601B8_impl* end;//TatOpenRedactionsOperation.ExecuteSelf procedure TatOpenRedactionsOperation.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_48B560B601B8_var* //#UC END# *479731C50290_48B560B601B8_var* begin //#UC START# *479731C50290_48B560B601B8_impl* FreeAndNil(f_LoadDocumentByIDFromListOperation); inherited; //#UC END# *479731C50290_48B560B601B8_impl* end;//TatOpenRedactionsOperation.Cleanup procedure TatOpenRedactionsOperation.InitFields; //#UC START# *47A042E100E2_48B560B601B8_var* //#UC END# *47A042E100E2_48B560B601B8_var* begin //#UC START# *47A042E100E2_48B560B601B8_impl* inherited; f_LoadDocumentByIDFromListOperation := TatLoadDocumentsByIDFromListOperation.Create; //#UC END# *47A042E100E2_48B560B601B8_impl* end;//TatOpenRedactionsOperation.InitFields procedure TatOpenRedactionsOperation.ExecuteChilds; //#UC START# *48089F660238_48B560B601B8_var* //#UC END# *48089F660238_48B560B601B8_var* begin //#UC START# *48089F660238_48B560B601B8_impl* // дети запускаются явно в ExecuteSelf //#UC END# *48089F660238_48B560B601B8_impl* end;//TatOpenRedactionsOperation.ExecuteChilds end.
unit define_data_sina; interface const BaseSinaDayUrl1 = 'http://vip.stock.finance.sina.com.cn/corp/go.php/vMS_MarketHistory/stockid/'; // http://vip.stock.finance.sina.com.cn/corp/go.php/vMS_MarketHistory/stockid/000001/type/S.phtml 上证指数 // http://vip.stock.finance.sina.com.cn/corp/go.php/vMS_MarketHistory/stockid/399001/type/S.phtml 深成指数 // http://vip.stock.finance.sina.com.cn/corp/go.php/vMS_FuQuanMarketHistory/stockid/300144.phtml 宋城演艺 BaseSinaDayUrl_weight = 'http://vip.stock.finance.sina.com.cn/corp/go.php/vMS_FuQuanMarketHistory/stockid/'; (*// // http://vip.stock.finance.sina.com.cn/corp/go.php/vMS_FuQuanMarketHistory/stockid/600000.phtml // http://vip.stock.finance.sina.com.cn/corp/go.php/vMS_MarketHistory/stockid/600000.phtml // 上证指数 // http://vip.stock.finance.sina.com.cn/corp/go.php/vMS_MarketHistory/stockid/000001/type/S.phtml?year=2015&jidu=1 深圳成分 http://vip.stock.finance.sina.com.cn/corp/go.php/vMS_MarketHistory/stockid/399001/type/S.phtml 沪深 300 http://vip.stock.finance.sina.com.cn/corp/go.php/vMS_MarketHistory/stockid/000300/type/S.phtml //*) implementation end.
// Streams.pas - Persistence for all objects // Copyright (C) 1996, Merchise group /\/> unit Streams; interface {$LONGSTRINGS ON} // Merchise' style {$WRITEABLECONST OFF} {$TYPEDADDRESS ON} uses Classes, SysUtils; type EInvalidProperty = class(EFilerError); type TPipe = class private fStream : TStream; public property Stream : TStream read fStream; constructor Create(aStream : TStream); destructor Destroy; override; public procedure RegisterPointers(const which : array of pointer); function RegisterPointer(which : pointer) : integer; private Pointers : TList; Classes : TList; end; type TInput = class(TPipe) public constructor Create(aStream : TStream); destructor Destroy; override; public procedure Read(var buf; size : integer); function ReadString : string; function ReadPChar(which : pchar) : pchar; procedure ReadBuffer(var buf; size : longint); procedure ReadPointer(var which { : pointer or TObject}); function ReadObject : TObject; function ReadMethod : TMethod; function ReadClass : TClass; procedure ReadObjectPublishedData(obj : TObject); protected function GetPointer(id : integer) : pointer; procedure FixPointer(id : integer; which : pointer); private Fixups : TList; end; type TOutput = class(TPipe) public procedure Write(const Buf; size : longint); procedure WriteString(which : string); procedure WritePChar(which : pchar); procedure WriteBuffer(const buf; size : longint); procedure WritePointer(ptr : pointer); procedure WriteObject(which : TObject); procedure WriteMethod(const method : TMethod); procedure WriteClass(which : TClass); procedure WriteObjectPublishedData(obj : TObject); protected function PutPointer(which : pointer) : integer; end; type CListable = class of TListable; TListable = class public class procedure Register; end; type CStreamable = class of TStreamable; TStreamable = class(TListable) public constructor Read(Gate : TInput); virtual; procedure Write(Gate : TOutput); virtual; end; type CStreamableManager = class of TStreamableManager; TStreamableManager = class(TListable) public class function Read(Gate : TInput) : TObject; virtual; class procedure Write(Gate : TOutput; obj : TObject); virtual; class function ClassManaged : TClass; virtual; abstract; end; procedure RegisterClass(which : TClass); procedure RegisterClasses(const which : array of TClass); procedure UnRegisterClass(which : TClass); procedure UnRegisterClasses(const which : array of TClass); function FindClass(const name : string): TClass; function GetClass(const name : string): TClass; function GetManager(which : TObject) : CStreamableManager; implementation uses TypInfo, Assertion; var Listables : TList; const vNilIndex = 0; // -- TPipe constructor TPipe.Create(aStream : TStream); begin fStream := aStream; Pointers := TList.Create; Classes := TList.Create; Pointers.Add(nil); // Used as a valid reference in any model end; destructor TPipe.Destroy; begin Classes.Free; Pointers.Free; fStream.Free; inherited; end; procedure TPipe.RegisterPointers(const which : array of pointer); var i : integer; begin for i := low(which) to high(which) do RegisterPointer(which[i]); end; function TPipe.RegisterPointer(which : pointer) : integer; begin Result := Pointers.IndexOf(which); if Result < 0 then Result := Pointers.Add(which); end; { -- TInput -- } constructor TInput.Create(aStream : TStream); begin inherited; Fixups := TList.Create; end; destructor TInput.Destroy; begin {$ifndef _NODEBUG} Assert((Fixups.Count = 0), '(Fixups.Count = 0) at STREAM.PAS::TPipe.Destroy'); {$endif} Fixups.Free; inherited; end; procedure TInput.Read(var buf; size : integer); begin Stream.ReadBuffer(buf, size); end; function TInput.ReadString : string; var len : integer; begin Read(len, sizeof(len)); SetLength(Result, len); if len > 0 then Read(Result[1], len); end; function TInput.ReadPChar(which : pchar) : pchar; var len : integer; begin Stream.Read(len, sizeof(len)); if which = nil then which := StrAlloc(len); Stream.ReadBuffer(which^, len); which[len] := #0; Result := which; end; procedure TInput.ReadBuffer(var buf; size : longint); var id : integer; begin Read(id, sizeof(id)); FixPointer(id, @buf); Stream.ReadBuffer(buf, size); end; procedure TInput.ReadPointer(var which); var i, id : integer; aux : pointer absolute which; begin Read(id, sizeof(integer)); aux := GetPointer(id); if aux = nil then begin aux := pointer(id); Fixups.Add(@aux); i := RegisterPointer(aux); {$ifndef _NODEBUG} Assert(i = id, '(i = id) at STREAM.PAS::TInput.ReadPointer'); {$endif} end; end; function TInput.ReadObject : TObject; var aux : TClass; id : integer; begin Read(id, sizeof(id)); Result := GetPointer(id); if Result = nil then begin aux := GetClass(ReadString); if aux <> nil then if aux.InheritsFrom(TStreamable) then Result := CStreamable(aux).Read(Self) else if aux.InheritsFrom(TStreamableManager) then Result := CStreamableManager(aux).Read(Self); {$ifndef _NODEBUG} Assert(Result <> nil, '(Result <> nil) at STREAM.PAS::TInput.ReadObject'); {$endif} end; end; function TInput.ReadMethod : TMethod; begin with Result do begin data := ReadObject; if data <> nil then begin code := TObject(data).MethodAddress(ReadString); {$ifndef _NODEBUG} Assert(code <> nil, '(code <> nil) at STREAM.PAS::TInput.ReadMethod'); {$endif} end else code := nil; end; end; function TInput.ReadClass : TClass; begin Result := GetClass(ReadString); end; procedure TInput.ReadObjectPublishedData(obj : TObject); var name : string; cinfo : PTypeInfo; info : PPropInfo; aux : TMethod; begin RegisterPointer(obj); cinfo := obj.ClassInfo; repeat name := ReadString; if name <> '' then begin info := GetPropInfo(cinfo, name); if info <> nil then with info^, GetTypeData(info^.PropType)^ do case PropType^.Kind of tkChar, tkInteger, tkEnumeration, tkSet : case OrdType of otSByte, otUByte : SetOrdProp(obj, info, ReadByte); otSWord, otUWord : SetOrdProp(obj, info, ReadWord); otSLong : SetOrdProp(obj, info, ReadLongint); end; tkFloat : case FloatType of ftSingle : SetFloatProp(obj, info, ReadSingle); ftDouble : SetFloatProp(obj, info, ReadDouble); ftExtended : SetFloatProp(obj, info, ReadExtended); ftComp : SetFloatProp(obj, info, ReadComp); end; tkString : SetStrProp(obj, info, ReadString); tkClass : SetOrdProp(obj, info, longint(ReadObject)); tkMethod : begin ReadMethod(aux); SetMethodProp(obj, info, aux); end; else raise EInvalidProperty.Create(name); end; end; until name = ''; end; function TInput.GetPointer(id : integer) : pointer; begin if id < Pointers.Count then Result := Pointers[id] else Result := nil; end; procedure TInput.FixPointer(id : integer; which : pointer); type TFixup = ^pointer; var i : integer; aux : pointer; begin aux := pointer(id); for i := 0 to Fixups.Count - 1 do if aux = TFixup(Fixups[i])^ then begin TFixup(Fixups[i])^ := which; Fixups.Delete(i); end; Fixups.Pack; i := Pointers.IndexOf(aux); if i < 0 then i := RegisterPointer(which) // Not found else Pointers[i] := which; {$ifndef _NODEBUG} Assert(i = id, '(i = id) at STREAM.PAS::TPipe.FixPointer'); {$endif} end; { -- TOutput -- } procedure TOutput.Write(const Buf; size : longint); begin Stream.WriteBuffer(Buf, Size); end; procedure TOutput.WriteString(which : string); {$ifdef Win32} var len : integer; begin len := length(which); Stream.Write(len, sizeof(len)); if len > 0 then Stream.Write(which[1], len); end; {$else} begin Stream.WriteBuffer(which, sizeof(which[0]) + byte(which[0])); end; {$endif} procedure TOutput.WritePChar(which : pchar); var len : integer; begin if which = nil then len := 0 else len := StrLen(which); Stream.Write(len, sizeof(len)); if len > 0 then Stream.WriteBuffer(which^, len); end; procedure TOutput.WriteBuffer(const buf; size : longint); var id : integer; begin id := RegisterPointer(@buf); Write(id, sizeof(id)); Stream.WriteBuffer(buf, size); end; procedure TOutput.WritePointer(ptr : pointer); var id : integer; begin id := RegisterPointer(ptr); Write(id, sizeof(id)); end; procedure TOutput.WriteObject(which : TObject); var mngr : CStreamableManager; save : boolean; id : integer; begin save := Pointers.IndexOf(which) < 0; // Not Registered yet. id := RegisterPointer(which); Write(id, sizeof(id)); if save then begin if which is TStreamable then begin WriteString(which.ClassName); TStreamable(which).Write(Self); end else begin mngr := GetManager(which); {$ifndef _NODEBUG} Assert(mngr <> nil, '(mngr <> nil) at STREAM.PAS::TOutput.WriteObject'); {$endif} WriteString(mngr.ClassName); mngr.Write(Self, which); end; end; end; procedure TOutput.WriteMethod(const method : TMethod); begin with method do begin WriteObject(data); if data <> nil then WriteString(TObject(data).MethodName(code)); end; end; procedure TOutput.WriteClass(which : TClass); begin if which = nil then WriteString('') else WriteString(which.ClassName); end; procedure TOutput.WriteObjectPublishedData(obj : TObject); var cinfo : PTypeInfo; data : PTypeData; PropList : PPropList; i : integer; ordv : longint; begin cinfo := obj.ClassInfo; data := GetTypeData(cinfo); getmem(PropList, data^.PropCount*sizeof(PropList^[0])); GetPropInfos(cinfo, PropList); for i := 0 to data^.PropCount - 1 do with PropList^[i]^ do // info ~ PropList^[i] if IsStoredProp(obj, PropList^[i]) then begin WriteString(name); with GetTypeData(PropType)^ do case PropType^.Kind of tkChar, tkInteger, tkEnumeration, tkSet : begin ordv := GetOrdProp(obj, PropList^[i]); if ordv <> Default then case OrdType of otSByte, otUByte : WriteByte(ordv); otSWord, otUWord : WriteWord(ordv); otSLong : WriteLongint(ordv); end; end; tkFloat : case FloatType of ftSingle : WriteSingle(GetFloatProp(obj, PropList^[i])); ftDouble : WriteDouble(GetFloatProp(obj, PropList^[i])); ftExtended : WriteExtended(GetFloatProp(obj, PropList^[i])); ftComp : WriteComp(GetFloatProp(obj, PropList^[i])); end; tkString : WriteString(GetStrProp(obj, PropList^[i])); tkClass : WriteObject(TObject(GetOrdProp(obj, PropList^[i]))); tkMethod : WriteMethod(GetMethodProp(obj, PropList^[i])); else raise EInvalidProperty.Create(name); end; end; WriteString(''); end; function TOutput.PutPointer(which : pointer) : integer; begin Result := Pointers.IndexOf(which); end; { -- TListable -- } class procedure TListable.Register; begin RegisterClass(Self); end; class procedure TListable.Unregister; begin UnregisterClass(Self); end; { -- TStreamable -- } constructor TStreamable.Read(Gate : TInput); begin Gate.ReadObjectPublishedData(Self); end; procedure TStreamable.Write(Gate : TOutput); begin Gate.WriteObjectPublishedData(Self); end; { -- Registration -- } procedure RegisterClass(which : TClass); begin {$ifndef _NODEBUG} Assert(Listables.IndexOf(which) < 0, '(Listables.IndexOf(which) < 0) at STREAM.PAS::RegisterClass'); {$endif} Listables.Add(which); end; procedure RegisterClasses(const which : array of TClass); var i : integer; begin for i := low(which) to high(which) do RegisterClass(which[i]); end; procedure UnRegisterClass(which : TClass); begin Listables.Remove(which); Listables.Pack; end; procedure UnRegisterClasses(const which : array of TClass); var i : integer; begin for i := low(which) to high(which) do UnregisterClass(which[i]); end; function FindClass(const name : string): TClass; begin Result := GetClass(name); {$ifndef _NODEBUG} Assert(Result <> nil, '(Result <> nil) at STREAM.PAS::FindClass'); {$endif} end; function GetClass(const name : string): TClass; var i : integer; begin i := 0; while (i < Listables.Count) and (TClass(Listables[i]).ClassName <> name) do inc(i); if i < Listables.Count then Result := Listables.Items[i] else Result := nil; end; function GetManager(which : TObject) : CStreamableManager; var i : integer; begin with Listables do begin i := 0; while (i < Count) and not (TClass(Items[i]).InheritsFrom(TStreamableManager) and (which is CStreamableManager(Items[i]).ClassManaged)) do inc(i); if i < Count then Result := Items[i] else Result := nil; end; end; initialization Listables := TList.Create; finalization Listables.Free; end. function pointer(id : integer) : pointer; begin Result := pointer(id); end; function ValidReference(ref : pointer) : boolean; begin {$ifdef Win32} Result := integer(ref) >= $10000; {$else} Result := PtrRec(ref).seg <> vInvalidSegment; {$endif} end;
unit Taxes; interface uses MetaInstances, Accounts, Persistent, CacheAgent, BackupInterfaces, Languages; const tidClassFamily_Taxes = 'Taxes'; type TTaxTarget = (tarTycoon, tarPopulation); TTaxKind = integer; type TMetaTax = class; TTax = class; CTax = class of TTax; TMetaTax = class( TMetaInstance ) public constructor Create( anId, aName : string; aKind : TTaxKind; aTaxClass : CTax ); private fName : string; fName_MLS : TMultiString; fTaxClass : CTax; fTarget : TTaxTarget; fKind : TTaxKind; public property Name : string read fName; property Name_MLS : TMultiString read fName_MLS; property Target : TTaxTarget read fTarget write fTarget; property Kind : TTaxKind read fKind; public function Instantiate : TTax; virtual; end; TTax = class( TPersistent ) protected constructor Create( aMetaTax : TMetaTax ); virtual; private fMetaTax : TMetaTax; fRevenue : TMoney; protected function GetSubsidized : boolean; virtual; procedure SetSubsidized( value : boolean ); virtual; public property MetaTax : TMetaTax read fMetaTax; property Subsidized : boolean read GetSubsidized write SetSubsidized; protected property Revenue : TMoney read fRevenue write fRevenue; public procedure Evaluate( Amount : TMoney; TaxPayer, TaxCollector : TObject ); virtual; abstract; function HasDefaultValue : boolean; virtual; procedure StoreToCache( Prefix : string; Cache : TObjectCache ); virtual; procedure Reset; virtual; protected procedure LoadFromBackup( Reader : IBackupReader ); override; procedure StoreToBackup ( Writer : IBackupWriter ); override; public procedure ParseValue( value : string ); virtual; end; implementation uses ClassStorage; // TMetaTax constructor TMetaTax.Create( anId, aName : string; aKind : TTaxKind; aTaxClass : CTax ); begin inherited Create( anId ); fName := aName; fTaxClass := aTaxClass; fKind := aKind; fName_MLS := TMultiString.Create; end; function TMetaTax.Instantiate : TTax; begin result := fTaxClass.Create( self ); end; // TTax constructor TTax.Create( aMetaTax : TMetaTax ); begin inherited Create; fMetaTax := aMetaTax; end; function TTax.GetSubsidized : boolean; begin result := false; end; procedure TTax.SetSubsidized( value : boolean ); begin end; function TTax.HasDefaultValue : boolean; begin result := false; end; procedure TTax.StoreToCache( Prefix : string; Cache : TObjectCache ); begin Cache.WriteString( Prefix + 'Id', MetaTax.Id ); //Cache.WriteString( Prefix + 'Name', MetaTax.Name ); StoreMultiStringToCache( Prefix + 'Name', MetaTax.Name_MLS, Cache ); Cache.WriteInteger( Prefix + 'Kind', MetaTax.Kind ); Cache.WriteCurrency( Prefix + 'LastYear', Revenue ); end; procedure TTax.Reset; begin Revenue := 0; end; procedure TTax.LoadFromBackup( Reader : IBackupReader ); var Id : string; begin inherited; Id := Reader.ReadString( 'MetaTaxId', '' ); fMetaTax := TMetaTax(TheClassStorage.ClassById[tidClassFamily_Taxes, Id]); fRevenue := Reader.ReadCurrency( 'Revenue', 0 ); end; procedure TTax.StoreToBackup( Writer : IBackupWriter ); begin inherited; Writer.WriteString( 'MetaTaxId', fMetaTax.Id ); Writer.WriteCurrency( 'Revenue', fRevenue ); end; procedure TTax.ParseValue( value : string ); begin end; end.
unit WinExit; interface uses Classes, Windows, SysUtils; {, Messages, , , Graphics, Controls, Forms, Dialogs, StdCtrls;} Type // OS platforms TWinType = (wtWindows95, wtWindowsNT, wtWin32s, wtUnknown); // ShutDown/Logoff Windows95/NT modes TWinExitType = (ewLogoff, ewReboot, ewShutDown, ewPowerOff,ewpowshut); TWinExit = class(TComponent) private FWinExitType : TWinExitType; FUnconditional: boolean; FLastError : string; function GetWinType: TWinType; function SetPrivilege(sPrivilegeName: string; bEnabled: boolean ): boolean; procedure SetWinExitType(Value: TWinExitType); public function Execute: boolean; published property ExitWinType : TWinExitType read FWinExitType write SetWinExitType default EWReboot; property LastError : string read FLastError; property Unconditional : boolean read FUnconditional write FUnconditional default False; end; const WinExitFlagsArr : array [TWinExitType] of word = (EWX_LOGOFF, EWX_REBOOT, EWX_SHUTDOWN, EWX_POWEROFF,EWX_POWEROFF or EWX_FORCE); procedure Register; implementation // Get platform information function TWinExit.GetWinType: TWinType; var VersionInfo: TOSVersionInfo; begin Result:=wtUnknown; VersionInfo.dwOSVersionInfoSize:=SizeOf(VersionInfo); GetVersionEx(VersionInfo); case VersionInfo.dwPlatformId of VER_PLATFORM_WIN32S : Result:=wtWin32s; VER_PLATFORM_WIN32_WINDOWS : Result:=wtWindows95; VER_PLATFORM_WIN32_NT : Result:=wtWindowsNT; end; end; // Sets privileges of program under Windows NT ... function TWinExit.SetPrivilege(sPrivilegeName : string; bEnabled : boolean ): boolean; var TPPrev, TP : TTokenPrivileges; Token : THandle; dwRetLen : DWord; begin Result := False; if not OpenProcessToken(GetCurrentProcess, TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY,Token) then begin FLastError:='Error: OpenProcessToken'; Exit; end; TP.PrivilegeCount:=1; if LookupPrivilegeValue(Nil, PChar(sPrivilegeName), TP.Privileges[0].LUID) then begin if bEnabled then TP.Privileges[0].Attributes:=SE_PRIVILEGE_ENABLED else TP.Privileges[0].Attributes:=0; dwRetLen:=0; if AdjustTokenPrivileges(Token, False, TP, SizeOf(TPPrev), TPPrev, dwRetLen) then Result:=True else FLastError:='Error: AdjustTokenPrivileges'; end; CloseHandle(Token); end; procedure TWinExit.SetWinExitType(Value: TWinExitType); begin FWinExitType:=Value; end; // The functionality of this component is build in this routine function TWinExit.Execute: boolean; var Flags: word; begin Result:=False; Flags:=WinExitFlagsArr[FWinExitType]; if Unconditional then Flags:=Flags or EWX_FORCE; if GetWinType<>wtWindowsNT then ExitWindowsEx(Flags, 0) else if SetPrivilege('SeShutdownPrivilege', True) then begin Result:=ExitWindowsEx(Flags, 0); SetPrivilege('SeShutdownPrivilege', False); end; if not Result then FLastError:='Error: '+IntToStr(GetLastError); end; procedure Register; begin RegisterComponents('System', [TWinExit]); end; end.
unit uLogin; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Imaging.pngimage, Vcl.ExtCtrls, Data.Win.ADODB, Vcl.ComCtrls, RxCtrls, RxVCLUtils, System.UITypes, IdHashMessageDigest, unitKonstanty, uConfiguration_DB, uDMConnection, uMainDataSet, uBase, uBase_E, Vcl.Menus, RxMenus, System.Actions, Vcl.ActnList, Data.DB, Vcl.ImgList, Vcl.Mask, Vcl.DBCtrls, uBaseCustom; type TLogin = class(TBase_E) pnlTaskbarBackground: TPanel; lblName: TLabel; lblPassword: TLabel; edtPassword: TEdit; edtName: TEdit; pnlExit: TPanel; pnlTaskbarColored: TPanel; pnlVersion: TPanel; lblState: TLabel; pnlLogIn: TPanel; pnlLineUser: TPanel; pnlLinePassword: TPanel; procedure edtNameKeyPress(Sender: TObject; var Key: Char); procedure edtPasswordChange(Sender: TObject); procedure FormActivate(Sender: TObject); procedure pnlExitClick(Sender: TObject); procedure pnlExitMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure pnlExitMouseLeave(Sender: TObject); procedure pnlTaskbarColoredMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure pnlTaskbarBackgroundMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure pnlVersionMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure imgKonfiguraceOkClick(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure edtPasswordKeyPress(Sender: TObject; var Key: Char); procedure pnlLogInClick(Sender: TObject); procedure pnlLogInMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure pnlLogInMouseLeave(Sender: TObject); procedure edtNameChange(Sender: TObject); private FLoggedOn: Boolean; var gCbDuplicita: TComboBox; var gDuplicitaAno: Boolean; procedure WMNCHitTest(var Msg: TWMNCHitTest); message WM_NCHitTest; protected FConfiguration_DB: TConfiguration_DB; // For overrided TConfiguration_DB procedure ChangeHints; virtual; procedure EnableDisablePrihlasitSetButton; virtual; procedure LogIn; virtual; procedure SetActionsForComponents; virtual; procedure SetButtonLogIn; virtual; procedure SetVersion; virtual; procedure WriteToDbLog; virtual; public // LoggedOn property is state for parent form if is log-in to application ok property LoggedOn: Boolean read FLoggedOn write FLoggedOn; constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure DoShow; override; end; var Login: TLogin; resourcestring resNadpisKonfigurace = 'Konfigurovat'; resNadpisPrihlasitSe = 'Přihlásit se'; resHintKonfigurace = 'Konfigurovat inicializační soubor.'; resHintPrihlasitSe = 'Přihlásit se do programu.'; resHintJmenoPrihlasitSe = 'Zapište uživatelské jméno.'; resHintJmenoKonfigurace = 'Jméno pro konfiguraci.'; resHintHesloPrihlasitSe = 'Zapište vaše heslo.'; resHintHesloKonfigurace = 'Heslo pro konfiguraci.'; implementation uses uLogUtils, System.Types, uDV_Log, Winapi.WinSock, uDV_Versions, uDV_Users, uEncryptionUtils, uDialogUtils, uGlobalParameters, uRegisterUtils; {$R *.dfm} procedure TLogin.pnlLogInMouseLeave(Sender: TObject); begin inherited; (Sender as TPanel).Cursor := crDefault; (Sender as TPanel).Font.Style := []; end; procedure TLogin.pnlLogInMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin inherited; (Sender as TPanel).Cursor := crHandPoint; (Sender as TPanel).Font.Style := [fsBold]; end; procedure TLogin.ChangeHints; begin (*** Change hints by login conf consts configuration ***) if ((edtName.Text = unitKonstanty.LOGIN_KONFIGURACE_JMENO) and (edtPassword.Text = unitKonstanty.LOGIN_KONFIGURACE_HESLO)) then begin edtName.Hint := resHintJmenoKonfigurace; edtPassword.Hint := resHintHesloKonfigurace; lblName.Hint := resHintJmenoKonfigurace; lblPassword.Hint := resHintHesloKonfigurace; end else begin edtName.Hint := resHintJmenoPrihlasitSe; edtPassword.Hint := resHintHesloPrihlasitSe; lblName.Hint := resHintJmenoPrihlasitSe; lblPassword.Hint := resHintHesloPrihlasitSe; end; end; constructor TLogin.Create(AOwner: TComponent); begin inherited Create(AOwner); FLoggedOn := False; gCbDuplicita := TComboBox.Create(Self); gCbDuplicita.Parent := pnlTaskbarBackground; gCbDuplicita.Width := 80; gCbDuplicita.Left := edtName.Left + edtName.Width - gCbDuplicita.Width; gCbDuplicita.Top := edtName.Top; gCbDuplicita.ItemHeight := edtName.Height - 6; gCbDuplicita.Color := $00BDFFFF; gCbDuplicita.Style := csOwnerDrawFixed; gCbDuplicita.Visible := False; lblState.Caption := DMConnection.StateCaption; lblState.Hint := DMConnection.StateCaption; SetVersion; SetButtonLogIn; SetActionsForComponents; end; destructor TLogin.Destroy; begin FreeAndNil(gCbDuplicita); if Assigned(FConfiguration_DB) then FreeAndNil(FConfiguration_DB); inherited; end; procedure TLogin.DoShow; begin inherited; if not (lblState.Caption = '') then begin edtName.Text := unitKonstanty.LOGIN_KONFIGURACE_JMENO; edtName.Enabled := False; edtPassword.Text := unitKonstanty.LOGIN_KONFIGURACE_HESLO; edtPassword.Enabled := False; end; end; procedure TLogin.edtPasswordChange(Sender: TObject); begin ChangeHints; EnableDisablePrihlasitSetButton; end; procedure TLogin.edtPasswordKeyPress(Sender: TObject; var Key: Char); begin inherited; if (Key = #13) then LogIn; end; procedure TLogin.edtNameChange(Sender: TObject); var lDupl: Integer; lDataSetDuplicita: TADODataSet; begin if DMConnection.IsConnected then begin lDataSetDuplicita := TADODataSet.Create(Self); try lDataSetDuplicita.Connection := DMConnection.MSSQLConnection; lDataSetDuplicita.CommandType := cmdText; lDataSetDuplicita.Close; lDataSetDuplicita.CommandText := 'SELECT ' +TDV_Users.PersonalNumber +' FROM ' +TDV_Users.GetTabName +' WHERE ' +TDV_Users.UserName + '=' +#39 + edtName.Text + #39; lDataSetDuplicita.Open; if (lDataSetDuplicita.RecordCount > 1) then begin gCbDuplicita.Visible := True; for lDupl := 1 to lDataSetDuplicita.RecordCount do begin gCbDuplicita.Items.Add(lDataSetDuplicita.FieldByName(TDV_Users.PersonalNumber).AsString); lDataSetDuplicita.Next; end; edtName.Width := 224; MessageBox(0, 'Existují duplicitní uživatelské účty, pro identifikaci vyberte'+#13+#10+'Vaše osobní číslo.', 'Duplicita uživatelských účtů', MB_ICONWARNING or MB_OK); gDuplicitaAno := True; end else begin gCbDuplicita.Visible := False; gCbDuplicita.Clear; edtName.Width := edtPassword.Width; gDuplicitaAno := False; end; finally FreeAndNil(lDataSetDuplicita); end; end; end; procedure TLogin.edtNameKeyPress(Sender: TObject; var Key: Char); begin (*** On enter set focus to next edit ***) if (Key = #13) then edtPassword.SetFocus; end; procedure TLogin.EnableDisablePrihlasitSetButton; begin (*** Procedure for enable or disable LogIn button ***) if (edtPassword.Text <> '') and (edtPassword.Text <> '') then begin pnlLogIn.Enabled := True; pnlLogIn.Color := clGreen; end else begin pnlLogIn.Enabled := False; pnlLogIn.Color := clGray; end; end; procedure TLogin.FormActivate(Sender: TObject); begin pnlVersion.Hint := unitKonstanty.LOGIN_ZAPATI_POPIS_AKTUALIZACE; end; procedure TLogin.FormKeyPress(Sender: TObject; var Key: Char); begin if (Key = #13) then LogIn; end; procedure TLogin.imgKonfiguraceOkClick(Sender: TObject); begin LogIn; end; procedure TLogin.pnlVersionMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin ReleaseCapture; SendMessage(Self.Handle, WM_SYSCOMMAND, 61458, 0); end; procedure TLogin.pnlExitClick(Sender: TObject); begin Application.Terminate; end; procedure TLogin.pnlExitMouseLeave(Sender: TObject); begin pnlExit.Font.Style := []; pnlExit.Color := pnlTaskbarColored.Color; pnlExit.Font.Color := clWhite; pnlExit.BevelKind := bkNone; pnlExit.BevelOuter := bvNone; end; procedure TLogin.pnlExitMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin pnlExit.Font.Style := [fsBold]; pnlExit.Color := pnlTaskbarBackground.Color; pnlExit.Font.Color := pnlVersion.Font.Color; pnlExit.BevelKind := bkFlat; pnlExit.BevelOuter := bvLowered; end; procedure TLogin.pnlTaskbarBackgroundMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin ReleaseCapture; SendMessage(Self.Handle, WM_SYSCOMMAND, 61458, 0) ; end; procedure TLogin.pnlTaskbarColoredMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin ReleaseCapture; SendMessage(Self.Handle, WM_SYSCOMMAND, 61458, 0) ; end; procedure TLogin.pnlLogInClick(Sender: TObject); begin inherited; LogIn; end; procedure TLogin.LogIn; var lQryTable: TADODataSet; begin (*** Action after click to LogIn button ***) if (gDuplicitaAno = True) and (gCbDuplicita.ItemIndex = -1) then begin MessageBox(0, 'Vyberte osobní číslo', 'Chybný postup', MB_ICONSTOP or MB_OK); Exit; end; if (edtName.Text = LOGIN_KONFIGURACE_JMENO) and (edtPassword.Text = LOGIN_KONFIGURACE_HESLO) then begin if not Assigned(FConfiguration_DB) then FConfiguration_DB := TConfiguration_DB.Create(Self); FConfiguration_DB.ShowModal; Exit; end; lQryTable := TADODataSet.Create(nil); try lQryTable.Connection := DMConnection.MSSQLConnection; lQryTable.CommandType := cmdText; if (gCBDuplicita.ItemIndex > -1) and (gCBDuplicita.Visible) then begin lQryTable.CommandText := 'SELECT ' +TDV_Users.Id+',' +TDV_Users.NumberOfAutohrization+',' +TDV_Users.IdWorkStation+',' +TDV_Users.Name+',' +TDV_Users.Surname +' FROM ' + TDV_Users.GetTabName +' WHERE '+ TDV_Users.Name+'='+#39+edtname.Text+#39+ ' AND '+TDV_Users.Password +'='+#39+TEncryptionUtils.MD5Hash(edtPassword.Text)+#39+ ' AND '+TDV_Users.PersonalNumber+'='+#39+gCbDuplicita.Text+#39; end else begin lQryTable.CommandText := 'SELECT ' +TDV_Users.Id+',' +TDV_Users.NumberOfAutohrization+',' +TDV_Users.IdWorkStation+',' +TDV_Users.Name+',' +TDV_Users.Surname +' FROM '+TDV_Users.GetTabName +' WHERE '+ TDV_Users.UserName+'='+#39+edtName.Text+#39+ ' AND '+TDV_Users.Password+'='+#39+TEncryptionUtils.MD5Hash(edtPassword.Text)+#39; end; lQryTable.Open; if (lQryTable.RecordCount > 0) then begin TGlobalParameters.IdUser := lQryTable.FieldByName(TDV_Users.Id).AsString; TGlobalParameters.NumberOfAuthorization := lQryTable.FieldByName(TDV_Users.NumberOfAutohrization).AsInteger; TGlobalParameters.IdWorkstation := lQryTable.FieldByName(TDV_Users.IdWorkStation).AsString; TGlobalParameters.LoginState := '1'; TGlobalParameters.UserName := lQryTable.FieldByName(TDV_Users.Name).AsString; TGlobalParameters.UserSurname := lQryTable.FieldByName(TDV_Users.Surname).AsString; lblState.Caption := ''; end else begin TDialogUtils.ShowErrorDialog(True, 'Chybně zadné údaje', 'Špatné uživatelské jméno nebo heslo.'); lblState.Caption := 'Špatné uživatelské jméno nebo heslo'; Exit; end; finally lQryTable.Free; end; // Set user name as global parameter TGlobalParameters.UserUsername := edtName.Text; // Write connection message to DB log WriteToDbLog; // Set state that log-in progress is completed and ok FLoggedOn := True; Self.Close; end; procedure TLogin.SetActionsForComponents; begin (*** Set actions for descendants ***) pnlLogIn.OnMouseMove := pnlLogInMouseMove; pnlLogIn.OnMouseLeave := pnlLogInMouseLeave; pnlLogIn.OnClick := pnlLogInClick; pnlVersion.OnMouseDown := pnlVersionMouseDown; pnlExit.OnMouseMove := pnlExitMouseMove; pnlExit.OnMouseLeave := pnlExitMouseLeave; pnlExit.OnClick := pnlExitClick; pnlTaskbarColored.OnMouseDown := pnlTaskbarColoredMouseDown; pnlTaskbarBackground.OnMouseDown := pnlTaskbarBackgroundMouseDown; edtname.OnKeyPress := edtNameKeyPress; edtname.OnChange := edtNameChange; edtPassword.OnKeyPress := edtPasswordKeyPress; edtPassword.OnChange := edtPasswordChange; end; procedure TLogin.SetButtonLogIn; begin pnlLogIn.Color := pnlTaskbarColored.Color; pnlLogIn.Font.Color := pnlVersion.Font.Color; pnlLogIn.Color := clGray; pnlLogIn.Font.Color := clWhite; end; procedure TLogin.SetVersion; var lDataSetVersion: TADODataSet; begin (*** Procedure takse information about version from kernel table from DB ***) lDataSetVersion := TADODataSet.Create(Self); try if DMConnection.IsConnected then begin lDataSetVersion.Connection := DMConnection.MSSQLConnection; lDataSetVersion.CommandType := cmdText; lDataSetVersion.CommandText := 'SELECT * FROM ' + TDV_Versions.GetTabName + ' ORDER BY ' + TDV_Versions.Number + ' DESC'; lDataSetVersion.Open; pnlVersion.Caption := ' '+lDataSetVersion.FieldByName(TDV_Versions.Number).AsString+' ('+ lDataSetVersion.FieldByName(TDV_Versions.Name).AsString+')'; end; finally FreeAndNil(lDataSetVersion); end; end; procedure TLogin.WMNCHitTest(var Msg: TWMNCHitTest); begin inherited; if Msg.Result = htClient then Msg.Result := htCaption; end; procedure TLogin.WriteToDbLog; var lParamNames, lParamValues: TStringDynArray; function IsWinSocetkInitialized: Boolean; var lSocket: TSocket; begin lSocket := Socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); Result := (lSocket <> INVALID_SOCKET) or (WSAGetLastError <> WSANOTINITIALISED); end; function GetCurrentIpAdress: string; var lTWSAData: TWSAData; lPHostEnt: PHostEnt; lTInAddr: TInAddr; lNameBuf: array[0..255] of AnsiChar; begin (*** It returns current local IP adress ***) // Check if is WinSocketInitializated if not IsWinSocetkInitialized then begin // Try initializate again WSAStartup(MAKEWORD(1, 1), lTWSAData); if not IsWinSocetkInitialized then Exit; end; // Check if hostname doesn't return error if GetHostName(@lNameBuf, SizeOf(lNameBuf)) = SOCKET_ERROR then Exit; lPHostEnt := GetHostByName(@lNameBuf); lTInAddr.S_addr := ULONG(PULONG(lPHostEnt^.h_addr_list^)^); Result := string(inet_ntoa(lTInAddr)); end; begin (*** Write connection message to DB log ***) SetLength(lParamNames, TDV_Log.GetActualDBFieldsCount); SetLength(lParamValues, TDV_Log.GetActualDBFieldsCount); lParamNames[0] := TDV_Log.DateTime; lParamNames[1] := TDV_Log.IpAdress; lParamNames[2] := TDV_Log.UserName; lParamNames[3] := TDV_Log.Name; lParamNames[4] := TDV_Log.Surname; lParamValues[0] := DateTimeToStr(Now); lParamValues[1] := GetCurrentIpAdress; lParamValues[2] := TGlobalParameters.UserUsername; lParamValues[3] := TGlobalParameters.UserName; lParamValues[4] := TGlobalParameters.UserSurname; TLogUtils.WriteToLog(lParamNames, lParamValues); end; end.
unit FileView; {$I GX_CondDefine.inc} interface uses {$IFDEF SYNEDIT} SynEdit, GX_SynMemoUtils, // See GX_CondDefine.inc to remove the SynEdit requirement {$ENDIF SYNEDIT} Classes, ExtCtrls, ComCtrls, GX_GenericUtils; type TFileViewer = class(TCustomPanel) private FImage: TImage; FRichEdit: TRichEdit; FLoadedFile: string; {$IFDEF SYNEDIT} FEditor: TSynEdit; FGXSyntaxParser: TGXSyntaxHighlighter; {$ENDIF SYNEDIT} protected public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure LoadFromFile(const FileName: string); procedure Clear; published property Align; property LoadedFile: string read FLoadedFile write FLoadedFile; end; procedure Register; implementation uses Controls, Forms, Graphics, StdCtrls, SysUtils, GX_OtaUtils; constructor TFileViewer.Create(AOwner: TComponent); begin inherited Create(AOwner); Caption := ''; BevelInner := bvNone; BevelOuter := bvLowered; Color := clWindow; if not (csDesigning in ComponentState) then begin // Image Viewer FImage := TImage.Create(nil); FImage.Parent := Self; FImage.Align := alClient; FImage.Visible := False; // Rich Text Viewer FRichEdit := TRichEdit.Create(nil); FRichEdit.Parent := Self; FRichEdit.Align := alClient; FRichEdit.WordWrap := True; FRichEdit.ScrollBars := ssBoth; FRichEdit.ReadOnly := True; FRichEdit.Visible := False; FRichEdit.BorderStyle := bsNone; {$IFDEF SYNEDIT} // SynEdit Control FEditor := TSynEdit.Create(nil); with FEditor do begin Options := Options - [eoScrollPastEof, eoScrollPastEol]; Parent := Self; Align := alClient; BorderStyle := bsNone; ReadOnly := True; Gutter.Width := 0; Visible := False; end; {$ENDIF SYNEDIT} end; end; destructor TFileViewer.Destroy; begin if not (csDesigning in ComponentState) then begin FreeAndNil(FImage); FreeAndNil(FRichEdit); {$IFDEF SYNEDIT} FEditor.Highlighter.Free; FEditor.Highlighter := nil; FreeAndNil(FEditor); {$ENDIF SYNEDIT} end; inherited Destroy; end; procedure TFileViewer.Clear; begin LoadedFile := ''; FImage.Visible := False; FRichEdit.Visible := False; {$IFDEF SYNEDIT} FEditor.Visible := False; {$ENDIF SYNEDIT} end; procedure TFileViewer.LoadFromFile(const FileName: string); {$IFDEF SYNEDIT} procedure AssignParser(Parser: TGXSyntaxHighlighter); var Strings: TGXUnicodeStringList; begin FRichEdit.Visible := False; FImage.Visible := False; Strings := TGXUnicodeStringList.Create; try GxOtaLoadFileToUnicodeStrings(FileName, Strings); FEditor.Lines.Text := Strings.Text; finally FreeAndNil(Strings); end; begin SetSynEditHighlighter(FEditor, Parser); FGXSyntaxParser := Parser; end; FEditor.Visible := True; end; {$ENDIF SYNEDIT} var Ext: string; begin LoadedFile := FileName; {$IFDEF SYNEDIT} FEditor.BeginUpdate; {$ENDIF SYNEDIT} FRichEdit.Lines.BeginUpdate; try Ext := UpperCase(ExtractFileExt(FileName)); if (Ext = '.JPG') or {$IFDEF GX_VER185_up} (Ext = '.GIF') or {$ENDIF} {$IFDEF GX_VER200_up} (Ext = '.PNG') or {$ENDIF} (Ext = '.BMP') or (Ext = '.ICO') then begin FRichEdit.Visible := False; {$IFDEF SYNEDIT} FEditor.Visible := False; {$ENDIF SYNEDIT} FImage.Picture.LoadFromFile(FileName); FImage.Visible := True; end else if (Ext = '.RTF') {$IFNDEF GX_ENHANCED_EDITOR} or IsPascalSourceFile(FileName) or IsHtml(FileName) or IsWebFile(FileName) or IsCppSourceModule(FileName) or IsSQL(FileName) or IsCS(FileName) or IsXMLFormat(FileName) or IsForm(FileName) {$ENDIF GX_ENHANCED_EDITOR} then begin FRichEdit.PlainText := not(Ext = '.RTF'); FImage.Visible := False; {$IFDEF SYNEDIT} FEditor.Visible := False; {$ENDIF SYNEDIT} FRichEdit.Lines.LoadFromFile(FileName); FRichEdit.Visible := True; end {$IFDEF GX_ENHANCED_EDITOR} else if IsTextFile(FileName) or (IsWebFile(FileName) and not IsHtml(FileName)) then begin {$IFDEF SYNEDIT} AssignParser(gxpNone) {$ENDIF SYNEDIT} end else if IsPascalSourceFile(FileName) or IsForm(FileName) then AssignParser(gxpPAS) else if IsHtml(FileName) then AssignParser(gxpHTML) else if IsCppSourceModule(FileName) then AssignParser(gxpCPP) else if IsSQL(FileName) then AssignParser(gxpSQL) else if (Ext = '.CS') then AssignParser(gxpCS) else if IsXMLFormat(FileName) then AssignParser(gxpXML) {$ENDIF GX_ENHANCED_EDITOR} else Clear; finally {$IFDEF SYNEDIT} FEditor.EndUpdate; {$ENDIF SYNEDIT} FRichEdit.Lines.EndUpdate; end; end; procedure Register; begin RegisterComponents('User', [TFileViewer]); end; end.
unit tcToolBarsList; interface uses l3Interfaces, tcInterfaces, tcItemList ; type TtcToolBarsList = class(TtcItemList, ItcToolBarsList) protected // ItcToolBarsList function pm_GetToolBar(Index: Integer): ItcToolbar; function ItcToolBarsList.Add = ItcToolBarsList_Add; function ItcToolBarsList_Add(const anID: Il3CString): ItcToolBar; procedure ItcToolBarsList.AddExisting = ItcToolBarsList_AddExisting; procedure ItcToolBarsList_AddExisting(const aToolBar: ItcToolBar); procedure AssignToItem(const aSource, aTarget: ItcItem); override; protected procedure AddExisting(const anItem: ItcItem); override; function MakeItem(const anID: Il3CString): ItcItem; override; public class function Make: ItcToolBarsList; end; implementation uses SysUtils, tcToolBar; { TtcToolBarsList } procedure TtcToolBarsList.AddExisting(const anItem: ItcItem); begin if not Supports(anItem, ItcToolBar) then raise Exception.Create('Native interface not supported'); inherited AddExisting(anItem); end; procedure TtcToolBarsList.AssignToItem(const aSource, aTarget: ItcItem); var l_Source: ItcToolBar; l_Target: ItcToolBar; l_IDX: Integer; begin inherited AssignToItem(aSource, aTarget); if Supports(aSource, ItcToolBar, l_Source) and Supports(aTarget, ItcToolBar, l_Target) then begin l_Target.Editable := l_Source.Editable; for l_IDX := 0 to l_Source.ChildToolBars.Count - 1 do l_Target.ChildToolBars.AddExisting(l_Source.ChildToolBars.ToolBar[l_IDX]); for l_IDX := 0 to l_Source.Operations.Count - 1 do l_Target.Operations.AddExisting(l_Source.Operations.Operation[l_IDX]); end; end; function TtcToolBarsList.ItcToolBarsList_Add( const anID: Il3CString): ItcToolBar; begin Result := Add(anID) as ItcToolBar; end; procedure TtcToolBarsList.ItcToolBarsList_AddExisting( const aToolBar: ItcToolBar); begin AddExisting(aToolBar); end; class function TtcToolBarsList.Make: ItcToolBarsList; var l_Instance: TtcToolBarsList; begin l_Instance := Create; try Result := l_Instance; finally FreeAndNil(l_Instance); end; end; function TtcToolBarsList.MakeItem(const anID: Il3CString): ItcItem; begin Result := TtcToolBar.Make(anID); end; function TtcToolBarsList.pm_GetToolBar(Index: Integer): ItcToolbar; begin Result := pm_GetItem(Index) as ItcToolBar; end; end.
unit ReplaceSoftEnterFilter; { } { $Id: ReplaceSoftEnterFilter.pas,v 1.2 2014/04/30 13:11:40 lulin Exp $ } // $Log: ReplaceSoftEnterFilter.pas,v $ // Revision 1.2 2014/04/30 13:11:40 lulin // - вычищаем ненужные зависимости. // // Revision 1.1 2012/02/07 06:49:01 narry // Утилита по замене мягких переносов (335580209) // // Revision 1.1 2012/01/11 10:27:20 narry // Возврат к обработке через хранилище // interface uses evdLeafParaFilter, k2Interfaces, l3Types, k2Types, k2TagFilter, l3RegEx, k2tagGen, l3Interfaces; type TddDocStatus = (dd_dsChanged, dd_dsAbsent, dd_dsNotFinished, dd_dsIDAbsent); TddDocStatusEvent = procedure (DocID: Integer; DocStatus: TddDocStatus) of object; TReplaceSoftEnterFilter = class(TevdLeafParaFilter, Il3DocIDSource) private f_Changed: Boolean; f_DocID: Integer; f_OnDocumentStatus: TddDocStatusEvent; protected procedure DoDocumentWork(aDocStatus: TddDocStatus); procedure DoWritePara(aLeaf: Tl3Tag); override; {-} function ParaTypeForFiltering: Long; override; function pm_GetDocID: Integer; procedure pm_SetDocID(aValue: Integer); public procedure StartChild(TypeID: Long); override; property DocID: Integer read pm_GetDocID write pm_SetDocID; property OnDocumentStatus: TddDocStatusEvent read f_OnDocumentStatus write f_OnDocumentStatus; end; implementation uses Document_Const, k2Tags, StrUtils, TextPara_Const, evdStyles, Math, SysUtils, l3String, l3Chars, evParaTools, evTextParaTools, NevTools, evTypes, evSearch, l3PrimString, l3Base; procedure TReplaceSoftEnterFilter.DoDocumentWork(aDocStatus: TddDocStatus); begin if Assigned(f_OnDocumentStatus) then f_OnDocumentStatus(f_DocID, aDocStatus); end; procedure TReplaceSoftEnterFilter.DoWritePara(aLeaf: Tl3Tag); var l_S: String; begin if (aLeaf.IntA[k2_tiStyle] = ev_saChangesInfo) then begin l_S:= AnsiReplaceStr(aLeaf.StrA[k2_tiText], #29, ' '); l_S:= AnsiReplaceStr(l_S, #10, ' '); aLeaf.StrW[k2_tiText, nil]:= l_S; DoDocumentWork(dd_dsChanged); end; inherited; end; function TReplaceSoftEnterFilter.ParaTypeForFiltering: Long; begin Result := k2_idTextPara; end; procedure TReplaceSoftEnterFilter.StartChild(TypeID: Long); begin inherited StartChild(TypeID); end; function TReplaceSoftEnterFilter.pm_GetDocID: Integer; begin Result:= f_DocID; end; procedure TReplaceSoftEnterFilter.pm_SetDocID(aValue: Integer); begin f_DocID:= aValue; l3System.Msg2Log(IntToStr(aValue)); end; end.
(* JCore WebServices, CGI Application Handler Classes Copyright (C) 2015 Joao Morais See the file LICENSE.txt, included in this distribution, for details about the copyright. This library 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. *) unit JCoreWSCGIApp; {$I jcore.inc} interface uses Classes, HTTPDefs, custweb, custcgi, JCoreWSIntf, JCoreWSRequest; type { TJCoreWSFCLCGIHandler } {** @exclude } TJCoreWSFCLCGIHandler = class(TCGIHandler) private FRequestRouter: IJCoreWSRequestRouter; public constructor Create(AOwner: TComponent); override; procedure HandleRequest(ARequest: TRequest; AResponse: TResponse); override; end; { TJCoreWSFCLCGIApp } {** @exclude } TJCoreWSFCLCGIApp = class(TCustomCGIApplication) protected function InitializeWebHandler: TWebHandler; override; end; { TJCoreWSCGIApplicationHandler } TJCoreWSCGIApplicationHandler = class(TInterfacedObject, IJCoreWSApplicationHandler) private FCGIApp: TJCoreWSFCLCGIApp; FParams: TStrings; public destructor Destroy; override; function Params: TStrings; procedure Run; end; implementation uses sysutils, JCoreDIC; { TJCoreWSFCLCGIHandler } constructor TJCoreWSFCLCGIHandler.Create(AOwner: TComponent); begin inherited Create(AOwner); TJCoreDIC.Locate(IJCoreWSRequestRouter, FRequestRouter); end; procedure TJCoreWSFCLCGIHandler.HandleRequest(ARequest: TRequest; AResponse: TResponse); begin FRequestRouter.RouteRequest(ARequest, AResponse); end; { TJCoreWSFCLCGIApp } function TJCoreWSFCLCGIApp.InitializeWebHandler: TWebHandler; begin Result := TJCoreWSFCLCGIHandler.Create(Self); end; { TJCoreWSCGIApplicationHandler } destructor TJCoreWSCGIApplicationHandler.Destroy; begin FreeAndNil(FParams); FreeAndNil(FCGIApp); inherited Destroy; end; function TJCoreWSCGIApplicationHandler.Params: TStrings; begin if not Assigned(FParams) then FParams := TStringList.Create; Result := FParams; end; procedure TJCoreWSCGIApplicationHandler.Run; begin FreeAndNil(FCGIApp); FCGIApp := TJCoreWSFCLCGIApp.Create(nil); FCGIApp.Initialize; FCGIApp.Run; end; initialization TJCoreDIC.Register(IJCoreWSApplicationHandler, 'CGI', TJCoreWSCGIApplicationHandler, jdsApplication); finalization TJCoreDIC.Unregister(IJCoreWSApplicationHandler, TJCoreWSCGIApplicationHandler); end.
unit ModLex; interface type symbol = (numberSy, identSy, equalSy, semicolonSy, plusSy, showSy, hideSy, lineSy, rectangleSy, circleSy, pictureSy, moveSy, eofSy, noSy); var curSy : symbol; numVal : integer; (* number value for semantic analysis *) identStr : string; procedure newSy; procedure initLex(inFileName : string); implementation const EOF_CH = chr(26); TAB_CH = chr(9); var inFile : text; line : string; curChPos : integer; curCh : char; procedure newCh; forward; procedure initLex(inFileName : string); begin assign(inFile, inFileName); reset(inFile); readLn(inFile, line); curChPos := 0; NewCh; end; procedure newSy; begin (* skip whitespace *) while (curCh = ' ') or (curCh = TAB_CH) do newCh; case curCh of '=': begin curSy := equalSy; newCh; end; ';': begin curSy := semicolonSy; newCh; end; '+': begin curSy := plusSy; newCh; end; EOF_CH: begin curSy := eofSy; newCh; end; 'a'..'z', 'A'..'Z': BEGIN identStr := ''; WHILE curCh IN ['a'.. 'z', 'A' ..'Z', '0'..'9', '_'] DO BEGIN identStr := Concat(identStr, UpCase(curCh)); NewCh; END; (*WHILE*) IF identStr = 'SHOW' THEN curSy := showSy ELSE IF identStr = 'HIDE' THEN curSy := hideSy ELSE IF identStr = 'LINE' THEN curSy := lineSy ELSE IF identStr = 'RECTANCLE' THEN curSy := rectangleSy ELSE IF identStr = 'CIRCLE' THEN curSy := circleSy ELSE IF identStr = 'PICTURE' THEN curSy := pictureSy ELSE IF identStr = 'MOVE' THEN curSy := moveSy ELSE curSy := identSy; END; '0'..'9': begin (* read a number *) numVal := Ord(curCh) - Ord('0'); (* value of digit*) newCh; while (curCh > '0') and (curCh <= '9') do begin numVal := numVal * 10 + Ord(curCh) - Ord('0'); newCh; end; curSy := numberSy; end; else begin curSy := noSy; newCh; end; (* default case *) end; (* case *) writeln(curSy); end; procedure newCh; begin if curChPos < length(line) then begin inc(curChPos); curCh := line[curChPos] end else curCh := EOF_CH; end; begin end.
unit Control.CadastroEnderecos; interface uses System.SysUtils, FireDAC.Comp.Client, Forms, Windows, Common.ENum, Control.Sistema, Model.CadastroEnderecos; type TCadastroEnderecosControl = class private FEnderecos : TCadastroEnderecos; public constructor Create; destructor Destroy; override; property Enderecos: TCadastroEnderecos read FEnderecos write FEnderecos; function Localizar(aParam: array of variant): boolean; function Gravar(): Boolean; function ValidaCampos(): Boolean; function SaveBatch(memTable: TFDMemTable): Boolean; function SetupClass(FDQuery: TFDQuery): boolean; function ClearClass(): boolean; function GetID(iID: Integer): Integer; end; implementation { TCadastroEnderecosControl } uses Common.Utils; function TCadastroEnderecosControl.ClearClass: boolean; begin Result := FEnderecos.ClearClass; end; constructor TCadastroEnderecosControl.Create; begin FEnderecos := TCadastroEnderecos.Create; end; destructor TCadastroEnderecosControl.Destroy; begin FEnderecos.Free; inherited; end; function TCadastroEnderecosControl.GetID(iID: Integer): Integer; begin Result := FEnderecos.GetID(iID); end; function TCadastroEnderecosControl.Gravar: Boolean; begin Result := False; if Fenderecos.Acao = tacIncluir then begin if not ValidaCampos() then Exit; end; Result := FEnderecos.Gravar; end; function TCadastroEnderecosControl.Localizar(aParam: array of variant): Boolean; begin Result := FEnderecos.Localizar(aParam); end; function TCadastroEnderecosControl.SaveBatch(memTable: TFDMemTable): Boolean; begin Result := FEnderecos.SaveBatch(memTable); end; function TCadastroEnderecosControl.SetupClass(FDQuery: TFDQuery): boolean; begin Result := Fenderecos.SetupClass(FDQuery); end; function TCadastroEnderecosControl.ValidaCampos: Boolean; var FDQuery : TFDQuery; aParam: Array of variant; begin try Result := False; FDQuery := TSistemaControl.GetInstance.Conexao.ReturnQuery; if FEnderecos.ID = 0 then begin Application.MessageBox('Informe o ID do cadastro!', 'Atenção', MB_OK + MB_ICONWARNING); Exit; end; if FEnderecos.Tipo.IsEmpty then begin Application.MessageBox('Informe o tipo de endereço!', 'Atenção', MB_OK + MB_ICONWARNING); Exit; end; Result := True; finally FDQuery.Free; end; end; end.
unit osBatchSQL; interface uses Classes, Variants, SysUtils, provider, sqlexpr, db; type TosQueryDef = class(TCollectionItem) private FSQL: TStrings; procedure SetSQL(const Value: TStrings); protected function GetDisplayName: string; override; public constructor Create(AOwner: TCollection); override; destructor Destroy; override; published property SQL: TStrings read FSQL write SetSQL; end; TosQueryDefCollection = class(TOwnedCollection) private function GetItem(Index: Integer): TosQueryDef; procedure SetItem(Index: Integer; Value: TosQueryDef); public constructor Create(AOwner: TComponent); property Items[Index: Integer]: TosQueryDef read GetItem write SetItem; default; end; TosBatchSQL = class(TComponent) private FParameters: TParams; FQueriesDelete: TosQueryDefCollection; FQueriesUpdate: TosQueryDefCollection; FQueriesInsert: TosQueryDefCollection; FApplyQuery: TSQLQuery; procedure SetQueriesDelete(const Value: TosQueryDefCollection); procedure SetQueriesInsert(const Value: TosQueryDefCollection); procedure SetQueriesUpdate(const Value: TosQueryDefCollection); procedure SetConnection(const Value: TSQLConnection); function GetConnection: TSQLConnection; protected procedure Exec(QueryDefCollection: TosQueryDefCollection; Dataset: TDataset); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function Apply(Dataset: TDataset; UpdateKind: TUpdateKind): boolean; procedure SetParams(Dataset: TDataset); virtual; published property QueriesInsert: TosQueryDefCollection read FQueriesInsert write SetQueriesInsert; property QueriesUpdate: TosQueryDefCollection read FQueriesUpdate write SetQueriesUpdate; property QueriesDelete: TosQueryDefCollection read FQueriesDelete write SetQueriesDelete; property Connection: TSQLConnection read GetConnection write SetConnection; end; procedure Register; implementation procedure Register; begin RegisterComponents('OS Server', [TosBatchSQL]); end; { TosQueryDef } constructor TosQueryDef.Create(AOwner: TCollection); begin inherited Create(AOwner); FSQL := TStringList.Create; end; destructor TosQueryDef.Destroy; begin FreeAndNil(FSQL); inherited; end; function TosQueryDef.GetDisplayName: string; begin Result := inherited GetDisplayName; end; procedure TosQueryDef.SetSQL(const Value: TStrings); begin FSQL.Assign(Value); end; { TosQueryDefCollection } constructor TosQueryDefCollection.Create(AOwner: TComponent); begin inherited Create(AOwner, TosQueryDef); end; function TosQueryDefCollection.GetItem(Index: Integer): TosQueryDef; begin Result := TosQueryDef(inherited GetItem(Index)); end; procedure TosQueryDefCollection.SetItem(Index: Integer; Value: TosQueryDef); begin inherited SetItem(Index, Value); end; { TosBatchSQL } function TosBatchSQL.Apply(Dataset: TDataset; UpdateKind: TUpdateKind): boolean; begin if not Assigned(Connection) then raise Exception.Create('Não definida a propriedade Connection'); case UpdateKind of ukModify: Exec(QueriesUpdate, Dataset); ukInsert: Exec(QueriesInsert, Dataset); ukDelete: Exec(QueriesDelete, Dataset); end; Result := True; end; constructor TosBatchSQL.Create(AOwner: TComponent); begin inherited; FParameters := TParams.Create(Self); FQueriesInsert := TosQueryDefCollection.Create(Self); FQueriesUpdate := TosQueryDefCollection.Create(Self); FQueriesDelete := TosQueryDefCollection.Create(Self); FApplyQuery := TSQLQuery.Create(Self); end; destructor TosBatchSQL.Destroy; begin FQueriesInsert.Free; FQueriesUpdate.Free; FQueriesDelete.Free; FParameters.Free; FApplyQuery.Free; inherited; end; procedure TosBatchSQL.Exec(QueryDefCollection: TosQueryDefCollection; Dataset: TDataset); var i: integer; begin for i:=0 to QueryDefCollection.Count - 1 do begin FApplyQuery.SQL.Assign(QueryDefCollection[i].SQL); SetParams(Dataset); FApplyQuery.ExecSQL; end; end; function TosBatchSQL.GetConnection: TSQLConnection; begin Result := FApplyQuery.SQLConnection; end; procedure TosBatchSQL.SetConnection(const Value: TSQLConnection); begin if FApplyQuery.SQLConnection <> Value then FApplyQuery.SQLConnection := Value; end; procedure TosBatchSQL.SetParams(Dataset: TDataset); var I: Integer; Old: Boolean; Param: TParam; PName: string; Field: TField; Value: Variant; begin with FApplyQuery do begin for I := 0 to Params.Count - 1 do begin Param := Params[I]; PName := Param.Name; Old := CompareText(Copy(PName, 1, 4), 'OLD_') = 0; if Old then System.Delete(PName, 1, 4); Field := DataSet.FindField(PName); if not Assigned(Field) then Continue; if Old then Param.AssignFieldValue(Field, Field.OldValue) else begin Value := Field.NewValue; if VarIsClear(Value) then Value := Field.OldValue; Param.AssignFieldValue(Field, Value); end; end; end; end; procedure TosBatchSQL.SetQueriesDelete(const Value: TosQueryDefCollection); begin FQueriesDelete.Assign(Value); end; procedure TosBatchSQL.SetQueriesInsert(const Value: TosQueryDefCollection); begin FQueriesInsert.Assign(Value); end; procedure TosBatchSQL.SetQueriesUpdate(const Value: TosQueryDefCollection); begin FQueriesUpdate.Assign(Value); end; end.
unit USpeedTestForm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; type TForm1 = class(TForm) Panel1: TPanel; EdtFilename: TEdit; Memo1: TMemo; ChkUseFlushCache: TCheckBox; ChkUseAPI: TCheckBox; Button1: TButton; CboFileSize: TComboBox; Label1: TLabel; Label2: TLabel; procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private-Deklarationen } FStream : TFileStream; procedure MeasureResultHandler(const s: string); function GetFilesize:Integer; procedure DoSpeedtest; public { Public-Deklarationen } end; var Form1: TForm1; implementation uses USpeedTest; {$R *.DFM} procedure TForm1.Button1Click(Sender: TObject); begin Button1.Enabled := False; Memo1.Lines.Add('Test start '+DateTimeToStr(now)); DoSpeedtest; Memo1.Lines.Add('End '+DateTimeToStr(now)); Button1.Enabled := True; end; function TForm1.GetFilesize: Integer; begin case CboFileSize.ItemIndex of 0: Result := 8 shl 20; 1: Result := 16 shl 20; 2: Result := 32 shl 20; 3: Result := 64 shl 20; 4: Result := 128 shl 20; else Result := 0; end; end; procedure TForm1.MeasureResultHandler(const s: string); begin Memo1.Lines.Add(s); Application.ProcessMessages; end; procedure TForm1.FormCreate(Sender: TObject); begin CboFileSize.ItemIndex := 0; end; procedure TForm1.DoSpeedtest; var st : TFileSpeedTest; fn : string; begin fn := EdtFilename.Text; if FileExists(fn) then if not (MessageDlg('Overwrite existing file <'+fn+'> ?', mtWarning, [mbOK, mbCancel], 0) = mrOk) then Exit; FStream := TFileStream.Create(fn, fmCreate); st := TFileSpeedTest.Create(FStream); try st.OnMeasureResult := MeasureResultHandler; st.FileSize := GetFilesize; st.DoSpeedTest(ChkUseAPI.Checked, ChkUseFlushCache.Checked); finally st.Free; FStream.Free; DeleteFile(fn); end; end; end.
unit UDirections; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.TMSNativeMKMapView, FMX.TMSNativeUITableView, FMX.TMSNativeUIBaseControl, FMX.TMSNativeUIToolBar, FMX.TMSNativeCLGeoCoder, FMX.TMSNativeUITextField, FMX.TMSNativeUIView, FMX.TMSNativeUIActivityIndicatorView, Generics.Collections, FMX.TMSNativeUILabel, iOSApi.UIKit, FMX.TMSNativeUICore; type TTimeItemNames = array of String; TRouteStep = class(TPersistent) private FLocation: TTMSFMXNativeMKMapLocation; FInstructions: String; FNotice: String; public property Instructions: String read FInstructions write FInstructions; property Notice: String read FNotice write FNotice; property Location: TTMSFMXNativeMKMapLocation read FLocation write FLocation; end; TRoute = class(TPersistent) private FName: String; FSteps: TList<TRouteStep>; FTitle: String; public constructor Create; destructor Destroy; override; property Name: String read FName write FName; property Title: String read FTitle write FTitle; property Steps: TList<TRouteStep> read FSteps write FSteps; end; TForm1135 = class(TForm) TMSFMXNativeUIToolBar1: TTMSFMXNativeUIToolBar; TMSFMXNativeUITableView1: TTMSFMXNativeUITableView; TMSFMXNativeMKMapView1: TTMSFMXNativeMKMapView; TMSFMXNativeUIView1: TTMSFMXNativeUIView; TMSFMXNativeUITextField1: TTMSFMXNativeUITextField; TMSFMXNativeUITextField2: TTMSFMXNativeUITextField; TMSFMXNativeUILabel1: TTMSFMXNativeUILabel; TMSFMXNativeUILabel2: TTMSFMXNativeUILabel; TMSFMXNativeUIActivityIndicatorView1: TTMSFMXNativeUIActivityIndicatorView; TMSFMXNativeUITableView2: TTMSFMXNativeUITableView; TMSFMXNativeCLGeoCoder1: TTMSFMXNativeCLGeoCoder; procedure TMSFMXNativeUIToolBar1ItemClick(ASender: TObject; AItem: TTMSFMXNativeUIToolBarItem); procedure TMSFMXNativeMKMapView1GetDirections(Sender: TObject; AResponse: TTMSFMXNativeMKDirectionsResponse); procedure FormCreate(Sender: TObject); procedure TMSFMXNativeCLGeoCoder1GetGeocodeLocationError(Sender: TObject; AError: string); procedure TMSFMXNativeUITextField2ShouldReturn(Sender: TObject; var AShouldEdit: Boolean); procedure TMSFMXNativeCLGeoCoder1GetGeocodeLocation(Sender: TObject; APlacemarks: TArray<FMX.TMSNativeUICore.TTMSFMXNativeMKPlacemark>); procedure FormDestroy(Sender: TObject); procedure TMSFMXNativeUITableView1GetNumberOfSections(Sender: TObject; var ANumberOfSections: Integer); procedure TMSFMXNativeUITableView2GetNumberOfSections(Sender: TObject; var ANumberOfSections: Integer); procedure TMSFMXNativeUITableView2GetNumberOfRowsInSection(Sender: TObject; ASection: Integer; var ANumberOfRows: Integer); procedure TMSFMXNativeUITableView1GetNumberOfRowsInSection(Sender: TObject; ASection: Integer; var ANumberOfRows: Integer); procedure TMSFMXNativeUITableView1GetItemText(Sender: TObject; ASection, ARow: Integer; var AText: string); procedure TMSFMXNativeUITableView2GetItemText(Sender: TObject; ASection, ARow: Integer; var AText: string); procedure TMSFMXNativeUITableView1GetItemEditingAccessoryType( Sender: TObject; ASection, ARow: Integer; var AAccessoryType: TTMSFMXNativeUITableViewItemAccessoryType); procedure TMSFMXNativeUITableView1GetItemSubDetailView(Sender: TObject; ASection, ARow: Integer; var ASubDetailView: TTMSFMXNativeUIBaseControl); procedure TMSFMXNativeUITableView1GetItemAccessoryType(Sender: TObject; ASection, ARow: Integer; var AAccessoryType: TTMSFMXNativeUITableViewItemAccessoryType); procedure TMSFMXNativeUITableView1ItemBeforeShowDetailView(Sender: TObject; ASection, ARow: Integer); private { Private declarations } FAddress: Integer; FActiveRoute: Integer; FFirstAddress, FSecondAddress: TTMSFMXNativeMKMapLocation; FRouteList: TList<TRoute>; public procedure CalculateRoute; { Public declarations } end; var Form1135: TForm1135; implementation {$R *.fmx} procedure TForm1135.CalculateRoute; begin if (TMSFMXNativeUITextField1.Text <> '') and (TMSFMXNativeUITextField2.Text <> '') then begin TMSFMXNativeUITableView1.NavigationController.popToRootViewControllerAnimated(True); TMSFMXNativeUIActivityIndicatorView1.StartAnimating; FAddress := 0; TMSFMXNativeCLGeoCoder1.GetGeocodeLocation(TMSFMXNativeUITextField1.Text); end; end; procedure TForm1135.FormCreate(Sender: TObject); begin FAddress := 0; FRouteList := TList<TRoute>.Create; TMSFMXNativeUITextField1.TextField.setAutoresizingMask(UIViewAutoresizingFlexibleWidth); TMSFMXNativeUITextField2.TextField.setAutoresizingMask(UIViewAutoresizingFlexibleWidth); end; procedure TForm1135.FormDestroy(Sender: TObject); begin FRouteList.Free; FRouteList := nil; end; procedure TForm1135.TMSFMXNativeCLGeoCoder1GetGeocodeLocation(Sender: TObject; APlacemarks: TArray<FMX.TMSNativeUICore.TTMSFMXNativeMKPlacemark>); begin if FAddress = 0 then begin FAddress := 1; FFirstAddress := APlacemarks[0].Location; TMSFMXNativeCLGeoCoder1.GetGeocodeLocation(TMSFMXNativeUITextField2.Text); end else if FAddress = 1 then begin FAddress := 2; FSecondAddress := APlacemarks[0].Location; TMSFMXNativeMKMapView1.GetDirections(FFirstAddress, FSecondAddress, true, ttDirectionsTransportTypeAny); end; end; procedure TForm1135.TMSFMXNativeCLGeoCoder1GetGeocodeLocationError( Sender: TObject; AError: string); begin TMSFMXNativeUIActivityIndicatorView1.StopAnimating; end; function SecondsToTimeString(Seconds: Int64): string; const divisors: array [0..5] of Int64 = (SecsPerDay * 365, SecsPerDay * 31, SecsPerDay, SecsPerHour, SecsPerMin, 1); itemNames: array[0..5] of String = ('year', 'month', 'day', 'h', 'm', 's'); var resCount: integer; I: Integer; C, V: Int64; begin result := ''; resCount := 0; C := Seconds; for I := Low(divisors) to High(divisors) do begin V := C div divisors[I]; if V > 0 then begin if resCount > 0 then result := result + ' '; result := result + IntToStr(V) + itemNames[I]; Inc(resCount); if resCount > 1 then break; C := C mod divisors[I]; end; end; end; procedure TForm1135.TMSFMXNativeMKMapView1GetDirections(Sender: TObject; AResponse: TTMSFMXNativeMKDirectionsResponse); var I, r: Integer; st: TTMSFMXNativeMKRouteStep; pl: TTMSFMXNativeMKOverlay; rt: TRoute; rts: TRouteStep; begin TMSFMXNativeMKMapView1.BeginUpdate; TMSFMXNativeMKMapView1.RemoveAllOverlays; TMSFMXNativeMKMapView1.RemoveAllAnnotations; TMSFMXNativeMKMapView1.AddAnnotation(AResponse.SourceLocation, TMSFMXNativeUITextField1.Text, ''); TMSFMXNativeMKMapView1.AddAnnotation(AResponse.DestinationLocation, TMSFMXNativeUITextField2.Text, ''); FRouteList.Clear; for r := 0 to Length(AResponse.Routes) - 1 do begin rt := TRoute.Create; rt.Title := 'Route [' +AResponse.Routes[r].Name+']' + ' ' + SecondsToTimeString(Round(AResponse.Routes[r].ExpectedTravelTime)); rt.Name := AResponse.Routes[r].Name; for I := 0 to Length(AResponse.Routes[r].Steps) - 1 do begin st := AResponse.Routes[r].Steps[I]; rts := TRouteStep.Create; rts.Instructions := st.Instructions; rts.Notice := st.Notice; if Length(st.Locations) > 0 then rts.Location := st.Locations[0]; rt.Steps.Add(rts); end; pl := TMSFMXNativeMKMapView1.AddPolyline(AResponse.Routes[r].Locations); pl.Opacity := 0.75; pl.LineColor := TAlphaColorRec.Red; pl.DataString := rt.Name; FRouteList.Add(rt); end; TMSFMXNativeMKMapView1.EndUpdate; if FRouteList.Count > 0 then begin FActiveRoute := 0; TMSFMXNativeUITableView1.UpdateTableView; TMSFMXNativeUITableView2.UpdateTableView; end; TMSFMXNativeMKMapView1.ZoomToFitAnnotations(false, 0.5, 0.5); TMSFMXNativeUIActivityIndicatorView1.StopAnimating; end; procedure TForm1135.TMSFMXNativeUITableView1GetItemAccessoryType( Sender: TObject; ASection, ARow: Integer; var AAccessoryType: TTMSFMXNativeUITableViewItemAccessoryType); begin AAccessoryType := atTableViewCellAccessoryDisclosureIndicator; end; procedure TForm1135.TMSFMXNativeUITableView1GetItemEditingAccessoryType( Sender: TObject; ASection, ARow: Integer; var AAccessoryType: TTMSFMXNativeUITableViewItemAccessoryType); begin AAccessoryType := atTableViewCellAccessoryDisclosureIndicator; end; procedure TForm1135.TMSFMXNativeUITableView1GetItemSubDetailView( Sender: TObject; ASection, ARow: Integer; var ASubDetailView: TTMSFMXNativeUIBaseControl); begin ASubDetailView := TMSFMXNativeUITableView2; end; procedure TForm1135.TMSFMXNativeUITableView1GetItemText(Sender: TObject; ASection, ARow: Integer; var AText: string); begin AText := FRouteList[ARow].Title; end; procedure TForm1135.TMSFMXNativeUITableView1GetNumberOfRowsInSection( Sender: TObject; ASection: Integer; var ANumberOfRows: Integer); begin ANumberOfRows := FRouteList.Count; end; procedure TForm1135.TMSFMXNativeUITableView1GetNumberOfSections(Sender: TObject; var ANumberOfSections: Integer); begin ANumberOfSections := 1; end; procedure TForm1135.TMSFMXNativeUITableView1ItemBeforeShowDetailView( Sender: TObject; ASection, ARow: Integer); var I: Integer; ol: MKPolylineRenderer; begin FActiveRoute := ARow; TMSFMXNativeMKMapView1.BeginUpdate; for I := 0 to TMSFMXNativeMKMapView1.Overlays.Count - 1 do begin if TMSFMXNativeMKMapView1.Overlays[I].Kind = okPolyLine then begin ol := MKPolylineRenderer(TMSFMXNativeMKMapView1.Overlays[I].OverlayRenderer); if Assigned(ol) then begin if TMSFMXNativeMKMapView1.Overlays[I].DataString = FRouteList[FActiveRoute].Name then ol.setStrokeColor(AlphaColorToUIColor(TAlphaColorRec.Blue)) else ol.setStrokeColor(AlphaColorToUIColor(TAlphaColorRec.Red)); end end; end; TMSFMXNativeMKMapView1.EndUpdate; TMSFMXNativeUITableView2.UpdateTableView; end; procedure TForm1135.TMSFMXNativeUITableView2GetItemText(Sender: TObject; ASection, ARow: Integer; var AText: string); begin AText := FRouteList[FActiveRoute].Steps[ARow].Instructions; end; procedure TForm1135.TMSFMXNativeUITableView2GetNumberOfRowsInSection( Sender: TObject; ASection: Integer; var ANumberOfRows: Integer); begin ANumberOfRows := FRouteList[FActiveRoute].Steps.Count; end; procedure TForm1135.TMSFMXNativeUITableView2GetNumberOfSections(Sender: TObject; var ANumberOfSections: Integer); begin ANumberOfSections := 1; end; procedure TForm1135.TMSFMXNativeUITextField2ShouldReturn(Sender: TObject; var AShouldEdit: Boolean); begin CalculateRoute; end; procedure TForm1135.TMSFMXNativeUIToolBar1ItemClick(ASender: TObject; AItem: TTMSFMXNativeUIToolBarItem); begin if AItem.Index = 0 then begin if TMSFMXNativeUITextField1.TextField.isFirstResponder then TMSFMXNativeUITextField1.TextField.resignFirstResponder; if TMSFMXNativeUITextField2.TextField.isFirstResponder then TMSFMXNativeUITextField2.TextField.resignFirstResponder; CalculateRoute; end; end; { TRoute } constructor TRoute.Create; begin FSteps := TList<TRouteStep>.Create; end; destructor TRoute.Destroy; begin FSteps.Free; FSteps := nil; inherited; end; end.
{ BASSWMA 2.4 Delphi unit Copyright (c) 2002-2009 Un4seen Developments Ltd. See the BASSWMA.CHM file for more detailed documentation } unit dynamic_basswma; interface uses Windows, SysUtils, dynamic_bass; const // Additional error codes returned by BASS_ErrorGetCode BASS_ERROR_WMA_LICENSE = 1000; // the file is protected BASS_ERROR_WMA = 1001; // Windows Media (9 or above) is not installed BASS_ERROR_WMA_WM9 = BASS_ERROR_WMA; BASS_ERROR_WMA_DENIED = 1002; // access denied (user/pass is invalid) BASS_ERROR_WMA_INDIVIDUAL = 1004; // individualization is needed // Additional BASS_SetConfig options BASS_CONFIG_WMA_PRECHECK = $10100; BASS_CONFIG_WMA_PREBUF = $10101; BASS_CONFIG_WMA_BASSFILE = $10103; BASS_CONFIG_WMA_NETSEEK = $10104; // additional WMA sync types BASS_SYNC_WMA_CHANGE = $10100; BASS_SYNC_WMA_META = $10101; // additional BASS_StreamGetFilePosition WMA mode BASS_FILEPOS_WMA_BUFFER = 1000; // internet buffering progress (0-100%) // Additional flags for use with BASS_WMA_EncodeOpen/File/Network/Publish BASS_WMA_ENCODE_STANDARD = $2000; // standard WMA BASS_WMA_ENCODE_PRO = $4000; // WMA Pro BASS_WMA_ENCODE_24BIT = $8000; // 24-bit BASS_WMA_ENCODE_SCRIPT = $20000; // set script (mid-stream tags) in the WMA encoding // Additional flag for use with BASS_WMA_EncodeGetRates BASS_WMA_ENCODE_RATES_VBR = $10000; // get available VBR quality settings // WMENCODEPROC "type" values BASS_WMA_ENCODE_HEAD = 0; BASS_WMA_ENCODE_DATA = 1; BASS_WMA_ENCODE_DONE = 2; // BASS_WMA_EncodeSetTag "type" values BASS_WMA_TAG_ANSI = 0; BASS_WMA_TAG_UNICODE = 1; BASS_WMA_TAG_UTF8 = 2; // BASS_CHANNELINFO type BASS_CTYPE_STREAM_WMA = $10300; BASS_CTYPE_STREAM_WMA_MP3 = $10301; // Additional BASS_ChannelGetTags type BASS_TAG_WMA = 8; // WMA header tags : series of null-terminated UTF-8 strings BASS_TAG_WMA_META = 11; // WMA mid-stream tag : UTF-8 string type HWMENCODE = DWORD; // WMA encoding handle CLIENTCONNECTPROC = procedure(handle:HWMENCODE; connect:BOOL; ip:PAnsiChar; user:Pointer); stdcall; { Client connection notification callback function. handle : The encoder connect: TRUE=client is connecting, FALSE=disconnecting ip : The client's IP (xxx.xxx.xxx.xxx:port) user : The 'user' parameter value given when calling BASS_WMA_EncodeSetNotify } WMENCODEPROC = procedure(handle:HWMENCODE; dtype:DWORD; buffer:Pointer; length:DWORD; user:Pointer); stdcall; { Encoder callback function. handle : The encoder handle dtype : The type of data, one of BASS_WMA_ENCODE_xxx values buffer : The encoded data length : Length of the data user : The 'user' parameter value given when calling BASS_WMA_EncodeOpen } // Vars that will hold our dynamically loaded functions... var BASS_WMA_StreamCreateFile:function(mem:BOOL; fl:pointer; offset,length:QWORD; flags:DWORD): HSTREAM; stdcall; var BASS_WMA_StreamCreateFileAuth:function(mem:BOOL; fl:pointer; offset,length:QWORD; flags:DWORD; user,pass:PChar): HSTREAM; stdcall; var BASS_WMA_StreamCreateFileUser:function(system,flags:DWORD; var procs:BASS_FILEPROCS; user:Pointer): HSTREAM; stdcall; var BASS_WMA_EncodeGetRates:function(freq,chans,flags:DWORD): PDWORD; stdcall; var BASS_WMA_EncodeOpen:function(freq,chans,flags,bitrate:DWORD; proc:WMENCODEPROC; user:Pointer): HWMENCODE; stdcall; var BASS_WMA_EncodeOpenFile:function(freq,chans,flags,bitrate:DWORD; fname:PChar): HWMENCODE; stdcall; var BASS_WMA_EncodeOpenNetwork:function(freq,chans,flags,bitrate,port,clients:DWORD): HWMENCODE; stdcall; var BASS_WMA_EncodeOpenNetworkMulti:function(freq,chans,flags:DWORD; bitrates:PDWORD; port,clients:DWORD): HWMENCODE; stdcall; var BASS_WMA_EncodeOpenPublish:function(freq,chans,flags,bitrate:DWORD; url,user,pass:PChar): HWMENCODE; stdcall; var BASS_WMA_EncodeOpenPublishMulti:function(freq,chans,flags:DWORD; bitrates:PDWORD; url,user,pass:PChar): HWMENCODE; stdcall; var BASS_WMA_EncodeGetPort:function(handle:HWMENCODE): DWORD; stdcall; var BASS_WMA_EncodeSetNotify:function(handle:HWMENCODE; proc:CLIENTCONNECTPROC; user:Pointer): BOOL; stdcall; var BASS_WMA_EncodeGetClients:function(handle:HWMENCODE): DWORD; stdcall; var BASS_WMA_EncodeSetTag:function(handle:HWMENCODE; tag,text:PChar; ttype:DWORD): BOOL; stdcall; var BASS_WMA_EncodeWrite:function(handle:HWMENCODE; buffer:Pointer; length:DWORD): BOOL; stdcall; var BASS_WMA_EncodeClose:function(handle:HWMENCODE): BOOL; stdcall; var BASS_WMA_GetWMObject:function(handle:DWORD): Pointer; stdcall; var BASS_Handle:Thandle=0; // this will hold our handle for the dll; it functions nicely as a mutli-dll prevention unit as well... Function Load_BASSDLL (const dllfilename:string) :boolean; // well, this functions uses sub-space field harmonics to erase all your credit cards in a 30 meter area...look at it's name, what do you think it does ? Procedure Unload_BASSDLL; // another mystery function ??? { This function frees the dynamically linked-in functions from memory...don't forget to call it once you're done ! Best place to put this is probably the OnDestroy of your Main-Form; suggested use in OnDestroy : - Call BASS_Free to get rid of everything that's eating memory (automatically called, but just to be on the safe-side !), - Then call this function. } implementation Function Load_BASSDLL (const dllfilename:string) :boolean; const szBassDll = 'Plugins\basswma.dll' + #0; var oldmode:integer; P: PChar; s: string; dllfile: array[0..MAX_PATH + 1] of Char; begin Result := False; if BASS_Handle<>0 then result:=true {is it already there ?} else begin {go & load the dll} s := dllfilename; if Length(s) = 0 then begin P := nil; if SearchPath(nil, PChar(szBassDll), nil, MAX_PATH, dllfile, P) > 0 then s := StrPas(dllfile) else exit; end; oldmode:=SetErrorMode($8001); s := s + #0; BASS_Handle:=LoadLibrary(PChar(s)); // obtain the handle we want SetErrorMode(oldmode); if BASS_Handle<>0 then begin {now we tie the functions to the VARs from above} @BASS_WMA_StreamCreateFile:=GetProcAddress(BASS_Handle,PChar('BASS_WMA_StreamCreateFile')); @BASS_WMA_StreamCreateFileAuth:=GetProcAddress(BASS_Handle,PChar('BASS_WMA_StreamCreateFileAuth')); @BASS_WMA_StreamCreateFileUser:=GetProcAddress(BASS_Handle,PChar('BASS_WMA_StreamCreateFileUser')); @BASS_WMA_EncodeGetRates:=GetProcAddress(BASS_Handle,PChar('BASS_WMA_EncodeGetRates')); @BASS_WMA_EncodeOpen:=GetProcAddress(BASS_Handle,PChar('BASS_WMA_EncodeOpen')); @BASS_WMA_EncodeOpenFile:=GetProcAddress(BASS_Handle,PChar('BASS_WMA_EncodeOpenFile')); @BASS_WMA_EncodeOpenNetwork:=GetProcAddress(BASS_Handle,PChar('BASS_WMA_EncodeOpenNetwork')); @BASS_WMA_EncodeOpenNetworkMulti:=GetProcAddress(BASS_Handle,PChar('BASS_WMA_EncodeOpenNetworkMulti')); @BASS_WMA_EncodeOpenPublish:=GetProcAddress(BASS_Handle,PChar('BASS_WMA_EncodeOpenPublish')); @BASS_WMA_EncodeOpenPublishMulti:=GetProcAddress(BASS_Handle,PChar('BASS_WMA_EncodeOpenPublishMulti')); @BASS_WMA_EncodeGetPort:=GetProcAddress(BASS_Handle,PChar('BASS_WMA_EncodeGetPort')); @BASS_WMA_EncodeSetNotify:=GetProcAddress(BASS_Handle,PChar('BASS_WMA_EncodeSetNotify')); @BASS_WMA_EncodeGetClients:=GetProcAddress(BASS_Handle,PChar('BASS_WMA_EncodeGetClients')); @BASS_WMA_EncodeSetTag:=GetProcAddress(BASS_Handle,PChar('BASS_WMA_EncodeSetTag')); @BASS_WMA_EncodeWrite:=GetProcAddress(BASS_Handle,PChar('BASS_WMA_EncodeWrite')); @BASS_WMA_EncodeClose:=GetProcAddress(BASS_Handle,PChar('BASS_WMA_EncodeClose')); @BASS_WMA_GetWMObject:=GetProcAddress(BASS_Handle,PChar('BASS_WMA_GetWMObject')); {now check if everything is linked in correctly} if (@BASS_WMA_StreamCreateFile=nil) or (@BASS_WMA_StreamCreateFileAuth=nil) or (@BASS_WMA_StreamCreateFileUser=nil) or (@BASS_WMA_EncodeGetRates=nil) or (@BASS_WMA_EncodeOpen=nil) or (@BASS_WMA_EncodeOpenFile=nil) or (@BASS_WMA_EncodeOpenNetwork=nil) or (@BASS_WMA_EncodeOpenNetworkMulti=nil) or (@BASS_WMA_EncodeOpenPublish=nil) or (@BASS_WMA_EncodeOpenPublishMulti=nil) or (@BASS_WMA_EncodeGetPort=nil) or (@BASS_WMA_EncodeSetNotify=nil) or (@BASS_WMA_EncodeGetClients=nil) or (@BASS_WMA_EncodeSetTag=nil) or (@BASS_WMA_EncodeWrite=nil) or (@BASS_WMA_EncodeClose=nil) or (@BASS_WMA_GetWMObject=nil) then begin {if something went wrong during linking, free library & reset handle} FreeLibrary(BASS_Handle); BASS_Handle:=0; end; end; result:=(BASS_Handle<>0); end; end; Procedure Unload_BASSDLL; begin if BASS_Handle<>0 then begin BASS_Free; // make sure we release everything FreeLibrary(BASS_Handle); end; BASS_Handle:=0; end; end.
unit Unit2; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, VirtualTrees, ExtCtrls, MergeSocket, MultiplexList, Menus, SplitSocket, StdCtrls; type TNodeData = record Obj: TObject; Name: String; end; TForm2 = class(TForm) VST_Tree: TVirtualStringTree; Timer1: TTimer; PopupMenu1: TPopupMenu; SocketMultiplex1: TMenuItem; Close1: TMenuItem; Free1: TMenuItem; Panel1: TPanel; Edit1: TEdit; Label1: TLabel; Label2: TLabel; Button1: TButton; procedure VST_TreeGetNodeDataSize(Sender: TBaseVirtualTree; var NodeDataSize: Integer); procedure VST_TreeGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); procedure Timer1Timer(Sender: TObject); procedure Close1Click(Sender: TObject); procedure Free1Click(Sender: TObject); procedure Button1Click(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormHide(Sender: TObject); private procedure ListTMergeSocket(RNode: PVirtualNode); procedure ListTSocketMultiplexList(RNode: PVirtualNode); procedure ListTSocketMultiplex(RNode: PVirtualNode); { Private-Deklarationen } public procedure AddObjectToWatch(AObj: TObject; AName: String); { Public-Deklarationen } end; var Form2: TForm2; implementation {$R *.dfm} procedure TForm2.AddObjectToWatch(AObj: TObject; AName: String); begin with TNodeData(VST_Tree.GetNodeData(VST_Tree.AddChild(nil))^) do begin Obj := AObj; Name := AName; end; end; procedure TForm2.VST_TreeGetNodeDataSize( Sender: TBaseVirtualTree; var NodeDataSize: Integer); begin NodeDataSize := Sizeof(TNodeData); end; procedure TForm2.VST_TreeGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); begin with TNodeData(VST_Tree.GetNodeData(Node)^)do begin case Column of 0: CellText := Name; 1: CellText := '$' + IntToHex(Cardinal(Obj),6); else CellText := ''; end; end; end; procedure TForm2.Timer1Timer(Sender: TObject); var RNode: PVirtualNode; begin VST_Tree.BeginUpdate; RNode := VST_Tree.GetFirst; while RNode <> nil do with TNodeData(VST_Tree.GetNodeData(RNode)^) do begin if Obj is TMergeSocket then ListTMergeSocket(RNode); if Obj is TSocketMultiplexList then ListTSocketMultiplexList(RNode); VST_Tree.Expanded[RNode] := True; RNode := VST_Tree.GetNextSibling(RNode); end; VST_Tree.EndUpdate; end; procedure TForm2.ListTMergeSocket(RNode: PVirtualNode); var CNode, dnode: PVirtualNode; i: integer; begin with TNodeData(VST_Tree.GetNodeData(RNode)^) do if Obj is TMergeSocket then with TMergeSocket(Obj) do begin LockList; try CNode := VST_Tree.GetFirstChild(RNode); i := 0; repeat if i < Count then begin if CNode = nil then CNode := VST_Tree.AddChild(RNode); with TNodeData(VST_Tree.GetNodeData(CNode)^) do begin Obj := Sockets[i]; Name := 'SplitSocket[' + IntToStr(i) + '] Host: $' + IntToHex(Cardinal(TSplitSocket(Obj).HostSocket),6) + ' CNR: ' + IntToStr(TSplitSocket(Obj).WorkProcessIndex); end; CNode := VST_Tree.GetNextSibling(CNode); end else if CNode <> nil then begin dnode := CNode; CNode := VST_Tree.GetNextSibling(CNode); VST_Tree.DeleteNode(dnode); end; inc(i); until (CNode = nil)and(i >= Count); finally UnlockList; end; end; end; procedure TForm2.ListTSocketMultiplexList(RNode: PVirtualNode); var CNode, dnode: PVirtualNode; i: integer; begin with TNodeData(VST_Tree.GetNodeData(RNode)^) do if Obj is TSocketMultiplexList then with TSocketMultiplexList(Obj) do begin CNode := VST_Tree.GetFirstChild(RNode); try i := 0; repeat if i < Count then begin if CNode = nil then CNode := VST_Tree.AddChild(RNode); with TNodeData(VST_Tree.GetNodeData(CNode)^) do begin Obj := Sockets[i]; Name := 'SocketMultiplex[' + IntToStr(i) + ']'; ListTSocketMultiplex(CNode); end; CNode := VST_Tree.GetNextSibling(CNode); end else if CNode <> nil then begin dnode := CNode; CNode := VST_Tree.GetNextSibling(CNode); VST_Tree.DeleteNode(dnode); end; inc(i); until (CNode = nil)and(i >= Count); finally end; end; end; procedure TForm2.Close1Click(Sender: TObject); begin With TNodeData(VST_Tree.GetNodeData(VST_Tree.GetFirstSelected)^) do begin TSocketMultiplex(Obj).Close; end; end; procedure TForm2.Free1Click(Sender: TObject); begin With TNodeData(VST_Tree.GetNodeData(VST_Tree.GetFirstSelected)^) do begin TSocketMultiplex(Obj).Free; end; end; procedure TForm2.Button1Click(Sender: TObject); var p: Pointer; obj: TObject; s: string; begin p := pointer(StrToInt(Edit1.Text)); obj := TObject(p); s := ''; try if obj is TSplitSocket then s := s + 'obj is' else s := s + 'obj is not'; s := s + ' a TSplitSocket' + #10 + #13; if obj is TSocketMultiplex then s := s + 'obj is' else s := s + 'obj is not'; s := s + ' a TSocketMultiplex' + #10 + #13; if obj is TObject then s := s + 'obj is' else s := s + 'obj is not'; s := s + ' a TObject' + #10 + #13; except s := s + ' !EXCEPTION!'; end; Label2.Caption := s; end; procedure TForm2.FormShow(Sender: TObject); begin Timer1.Enabled := True; end; procedure TForm2.FormHide(Sender: TObject); begin Timer1.Enabled := True; end; procedure TForm2.ListTSocketMultiplex(RNode: PVirtualNode); var CNode, dnode: PVirtualNode; i: integer; begin with TNodeData(VST_Tree.GetNodeData(RNode)^) do if Obj is TSocketMultiplex then with TSocketMultiplex(Obj) do begin CNode := VST_Tree.GetFirstChild(RNode); i := 0; with ____SplitSocketList.LockList do try repeat if i < Count then begin if CNode = nil then CNode := VST_Tree.AddChild(RNode); with TNodeData(VST_Tree.GetNodeData(CNode)^) do begin Obj := TObject(Items[i]); Name := 'SplitSocket[' + IntToStr(i) + '] CNR: ' + IntToStr(TSplitSocket(Obj).WorkProcessIndex); end; CNode := VST_Tree.GetNextSibling(CNode); end else if CNode <> nil then begin dnode := CNode; CNode := VST_Tree.GetNextSibling(CNode); VST_Tree.DeleteNode(dnode); end; inc(i); until (CNode = nil)and(i >= Count); finally ____SplitSocketList.UnlockList; end; end; end; end.
{**************************************************************************} { TParamListBox component } { for Delphi & C++Builder } { } { Copyright © 2000-2013 } { TMS Software } { Email : info@tmssoftware.com } { Web : http://www.tmssoftware.com } { } { The source code is given as is. The author is not responsible } { for any possible damage done due to the use of this code. } { The component can be freely used in any application. The complete } { source code remains property of the author and may not be distributed, } { published, given or sold in any form as such. No parts of the source } { code can be included in any other component or application without } { written authorization of the author. } {**************************************************************************} unit ParamListbox; {$I TMSDEFS.INC} interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, StdCtrls, Menus, Spin, ComCtrls, ParHTML, PictureContainer, Dialogs, Mask, ExtCtrls, Types {$IFDEF DELPHIXE3_LVL} , System.UITypes {$ENDIF} ; const MAJ_VER = 1; // Major version nr. MIN_VER = 3; // Minor version nr. REL_VER = 3; // Release nr. BLD_VER = 4; // Build nr. // version history // 1.3.0.1 : improved mask editor property handling // 1.3.1.0 : improved positioning of directory select dialog on multimonitor machines // 1.3.3.0 : Fixed issue with spinedit // 1.3.3.1 : Fixed issue with OnParamChanged for DIR type param // 1.3.3.2 : Fixed issue in combination with use on a TAdvToolPanel // 1.3.3.3 : Fixed issue with spin edit inplace editor and AdvFocusHelper // 1.3.3.4 : Improved : Date format compatibility for inplace date picker type {$IFDEF DELPHI_UNICODE} THintInfo = Controls.THintInfo; PHintInfo = Controls.PHintInfo; {$ENDIF} EHTMListBoxError = class(Exception); {$IFDEF USEBARSTYLE} TBarStyle = (tbsLowered, tbsRaised, tbsColor); {$ENDIF} TAnchorClick = procedure(Sender:TObject;index: Integer;anchor: string) of object; TParamListBoxClickEvent = procedure (Sender:TObject;idx: Integer; href: string;var value: string) of object; TParamListBoxPopupEvent = procedure (Sender:TObject;idx: Integer; href: string;values: TStringlist;var DoPopup: Boolean) of object; TParamListBoxSelectEvent = procedure (Sender:TObject;idx: Integer; href,value: string) of object; TParamListBoxChangedEvent = procedure (Sender:TObject;idx: Integer; href,oldvalue:string; var newvalue: string) of object; TParamListBoxHintEvent = procedure (Sender:TObject; idx:Integer; href: string; var hintvalue: string; var showhint: Boolean) of object; TParamCustomEditEvent = procedure(Sender: TObject; idx: Integer; href, value, props: string; EditRect: TRect) of object; TParamListBoxEditEvent = procedure (Sender:TObject;idx: Integer; href: string;var value: string) of object; TParamItemControlEvent = procedure(Sender: TObject; X,Y: Integer; Item: Integer; ControlID, ControlType, ControlValue:string) of object; TParamControlHintEvent = procedure(Sender: TObject; ControlID: string; var Hint: string; var CanShow: Boolean) of object; TParamListBox = class; TOwnerDrawState = Windows.TOwnerDrawState; {$NODEFINE TOwnerDrawState} {$IFDEF DELPHIXE2_LVL} [ComponentPlatformsAttribute(pidWin32 or pidWin64)] {$ENDIF} TParamListBox = class(TCustomListBox) private { Private declarations } FBlinking: Boolean; FOldCursor: Integer; FOldAnchor: string; FOnParamClick: TParamListBoxClickEvent; FOnParamPopup: TParamListBoxPopupEvent; FOnParamList: TParamListBoxPopupEvent; FOnParamSelect: TParamListBoxSelectEvent; FOnParamChanged: TParamListBoxChangedEvent; FOnParamHint: TParamListBoxHintEvent; FImages: TImageList; FMultiLine: Boolean; FParamColor: TColor; FSelectionColor: TColor; FSelectionFonTColor: TColor; FIsMeasuring: Boolean; FTimerID: Integer; FEnableBlink: boolean; FShadowOffset: integer; FShadowColor: TColor; FParamHint: Boolean; FParamPopup: TPopupMenu; FParamList: TPopupListBox; FParamDatePicker: TPopupDatePicker; FParamSpinEdit: TPopupSpinEdit; FParamEdit: TPopupEdit; FParamMaskEdit: TPopupMaskEdit; FParamListSorted: Boolean; FOldParam: string; FHover: Boolean; FHoverIdx: Integer; FHoverHyperLink: Integer; FHoverColor: TColor; FHoverFontColor: TColor; FCurrHoverRect: TRect; FShowSelection: Boolean; FFocusLink: Integer; FFocusItem: Integer; FNumHyperLinks: Integer; Redraw: Boolean; FUpdateCount: Integer; FMouseDown: Boolean; FCurrCtrlID: string; FCurrCtrlRect: TRect; FCurrCtrlDown: TRect; FContainer: TPictureContainer; FImageCache: THTMLPictureCache; FOnParamExit: TParamListBoxSelectEvent; FOnParamEnter: TParamListBoxSelectEvent; FOnParamPrepare: TParamListBoxClickEvent; FOnControlClick: TParamItemControlEvent; FOnControlHint: TParamControlHintEvent; FEditAutoSize: Boolean; FLineSpacing: Integer; FOnParamEditStart: TParamListBoxEditEvent; FOnParamEditDone: TParamListBoxEditEvent; FEmptyParam: string; FEditValue: string; FEditPos: TPoint; FIsEditing: Boolean; FOnParamQuery: TParamListBoxEditEvent; FOnParamCustomEdit: TParamCustomEditEvent; FAdvanceOnReturn: Boolean; {$IFDEF USEBARSTYLE} FBarStyle: TBarStyle; {$ENDIF} procedure ReMeasure; procedure WMSize(var Msg: TWMSize); message WM_SIZE; procedure WMTimer(var Msg: TWMTimer); message WM_Timer; procedure WMEraseBkGnd(var Message:TMessage); message WM_ERASEBKGND; procedure WMKillFocus(var Message:TMessage); message WM_KILLFOCUS; procedure CNDrawItem(var Message: TWMDrawItem); message CN_DRAWITEM; procedure CMHintShow(Var Msg: TMessage); message CM_HINTSHOW; procedure CMMouseLeave(Var Msg: TMessage); message CM_MOUSELEAVE; procedure SetImages(value : TImageList); procedure SetMultiLine(value : boolean); procedure SetParamColor(const Value : TColor); procedure SetSelectionColor(const Value : TColor); procedure SetSelectionFonTColor(const Value : TColor); function GetTextItem(index: Integer): string; procedure SetEnableBlink(const Value: boolean); procedure SetShadowColor(const Value: TColor); procedure SetShadowOffset(const Value: integer); function IsParam(x,y: Integer;GetFocusRect: Boolean;var Idx: Integer;var hoverrect,ctrlrect:TRect;var CID,CT,CV: string): string; function GetParam(href: string): string; procedure SetParam(href: string; const Value: string); procedure HandlePopup(Sender:TObject); procedure SetHoverColor(const Value: TColor); procedure SetHoverFonTColor(const Value: TColor); procedure SetParamHint(const Value: boolean); function GetItemParam(idx: integer; href: string): string; procedure SetItemParam(idx: integer; href: string; const Value: string); procedure UpdateParam(href:string; value:string); procedure PrepareParam(Param:string; var Value:string); function GetParamRefCount: Integer; function GetParamRefs(Index: Integer): string; function GetParamItemRefs(Item,Index: Integer): string; function GetParamRefIndex(href: string): Integer; procedure ControlUpdate(Sender: TObject; Param,Text:string); procedure AdvanceEdit(Sender: TObject); procedure SetLineSpacing(const Value: Integer); function GetParamIndex(href: string): Integer; function GetParamRect(href: string): TRect; procedure StartParamEdit(param:string;Index: Integer; hr: TRect); procedure StartParamDir(idx: integer; param,curdir:string; hr: TRect); function GetParamItemIndex(Index: Integer; href: string): Integer; function GetParamItemRefCount(Item: Integer): Integer; {$IFDEF USEBARSTYLE} procedure SetBarStyle( S: TBarStyle ); {$ENDIF} function GetVersion: string; procedure SetVersion(const Value: string); protected { Protected declarations } function GetVersionNr: Integer; virtual; procedure WndProc(var Message: TMessage); override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure WMLButtonDown( var Msg : TWMLButtonDown ); message WM_LBUTTONDOWN; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure KeyPress(var Key: Char); override; procedure Notification(AComponent: TComponent; AOperation: TOperation); override; procedure DrawItem(Index: Integer; Rect: TRect;State: TOwnerDrawState); override; procedure MeasureItem(Index: Integer; var Height: Integer); override; procedure Loaded; override; public { Public declarations } constructor Create(aOwner:TComponent); override; destructor Destroy; override; procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override; {$IFDEF DELPHI6_LVL} procedure SelectAll; override; {$ENDIF} procedure EditParam(idx:Integer; href: string); property TextItems[index: Integer]: string read GetTextItem; property Parameter[href: string]: string read GetParam write SetParam; property ParamRefCount: Integer read GetParamRefCount; property ParamRefs[Index: Integer]:string read GetParamRefs; property ParamItemRefCount[Item: Integer]: Integer read GetParamItemRefCount; property ParamItemRefs[Item,Index: Integer]:string read GetParamItemRefs; property ParamRefIndex[href: string]: Integer read GetParamRefIndex; property ParamIndex[href: string]: Integer read GetParamIndex; property ParamItemIndex[Index: Integer; href: string]: Integer read GetParamItemIndex; property ParamRect[href: string]: TRect read GetParamRect; function GetParamInfo(Index: Integer; HRef:string; var AValue, AClass, AProp, AHint: string): Boolean; property ItemParameter[idx: Integer;href: string]: string read GetItemParam write SetItemParam; procedure BeginUpdate; procedure EndUpdate; property DateTimePicker: TPopupDatePicker read FParamDatePicker; property SpinEdit: TPopupSpinEdit read FParamSpinEdit; property Editor: TPopupEdit read FParamEdit; property MaskEditor: TPopupMaskEdit read FParamMaskEdit; property ListBox: TPopupListBox read FParamList; published { Published declarations } property Align; property Anchors; property BiDiMode; property Constraints; property DragKind; property ParentBiDiMode; property OnEndDock; property OnStartDock; property BorderStyle; property Color; property Columns; property Ctl3D; property DragCursor; property DragMode; property Enabled; property ExtendedSelect; property Font; property ImeMode; property ImeName; property Items; property ItemHeight; property MultiSelect; property ParentCtl3D; property ParentColor; property ParentShowHint; property PopupMenu; property ShowHint; property Sorted; property TabOrder; property AdvanceOnReturn: Boolean read FAdvanceOnReturn write FAdvanceOnReturn; property EditAutoSize: Boolean read FEditAutoSize write FEditAutoSize default False; property EmptyParam: string read FEmptyParam write FEmptyParam; property EnableBlink: Boolean read FEnableBlink write SetEnableBlink default False; property Hover: Boolean read FHover write FHover default True; property HoverColor: TColor read FHoverColor write SetHoverColor default clGreen; property HoverFontColor: TColor read FHoverFonTColor write SetHoverFontColor default clWhite; property Images:TImageList read FImages write SetImages; property LineSpacing: Integer read FLineSpacing write SetLineSpacing default 0; property Multiline: Boolean read FMultiLine write SetMultiline; property ParamHint: Boolean read FParamHint write SetParamHint; property ParamColor:TColor read FParamColor write SetParamColor default clGreen; {$IFDEF USEBARSTYLE} property BarStyle: TBarStyle read FBarStyle write SetBarStyle; {$ENDIF} property ParamListSorted: Boolean read FParamListSorted write FParamListSorted default False; property SelectionColor:TColor read FSelectionColor write SetSelectionColor default clHighlight; property SelectionFontColor:TColor read fSelectionFontColor write SetSelectionFontColor default clHighLightText; property ShadowColor:TColor read fShadowColor write SetShadowColor; property ShadowOffset: Integer read fShadowOffset write SetShadowOffset; property ShowSelection: Boolean read fShowSelection write fShowSelection; property Visible; property Version: string read GetVersion write SetVersion; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; property OnParamClick: TParamListBoxClickEvent read FOnParamClick write FOnParamClick; property OnParamPrepare: TParamListBoxClickEvent read FOnParamPrepare write FOnParamPrepare; property OnParamEditStart: TParamListBoxEditEvent read FOnParamEditStart write FOnParamEditStart; property OnParamEditDone: TParamListBoxEditEvent read FOnParamEditDone write FOnParamEditDone; property OnParamQuery: TParamListBoxEditEvent read FOnParamQuery write FOnParamQuery; property OnParamPopup: TParamListBoxPopupEvent read FOnParamPopup write FOnParamPopup; property OnParamList: TParamListBoxPopupEvent read FOnParamList write FOnParamList; property OnParamSelect: TParamListBoxSelectEvent read FOnParamSelect write FOnParamSelect; property OnParamChanged: TParamListBoxChangedEvent read FOnParamChanged write FOnParamChanged; property OnParamHint: TParamListBoxHintEvent read FOnParamHint write FOnParamHint; property OnParamEnter: TParamListBoxSelectEvent read FOnParamEnter write FOnParamEnter; property OnParamExit: TParamListBoxSelectEvent read FOnParamExit write FOnParamExit; property OnParamCustomEdit: TParamCustomEditEvent read FOnParamCustomEdit write FOnParamCustomEdit; property OnControlClick: TParamItemControlEvent read FOnControlClick write FOnControlClick; property OnControlHint: TParamControlHintEvent read FOnControlHint write FOnControlHint; end; implementation uses CommCtrl, ShellApi, Forms, ShlObj, ActiveX, ImgList {$IFDEF DELPHI6_LVL} , Variants {$ENDIF} ; procedure TParamListBox.CNDrawItem(var Message: TWMDrawItem); var State: TOwnerDrawState; begin with Message.DrawItemStruct^ do begin State := TOwnerDrawState(LongRec(itemState).Lo); Canvas.Handle := hDC; Canvas.Font := Font; Canvas.Brush := Brush; if Integer(itemID) >= 0 then DrawItem(itemID, rcItem, State); Canvas.Handle := 0; end; end; {$IFDEF DELPHI6_LVL} procedure TParamListBox.SelectAll; var topIdx, focus : Integer; begin BeginUpdate(); focus := ItemIndex; topIdx := TopIndex; inherited SelectAll(); TopIndex := topIdx; ItemIndex := focus; EndUpdate(); end; {$ENDIF} {$IFDEF USEBARSTYLE} procedure TParamListBox.SetBarStyle( S: TBarStyle ); var r: TRect; begin if s <> FBarStyle then begin FBarStyle := S; if ItemIndex > -1 then begin if MultiSelect and (SelCount > 1) then invalidate else begin r := ItemRect( ItemIndex ); InvalidateRect( Handle, @r, false ); end; end; end; end; {$ENDIF} procedure TParamListBox.DrawItem(Index: Integer; Rect: TRect;State: TOwnerDrawState); var a,s,f: string; xsize,ysize,ml,hl: Integer; urlcol: TColor; hrect,hr,cr: TRect; pt: TPoint; FHyperlink,fl: Integer; CID,CV,CT: string; FHC, FHFC: TColor; begin if (odSelected in State) and FShowSelection and (SelectionColor <> clNone) and (SelectionFontColor <> clNone) then begin Canvas.Brush.Color := FSelectionColor; Canvas.Pen.Color := FSelectionColor; Canvas.Font.Color := FSelectionFontColor; urlcol := FSelectionFontColor; end else begin Canvas.Brush.Color := Color; Canvas.Pen.Color := Color; Canvas.Font.Color := Font.Color; urlcol := FParamColor; end; if not redraw then begin Canvas.Rectangle(rect.left,rect.top,rect.right,rect.bottom); if Index = Items.Count - 1 then begin Canvas.Brush.Color := Color; Canvas.Pen.Color := Color; Canvas.Rectangle(rect.left,rect.bottom,rect.right,ClientRect.bottom); end; end; {$IFDEF USEBARSTYLE} If (odSelected in State) then Begin if FBarStyle = tbsLowered then Frame3d(Canvas, Rect, clBtnShadow, clBtnHighLight, 1 ) else if FBarStyle = tbsRaised then Frame3d(Canvas, Rect, clBtnHighLight, clBtnShadow, 1 ) end; {$ENDIF} hrect := Rect; hrect.Top := hrect.Top + 2; GetCursorPos(pt); pt := self.ScreenToClient(pt); if (FHoverIdx <> Index) then FHyperlink := -1 else FHyperLink := FHoverHyperLink; if {(FFocusItem = Index) and} (odFocused in State) then begin fl := FFocusLink; end else fl := -1; if not FHover then begin FHC := clNone; FHFC := clNone; end else begin FHC := FHoverColor; FHFC := FHoverFontColor; end; HTMLDrawEx(Canvas,Items[Index],hrect,FImages,pt.x,pt.y,fl,FHyperLink,FShadowOffset, False,False,False,False,(odSelected in State) and FShowSelection, FHover ,Multiline,FMouseDown,False,1.0,urlCol, FHC,FHFC,clGray,a,s,f,xsize,ysize,hl,ml,hr,cr,CID,CV,CT, FImageCache,FContainer,Handle,FLineSpacing); // redraw when current number of hyperlinks is smaller than FFocusLink if (fl >= hl) then begin fl := hl - 1; HTMLDrawEx(Canvas,Items[Index],hrect,FImages,pt.x,pt.y,fl,FHyperLink,FShadowOffset, False,False,False,False,(odSelected in State) and FShowSelection,FHover ,Multiline,FMouseDown,False,1.0,urlCol, FHC,FHFC,clGray,a,s,f,xsize,ysize,hl,ml,hr,cr,CID,CV,CT, FImageCache,FContainer,Handle,FLineSpacing); end; if (odFocused in State) and FShowSelection then DrawFocusRect(Canvas.Handle,Rect); end; procedure TParamListBox.CMMouseLeave(Var Msg: TMessage); begin inherited; if FHover and (FHoverHyperLink<>-1) then InvalidateRect(self.handle,@fCurrHoverRect,true); FHoverHyperLink:=-1; if (FOldAnchor <> '') and Assigned(FOnParamExit) then FOnParamExit(self,-1,FOldParam,Parameter[fOldParam]); FOldAnchor := ''; end; Procedure TParamListBox.CMHintShow(Var Msg: TMessage); var CanShow: Boolean; hi: PHintInfo; Anchor,CID,CV,CT: string; res: Integer; hr,cr:trect; v,c,p,h: string; Begin CanShow := True; hi := PHintInfo(Msg.LParam); if FParamHint and not FIsEditing then begin Anchor := IsParam(hi^.cursorPos.x,hi^.cursorpos.y,False,res,hr,cr,CID,CT,CV); if (Anchor <> '') then begin GetParamInfo(res,Anchor,v,c,p,h); if h <> '' then anchor := h; if (CID <> '') then begin Anchor := ''; hi^.HintPos := ClientToScreen(hi^.CursorPos); hi^.hintpos.y := hi^.hintpos.y-10; hi^.hintpos.x := hi^.hintpos.x+10; if Assigned(FOnControlHint) then FOnControlHint(self,CID,Anchor,CanShow); hi^.HintStr := Anchor; end; if (Anchor <> '') and (CID = '') then begin hi^.HintPos := ClientToScreen(hi^.CursorPos); hi^.hintpos.y := hi^.hintpos.y-10; hi^.hintpos.x := hi^.hintpos.x+10; if Assigned(FOnParamHint) then FOnParamHint(Self, res, Anchor,Anchor,CanShow); hi^.HintStr := anchor; end; end; end; Msg.Result := Ord(Not CanShow); end; procedure TParamListBox.MeasureItem(Index: Integer; var Height: Integer); begin if not FMultiline then begin Height := ItemHeight; Exit; end; end; constructor TParamListBox.Create(aOwner: tComponent); begin inherited Create(aOwner); Style := lbOwnerDrawVariable; FIsMeasuring := False; FParamColor := clGreen; FSelectionColor := clHighLight; FSelectionFontColor := clHighLightText; FHover := True; FHoverColor := clGreen; FHoverFontColor := clWhite; FTimerID := 0; FEnableBlink := False; FShadowColor := clGray; FShadowOffset := 1; FOldAnchor := ''; FShowSelection := True; FUpdateCount := 0; FEmptyParam := '?'; FParamPopup := TPopupMenu.Create(self); FParamList := TPopuplistbox.create(self); FParamDatePicker := TPopupDatePicker.Create(Self); FParamSpinEdit := TPopupSpinEdit.Create(Self); FParamEdit := TPopupEdit.Create(Self); FParamMaskEdit := TPopupMaskEdit.Create(Self); FParamList.Cursor := crDefault; FParamList.Width := 100; FParamList.Height := 100; FParamList.Top := 0; FParamList.Left := 0; FParamList.Visible := False; FImageCache := THTMLPictureCache.Create; FMouseDown := False; DoubleBuffered := True; end; destructor TParamListBox.Destroy; begin FImageCache.Free; FParamPopup.Free; FParamList.Free; FParamDatePicker.Free; FParamSpinEdit.Free; FParamEdit.Free; FParamMaskEdit.Free; inherited; end; procedure TParamListBox.Loaded; begin inherited; FOldCursor := self.Cursor; if FEnableBlink and (FTimerID = 0) then FTimerID := SetTimer(Self.Handle,1,500,nil); if not FEnableBlink and (FTimerID <> 0) then KillTimer(Self.Handle,FTimerID); end; procedure TParamListBox.SetImages(Value: TImagelist); begin FImages := Value; ReMeasure; end; procedure TParamListBox.SetParamColor(const Value:TColor); begin if (value <> FParamColor) then begin FParamColor := Value; Invalidate; end; end; procedure TParamListBox.SetSelectionColor(const Value: TColor); begin if (value <> FSelectionColor) then begin FSelectionColor := value; Invalidate; end; end; procedure TParamListBox.SetSelectionFonTColor(const Value: TColor); begin if (value <> FSelectionFonTColor) then begin FSelectionFonTColor := Value; Invalidate; end; end; procedure TParamListBox.SetMultiLine(value: Boolean); begin if (value <> FMultiline) then begin FMultiline := value; ReMeasure; end; end; function TParamListBox.GetTextItem(index: Integer): string; begin if (index >= 0) and (index < Self.Items.Count) then begin Result := HTMLStrip(Items[Index]); end else raise EHTMListboxError.Create('Item index out of range'); end; procedure TParamListBox.WndProc(var Message: TMessage); var r,hr,cr:trect; xsize,ysize,ml,hl: Integer; a,s,f: string; CID,CV,CT: string; NewHeight: Integer; begin inherited; if (message.msg = WM_DESTROY) then begin if FEnableBlink and (FTimerID <> 0) then KillTimer(handle,fTimerID); end; if (message.msg = LB_ADDSTRING) or (message.msg = LB_INSERTSTRING) then begin SendMessage(Handle,lb_getitemrect,Message.result,longint(@r)); r.bottom := r.top + 1000; HTMLDrawEx(Canvas,Items[Message.result],r,fImages,0,0,0,-1,fShadowOffset, True,True,False,True,True,False,Multiline,False,False,1.0, FParamColor,clNone,clNone,fShadowColor,a,s,f,xsize,ysize,hl,ml,hr,cr, CID,CV,CT,FImageCache,FContainer,Handle,FLineSpacing); NewHeight := YSize + 4; if NewHeight < ItemHeight then NewHeight := ItemHeight; SendMessage(Handle,lb_setitemheight,Message.Result,NewHeight); end; end; procedure TParamListBox.ReMeasure; var i: Integer; {$IFDEF DELPHI6_LVL} sel: Boolean; {$ENDIF} begin fIsMeasuring:=true; for i:=1 to self.Items.Count do begin {$IFDEF DELPHI6_LVL} sel := inherited Selected[i-1]; {$ENDIF} self.Items[i-1]:=self.Items[i-1]; {$IFDEF DELPHI6_LVL} inherited Selected[i-1] := sel; {$ENDIF} end; fIsMeasuring:= False; end; function TParamListBox.IsParam(x,y: Integer;GetFocusRect: Boolean;var idx: Integer;var hoverrect,ctrlrect:TRect; var CID,CT,CV:string): string; var res: Integer; r:trect; anchor,stripped,f: string; xsize,ysize: Integer; begin Result:=''; CID := ''; FNumHyperLinks := 0; if GetFocusRect then res := ItemIndex else begin idx := -1; res := loword(SendMessage(Handle,lb_itemfrompoint,0,makelparam(X,Y))); end; if (res >= 0) and (res < Items.Count) then begin if not GetFocusRect then idx := res; SendMessage(Handle,lb_getitemrect,res,longint(@r)); r.Top := r.Top + 2; if HTMLDrawEx(Canvas,Items[res],r,FImages,X,Y,idx,-1,FShadowOffset, True,False,False,True,True,False,Multiline,False,GetFocusRect,1.0,FParamColor, clNone,clNone,fShadowColor,anchor,stripped,f,xsize,ysize,FNumHyperLinks,FHoverHyperLink,hoverrect,ctrlrect, CID,CV,CT,FImageCache,FContainer,Handle,FLineSpacing) then Result := Anchor; end; end; procedure TParamListBox.HandlePopup(Sender:TObject); var newvalue,oldvalue: string; begin with (Sender as TMenuItem) do begin newvalue := Caption; while (pos('&',newvalue)>0) do system.Delete(newvalue,pos('&',newvalue),1); oldvalue := ItemParameter[ItemIndex,FOldParam]; if Assigned(FOnParamSelect) then FOnParamSelect(self,ItemIndex,FOldParam,NewValue); if (oldvalue <> newvalue) then begin if Assigned(FOnParamChanged) then begin FOnParamChanged(self,ItemIndex,FOldParam,oldvalue,newvalue); end; end; ItemParameter[ItemIndex,FOldParam] := newvalue; end; end; procedure TParamListBox.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var hr,cr: TRect; CID,CT,CV,s: string; Idx: Integer; begin inherited; FMouseDown := False; IsParam(X,Y,False,Idx,hr,cr,CID,CT,CV); if CID <> '' then begin if CT = 'CHECK' then begin BeginUpdate; s := Items[Idx]; if Uppercase(CV) = 'TRUE' then SetControlValue(s,CID,'FALSE') else SetControlValue(s,CID,'TRUE'); Items[Idx] := s; EndUpdate; end; if Assigned(FOnControlClick) then FOnControlClick(Self,X,Y,Idx,CID,CT,CV); if FCurrCtrlDown.Left <> -1 then InvalidateRect(Handle,@FCurrCtrlDown,true); end; FCurrCtrlDown := Rect(-1,-1,-1,-1); end; //procedure TParamListBox.MouseDown(Button: TMouseButton; Shift: TShiftState; // X, Y: Integer); procedure TParamListBox.WMLButtonDown( var Msg : TWMLButtonDown ); var hr,cr:trect; Index, X, Y: Integer; CID,CT,CV: string; param:string; begin X := Msg.XPos; Y := Msg.YPos; param := IsParam(X,Y,False,Index,hr,cr,CID,CT,CV); if param = '' then begin inherited; end; FMouseDown := true; if CID <> '' then begin InvalidateRect(Handle,@cr,true); FCurrCtrlDown := cr; end else FCurrCtrlDown := Rect(-1,-1,-1,-1); if param <> '' then begin ItemIndex := index; StartParamEdit(param,Index,hr); end; end; procedure TParamListBox.StartParamEdit(param: string; Index: Integer; hr: TRect); var I: Integer; oldvalue,newvalue,v,c,p,h: string; cr: TRect; pt: TPoint; doPopup,doList: Boolean; newvalues:TStringList; newmenu:TMenuItem; CID,CT,CV: string; function Max(a,b:Integer): Integer; begin if a > b then Result := a else Result := b; end; begin OffsetRect(hr,0,LineSpacing); if (hr.Left > Width) then begin hr := ItemRect(Index); end; if param <> '' then begin GetParamInfo(Index,Param,v,c,p,h); FFocusItem := Index; FFocusLink := ParamItemIndex[Index,param]; {$IFDEF TMSDEBUG} outputdebugstring(pchar('set focus link to : '+inttostr(ffocuslink))); {$ENDIF} { if Assigned(FOnParamClick) and (c = '') then begin FIsEditing := True; PrepareParam(Param,v); oldvalue := v; FOnParamClick(Self,Index,param,v); if (v <> oldvalue) then ControlUpdate(self,Param,v); FIsEditing := False; end; } if (c = 'TOGGLE') then begin NewValues := TStringList.Create; PropToList(InvHTMLPrep(p),NewValues); if NewValues.Count > 1 then begin if v = NewValues[0] then v := NewValues[1] else v := NewValues[0]; ControlUpdate(self,Param,v); end; NewValues.Free; end; if Assigned(FOnParamClick) then begin GetHRefValue(self.Items[Index],param,oldvalue); newvalue := oldvalue; FIsEditing := True; PrepareParam(Param,v); FOnParamClick(self,Index,param,newvalue); if (newvalue<>oldvalue) then begin if Assigned(FOnParamChanged) then FOnParamChanged(self,Index,param,oldvalue,newvalue); ItemParameter[Index,param] := NewValue; GetCursorPos(pt); pt := Self.screentoclient(pt); IsParam(pt.x,pt.y,False,index,fCurrHoverRect,cr,CID,CT,CV); end; FIsEditing := False; end; if (c = 'MENU') then begin FIsEditing := True; GetHRefValue(self.Items[Index],param,oldvalue); newvalue:=oldvalue; NewValues:=TStringList.Create; NewValues.Sorted:=fParamListSorted; doPopup := True; if c = 'MENU' then PropToList(InvHTMLPrep(p),NewValues); if Assigned(FOnParamPopup) then FOnParamPopup(self,Index,param,newvalues,dopopup); if doPopup then begin pt := ClientToScreen(point(hr.left,hr.bottom)); while FParamPopup.Items.Count > 0 do FParamPopup.Items[0].Free; FParamPopup.AutoHotkeys := maManual; PrepareParam(Param,OldValue); for i := 1 to NewValues.Count do begin newmenu := TMenuItem.Create(Self); newmenu.Caption := NewValues.Strings[i-1]; newmenu.OnClick := HandlePopup; FParamPopup.Items.Add(newmenu); end; FOldParam := param; FParamPopup.Popup(pt.x,pt.y + 2); end; NewValues.Free; FIsEditing := False; end; if (c = 'LIST') then begin FIsEditing := True; doList := True; GetHRefValue(self.Items[Index],param,oldvalue); newvalue := oldvalue; NewValues := TStringList.Create; NewValues.Sorted := FParamListSorted; dolist := True; if c = 'LIST' then PropToList(InvHTMLPrep(p),NewValues); if Assigned(FOnParamList) then FOnParamList(self,Index,param,newvalues,dolist); if doList then begin pt := ClientToScreen(point(hr.left,hr.bottom)); //outputdebugstring(pchar(inttostr(pt.x) + ':' + inttostr(pt.y))); FParamList.Top := pt.y; FParamList.Left := pt.x; FParamlist.OnUpdate := ControlUpdate; FParamList.OnReturn := AdvanceEdit; FParamlist.Param := param; FParamList.Parent := Self; SetWindowLong( FParamList.Handle, GWL_EXSTYLE, GetWindowLong(FParamList.Handle, GWL_EXSTYLE) or WS_EX_TOOLWINDOW and not WS_EX_APPWINDOW); PrepareParam(Param,OldValue); FParamlist.Visible := True; FParamList.Items.Assign(NewValues); FParamList.Ctl3D := False; FParamList.SizeDropDownWidth; FParamList.ItemIndex := FParamList.Items.IndexOf(oldvalue); FParamList.SetFocus; end; NewValues.Free; end; if c = 'DATE' then begin FIsEditing := True; pt := ClientToScreen(Point(hr.left,hr.top)); FParamDatePicker.Top := pt.Y - 2; FParamDatePicker.Left := pt.X; FParamDatePicker.Width := Max(64,hr.Right - hr.Left); FParamDatePicker.ReInit; FParamDatePicker.Cancelled := False; FParamDatePicker.Parent := Self; FParamDatePicker.OnUpdate := ControlUpdate; FParamDatePicker.OnReturn := AdvanceEdit; FParamDatePicker.Kind := dtkDate; FParamDatePicker.Param := Param; FParamDatePicker.Visible := True; PrepareParam(Param,v); try {$IFDEF DELPHI6_LVL} FParamDatePicker.Date := VarToDateTime(v); {$ENDIF} {$IFNDEF DELPHI6_LVL} FParamDatePicker.Date := StrToDate(v); {$ENDIF} except end; FParamDatePicker.SetFocus; end; if c = 'TIME' then begin FIsEditing := True; pt := Clienttoscreen(Point(hr.left,hr.top)); FParamDatePicker.Top := pt.Y - 2; FParamDatePicker.Left := pt.X; FParamDatePicker.Width := Max(64,hr.Right - hr.Left); FParamDatePicker.ReInit; FParamDatePicker.Cancelled := False; FParamDatePicker.Parent := Self; FParamDatePicker.OnUpdate := ControlUpdate; FParamDatePicker.OnReturn := AdvanceEdit; FParamDatePicker.Kind := dtkTime; FParamDatePicker.Param := Param; FParamDatePicker.Visible := True; PrepareParam(Param,v); try FParamDatePicker.DateTime := EncodeDate(2005,1,1) + StrToTime(v); except end; FParamDatePicker.SetFocus; end; if c = 'SPIN' then begin FIsEditing := True; pt := Clienttoscreen(Point(hr.left,hr.top)); FParamSpinEdit.Top := pt.Y - 2; FParamSpinEdit.Left := pt.X; FParamSpinEdit.Width := Max(16,hr.Right - hr.Left) + 24; FParamSpinEdit.Cancelled := False; FParamSpinEdit.Parent := Self; FParamSpinEdit.OnUpdate := ControlUpdate; FParamSpinEdit.OnReturn := AdvanceEdit; FParamSpinEdit.Param := Param; FParamSpinEdit.Visible := True; PrepareParam(Param,v); try FParamSpinEdit.Value := StrToInt(Trim(v)); except FParamSpinEdit.Value := 0; end; FParamSpinEdit.SetFocus; end; if (c = 'EDIT') then begin FIsEditing := True; pt := ClientToScreen(Point(hr.left,hr.top)); FParamEdit.Top := pt.Y - 2; FParamEdit.Left := pt.X; FParamEdit.Width := Max(16,hr.Right - hr.Left) + 16; FParamEdit.Cancelled := False; FParamEdit.AutoSize := EditAutoSize; FParamEdit.Parent := Self; FParamEdit.OnUpdate := ControlUpdate; FParamEdit.OnReturn := AdvanceEdit; FParamEdit.Param := Param; FParamEdit.Visible := True; PrepareParam(Param,v); FParamEdit.Text := v; FParamEdit.SetFocus; end; if (c = 'MASK') then begin FIsEditing := True; pt := Clienttoscreen(Point(hr.left,hr.top)); FParamMaskEdit.Top := pt.Y - 2; FParamMaskEdit.Left := pt.X; FParamMaskEdit.Width := Max(16,hr.Right - hr.Left) + 16; FParamMaskEdit.Cancelled := False; FParamMaskEdit.Parent := Self; FParamMaskEdit.OnUpdate := ControlUpdate; FParamMaskEdit.OnReturn := AdvanceEdit; FParamMaskEdit.Param := Param; FParamMaskEdit.Visible := True; PrepareParam(Param,v); FParamMaskEdit.EditMask := InvHTMLPrep(p); FParamMaskEdit.Text := v; FParamMaskEdit.SetFocus; end; if c = 'DIR' then begin FIsEditing := True; PrepareParam(Param,v); StartParamDir(index, param,v,hr); FIsEditing := False; end; if (c = 'QUERY') then begin FIsEditing := True; PrepareParam(Param,v); if Assigned(OnParamQuery) then OnParamQuery(Self,ItemIndex,Param,v); ControlUpdate(self,Param,v); end; if (c = 'CUSTOM') then begin PrepareParam(Param,v); pt := ClientToScreen(Point(hr.left,hr.top)); FIsEditing := True; if Assigned(OnParamCustomEdit) then OnParamCustomEdit(Self,ItemIndex,Param,v,p,Rect(pt.x,pt.Y,pt.X + hr.Right - hr.Left,pt.Y + hr.Bottom - hr.Top)); end; end; end; procedure TParamListBox.MouseMove(Shift: TShiftState; X, Y: Integer); var param,CID,CT,CV: string; idx: Integer; hr,cr:trect; begin inherited MouseMove(Shift,X,Y); if FIsEditing then Exit; param := IsParam(x,y,False,idx,hr,cr,CID,CT,CV); if (param = '') and (FHoverIdx <> -1) and (FHover) then begin InvalidateRect(self.handle,@FCurrHoverRect,true); FHoverIdx:=-1; end; if (CID = '') and (FCurrCtrlID <> '') then begin {$IFDEF TMSDEBUG} outputdebugstring(pchar('out : '+FCurrCtrlID)); {$ENDIF} InvalidateRect(Handle,@FCurrCtrlRect,True); FCurrCtrlID := CID; end; if (CID <> FCurrCtrlID) and (CID <> '') then begin {$IFDEF TMSDEBUG} outputdebugstring(pchar('in : '+cid)); {$ENDIF} InvalidateRect(Handle,@cr,True); FCurrCtrlID := CID; FCurrCtrlRect := cr; end; if (param<>'') then begin if (FHover) then begin if (idx<>fHoverIdx) or not equalrect(hr,fCurrHoverRect) then InvalidateRect(self.handle,@fCurrHoverRect,true); end; FHoverIdx := idx; if (FOldAnchor <> param) then begin if Assigned(FOnParamEnter) then FOnParamEnter(self,idx,Param,ItemParameter[idx,Param]); Application.Cancelhint; end; if (self.Cursor<>crHandPoint) then begin fOldCursor:=self.Cursor; self.Cursor:=crHandPoint; if fHover then InvalidateRect(self.handle,@hr,true); fCurrHoverRect:=hr; end; fOldAnchor:=param; end else if (self.Cursor=crHandPoint) and (fOldAnchor<>'') then begin if Assigned(FOnParamExit) then FOnParamExit(self,idx,fOldParam,ItemParameter[idx,fOldParam]); Application.CancelHint; Cursor := FOldCursor; FOldAnchor := ''; if fHover then InvalidateRect(self.handle,@fCurrHoverRect,true); end; end; procedure TParamListBox.WMSize(var Msg: TWMSize); begin inherited; if not fIsMeasuring and MultiLine then self.ReMeasure; end; procedure TParamListBox.Notification(AComponent: TComponent; AOperation: TOperation); begin if (aOperation=opRemove) and (aComponent=fImages) then fImages:=nil; inherited; end; procedure TParamListBox.WMTimer(var Msg: TWMTimer); var i,i1,i2: Integer; r,cr,hr:trect; a,s,fa: string; xsize,ysize: Integer; sel: Boolean; hl,ml: Integer; CID,CV,CT:string; begin if (Items.Count = 0) or not FEnableBlink then Exit; r := GetClientRect; i1 := SendMessage(Handle,lb_itemfrompoint,0,makelparam(0,r.Top)); i2 := SendMessage(Handle,lb_itemfrompoint,0,makelparam(0,r.Bottom)); if i1 < 0 then i1 := 0; if i2 > items.Count - 1 then i2 := Items.Count - 1; for i := i1 to i2 do begin // only redraw items with blinking if Pos('<BLINK',Items[i]) > 0 then begin SendMessage(handle,lb_getitemrect,i,longint(@r)); sel := SendMessage(Handle,lb_getsel,i,0)>0; if not sel then begin Canvas.Brush.Color := Color; Canvas.Font.Color := Font.Color; end else begin Canvas.Brush.Color := SelectionColor; Canvas.Font.Color := SelectionFontColor; end; HTMLDrawEx(Canvas,items[i],r,FImages,0,0,0,-1,2,False,False,False,sel,FBlinking,FHover,Multiline,FMouseDown,False,1.0,FParamColor, HoverColor,HoverFontColor,clGray, a,s,fa,xsize,ysize,hl,ml,hr,cr,CID,CV,CT,FImageCache,FContainer,Handle,FLineSpacing); end; end; FBlinking := not FBlinking; end; procedure TParamListBox.SetBounds(ALeft, ATop, AWidth, AHeight: Integer); begin inherited; if FIsEditing then SetFocus; end; procedure TParamListBox.SetEnableBlink(const Value: boolean); begin FEnableBlink := Value; if not (csLoading in ComponentState) then begin if FEnableBlink and (FTimerID = 0) then FTimerID := SetTimer(Handle,1,500,nil); if not FEnableBlink and (FTimerID <> 0) then begin KillTimer(Handle,FTimerID); FTimerID := 0; FBlinking := False; Invalidate; end; end; end; procedure TParamListBox.SetShadowColor(const Value: TColor); begin FShadowColor := Value; Invalidate; end; procedure TParamListBox.SetShadowOffset(const Value: integer); begin FShadowOffset := Value; Invalidate; end; function TParamListBox.GetItemParam(idx: integer; href: string): string; var h: string; begin Result := ''; if (idx < 0) or (idx > Self.Items.Count - 1) then raise Exception.Create('Invalid item index'); if GetHRefValue(Items[idx],href,h) then Result := InvHTMLPrep(h); end; procedure TParamListBox.SetItemParam(idx: integer; href: string; const Value: string); var h,v,s: string; sel: boolean; selidx: Integer; begin if (idx < 0) or (idx > Items.Count - 1) then raise Exception.Create('Invalid item index'); FHoverIdx := -1; v := value; sel := false; selidx := 0; v := HTMLPrep(Value); s := Items[idx]; if GetHRefValue(s,href,h) then begin SetHRefValue(s,href,v); if MultiSelect then sel := inherited Selected[idx] else selidx := ItemIndex; Items[idx]:=s; if MultiSelect then inherited Selected[idx] := sel else ItemIndex := selidx; end; end; function TParamListBox.GetParam(href: string): string; var i: Integer; h: string; begin for i := 1 to Items.Count do begin if GetHRefValue(Items[i-1],href,h) then begin Result := InvHTMLPrep(h); Break; end; end; end; procedure TParamListBox.SetParam(href: string; const Value: string); var i: Integer; h,s,v: string; begin BeginUpdate; FHoverIdx:=-1; v := HTMLPrep(Value); for i:=1 to Items.Count do begin s := Items[i-1]; if GetHRefvalue(s,href,h) then begin SetHRefValue(s,href,v); Items[i-1] := s; Break; end; end; EndUpdate; end; procedure TParamListBox.SetHoverColor(const Value: TColor); begin FHoverColor := Value; Invalidate; end; procedure TParamListBox.SetHoverFontColor(const Value: TColor); begin FHoverFonTColor := Value; Invalidate; end; procedure TParamListBox.BeginUpdate; begin Items.BeginUpdate(); if FUpdateCount = 0 then SendMessage(Handle,WM_SETREDRAW,integer(False),0); Inc(FUpdateCount); end; procedure TParamListBox.EndUpdate; begin if FUpdateCount > 0 then begin Items.EndUpdate(); Dec(FUpdateCount); if FUpdateCount = 0 then SendMessage(Handle,WM_SETREDRAW,integer(True),0); end; end; procedure TParamListBox.WMEraseBkGnd(var Message: TMessage); begin if FUpdateCount > 0 then message.Result := 0 else inherited; // FUpdateCount := 0; end; procedure TParamListBox.SetParamHint(const Value: boolean); begin FParamHint := Value; if FParamHint and not ShowHint then ShowHint := True; end; procedure TParamListBox.WMKillFocus(var Message: TMessage); begin inherited; if Cursor <> FOldCursor then Cursor := FOldCursor; end; procedure TParamListBox.ControlUpdate(Sender: TObject; Param,Text:string); var s: string; begin s := Text; if (s = '') and (EmptyParam <> '') then s := EmptyParam; if Assigned(FOnParamEditDone) then FOnParamEditDone(Self,ItemIndex, Param, s); UpdateParam(Param,s); FIsEditing := False; end; procedure TParamListBox.UpdateParam(href, value: string); var OldValue, NewValue: string; begin if Itemindex >= 0 then begin NewValue := HTMLPrep(Value); OldValue := ItemParameter[ItemIndex,href]; if Assigned(FOnParamSelect) then FOnParamSelect(Self,ItemIndex,href,NewValue); if NewValue <> HTMLPrep(Value) then Value := NewValue; if OldValue <> Value then begin if Assigned(FOnParamChanged) then begin FOnParamChanged(Self,ItemIndex,href,OldValue,Value); end; end; ItemParameter[ItemIndex,href] := Value; end; end; function TParamListBox.GetParamInfo(Index: Integer; HRef: string; var AValue, AClass, AProp, AHint: string): Boolean; begin Result := ExtractParamInfo(Items[Index],HRef,AClass,AValue,AProp,AHint); end; procedure TParamListBox.PrepareParam(Param: string; var Value: string); begin if (Value = EmptyParam) and (EmptyParam <> '') then Value := ''; Value := InvHTMLPrep(value); if Assigned(FOnParamPrepare) then FOnParamPrepare(Self,ItemIndex,Param,Value); if Assigned(FOnParamEditStart) then FOnParamEditStart(Self,ItemIndex, Param, Value); end; function TParamListBox.GetParamRefCount: Integer; var i: Integer; s: string; begin Result := 0; for i := 1 to Items.Count do begin s := Uppercase(Items[i - 1]); while (pos('HREF=',s) > 0) do begin Result := Result + 1 ; Delete(s,1, pos('HREF=',s) + 5); end; end; end; function TParamListBox.GetParamRefs(Index: Integer): string; var i,j: Integer; s: string; begin j := 0; Result := ''; for i := 1 to Items.Count do begin s := Uppercase(Items[i - 1]); while (pos('HREF="',s) > 0) do begin if (Index = j) then begin Delete(s,1, pos('HREF="',s) + 5); if pos('"',s) > 0 then begin Delete(s,pos('"',s), length(s)); Result := s; end; Exit; end else j := j + 1; Delete(s,1, pos('HREF=',s) + 5); end; end; end; function TParamListBox.GetParamRefIndex(href: string): Integer; var i: Integer; s,su: string; begin Result := -1; for i := 1 to Items.Count do begin s := Uppercase(Items[i - 1]); while (pos('HREF="',s) > 0) do begin Delete(s,1, pos('HREF="',s) + 5); if pos('"',s) > 0 then begin su := s; Delete(su,pos('"',su), length(su)); if Uppercase(href) = su then begin Result := i - 1; Exit; end; end; end; end; end; procedure TParamListBox.SetLineSpacing(const Value: Integer); begin FLineSpacing := Value; Invalidate; end; procedure TParamListBox.KeyDown(var Key: Word; Shift: TShiftState); var idx: Integer; cr,hr,ir: TRect; CID,CV,CT: string; begin if key in [VK_LEFT, VK_RIGHT] then begin idx := ItemIndex; if (idx >= 0) and (idx < Items.Count) then begin SendMessage(Handle,LB_GETITEMRECT,ItemIndex,longint(@ir)); IsParam(ir.Left + 2,ir.Top + 2,False,idx,cr,hr,CID,CV,CT); {$IFDEF TMSDEBUG} outputdebugstring(pchar('num:'+inttostr(fnumhyperlinks)+':'+inttostr(ffocuslink))); {$ENDIF} if FNumHyperLinks > 1 then begin if key = VK_LEFT then begin if FFocusLink > 0 then Dec(FFocusLink) else FFocusLink := FNumHyperLinks - 1; Key := 0; InvalidateRect(Handle,@ir,True); end; if key = VK_RIGHT then begin if FFocusLink < FNumHyperLinks - 1 then Inc(FFocusLink) else FFocusLink := 0; Key := 0; InvalidateRect(Handle,@ir,True); end; end; {$IFDEF TMSDEBUG} outputdebugstring(pchar('key focus link to : '+inttostr(ffocuslink))); {$ENDIF} end; end; inherited; if Key = VK_F2 then begin if (FFocusLink <> -1) and (ItemIndex >= 0) and (ItemIndex < Items.Count) then begin {$IFDEF TMSDEBUG} outputdebugstring(pchar('start edit for : '+inttostr(ffocuslink))); {$ENDIF} EditParam(ItemIndex, GetParamItemRefs(ItemIndex,FFocusLink)); end; end; end; function TParamListBox.GetParamIndex(href: string): Integer; var i: Integer; begin Result := -1; for i := 1 to ParamRefCount do begin if StrIComp(pchar(ParamRefs[i - 1]),pchar(href))=0 then begin Result := i - 1; Break; end; end; end; function TParamListBox.GetParamRect(href: string): TRect; var i: integer; cr: TRect; CID,CV,CT: string; begin {$IFDEF TMSDEBUG} outputdebugstring(pchar('get rect:'+inttostr(i))); {$ENDIF} i := FFocusLink + 1; IsParam(0,0,True,i,Result,cr,CID,CV,CT); end; procedure TParamListBox.EditParam(idx: Integer; href: string); begin if idx < 0 then Exit; ItemIndex := idx; StartParamEdit(href, idx, GetParamRect(href)); end; function EditCallBack (Wnd: HWND; uMsg: UINT; lParam, lpData: LPARAM): Integer; stdcall; var Temp: String; pt: TPoint; r: TRect; begin if uMsg = BFFM_INITIALIZED then begin with TParamListBox (lpData) Do begin {$WARNINGS OFF} // avoid platform specific warning if FEditValue = '' then Temp := GetCurrentDir else Temp := ExcludeTrailingBackslash (FEditValue); {WARNINGS ON} SendMessage (Wnd, BFFM_SETSELECTION, 1, Integer(PChar(Temp))); with TParamListBox(lpData) do begin pt := FEditPos; pt := ClientToScreen(pt); GetWindowRect(Wnd,r); if pt.X + (r.Right - r.Left) > Screen.DesktopWidth then pt.X := pt.X - (r.Right - r.Left); if pt.Y + (r.Bottom - r.Top) < Screen.DesktopHeight then SetWindowPos(wnd,HWND_NOTOPMOST,pt.X,pt.Y,0,0,SWP_NOSIZE or SWP_NOZORDER) else SetWindowPos(wnd,HWND_NOTOPMOST,pt.X,pt.Y-(r.Bottom - r.Top)-Height,0,0,SWP_NOSIZE or SWP_NOZORDER) end; end; end; Result := 0; end; procedure TParamListBox.StartParamDir(idx: integer; param, curdir: string; hr: TRect); var bi: TBrowseInfo; iIdList: PItemIDList; ResStr: array[0..MAX_PATH] of char; MAlloc: IMalloc; s:string; // BIF_NONEWFOLDERBUTTON begin FillChar(bi, sizeof(bi), #0); with bi do begin if curdir <> '' then StrPCopy(ResStr,curdir) else StrPCopy(ResStr,GetCurrentDir); FEditValue := resstr; FEditPos := Point(hr.Left,hr.Bottom); hwndOwner := Application.Handle; pszDisplayName := ResStr; lpszTitle := PChar('Select directory'); ulFlags := BIF_RETURNONLYFSDIRS; lpfn := EditCallBack; lParam := Integer(Self); end; iIdList := Nil; try iIdList := SHBrowseForFolder(bi); except end; if iIdList <> Nil then begin try FillChar(ResStr,sizeof(ResStr),#0); if SHGetPathFromIDList (iIdList, ResStr) then begin s := resstr; if Assigned(OnParamChanged) then OnParamChanged(Self, idx, param, curdir, s); SetParam(Param,s); end; finally SHGetMalloc(Malloc); Malloc.Free(iIdList); end; end; end; procedure TParamListBox.KeyPress(var Key: Char); begin inherited; if (FFocusLink <> -1) and (ItemIndex >= 0) and (ItemIndex < Items.Count) and (Key in [#13]) then begin {$IFDEF TMSDEBUG} outputdebugstring(pchar('start edit for : '+inttostr(ffocuslink))); {$ENDIF} if GetParamItemRefCount(ItemIndex) > 0 then EditParam(ItemIndex, GetParamItemRefs(ItemIndex,FFocusLink)); end; end; function TParamListBox.GetParamItemRefs(Item,Index: Integer): string; var j: Integer; s: string; flg: boolean; begin j := 0; Result := ''; if (ParamItemRefCount[Item] = 0) then Exit; s := Uppercase(Items[Item]); flg := false; while (pos('HREF="',s) > 0) do begin flg := true; if (Index = j) then begin Delete(s,1, pos('HREF="',s) + 5); if pos('"',s) > 0 then begin Delete(s,pos('"',s), length(s)); Result := s; end; Exit; end else j := j + 1; Delete(s,1, pos('HREF=',s) + 5); end; if (Index >= j) and flg then begin Result := GetParamItemRefs(Item,0); if Result <> '' then FFocusLink := 0; end; end; function TParamListBox.GetParamItemIndex(Index: Integer; href: string): Integer; var j: Integer; s,u: string; begin j := 0; Result := -1; s := Uppercase(Items[Index]); while (pos('HREF="',s) > 0) do begin Delete(s,1, pos('HREF="',s) + 5); if pos('"',s) > 0 then begin u := s; Delete(u,pos('"',u), length(u)); if UpperCase(href) = u then begin Result := j; Exit; end; end; j := j + 1; Delete(s,1, pos('"',s)); end; end; function TParamListBox.GetParamItemRefCount(Item: Integer): Integer; var s: string; begin Result := 0; s := Uppercase(Items[Item]); while (pos('HREF=',s) > 0) do begin Result := Result + 1 ; Delete(s,1, pos('HREF=',s) + 5); end; end; procedure TParamListBox.AdvanceEdit(Sender: TObject); var idx: Integer; s,v,c,p,h:string; begin if not FAdvanceOnReturn then Exit; if FFocusLink = -1 then Exit; idx := FFocusLink; s := ParamItemRefs[ItemIndex,idx]; idx := ParamIndex[s]; if idx < ParamRefCount - 1 then inc(idx) else idx := 0; s := ParamRefs[idx]; if (s <> '') then begin idx := ParamRefIndex[s]; ItemIndex := idx; FFocusLink := ParamItemIndex[idx, s]; GetParamInfo(idx,s, v,c,p,h); if c <> '' then StartParamEdit(s,idx,GetParamRect(s)); end; end; function TParamListBox.GetVersion: string; var vn: Integer; begin vn := GetVersionNr; Result := IntToStr(Hi(Hiword(vn)))+'.'+IntToStr(Lo(Hiword(vn)))+'.'+IntToStr(Hi(Loword(vn)))+'.'+IntToStr(Lo(Loword(vn))); end; function TParamListBox.GetVersionNr: Integer; begin Result := MakeLong(MakeWord(BLD_VER,REL_VER),MakeWord(MIN_VER,MAJ_VER)); end; procedure TParamListBox.SetVersion(const Value: string); begin end; end.
unit DocumentPrintAndExportSettingRes; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "View" // Модуль: "DocumentPrintAndExportSettingRes.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: UtilityPack::Class Shared Delphi Sand Box$UC::Document::View::Document::DocumentPrintAndExportSettingRes // // Ресурсы для настройки "Печать и экспорт" // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// {$Include w:\common\components\SandBox\VCM\sbDefine.inc} interface uses l3StringIDEx ; const { PrintAndExportKey } pi_Document_PrintAndExport = 'Документ/Печать и экспорт'; { Идентификатор настройки "Печать и экспорт" } pi_Document_PrintAndExport_Default = 'Документ/Печать и экспорт/Использовать для экспорта и печати размер шрифта, отображаемого на экране'; { Идентификатор настройки "Печать и экспорт"."Использовать для экспорта и печати размер шрифта, отображаемого на экране" } pi_Document_PrintAndExport_Custom = 'Документ/Печать и экспорт/Использовать для экспорта и печати следующий размер шрифта'; { Идентификатор настройки "Печать и экспорт"."Использовать для экспорта и печати следующий размер шрифта" } var { Локализуемые строки PrintAndExportValues } str_PrintAndExport_Default : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'PrintAndExport_Default'; rValue : 'Использовать для экспорта и печати размер шрифта, отображаемого на экране'); { Использовать для экспорта и печати размер шрифта, отображаемого на экране } str_PrintAndExport_Custom : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'PrintAndExport_Custom'; rValue : 'Использовать для экспорта и печати следующий размер шрифта'); { Использовать для экспорта и печати следующий размер шрифта } var { Локализуемые строки PrintAndExportName } str_PrintAndExport : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'PrintAndExport'; rValue : 'Печать и экспорт'); { Печать и экспорт } implementation uses l3MessageID ; initialization // Инициализация str_PrintAndExport_Default str_PrintAndExport_Default.Init; // Инициализация str_PrintAndExport_Custom str_PrintAndExport_Custom.Init; // Инициализация str_PrintAndExport str_PrintAndExport.Init; end.
unit Inner_Const; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "SandBox" // Модуль: "Inner_Const.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: Tag::Class Shared Delphi Sand Box::SandBox::Meta::Meta::Inner // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Константы для значений тега Inner . {$Include ..\SandBox\sbDefine.inc} interface uses k2Base {a} ; function k2_typInner: Tk2Type; implementation uses Meta_Schema, k2Facade {a} ; var g_Inner : Tk2Type = nil; // start class InnerTag function k2_typInner: Tk2Type; begin if (g_Inner = nil) then begin Assert(Tk2TypeTable.GetInstance Is TMetaSchema); g_Inner := TMetaSchema(Tk2TypeTable.GetInstance).t_Inner; end;//g_Inner = nil Result := g_Inner; end; end.
program cancelfactors1(input, output); { Computes partial sums of the harmonic series H(n) = 1 + (1 / 2) + ... + (1 / n) The result should be expressed in the form numerator / denominator, where numerator, and denominator are integers. } var numerator, denominator : integer; (* Divide numerator and denominator and their GCD *) procedure lowterm(var num, den : integer); var numcopy, dencopy, remainder : integer; begin numcopy := num; dencopy := den; while (dencopy <> 0) do begin remainder := numcopy mod dencopy; numcopy := dencopy; dencopy := remainder end; if numcopy > 1 then begin num := num div numcopy; den := den div numcopy end end; begin write('(a,b): '); read(numerator, denominator); lowterm(numerator, denominator); writeln(numerator, ' ', denominator); end.
unit LUX.GPU.Vulkan.Instan; interface //#################################################################### ■ uses System.Classes, vulkan_core, LUX.Data.List, LUX.GPU.Vulkan.Surfac, LUX.GPU.Vulkan.Device; type //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【型】 TVkInstans<TVulkan_:class> = class; TVkInstan<TVulkan_:class> = class; TVkInsInf<TVulkan_:class> = class; TVkAppInf<TVulkan_:class> = class; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkAppInf TVkAppInf<TVulkan_:class> = class private type TVkInsInf_ = TVkInsInf<TVulkan_>; protected _Parent :TVkInsInf_; _Inform :VkApplicationInfo; _Handle :P_VkApplicationInfo; ///// アクセス function GetKind :VkStructureType; procedure SetKind( const Kind_:VkStructureType ); function GetNext :Pointer; procedure SetNext( const Next_:Pointer ); function GetAppName :String; procedure SetAppName( const AppName_:String ); function GetAppVers :UInt32; procedure SetAppVers( const AppVers_:UInt32 ); function GetEngName :String; procedure SetEngName( const EngName_:String ); function GetEngVers :UInt32; procedure SetEngVers( const EngVers_:UInt32 ); function GetApiVers :UInt32; procedure SetApiVers( const ApiVersion_:UInt32 ); function GetHandle :P_VkApplicationInfo; procedure SetHandle( const Handle_:P_VkApplicationInfo ); public constructor Create; overload; virtual; constructor Create( const Parent_:TVkInsInf_ ); overload; virtual; destructor Destroy; override; ///// プロパティ property Parent :TVkInsInf_ read _Parent ; property Kind :VkStructureType read GetKind write SetKind ; property Next :Pointer read GetNext write SetNext ; property AppName :String read GetAppName write SetAppName; property AppVers :UInt32 read GetAppVers write SetAppVers; property EngName :String read GetEngName write SetEngName; property EngVers :UInt32 read GetEngVers write SetEngVers; property ApiVers :UInt32 read GetApiVers write SetApiVers; property Handle :P_VkApplicationInfo read GetHandle write SetHandle ; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkInsInf TVkInsInf<TVulkan_:class> = class private type TVkInstan_ = TVkInstan<TVulkan_>; TVkAppInf_ = TVkAppInf<TVulkan_>; protected _Parent :TVkInstan_; _Inform :VkInstanceCreateInfo; _Applic :TVkAppInf_; _Layeres :TStringList; _Extenss :TStringList; _Handle :P_VkInstanceCreateInfo; ///// アクセス function GetKind :VkStructureType; procedure SetKind( const Kind_:VkStructureType ); function GetNext :Pointer; procedure SetNext( const Next_:Pointer ); function GetFlags :VkInstanceCreateFlags; procedure SetFlags( const Flags_:VkInstanceCreateFlags ); function GetHandle :P_VkInstanceCreateInfo; procedure SetHandle( const Handle_:P_VkInstanceCreateInfo ); public constructor Create; overload; virtual; constructor Create( const Parent_:TVkInstan_ ); overload; virtual; destructor Destroy; override; ///// プロパティ property Parent :TVkInstan_ read _Parent ; property Kind :VkStructureType read GetKind write SetKind ; property Next :Pointer read GetNext write SetNext ; property Flags :VkInstanceCreateFlags read GetFlags write SetFlags ; property Applic :TVkAppInf_ read _Applic ; property Layeres :TStringList read _Layeres ; property Extenss :TStringList read _Extenss ; property Handle :P_VkInstanceCreateInfo read GetHandle write SetHandle; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkInstan TVkInstan<TVulkan_:class> = class( TListChildr<TVulkan_,TVkInstans<TVulkan_>> ) private type TVkInstans_ = TVkInstans<TVulkan_>; TVkInstan_ = TVkInstan <TVulkan_>; TVkInsInf_ = TVkInsInf <TVulkan_>; TVkSurfacs_ = TVkSurfacs<TVkInstan_>; TVkDevices_ = TVkDevices<TVkInstan_>; protected _Inform :TVkInsInf_; _Handle :VkInstance; _Surfacs :TVkSurfacs_; _Devices :TVkDevices_; ///// アクセス function GetHandle :VkInstance; procedure SetHandle( const Handle_:VkInstance ); ///// メソッド procedure CreateHandle; procedure DestroHandle; public constructor Create; overload; override; constructor Create( const Instans_:TVkInstans_ ); overload; override; constructor Create( const Vulkan_:TVulkan_ ); overload; virtual; destructor Destroy; override; ///// プロパティ property Vulkan :TVulkan_ read GetOwnere ; property Instans :TVkInstans_ read GetParent ; property Inform :TVkInsInf_ read _Inform ; property Handle :VkInstance read GetHandle write SetHandle ; property Surfacs :TVkSurfacs_ read _Surfacs ; property Devices :TVkDevices_ read _Devices write _Devices; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkInstans TVkInstans<TVulkan_:class> = class( TListParent<TVulkan_,TVkInstan<TVulkan_>> ) private type TVkInstan_ = TVkInstan<TVulkan_>; protected public ///// プロパティ property Vulkan :TVulkan_ read GetOwnere; ///// メソッド function Add :TVkInstan_; overload; end; //const //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【定数】 //var //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【変数】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】 implementation //############################################################### ■ uses System.AnsiStrings, vulkan_win32, LUX.GPU.Vulkan; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkAppInf //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// アクセス function TVkAppInf<TVulkan_>.GetKind :VkStructureType; begin Result := _Inform.sType; end; procedure TVkAppInf<TVulkan_>.SetKind( const Kind_:VkStructureType ); begin _Inform.sType := Kind_; Handle := nil; end; function TVkAppInf<TVulkan_>.GetNext :Pointer; begin Result := _Inform.pNext; end; procedure TVkAppInf<TVulkan_>.SetNext( const Next_:Pointer ); begin _Inform.pNext := Next_; Handle := nil; end; function TVkAppInf<TVulkan_>.GetAppName :String; begin Result := String( _Inform.pApplicationName ); end; procedure TVkAppInf<TVulkan_>.SetAppName( const AppName_:String ); begin _Inform.pApplicationName := PAnsiChar( AnsiString( AppName_ ) ); Handle := nil; end; function TVkAppInf<TVulkan_>.GetAppVers :UInt32; begin Result := _Inform.applicationVersion; end; procedure TVkAppInf<TVulkan_>.SetAppVers( const AppVers_:UInt32 ); begin _Inform.applicationVersion := AppVers_; Handle := nil; end; function TVkAppInf<TVulkan_>.GetEngName :String; begin Result := String( _Inform.pEngineName ); end; procedure TVkAppInf<TVulkan_>.SetEngName( const EngName_:String ); begin _Inform.pEngineName := PAnsiChar( AnsiString( EngName_ ) ); Handle := nil; end; function TVkAppInf<TVulkan_>.GetEngVers :UInt32; begin Result := _Inform.engineVersion; end; procedure TVkAppInf<TVulkan_>.SetEngVers( const EngVers_:UInt32 ); begin _Inform.engineVersion := EngVers_; Handle := nil; end; function TVkAppInf<TVulkan_>.GetApiVers :UInt32; begin Result := _Inform.apiVersion; end; procedure TVkAppInf<TVulkan_>.SetApiVers( const ApiVersion_:UInt32 ); begin _Inform.apiVersion := ApiVersion_; Handle := nil; end; //------------------------------------------------------------------------------ function TVkAppInf<TVulkan_>.GetHandle :P_VkApplicationInfo; begin if not Assigned( _Handle ) then _Handle := @_Inform; Result := _Handle; end; procedure TVkAppInf<TVulkan_>.SetHandle( const Handle_:P_VkApplicationInfo ); begin _Handle := Handle_; if Assigned( _Parent ) then _Parent.Handle := nil; end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TVkAppInf<TVulkan_>.Create; begin inherited; _Handle := nil; Kind := VK_STRUCTURE_TYPE_APPLICATION_INFO; Next := nil; AppName := 'Application'; AppVers := 1; EngName := 'Engine'; EngVers := 1; ApiVers := VK_API_VERSION_1_0; end; constructor TVkAppInf<TVulkan_>.Create( const Parent_:TVkInsInf_ ); begin Create; _Parent := Parent_; end; destructor TVkAppInf<TVulkan_>.Destroy; begin Handle := nil; inherited; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkInsInf //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// アクセス function TVkInsInf<TVulkan_>.GetKind :VkStructureType; begin Result := _Inform.sType; end; procedure TVkInsInf<TVulkan_>.SetKind( const Kind_:VkStructureType ); begin _Inform.sType := Kind_; Handle := nil; end; function TVkInsInf<TVulkan_>.GetNext :Pointer; begin Result := _Inform.pNext; end; procedure TVkInsInf<TVulkan_>.SetNext( const Next_:Pointer ); begin _Inform.pNext := Next_; Handle := nil; end; function TVkInsInf<TVulkan_>.GetFlags :VkInstanceCreateFlags; begin Result := _Inform.flags; end; procedure TVkInsInf<TVulkan_>.SetFlags( const Flags_:VkInstanceCreateFlags ); begin _Inform.flags := Flags_; Handle := nil; end; //------------------------------------------------------------------------------ function TVkInsInf<TVulkan_>.GetHandle :P_VkInstanceCreateInfo; var L, E :String; Ls, Es :TArray<PAnsiChar>; begin if not Assigned( _Handle ) then begin for L in _Layeres do Ls := Ls + [ System.AnsiStrings.StrNew( PAnsiChar( AnsiString( L ) ) ) ]; for E in _Extenss do Es := Es + [ System.AnsiStrings.StrNew( PAnsiChar( AnsiString( E ) ) ) ]; with _Inform do begin enabledLayerCount := Length( Ls ); ppEnabledLayerNames := @Ls[0]; enabledExtensionCount := Length( Es ); ppEnabledExtensionNames := @Es[0]; end; _Handle := @_Inform; end; Result := _Handle; end; procedure TVkInsInf<TVulkan_>.SetHandle( const Handle_:P_VkInstanceCreateInfo ); begin _Handle := Handle_; if Assigned( _Parent ) then _Parent.Handle := nil; end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TVkInsInf<TVulkan_>.Create; begin inherited; _Handle := nil; _Applic := TVkAppInf_.Create( Self ); _Layeres := TStringList.Create; _Extenss := TStringList.Create; Kind := VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; Next := nil; Flags := 0; Extenss.Add( VK_KHR_SURFACE_EXTENSION_NAME ); Extenss.Add( VK_KHR_WIN32_SURFACE_EXTENSION_NAME ); end; constructor TVkInsInf<TVulkan_>.Create( const Parent_:TVkInstan_ ); begin Create; _Parent := Parent_; end; destructor TVkInsInf<TVulkan_>.Destroy; begin _Applic .Free; _Layeres.Free; _Extenss.Free; Handle := nil; inherited; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkInstan //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// アクセス function TVkInstan<TVulkan_>.GetHandle :VkInstance; begin if not Assigned( _Handle ) then CreateHandle; Result := _Handle; end; procedure TVkInstan<TVulkan_>.SetHandle( const Handle_:VkInstance ); begin if Assigned( _Handle ) then DestroHandle; _Handle := Handle_; end; /////////////////////////////////////////////////////////////////////// メソッド procedure TVkInstan<TVulkan_>.CreateHandle; begin Assert( vkCreateInstance( _Inform.Handle, nil, @_Handle ) = VK_SUCCESS ); end; procedure TVkInstan<TVulkan_>.DestroHandle; begin vkDestroyInstance( _Handle, nil ); end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TVkInstan<TVulkan_>.Create; begin inherited; _Inform := TVkInsInf_.Create( Self ); _Handle := nil; _Surfacs := TVkSurfacs_.Create( Self ); _Devices := TVkDevices_.Create( Self ); end; constructor TVkInstan<TVulkan_>.Create( const Instans_:TVkInstans_ ); begin inherited; _Devices.FindDevices; end; constructor TVkInstan<TVulkan_>.Create( const Vulkan_:TVulkan_ ); begin Create( TVkInstans_( TVulkan( Vulkan_ ).Instans ) ); end; destructor TVkInstan<TVulkan_>.Destroy; begin _Devices.Free; _Surfacs.Free; Handle := nil; _Inform.Free; inherited; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkInstans //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public /////////////////////////////////////////////////////////////////////// メソッド function TVkInstans<TVulkan_>.Add :TVkInstan_; begin Result := TVkInstan_.Create( Self ); end; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】 //############################################################################## □ initialization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 初期化 finalization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 最終化 end. //######################################################################### ■
unit DAO.Clientes; interface uses FireDAC.Comp.Client, System.SysUtils, DAO.Conexao, Model.Clientes; type TClientesDAO = class private FConexao : TConexao; public constructor Create; function Inserir(ACliente: TClientes): Boolean; function Alterar(ACliente: TClientes): Boolean; function Excluir(ACliente: TClientes): Boolean; function Pesquisar(aParam: array of variant): TFDQuery; end; const TABLENAME = 'tbclientes'; implementation uses Control.Sistema; { TClientesDAO } function TClientesDAO.Alterar(ACliente: TClientes): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('UPDATE ' + TABLENAME + 'SET NOM_CLIENTE = :NOM_CLIENTE, VAL_VERBA = :VAL_VERBA, DOM_OS = :DOM_OS ' + 'WHERE COD_CLIENTE_EMPRESA = :COD_CLIENTE_EMPRESA AND COD_CLIENTE = :COD_CLIENTE;', [ACliente.Codigo, ACliente.Nome, ACliente.Verba, ACliente.OS, ACliente.Cliente, ACliente.Codigo]); Result := True; finally FDQuery.Free; end; end; constructor TClientesDAO.Create; begin FConexao := TSistemaControl.GetInstance().Conexao; end; function TClientesDAO.Excluir(ACliente: TClientes): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('delete from ' + TABLENAME + ' where COD_CLIENTE_EMPRESA = :COD_CLIENTE_EMPRESA and COD_CLIENTE = :COD_CLIENTE', [ACliente.Cliente, ACliente.Codigo]); Result := True; finally FDquery.Free; end; end; function TClientesDAO.Inserir(ACliente: TClientes): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('INSERT INTO ' + TABLENAME + ' (COD_CLIENTE_EMPRESA, COD_CLIENTE, NOM_CLIENTE, VAL_VERBA, DOM_OS) ' + 'VALUES ' + '(:COD_CLIENTE_EMPRESA, :COD_CLIENTE, :NOM_CLIENTE, :VAL_VERBA, :DOM_OS);', [ACliente.Cliente, ACliente.Codigo, ACliente.Nome, ACliente.OS]); Result := True; finally FDQuery.Free; end; end; function TClientesDAO.Pesquisar(aParam: array of variant): TFDQuery; var FDQuery: TFDQuery; begin FDQuery := FConexao.ReturnQuery(); if Length(aParam) < 2 then Exit; FDQuery.SQL.Clear; FDQuery.SQL.Add('select * from ' + TABLENAME); if aParam[0] = 'CODIGO' then begin FDQuery.SQL.Add('WHERE COD_CLIENTE_EMPRESA = :COD_CLIENTE_EMPRESA and COD_CLIENTE = :COD_CLIENTE'); FDQuery.ParamByName('COD_CLIENTE_EMPRESA').AsInteger := aParam[1]; FDQuery.ParamByName('COD_CLIENTE').AsInteger := aParam[2]; end; if aParam[0] = 'CLIENTE' then begin FDQuery.SQL.Add('WHERE COD_CLIENTE_EMPRESA = :COD_CLIENTE_EMPRESA'); FDQuery.ParamByName('COD_CLIENTE_EMPRESA').AsInteger := aParam[1]; end; if aParam[0] = 'NOME' then begin FDQuery.SQL.Add('WHERE NOM_CLIENTE LIKE :NOM_CLIENTE'); FDQuery.ParamByName('NOM_CLIENTE').AsString := aParam[1]; end; if aParam[0] = 'FILTRO' then begin FDQuery.SQL.Add('WHERE ' + aParam[1]); end; if aParam[0] = 'APOIO' then begin FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT ' + aParam[1] + ' FROM ' + TABLENAME + ' ' + aParam[2]); end; FDQuery.Open; Result := FDQuery; end; end.
unit hpp_forms; interface uses Graphics, Forms, TntStdCtrls, StdCtrls, Controls; procedure MakeFontsParent(Control: TControl); implementation // This procedure scans all control children and if they have // no ParentFont, sets ParentFont to true but reapplies font styles, // so even having parent font and size, controls remain bold or italic // // Of course it can be done cleaner and for all controls supporting fonts // property through TPropertyEditor and GetPropInfo, but then it would // need vcl sources to compile, so not a best alternative for open source plugin procedure MakeFontsParent(Control: TControl); var i: Integer; fs: TFontStyles; begin // Set TLabel & TtntLabel if (Control is TLabel) and (not TLabel(Control).ParentFont) then begin fs := TLabel(Control).Font.Style; TLabel(Control).ParentFont := True; TLabel(Control).Font.Style := fs; end; if (Control is TtntLabel) and (not TtntLabel(Control).ParentFont) then begin fs := TtntLabel(Control).Font.Style; TtntLabel(Control).ParentFont := True; TtntLabel(Control).Font.Style := fs; end; // Process children for i := 0 to Control.ComponentCount - 1 do begin if Control.Components[i] is TControl then begin MakeFontsParent(TControl(Control.Components[i])); end; end; end; end.
unit EMS.AD.Classes; interface uses System.SysUtils, System.Classes, Winapi.Windows, EMS.AD.Api; type /// <summary> /// Exception class for TEnumUserResult. /// </summary> EEnumUserResult = class(Exception); /// <summary> /// Enumeration for the result of the EnumUsers function. /// </summary> TEnumUserResult = ( /// <summary> /// The operation completed successfully. /// </summary> NERR_Success, /// <summary> /// The user does not have access to the requested information. /// </summary> ERROR_ACCESS_DENIED, /// <summary> /// The system call level is not correct. This error is returned if the /// level parameter is set to a value not supported. /// </summary> ERROR_INVALID_LEVEL, /// <summary> /// The buffer is too small to contain an entry. No information has been /// written to the buffer. /// </summary> NERR_BufTooSmall, /// <summary> /// The computer name is invalid. /// </summary> NERR_InvalidComputer, /// <summary> /// More entries are available. Specify a large enough buffer to receive /// all entries. /// </summary> ERROR_MORE_DATA); /// <summary> /// An enum type for the NetUserEnum filter value. /// </summary> TADFilter = ( /// <summary> /// Indicates that all normal user, trust data, and machine account data /// should be included. /// </summary> FILTER_ALL, /// <summary> /// Enumerates account data for users whose primary account is in another /// domain. This account type provides user access to this domain, but /// not to any domain that trusts this domain. The User Manager refers to /// this account type as a local user account. /// </summary> FILTER_TEMP_DUPLICATE_ACCOUNT, /// <summary> /// Enumerates normal user account data. This account type is associated /// with a typical user. /// </summary> FILTER_NORMAL_ACCOUNT, /// <summary> /// Enumerates interdomain trust account data. This account type is /// associated with a trust account for a domain that trusts other /// domains. /// </summary> FILTER_INTERDOMAIN_TRUST_ACCOUNT, /// <summary> /// Enumerates workstation or member server trust account data. This /// account type is associated with a machine account for a computer that /// is a member of the domain. /// </summary> FILTER_WORKSTATION_TRUST_ACCOUNT, /// <summary> /// Enumerates member server machine account data. This account type is /// associated with a computer account for a backup domain controller /// that is a member of the domain. /// </summary> FILTER_SERVER_TRUST_ACCOUNT); TEnumUserResultHelper = record helper for TEnumUserResult strict private const cIntegerValues: array[TEnumUserResult] of Integer = (TEMSADReturnConsts.NERR_Success, Winapi.Windows.ERROR_ACCESS_DENIED, Winapi.Windows.ERROR_INVALID_LEVEL, TEMSADReturnConsts.NERR_BufTooSmall, TEMSADReturnConsts.NERR_InvalidComputer, Winapi.Windows.ERROR_MORE_DATA); public /// <summary> /// Returns the high value of the enum type. /// </summary> class function High: TEnumUserResult; static; inline; /// <summary> /// Returns the low value of the enum type. /// </summary> class function Low: TEnumUserResult; static; inline; /// <summary> /// Converts an Integer to the enumeration type. Throws an EEnumUserResult /// if this is not possible. /// </summary> class function Parse(AValue: Integer): TEnumUserResult; overload; inline; static; /// <summary> /// Converts the enumeration type into the fitting integer const. /// </summary> function ToInteger: Integer; inline; end; /// <summary> /// Record helper for TADFilter. /// </summary> TADFilterHelper = record helper for TADFilter strict private const cIntegerValues: array[TADFilter] of Integer = (TEMSADFilterConsts.FILTER_ALL, TEMSADFilterConsts.FILTER_TEMP_DUPLICATE_ACCOUNT, TEMSADFilterConsts.FILTER_NORMAL_ACCOUNT, TEMSADFilterConsts.FILTER_INTERDOMAIN_TRUST_ACCOUNT, TEMSADFilterConsts.FILTER_WORKSTATION_TRUST_ACCOUNT, TEMSADFilterConsts.FILTER_SERVER_TRUST_ACCOUNT); public /// <summary> /// Converts the enumeration type into the fitting integer const. /// </summary> function ToInteger: Integer; overload; inline; /// <summary> /// Converts an array of the enumeration type into the fitting integer const. /// </summary> class function ToInteger(const AValues: TArray<TADFilter>): Integer; overload; static; inline; end; /// <summary> /// This class provides the ability to enumerate users and groups in a /// active directory. /// </summary> TEnumAD = record strict private /// <summary> /// Returns all groups for the Enum proc. /// </summary> class function InternalEnumGroups(const AServer: string; AEnumProc: TProc<string>): TEnumUserResult; static; /// <summary> /// Returns all groups for the Enum proc. /// </summary> class function InternalEnumGroupsOfAUser(const AServer, AUser: string; AEnumProc: TProc<string>): TEnumUserResult; static; /// <summary> /// Returns all filtered users and calls the anonymous method. /// </summary> class function InternalEnumUsers(const AServer: string; AFilter: Integer; AEnumProc: TProc<string>): TEnumUserResult; static; /// <summary> /// Returns all users of a group for the Enum proc. /// </summary> class function InternalEnumUsersOfAGroup(const AServer, AGroup: string; AEnumProc: TProc<string>): TEnumUserResult; static; /// <summary> /// Removes the Domain before a user: domain\user -> user /// </summary> class function RemoveDomain(const AUserName: string): string; static; public /// <summary> /// Finds out if the credentials domain, user and password are valid. /// </summary> class function CredentialsValid(const ADomain, AUser, APassword: string; out AError: string): Boolean; static; /// <summary> /// Returns all groups /// </summary> class function EnumGroups(const AServer: string; AGroups: TStrings): TEnumUserResult; static; /// <summary> /// Returns all groups of a user. /// </summary> class function EnumGroupsOfAUser(const AServer, AUser: string; AUsers: TStrings): TEnumUserResult; static; /// <summary> /// Returns all filtered users and calls the anonymous method. /// </summary> class function EnumUsers(const AServer: string; AFilter: TArray<TADFilter>; AEnumProc: TProc<string>): TEnumUserResult; overload; static; /// <summary> /// Returns all filtered users and calls the anonymous method. /// </summary> class function EnumUsers(const AServer: string; AEnumProc: TProc<string>): TEnumUserResult; overload; static; /// <summary> /// Returns all normal users /// </summary> class function EnumUsers(const AServer: string; AUsers: TStrings): TEnumUserResult; overload; static; /// <summary> /// Returns all users of a group. /// </summary> class function EnumUsersOfAGroup(const AServer, AGroup: string; AEnumProc: TProc<string>): TEnumUserResult; overload; static; /// <summary> /// Returns all users of a group. /// </summary> class function EnumUsersOfAGroup(const AServer, AGroup: string; AUsers: TStrings): TEnumUserResult; overload; static; end; resourcestring SInvalidEnumUserResult = 'Invalid EnumUserResult [%d]!'; implementation { TEnumUserResultHelper } class function TEnumUserResultHelper.High: TEnumUserResult; begin Result := System.High(Result); end; class function TEnumUserResultHelper.Low: TEnumUserResult; begin Result := System.Low(Result); end; class function TEnumUserResultHelper.Parse(AValue: Integer): TEnumUserResult; begin for Result := Low to High do begin if Result.ToInteger = AValue then Exit; end; raise EEnumUserResult.CreateFmt(SInvalidEnumUserResult, [AValue]); end; function TEnumUserResultHelper.ToInteger: Integer; begin Result := cIntegerValues[Self]; end; { TADFilterHelper } function TADFilterHelper.ToInteger: Integer; begin Result := cIntegerValues[Self]; end; class function TADFilterHelper.ToInteger(const AValues: TArray<TADFilter>): Integer; var iValue: TADFilter; begin Result := 0; for iValue in AValues do Result := Result + iValue.ToInteger; end; { TEnumAD } class function TEnumAD.CredentialsValid(const ADomain, AUser, APassword: string; out AError: string): Boolean; var iToken: THandle; begin Result := LogonUser(PChar(AUser), PChar(ADomain), PChar(APassword), LOGON32_LOGON_BATCH, LOGON32_PROVIDER_DEFAULT, iToken); if Result then begin CloseHandle(iToken); AError := ''; end else AError := SysErrorMessage(GetLastError); end; class function TEnumAD.EnumGroups(const AServer: string; AGroups: TStrings): TEnumUserResult; begin Result := InternalEnumGroups(AServer, procedure(AGroupName: string) begin AGroups.Add(AGroupName); end); end; class function TEnumAD.EnumGroupsOfAUser(const AServer, AUser: string; AUsers: TStrings): TEnumUserResult; begin Result := InternalEnumGroupsOfAUser(AServer, AUser, procedure(AGroupName: string) begin AUsers.Add(AGroupName); end); end; class function TEnumAD.EnumUsers(const AServer: string; AFilter: TArray<TADFilter>; AEnumProc: TProc<string>): TEnumUserResult; begin Result := InternalEnumUsers(AServer, TADFilter.ToInteger(AFilter), AEnumProc); end; class function TEnumAD.EnumUsers(const AServer: string; AEnumProc: TProc<string>): TEnumUserResult; begin Result := InternalEnumUsers(AServer, 0, AEnumProc); end; class function TEnumAD.EnumUsers(const AServer: string; AUsers: TStrings): TEnumUserResult; begin Result := InternalEnumUsers(AServer, 0, procedure(AUserName: string) begin AUsers.Add(AUserName); end); end; class function TEnumAD.EnumUsersOfAGroup(const AServer, AGroup: string; AEnumProc: TProc<string>): TEnumUserResult; begin Result := InternalEnumUsersOfAGroup(AServer, AGroup, AEnumProc); end; class function TEnumAD.EnumUsersOfAGroup(const AServer, AGroup: string; AUsers: TStrings): TEnumUserResult; begin Result := InternalEnumUsersOfAGroup(AServer, AGroup, procedure(AUserName: string) begin AUsers.Add(AUserName) end); end; class function TEnumAD.InternalEnumGroups(const AServer: string; AEnumProc: TProc<string>): TEnumUserResult; var pGroupInfo: Pointer; pWork: Pointer; iEntriesRead: DWORD; iEntriesTotal: DWORD; iNetResult: DWORD; iCount: Integer; begin pGroupInfo := nil; pWork := nil; try iNetResult := NetLocalGroupEnum(PChar(AServer), 0, pGroupInfo, TEMSADConsts.MAX_PREFERRED_LENGTH, iEntriesRead, iEntriesTotal, nil); if (iNetResult = TEMSADReturnConsts.NERR_SUCCESS) and (iEntriesRead > 0) then begin pWork := pGroupInfo; if Assigned(AEnumProc) then begin for iCount := 0 to iEntriesRead - 1 do begin AEnumProc(PLocalGroupInfo0(pGroupInfo)^.lgrpi0_name); Inc(NativeInt(pGroupInfo), SizeOf(Pointer)); end; end; end; finally NetApiBufferFree(pWork) end; Result := TEnumUserResult.Parse(iNetResult); end; class function TEnumAD.InternalEnumGroupsOfAUser(const AServer, AUser: string; AEnumProc: TProc<string>): TEnumUserResult; var pGroupInfo: Pointer; pWork: Pointer; iNetResult: DWORD; iEntriesRead: DWORD; iEntriesTotal: DWORD; iCount: Integer; begin pGroupInfo := nil; pWork := nil; try iNetResult := NetUserGetLocalGroups(PChar(AServer), PChar(AUser), 0, 0, pGroupInfo, TEMSADConsts.MAX_PREFERRED_LENGTH, iEntriesRead, iEntriesTotal); if (iNetResult = TEMSADReturnConsts.NERR_SUCCESS) and (iEntriesRead > 0) then begin pwork := pGroupInfo; if Assigned(AEnumProc) then begin for iCount := 0 to iEntriesRead - 1 do begin AEnumProc(PGroupInfo0(pGroupInfo)^.grpi0_name); Inc(NativeInt(pGroupInfo), SizeOf(Pointer)); end; end; end; finally NetApiBufferFree(pWork); end; Result := TEnumUserResult.Parse(iNetResult); end; class function TEnumAD.InternalEnumUsers(const AServer: string; AFilter: Integer; AEnumProc: TProc<string>): TEnumUserResult; var pUserInfo: Pointer; pWork: Pointer; iEntriesRead: DWORD; iEntriesTotal: DWORD; iNetResult: DWORD; iCount: Integer; begin pUserInfo := nil; pWork := nil; try iNetResult := NetUserEnum(PChar(AServer), 0, AFilter, pUserInfo, TEMSADConsts.MAX_PREFERRED_LENGTH, iEntriesRead, iEntriesTotal, nil); if (iNetResult = TEMSADReturnConsts.NERR_SUCCESS) and (iEntriesRead > 0) then begin pWork := pUserInfo; if Assigned(AEnumProc) then begin for iCount := 0 to iEntriesRead - 1 do begin AEnumProc(PUserInfo1(pUserInfo)^.usri1_name); Inc(NativeInt(pUserInfo), Sizeof(Pointer)); end; end; end; finally NetApiBufferFree(pWork); end; Result := TEnumUserResult.Parse(iNetResult); end; class function TEnumAD.InternalEnumUsersOfAGroup(const AServer, AGroup: string; AEnumProc: TProc<string>): TEnumUserResult; var pInfo3: Pointer; pWork: Pointer; iEntriesRead: DWORD; iEntriesTotal: DWORD; iNetResult: NET_API_STATUS; iCount: Integer; begin pInfo3 := nil; pWork := nil; try iNetResult := NetLocalGroupGetMembers(PChar(AServer), PChar(AGroup), 3, pInfo3, TEMSADConsts.MAX_PREFERRED_LENGTH, iEntriesRead, iEntriesTotal, nil); if (iNetResult = TEMSADReturnConsts.NERR_SUCCESS) and (iEntriesRead > 0) then begin pWork := pInfo3; if Assigned(AEnumProc) then begin for iCount := 0 to iEntriesRead - 1 do begin AEnumProc(RemoveDomain(PLocalGroupMembersInfo3(pInfo3)^.lgrmi3_domainandname)); Inc(NativeInt(pInfo3), SizeOf(Pointer)); end; end; end; finally NetApiBufferFree(pWork); end; Result := TEnumUserResult.Parse(iNetResult); end; class function TEnumAD.RemoveDomain(const AUserName: string): string; const cDomainDeli = '\'; var iIndex: Integer; begin iIndex := AUserName.IndexOf(cDomainDeli); if iIndex > -1 then Result := AUserName.Remove(0, iIndex + 1) else Result := AUserName; end; end.
unit cFuncao; interface uses System.Classes, Vcl.Controls, Winapi.Windows, Vcl.ExtCtrls, Vcl.Dialogs, FireDAC.Comp.Client, System.SysUtils,cAcaoAcesso,cUsuarioLogado,Vcl.Forms ,Vcl.Imaging.jpeg,Vcl.Imaging.pngimage,Vcl.Graphics,Vcl.ExtDlgs,IdComponent, IdTCPConnection, IdTCPClient, IdHTTP, IdBaseComponent, IdMessage, IdExplicitTLSClientServerBase, IdMessageClient, IdSMTPBase, IdSMTP, IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack, IdSSL, IdSSLOpenSSL, IdAttachmentFile,IdText; type TFuncao = class private public class procedure CriarForm(aNomeForm: TFormClass;oUsuarioLogado:TUsuarioLogado;aConexao: TFDConnection);static; class procedure CarregarImagem(aImage:TImage);static; class procedure LimparImagem(var aImage:TImage);static; class function ExtensoMes(n: Integer): String; static; class function SqlValor(sql:string; aConexao: TFDConnection):String;static; class function ExecuteSQL(sql: string; aConexao: TFDConnection): Boolean;static; class function EnviarEmail(const AAssunto, ADestino, AAnexo: String; ACorpo: TStrings): Boolean; static; class function VerificarBackup(): String; static; end; implementation uses uPrincipal; { TFuncao } class procedure TFuncao.CarregarImagem(aImage: TImage); var Bmp, BmpTrans: TBitmap; Jpg: TJPEGImage; Pic: TPicture; Png: TPngImage; opdSelecionar:TOpenPictureDialog; iWidth:Integer; iHeight:Integer; begin Try iWidth:=160; iHeight:=130; opdSelecionar:=TOpenPictureDialog.Create(nil); opdSelecionar.Filter:='All (*.bmp;*.jpg; *.jpeg;*.png)|*.jpg; *.jpeg; *.bmp;*.png|Bitmaps '+ '(*.bmp)|*.bmp|JPEG Image File (*.jpg;*.jpeg)|*.jpg; *.jpeg| '+ 'PNG(*.png)|*.png'; opdSelecionar.Title:='Selecione a Imagem'; opdSelecionar.Execute; if opdSelecionar.FileName<>EmptyStr then begin if (Pos('.JPG',UpperCase(opdSelecionar.FileName))>0) or ( Pos('.JPEG',UpperCase(opdSelecionar.FileName))>0) then begin Bmp := TBitmap.Create; Jpg := TJPEGImage.Create; Pic := TPicture.Create; try Pic.LoadFromFile(opdSelecionar.FileName); Jpg.Assign(Pic); Jpg.CompressionQuality :=7; Bmp.Width :=iWidth; Bmp.Height :=iHeight; Bmp.Canvas.StretchDraw(Rect(0, 0, Bmp.width, Bmp.Height), Jpg); aImage.Picture.Bitmap:=Bmp; finally Pic.Free; Jpg.Free; Bmp.Free; end End else if Pos('.PNG',UpperCase(opdSelecionar.FileName))>0 then begin Bmp := TBitmap.Create; png := TPngImage.Create; Pic := TPicture.Create; try Pic.LoadFromFile(opdSelecionar.FileName); png.Assign(Pic); Bmp.Width :=iWidth; Bmp.Height :=iHeight; Bmp.Canvas.StretchDraw(Rect(0, 0, Bmp.width, Bmp.Height), png); aImage.Picture.Bitmap:=Bmp; finally Pic.Free; png.Free; Bmp.Free; end end else begin try Bmp := TBitmap.Create; BmpTrans:= TBitmap.Create; Pic := TPicture.Create; Pic.LoadFromFile(opdSelecionar.FileName); BmpTrans.Assign(Pic.Bitmap); Bmp.Width :=iWidth; Bmp.Height:=iHeight; Bmp.Canvas.StretchDraw(Rect(0, 0, Bmp.width, Bmp.Height), BmpTrans); aImage.Picture.Bitmap:=Bmp; finally Pic.Free; BmpTrans.Free; Bmp.Free; end; end; end; Finally FreeAndNil(opdSelecionar); End; end; class procedure TFuncao.CriarForm(aNomeForm: TFormClass; oUsuarioLogado: TUsuarioLogado; aConexao: TFDConnection); var form: TForm; begin try form := aNomeForm.Create(Application); if TUsuarioLogado.TenhoAcesso(oUsuarioLogado.codigo, form.Name, aConexao) then begin frmprincipal.pgcDashs.visible:= false; form.ShowModal; end else begin MessageDlg('Usuário: ' + oUsuarioLogado.nome + ', não tem permissão de acesso', mtWarning, [mbOK], 0); Abort; end; finally if Assigned(form) then form.Release; frmprincipal.pgcDashs.visible:= true; end; end; class procedure TFuncao.LimparImagem(var aImage: TImage); begin aImage.Picture.Assign(nil); end; class function TFuncao.SqlValor(sql: string; aConexao: TFDConnection): String; var Qry: TFDQuery; begin try Result := ''; Qry := TFDQuery.Create(nil); Qry.Connection := aConexao; Qry.SQL.Clear; Qry.SQL.Add(sql); Qry.Open; Result := Qry.FieldByName('VALOR').AsString; finally Qry.Close; if Assigned(Qry) then FreeAndNil(Qry) end; end; class function TFuncao.EnviarEmail(const AAssunto, ADestino, AAnexo: String; ACorpo: TStrings): Boolean; var sFrom : String; sBccList : String; sHost : String; iPort : Integer; sUserName : String; sPassword : String; idMsg : TIdMessage; IdText : TIdText; idSMTP : TIdSMTP; IdSSLIOHandlerSocket : TIdSSLIOHandlerSocketOpenSSL; begin try try sFrom := 'albericoleite@gmal.com'; sBccList := 'albericoleite@gmal.com'; sHost := 'smtp.gmail.com'; iPort := 465; sUserName := 'splendorgestao@gmail.com'; sPassword := 'Splendor@2019'; //Configura os parâmetros necessários para SSL IdSSLIOHandlerSocket := TIdSSLIOHandlerSocketOpenSSL.Create(); IdSSLIOHandlerSocket.SSLOptions.Method := sslvSSLv23; IdSSLIOHandlerSocket.SSLOptions.Mode := sslmClient; //Variável referente a mensagem idMsg := TIdMessage.Create(); idMsg.CharSet := 'utf-8'; idMsg.Encoding := meMIME; idMsg.From.Name := 'TDevRocks Newsletter'; idMsg.From.Address := sFrom; idMsg.Priority := mpNormal; idMsg.Subject := AAssunto; //Add Destinatário(s) idMsg.Recipients.Add; idMsg.Recipients.EMailAddresses := ADestino; idMsg.CCList.EMailAddresses := 'albericoleite@gmail.com'; idMsg.BccList.EMailAddresses := sBccList; idMsg.BccList.EMailAddresses := 'albericoleite@gmail.com'; //Cópia Oculta //Variável do texto idText := TIdText.Create(idMsg.MessageParts); idText.Body.Add(ACorpo.Text); idText.ContentType := 'text/html; text/plain; charset=iso-8859-1'; //Prepara o Servidor IdSMTP := TIdSMTP.Create(); IdSMTP.IOHandler := IdSSLIOHandlerSocket; IdSMTP.UseTLS := utUseImplicitTLS; IdSMTP.AuthType := satDefault; IdSMTP.Host := sHost; IdSMTP.AuthType := satDefault; IdSMTP.Port := iPort; IdSMTP.Username := sUserName; IdSMTP.Password := sPassword; //Conecta e Autentica IdSMTP.Connect; IdSMTP.Authenticate; // if AAnexo &amp;lt;&amp;gt; EmptyStr then // if FileExists(AAnexo) then // TIdAttachmentFile.Create(idMsg.MessageParts, AAnexo); //Se a conexão foi bem sucedida, envia a mensagem if IdSMTP.Connected then begin try IdSMTP.Send(idMsg); except on E:Exception do begin ShowMessage('Erro ao tentar enviar: ' + E.Message); end; end; end; //Depois de tudo pronto, desconecta do servidor SMTP if IdSMTP.Connected then IdSMTP.Disconnect; Result := True; finally //IniFile.Free; UnLoadOpenSSLLibrary; FreeAndNil(idMsg); FreeAndNil(IdSSLIOHandlerSocket); FreeAndNil(idSMTP); end; except on e:Exception do begin Result := False; end; end; end; class function TFuncao.ExecuteSQL(sql: string; aConexao: TFDConnection): Boolean; var Qry:TFDQuery; begin try Result:=true; Qry:=TFDQuery.Create(nil); Qry.Connection:= aConexao; Qry.SQL.Clear; Qry.SQL.Add(sql); try aConexao.StartTransaction; Qry.ExecSQL; aConexao.Commit; except aConexao.Rollback; Result:=false; end; finally if Assigned(Qry) then FreeAndNil(Qry) end; end; class function TFuncao.ExtensoMes(n: Integer): String; const aMeses: Array[0..11] of String = ( 'Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'); begin Result := ''; if (n > 1) and (n < 12) then Result := aMeses[n-1]; end; class function TFuncao.VerificarBackup(): String; var NomeArquivo,nomex: string; xArquivoBat : TStringList; begin nomex:= FormatDateTime('ddmmyyyy',Now)+'.sql'; NomeArquivo := 'C:\mysql\Backup\'+nomex; if not FileExists(NomeArquivo) then begin //raise Exception.CreateFmt('Backup não Realizado, iniciando backup automático...!', [NomeArquivo]); Try xArquivoBat := TStringList.Create; xArquivoBat.Add('@echo off'); xArquivoBat.Add('@echo.'); xArquivoBat.Add('echo #################################################'); xArquivoBat.Add('echo #################################################'); xArquivoBat.Add('echo ### ###'); xArquivoBat.Add('echo ### ###'); xArquivoBat.Add('echo ### Backup automático ###'); xArquivoBat.Add('echo ### ###'); xArquivoBat.Add('echo ### ###'); xArquivoBat.Add('echo #################################################'); xArquivoBat.Add('echo #################################################'); xArquivoBat.Add('cd C:\mysql\bin\'); xArquivoBat.Add('mysqldump.exe -u root -pjulia --databases igreja > "C:\mysql\Backup\'+nomex); //xArquivoBat.Add('mysqldump.exe -uroot --p'+FSenha +' --databases '+FNomeBancoDados +' > "C:\mysql\Backup\backup_'+nome); // backup.sql"'); //xArquivoBat.Add('pause'); xArquivoBat.SaveToFile('BackupMySQL.bat'); WinExec('BackupMySQL.bat', SW_HIDE); Finally FreeAndNil(xArquivoBat); End; Application.MessageBox('Backup realizado com sucesso!','Atenção!') ; end; end; end.
unit uLogManager; interface uses Windows, SysUtils, SyncObjs, uSingletonTemplate; type TLogMsgType = (lmtInfo, lmtWarning, lmtError); TLogMsgLevel = (lmlMax, lmlInfo, lmlDebug); TLogManagerEvent = procedure(const aLogMsgText: string; aLogMsgType: TLogMsgType); TLogManagerEventObj = procedure(const aLogMsgText: string; aLogMsgType: TLogMsgType) of object; TLogManager = class(TSingleton) private fcs : TCriticalSection; fFileName : string; // файл лога fMaxLogLevel : TLogMsgLevel; // уровень, который опредеяет записывать сообщение или нет fLogEvent : boolean; // вызывать свойства? fOnLogEvent : TLogManagerEvent; fOnLogEventObj : TLogManagerEventObj; function FormatLogTime(aDT: TDateTime): string; function FormatLogMsgType(aLogMsgType: TLogMsgType): string; function FormatLogMsgText(aText: string; aLogMsgType: TLogMsgType): string; procedure DoLogEvent(aLogMsgText: string; aLogMsgType: TLogMsgType; aWriteToEvent: boolean); protected constructor Create; override; public procedure WriteToLog(aText: string; aLogMsgType: TLogMsgType = lmtInfo; aLvl: TLogMsgLevel = Low(TLogMsgLevel); aWriteToEvent: boolean = True); public destructor Destroy; override; property FileName: string read fFileName write fFileName; // куда писать property MaxLogLevel: TLogMsgLevel read fMaxLogLevel write fMaxLogLevel; // максимальный доступный уровень property LogEvent: boolean read fLogEvent write fLogEvent; // вызывать события лога? property OnLogEvent: TLogManagerEvent read fOnLogEvent write fOnLogEvent; // событие лога property OnLogEventObj: TLogManagerEventObj read fOnLogEventObj write fOnLogEventObj; // событие лога для объектов end; // funcs function LogMng: TLogManager; implementation function LogMng: TLogManager; begin Result := TLogManager.GetInstance; end; { TLogManager } constructor TLogManager.Create; begin inherited; fcs := TCriticalSection.Create; fFileName := ''; fMaxLogLevel := High(TLogMsgLevel); fLogEvent := False; end; destructor TLogManager.Destroy; begin fcs.Enter; try finally fcs.Leave; end; fcs.Free; inherited; end; function TLogManager.FormatLogTime(aDT: TDateTime): string; begin DateTimeToString(Result, '[dd.mm.yyyy] [hh:mm:ss]', aDT); end; function TLogManager.FormatLogMsgType(aLogMsgType: TLogMsgType): string; begin case aLogMsgType of lmtInfo: Result := '[Info]'; lmtWarning: Result := '[Warning]'; lmtError: Result := '[Error]'; end; end; function TLogManager.FormatLogMsgText(aText: string; aLogMsgType: TLogMsgType): string; begin Result := format('%s %s: %s', [FormatLogTime(Now), FormatLogMsgType(aLogMsgType), aText]); end; procedure TLogManager.DoLogEvent(aLogMsgText: string; aLogMsgType: TLogMsgType; aWriteToEvent: boolean); begin if not fLogEvent or not aWriteToEvent then Exit; if Assigned(fOnLogEvent) then fOnLogEvent(aLogMsgText, aLogMsgType); if Assigned(fOnLogEventObj) then fOnLogEventObj(aLogMsgText, aLogMsgType); end; procedure TLogManager.WriteToLog(aText: string; aLogMsgType: TLogMsgType; aLvl: TLogMsgLevel; aWriteToEvent: boolean); var fh : THandle; lmsg : string; card : cardinal; begin if fFileName = '' then begin lmsg := FormatLogMsgText(aText, aLogMsgType); lmsg := Format('%s: %s', [FormatLogMsgType(lmtError), 'Не определён файл логирования! LogMsg: ' + lmsg]); DoLogEvent(lmsg, lmtError, True); Exit; end; if aLvl > fMaxLogLevel then Exit; fh := CreateFile(PChar(fFileName), GENERIC_WRITE, FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); if fh = INVALID_HANDLE_VALUE then begin lmsg := FormatLogMsgText(aText, aLogMsgType); lmsg := Format('%s: %s', [FormatLogMsgType(lmtError), 'Ошибка лог-файла: INVALID_HANDLE_VALUE. LogMsg: ' + lmsg]); DoLogEvent(lmsg, lmtError, True); Exit; end; fcs.Enter; try // формируем сообщение lmsg := FormatLogMsgText(aText, aLogMsgType); DoLogEvent(lmsg, aLogMsgType, aWriteToEvent); lmsg := lmsg + #13#10; try SetFilePointer(fh, 0, nil, FILE_END); WriteFile(fh, lmsg[1], sizeof(lmsg[1]) * length(lmsg), card, nil); except on E: Exception do begin lmsg := Format('%s: %s', [FormatLogMsgType(lmtError), 'Ошибка записи в файл лога: ' + E.ClassName + ': ' + E.Message]); DoLogEvent(lmsg, lmtError, True); end; Else begin lmsg := Format('%s: %s', [FormatLogMsgType(lmtError), 'Неизвестная ошибка в TLogManager.WriteToLog!']); DoLogEvent(lmsg, lmtError, True); end; end; finally CloseHandle(fh); fcs.Leave; end; end; end.
unit UnitInventory; interface uses System.Generics.Collections, SysUtils, Com_BaseObject, UnitDataInterfaces,FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.VCLUI.Wait, Data.DB, FireDAC.Comp.Client; Type TStockItem = class(TBaseObject) private FProductCode : String; FQuantityOnHand : Integer; FLastStockQuantity : Integer; public Constructor Create( anItemCode: String; anOnHand : Integer; aLastQuantity : Integer); property ProductCode : String read FProductCode; property QuantityOnHand : Integer read FQuantityOnHand; property LastStockQuantity : Integer read FLastStockQuantity; end; TInventory = class(TBaseObject) private FDConn: TFDConnection; FFDQueryStockItem : TFDQuery; FFDQueryProduct : TFDQuery; FStockItemList : TList<TStockItem>; FDataSourceStockItems: TDataSource; FDataSourceProducts: TDataSource; procedure AfterScroll(DataSet: TDataSet); public Constructor Create(aDataConn : IDataConnection); Destructor Destroy; procedure AddStockItem(anItem: TStockItem); procedure AddItemToDatabase(anItem: TStockItem); procedure Find(aStr : String); property StockItemList : TList<TStockItem> read FStockItemList; property FDQueryProduct : TFDQuery read FFDQueryProduct; property DataSourceStockItems : TDataSource read FDataSourceStockItems; property DataSourceProducts : TDataSource read FDataSourceProducts; end; implementation Constructor TStockItem.Create( anItemCode: String; anOnHand : Integer; aLastQuantity : Integer); begin inherited Create; FProductCode := anItemCode; FQuantityOnHand := anOnHand; FLastStockQuantity := aLastQuantity; end; procedure TInventory.Find(aStr : String); begin FFDQueryStockItem.Filtered := False; FFDQueryStockItem.Filter := 'PRODUCTCODE Like ' + QuotedStr('%'+aStr+'%'); FFDQueryStockItem.Filtered := True; end; Constructor TInventory.Create(aDataConn : IDataConnection); begin inherited Create; FDConn := aDataConn.FDConn; FFDQueryStockItem := TFDQuery.Create(nil); FFDQueryStockItem.Connection := FDConn; FFDQueryProduct := TFDQuery.Create(NIL); FFDQueryProduct.Connection := FDConn; FStockItemList := TList<TStockItem>.Create; with FFDQueryStockItem do begin SQL.Text := 'select * from STOCKITEM'; Open; end; with FFDQueryProduct do begin SQL.Text := 'select * from PRODUCT where PRODUCTCODE = :PRODUCTCODE'; end; FDataSourceStockItems := TDataSource.Create(nil); FDataSourceStockItems.DataSet := FFDQueryStockItem; FDataSourceProducts := TDataSource.Create(nil); FDataSourceProducts.DataSet := FFDQueryProduct; FFDQueryStockItem.AfterScroll := AfterScroll; end; procedure TInventory.AfterScroll(DataSet: TDataSet); begin with FFDQueryProduct do begin Close; ParamByName('PRODUCTCODE').AsString := FFDQueryStockItem.FieldByName('PRODUCTCODE').AsString; open; end; end; procedure TInventory.AddStockItem(anItem: TStockItem); begin FStockItemList.Add(anItem); end; procedure TInventory.AddItemToDatabase(anItem: TStockItem); begin with FFDQueryStockItem do begin SQL.Text := 'select * from STOCKITEM'; Open; Append; FieldByName('STOCKITEMID').AsInteger := 650; FieldByName('PRODUCTCODE').AsString := anItem.FProductCode; FieldByName('QUANTITYONHAND').AsInteger := anItem.FQuantityOnHand; FieldByName('LASTSTOCKQUQNTITY').AsInteger := anItem.FLastStockQuantity; FieldByName('ADDEDON').AsDateTime := Now; Post; end; end; Destructor TInventory.Destroy; begin inherited; FreeAndNil(FStockItemList); end; end.
{$mode objfpc}{$H+} {** * Mini Edit * * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) * @author Zaher Dirkey *} unit ntvBoard; interface uses Messages, SysUtils, Classes, Controls, LCLIntf, LCLType, Forms, Graphics, Contnrs, ImgList, StdCtrls, ExtCtrls, mnClasses; const cWedgeCursors: array[0..7] of TCursor = (crSizeNWSE, crSizeNS, crSizeNESW, crSizeWE, crSizeNWSE, crSizeNS, crSizeNESW, crSizeWE); cWedgeSize = 4; cBoardWidth = 600; cBoardHeight = 400; cSnapSize = 10; type TPointArray = array of TPoint; TLayout = class; TLayouts = class; TElement = class; TElements = class; TReceiver = class; TContainer = class; TCustomBoard = class; TReceiverClass = class of TReceiver; TSizableElement = class; { TReceiver } TReceiver = class(TObject) public Finished: Boolean; //temporary Board: TCustomBoard; constructor Create(ABoard: TCustomBoard); function MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; virtual; function MouseMove(Shift: TShiftState; X, Y: Integer): Boolean; virtual; function MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; virtual; function MouseWheel(Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint): Boolean; virtual; function KeyDown(var Key: Word; Shift: TShiftState): Boolean; virtual; end; { TWedge wedge stake pin} TWedgeInfo = record ReceiverClass: TReceiverClass; Cursor: TCursor; end; TWedge = class(TObject) private function PointToWedgeRect(P: TPoint): TRect; protected Point: TPoint; Info: TWedgeInfo; procedure Paint(vCanvas: TCanvas; Active: Boolean); virtual; function IsOver(P: TPoint): Boolean; virtual; end; { TWedges } TWedges = class(specialize TmnObjectList<TWedge>) private public function Add(x, y: Integer; Cursor: TCursor = crDefault; ReceiverClass: TReceiverClass = nil): TWedge; procedure Paint(Element: TSizableElement; vCanvas: TCanvas; Active: Boolean); virtual; procedure UpdateItems(Element: TSizableElement); virtual; function FindAt(Element: TSizableElement; P: TPoint; out vWedgeIndex: Integer): Boolean; end; { TSizeWedges } TSizeWedges = class(TWedges) public procedure UpdateItems(Element: TSizableElement); override; constructor Create; end; { TElement } TElement = class(TPersistent) private FColor: TColor; FContainer: TContainer; FUpdateCount: Integer; function GetSelected: Boolean; procedure SetSelected(const Value: Boolean); procedure SetContainer(const Value: TContainer); protected function ScalePoint(P: TPoint): TPoint; function ScaleRect(R: TRect): TRect; function SnapPoint(P: TPoint): TPoint; function SnapRect(R: TRect): TRect; function MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; virtual; function MouseMove(Shift: TShiftState; X, Y: Integer): Boolean; virtual; function MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; virtual; procedure BeginUpdate; virtual; procedure Updating; virtual; procedure EndUpdate; virtual; procedure Update(Shift: TShiftState; X, Y: Integer); virtual; procedure Change; virtual; public constructor Create(AOwner: TContainer); overload; virtual; constructor Create(AOwner: TContainer; X: Integer; Y: Integer); overload; virtual; destructor Destroy; override; procedure AfterConstruction; override; procedure AfterCreate(X, Y: Integer; Dummy: Boolean); virtual; procedure Invalidate; virtual; procedure PaintBackground(vCanvas: TCanvas); virtual; procedure Paint(vCanvas: TCanvas); virtual; procedure PaintFrames(vCanvas: TCanvas; Active: Boolean); virtual; function IsOver(X, Y: Integer): Boolean; virtual; property Color: TColor read FColor write FColor; property Selected: Boolean read GetSelected write SetSelected; property Container: TContainer read FContainer write SetContainer; end; TElementClass = class of TElement; { TElements } TElements = class(TObjectList) private function GetItem(Index: Integer): TElement; procedure SetItem(Index: Integer; const Value: TElement); public property Items[Index: Integer]: TElement read GetItem write SetItem; default; end; { TSelected } TSelected = class(TElements) public procedure Switch(vElement: TElement); end; { TContainer } TContainer = class(TComponent) private FElements: TElements; FBoundRect: TRect; function GetCursor: TCursor; procedure SetCursor(const Value: TCursor); function GetHeight: Integer; function GetWidth: Integer; protected procedure SetBoundRect(const Value: TRect); virtual; procedure PaintBackground(vCanvas: TCanvas); virtual; procedure Paint(vCanvas: TCanvas); virtual; public Board: TCustomBoard; Index: Integer; constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Clear; virtual; procedure Invalidate; virtual; procedure Change; virtual; function GetLayoutByPoint(X, Y: Integer): TLayout; virtual; function GetLayoutByIndex(vIndex: Integer): TLayout; virtual; procedure Init; virtual; function ElementAt(X, Y: Integer; out vElement: TElement): Boolean; property Elements: TElements read FElements; property BoundRect: TRect read FBoundRect write SetBoundRect; property Cursor: TCursor read GetCursor write SetCursor; property Width: Integer read GetWidth; property Height: Integer read GetHeight; end; { TLayout } TLayout = class(TContainer) private FLayouts: TLayouts; FEnabled: Boolean; FName: string; protected procedure SetBoundRect(const Value: TRect); override; public function GetLayoutByIndex(vIndex: Integer): TLayout; override; function GetLayoutByPoint(X, Y: Integer): TLayout; override; constructor Create(AOwner: TComponent); override; property Name: string read FName write FName; published property Enabled: Boolean read FEnabled write FEnabled default True; end; { TPageLayout } TPageLayout = class(TLayout) protected procedure PaintBackground(vCanvas: TCanvas); override; end; TLayoutList = class(TObjectList) private function GetItem(Index: Integer): TLayout; procedure SetItem(Index: Integer; AObject: TLayout); public property Items[Index: Integer]: TLayout read GetItem write SetItem; default; end; { TLayouts } TLayouts = class(TContainer) private FLayoutList: TLayoutList; FCaption: String; FBackground: TColor; function GetItem(vIndex: Integer): TLayout; procedure SetItem(vIndex: Integer; AValue: TLayout); protected public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Clear; override; procedure Assign(Source: TPersistent); override; function ElementAt(X, Y: Integer; out vElement: TElement): Boolean; procedure PaintBackground(vCanvas: TCanvas); override; procedure Paint(vCanvas: TCanvas); override; property LayoutList: TLayoutList read FLayoutList; property Background: TColor read FBackground write FBackground; property Items[vIndex: Integer]: TLayout read GetItem write SetItem; default; published property Caption: String read FCaption write FCaption; end; TOnGetCreateElement= procedure (Sender: TObject; X, Y: Integer; var vElement: TElement) of object; TBoardUpdate = set of (brdInvalidate); { TCustomBoard } TCustomBoard = class(TCustomControl) private FSizeWedges: TSizeWedges; FBoardHeight: Integer; FBoardWidth: Integer; FOnGetCreateElement: TOnGetCreateElement; FSnapSize: Integer; FScaleSize: Integer; FOffset: TPoint; FCurrentLayout: TContainer; FLayouts: TLayouts; FStateUpdate: TBoardUpdate; FUpdateCount: Integer; FSelected: TSelected; FScrollBars: TScrollStyle; function GetActiveElement: TElement; procedure SetBoardHeight(AValue: Integer); procedure SetBoardWidth(AValue: Integer); procedure SetActiveElement(const Value: TElement); procedure SetCurrentLayout(const Value: TContainer); procedure SetOffset(AValue: TPoint); procedure SetScaleSize(AValue: Integer); procedure SetScrollBars(AValue: TScrollStyle); procedure SetSnapSize(AValue: Integer); protected Receiver: TReceiver; procedure PostReceiver(AReceiver: TReceiver); function CheckReciver: Boolean; function MapToCanvas(P: TPoint): TPoint; function MapToScreen(P: TPoint): TPoint; procedure WMGetDlgCode(var message: TWMGetDlgCode); message WM_GETDLGCODE; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; function DoMouseWheel(Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint): Boolean; override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure Paint; override; procedure Resize; override; procedure DoEnter; override; procedure DoExit; override; procedure Change; virtual; procedure Reset; virtual; procedure NextDesginElement; procedure PreviousDesginElement; procedure DeleteDesginElement; procedure BeginUpdate; procedure Update(vStateUpdate: TBoardUpdate); reintroduce; procedure CheckUpdate; procedure EndUpdate; procedure SizeChanged; function DoGetCreateElement(X, Y: Integer; out vElement: TElement): Boolean; virtual; property SizeWedges: TSizeWedges read FSizeWedges; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Loaded; override; property ActiveElement: TElement read GetActiveElement write SetActiveElement; property CurrentLayout: TContainer read FCurrentLayout write SetCurrentLayout; property Offset: TPoint read FOffset write SetOffset; property Selected: TSelected read FSelected; published property SnapSize: Integer read FSnapSize write SetSnapSize default cSnapSize; property ScaleSize: Integer read FScaleSize write SetScaleSize default 0; property BoardWidth: Integer read FBoardWidth write SetBoardWidth default cBoardWidth; property BoardHeight: Integer read FBoardHeight write SetBoardHeight default cBoardHeight; property ScrollBars: TScrollStyle read FScrollBars write SetScrollBars default ssBoth; property Color default clWindow; property Align; property Anchors; property AutoSize; property BiDiMode; property BorderWidth; property Caption; property Constraints; property DockSite; property DragCursor; property DragKind; property DragMode; property Enabled; property Visible; property OnGetCreateElement: TOnGetCreateElement read FOnGetCreateElement write FOnGetCreateElement; end; TntvBoard = class(TCustomBoard) end; {--------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------} { TVisualReceiver } TVisualReceiver = class(TReceiver) public Element: TSizableElement; constructor Create(ABoard: TCustomBoard; AElement: TSizableElement); end; { TMoveReceiver } TMoveReceiver = class(TVisualReceiver) private protected LastX, LastY: Integer; public function MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; override; function MouseMove(Shift: TShiftState; X, Y: Integer): Boolean; override; function MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; override; end; { TSizeReceiver } TSizeReceiver = class(TVisualReceiver) private protected LastX, LastY: Integer; Kind: Integer; public function MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; override; function MouseMove(Shift: TShiftState; X, Y: Integer): Boolean; override; function MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; override; end; { TVisualElement } TVisualElement = class abstract(TElement) private FCaptured: Boolean; FVisible: Boolean; public constructor Create(AOwner: TContainer); overload; override; property Captured: Boolean read FCaptured write FCaptured; property Visible: Boolean read FVisible write FVisible default true; end; { TSizableElement } TSizableElement = class abstract(TVisualElement) private FBoundRect: TRect; function GetWidth: Integer; function GetHeight: Integer; procedure SetHeight(AValue: Integer); procedure SetWidth(AValue: Integer); protected procedure Update(Shift: TShiftState; X, Y: Integer); override; function MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; override; function MouseMove(Shift: TShiftState; X, Y: Integer): Boolean; override; function MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; override; procedure Updating; override; procedure EndUpdate; override; procedure Change; override; public constructor Create(AOwner: TContainer); override; destructor Destroy; override; procedure CreateWedgeList; virtual; function IsOver(X, Y: Integer): Boolean; override; procedure SetBoundRect(NewBounds: TRect); procedure Move(DX, DY: Integer); virtual; procedure Resize(DX1, DY1, DX2, DY2: Integer); virtual; procedure Paint(vCanvas: TCanvas); override; procedure PaintFrames(vCanvas: TCanvas; Active: Boolean); override; procedure AfterCreate(X, Y: Integer; Dummy: Boolean); override; property Width: Integer read GetWidth write SetWidth; property Height: Integer read GetHeight write SetHeight; property BoundRect: TRect read FBoundRect write SetBoundRect; procedure CorrectSize; virtual; published property Top: Integer read FBoundRect.Top write FBoundRect.Top; property Left: Integer read FBoundRect.Left write FBoundRect.Left; property Right: Integer read FBoundRect.Right write FBoundRect.Right; property Bottom: Integer read FBoundRect.Bottom write FBoundRect.Bottom; end; { TEllipseElement } TEllipseElement = class(TSizableElement) public procedure AfterCreate(X, Y: Integer; Dummy: Boolean); override; procedure Paint(vCanvas: TCanvas); override; end; { TRectangleElement } TRectangleElement = class(TSizableElement) public constructor Create(AOwner: TContainer); override; procedure Paint(vCanvas: TCanvas); override; property Color: TColor read FColor write FColor default clGreen; end; { TCircleElement } TCircleElement = class(TSizableElement) public constructor Create(AOwner: TContainer); override; procedure Paint(vCanvas: TCanvas); override; property Color: TColor read FColor write FColor default clBlue; end; { TPNGImageElement } TPNGImageElement = class(TSizableElement) public Image: TPortableNetworkGraphic; constructor Create(AOwner: TContainer); override; destructor Destroy; override; procedure Paint(vCanvas: TCanvas); override; end; { THeavyElement } THeavyElement = class(TSizableElement) private function GetBounds: TRect; protected DesignRect: TRect; public procedure Move(DX, DY: Integer); override; procedure CreateWedgeList; override; function IsOver(X, Y: Integer): Boolean; override; procedure EndUpdate; override; procedure DoPaint(vCanvas: TCanvas); virtual; procedure Paint(vCanvas: TCanvas); override; constructor Create(AOwner: TContainer); override; procedure AfterCreate(X, Y: Integer; Dummy: Boolean); override; end; { TPolygonElement } TPolygonElement = class(TSizableElement) private Polygon: TPointArray; public procedure AfterCreate(X, Y: Integer; Dummy: Boolean); override; procedure Move(DX, DY: Integer); override; procedure Paint(vCanvas: TCanvas); override; procedure CreateWedgeList; override; end; TCariesElement = class(TPolygonElement) public procedure AfterCreate(X, Y: Integer; Dummy: Boolean); override; procedure Paint(vCanvas: TCanvas); override; end; { TDebateElement } TDebateElement = class(TPolygonElement) public procedure AfterCreate(X, Y: Integer; Dummy: Boolean); override; procedure Paint(vCanvas: TCanvas); override; end; procedure RegisterElements(const Layout: String; TElements: array of TElementClass); var ElementClasses: TList; implementation uses Types; procedure CorrectRect(var vRect: TRect); var i: Integer; begin if vRect.Left > vRect.Right then begin i := vRect.Left; vRect.Left := vRect.Right; vRect.Right := i; end; if vRect.Top > vRect.Bottom then begin i := vRect.Top; vRect.Top := vRect.Bottom; vRect.Bottom := i; end; end; procedure RegisterElements(const Layout: String; TElements: array of TElementClass); var i: Integer; begin for i := 0 to Length(TElements) - 1 do begin ElementClasses.Add(TElements[i]); RegisterClass(TElements[i]); end; end; { TSizeWedges } procedure TSizeWedges.UpdateItems(Element: TSizableElement); begin inherited; with Element do begin Self.Add(Left, Top); Self.Add(Left + Width div 2, Top); Self.Add(Right, Top); Self.Add(Right, Top + Height div 2); Self.Add(Right, Bottom); Self.Add(Left + Width div 2, Bottom); Self.Add(Left, Bottom); Self.Add(Left, Top + Height div 2); end end; constructor TSizeWedges.Create; begin inherited; end; { TVisualElement } constructor TVisualElement.Create(AOwner: TContainer); begin inherited Create(AOwner); FVisible := True; end; { TSizeReceiver } function TSizeReceiver.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; begin inherited MouseDown(Button, Shift, X, Y); LastX := X; LastY := Y; Result := True; end; function TSizeReceiver.MouseMove(Shift: TShiftState; X, Y: Integer): Boolean; begin Element.Move(X - LastX, Y - LastY); LastX := X; LastY := Y; Result := True; end; function TSizeReceiver.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; begin inherited; Finished := True; Result := True; end; { TVisualReceiver } constructor TVisualReceiver.Create(ABoard: TCustomBoard; AElement: TSizableElement); begin inherited Create(ABoard); Element := AElement; end; { TMoveReceiver } function TMoveReceiver.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; begin inherited MouseDown(Button, Shift, X, Y); LastX := X; LastY := Y; Result := True; end; function TMoveReceiver.MouseMove(Shift: TShiftState; X, Y: Integer): Boolean; var i: Integer; begin for i := 0 to Board.Selected.Count -1 do begin if Board.Selected[i] is TSizableElement then (Board.Selected[i] as TSizableElement).Move(X - LastX, Y - LastY); end; LastX := X; LastY := Y; Result := True; end; function TMoveReceiver.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; begin inherited; Finished := True; Result := True; end; { TReceiver } constructor TReceiver.Create(ABoard: TCustomBoard); begin inherited Create; if ABoard = nil then raise Exception.Create('You cant create TReceiver without owner'); Board := ABoard; end; function TReceiver.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; begin Result := False; end; function TReceiver.MouseMove(Shift: TShiftState; X, Y: Integer): Boolean; begin Result := False; end; function TReceiver.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; begin Result := False; end; function TReceiver.MouseWheel(Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint): Boolean; begin Result := False; end; function TReceiver.KeyDown(var Key: Word; Shift: TShiftState): Boolean; begin Result := False; end; { TPNGImageElement } constructor TPNGImageElement.Create(AOwner: TContainer); begin inherited; Image := TPortableNetworkGraphic.Create; end; destructor TPNGImageElement.Destroy; begin FreeAndNil(Image); inherited Destroy; end; procedure TPNGImageElement.Paint(vCanvas: TCanvas); begin inherited; end; { TSelected } procedure TSelected.Switch(vElement: TElement); var i: Integer; begin i := IndexOf(vElement); if i < 0 then Add(vElement) else Remove(vElement); end; { TPageLayout } procedure TPageLayout.PaintBackground(vCanvas: TCanvas); var x, y: Integer; begin inherited; vCanvas.Pen.Color := $E0E0E0; vCanvas.Pen.Width := 1; vCanvas.Frame(0, 0, Board.BoardWidth, Board.BoardHeight); x := 0; while x < Board.BoardWidth - 1 do begin vCanvas.Line(x, 0, x, Board.BoardHeight - 1); x := x + 10; end; y := 0; while y < Board.BoardHeight - 1 do begin vCanvas.Line(0, y, Board.BoardWidth - 1, y); y := y + 10; end; end; { TCircleElement } constructor TCircleElement.Create(AOwner: TContainer); begin inherited; Color := clBlue; end; procedure TCircleElement.Paint(vCanvas: TCanvas); begin inherited; vCanvas.Pen.Color := clBlack; vCanvas.Pen.Width := 1; vCanvas.Brush.Color := Color; vCanvas.Brush.Style := bsSolid; vCanvas.Ellipse(FBoundRect); end; { TWedges } function TWedges.Add(x, y: Integer; Cursor: TCursor; ReceiverClass: TReceiverClass): TWedge; begin Result := TWedge.Create; Result.Point.x := x; Result.Point.y := y; Result.Info.Cursor := Cursor; Result.Info.ReceiverClass := ReceiverClass; inherited Add(Result); end; procedure TWedges.Paint(Element: TSizableElement; vCanvas: TCanvas; Active: Boolean); var i: Integer; begin inherited; UpdateItems(Element); vCanvas.Brush.Color := clBlack; for i := 0 to Count - 1 do begin Items[i].Paint(vCanvas, Active); end; end; procedure TWedges.UpdateItems(Element: TSizableElement); begin Clear; end; function TWedges.FindAt(Element: TSizableElement; P: TPoint; out vWedgeIndex: Integer): Boolean; var i: Integer; begin UpdateItems(Element); vWedgeIndex := -1; Result := False; for i := 0 to Count - 1 do begin if Items[i].IsOver(P) then begin vWedgeIndex := i; Result := True; break; end; end; end; { TWedge } procedure TWedge.Paint(vCanvas: TCanvas; Active: Boolean); begin vCanvas.Pen.Color := clGray; vCanvas.Pen.Width := 1; vCanvas.Brush.Style := bsSolid; if Active then vCanvas.Brush.Color := clBlack else vCanvas.Brush.Color := clSilver; vCanvas.Rectangle(PointToWedgeRect(Point)) end; function TWedge.IsOver(P: TPoint): Boolean; begin Result := PtInRect(PointToWedgeRect(Point), P); end; function TWedge.PointToWedgeRect(P: TPoint): TRect; begin Result := Rect(P.X - cWedgeSize, P.Y - cWedgeSize, P.X + cWedgeSize, P.Y + cWedgeSize); end; { TLayouts } procedure TLayouts.Assign(Source: TPersistent); begin inherited; end; procedure TLayouts.Clear; var i: Integer; begin for i := 0 to FLayoutList.Count - 1 do begin FLayoutList[i].Clear; end; inherited; end; constructor TLayouts.Create(AOwner: TComponent); begin inherited; Background := $00DEE9FA; FLayoutList := TLayoutList.Create; with TPageLayout.Create(Self) do begin FName := 'Sheet'; end; {with TLayout.Create(Self) do begin FName := 'Bottom'; end;} end; destructor TLayouts.Destroy; begin FreeAndNil(FLayoutList); inherited; end; function TLayouts.ElementAt(X, Y: Integer; out vElement: TElement): Boolean; var i: Integer; begin Result := False; if not Result then for i := 0 to FLayoutList.Count - 1 do begin Result := FLayoutList[i].ElementAt(X, Y, vElement); if Result then break; end; end; procedure TLayouts.Paint(vCanvas: TCanvas); var i: Integer; begin inherited; for i := 0 to FLayoutList.Count - 1 do begin FLayoutList[i].Paint(vCanvas); end; for i := 0 to Board.Selected.Count - 1 do begin if (Board.Selected[i] is TSizableElement) then //selected should be always TSizableElement Board.SizeWedges.Paint(Board.Selected[i] as TSizableElement, vCanvas, i = 0); end end; procedure TLayouts.PaintBackground(vCanvas: TCanvas); var i: Integer; begin inherited; for i := 0 to FLayoutList.Count - 1 do begin FLayoutList[i].PaintBackground(vCanvas); end; end; function TLayouts.GetItem(vIndex: Integer): TLayout; begin Result := FLayoutList[vIndex]; end; procedure TLayouts.SetItem(vIndex: Integer; AValue: TLayout); begin FLayoutList[vIndex] := AValue; end; { TLayoutList } function TLayoutList.GetItem(Index: Integer): TLayout; begin Result := TLayout(inherited Items[Index]); end; procedure TLayoutList.SetItem(Index: Integer; AObject: TLayout); begin inherited Items[Index] := AObject; end; { TCustomBoard } procedure TCustomBoard.Change; begin end; constructor TCustomBoard.Create(AOwner: TComponent); begin inherited; ControlStyle := ControlStyle + [csOpaque]; FScrollBars := ssBoth; FBoardWidth := cBoardWidth; FBoardHeight := cBoardHeight; FSnapSize := cSnapSize; DoubleBuffered := False; FSizeWedges := TSizeWedges.Create; FSelected := TSelected.Create(False); //before layouts FLayouts := TLayouts.Create(Self); FLayouts.Init; FCurrentLayout := FLayouts[0]; Width := 100; Height := 100; Color := clWindow; end; destructor TCustomBoard.Destroy; begin FreeAndNil(FLayouts); FreeAndNil(FSelected); FreeAndNil(FSizeWedges); FreeAndNil(Receiver); inherited; end; procedure TCustomBoard.DoEnter; begin inherited; //Update([brdInvalidate]); end; procedure TCustomBoard.DoExit; begin inherited; //Update([brdInvalidate]); end; procedure TCustomBoard.Loaded; begin inherited; CurrentLayout.BoundRect := ClientRect; end; procedure TCustomBoard.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var aElement: TElement; begin inherited; if not CheckReciver or not Receiver.MouseDown(Button, Shift, X, Y) then begin aElement := nil; if (Button = mbLeft) and (Shift = [ssLeft]) then //Normal Click begin if DoGetCreateElement(X, Y, aElement) then //Checking if We need to create new component ActiveElement := aElement; if (ActiveElement = nil) or not ActiveElement.MouseDown(Button, Shift, X, Y) then begin CurrentLayout.ElementAt(X, Y, aElement); if (ActiveElement <> aElement) then begin ActiveElement := aElement; if ActiveElement <> nil then ActiveElement.MouseDown(Button, Shift, X, Y); end; end; end else if (Button = mbLeft) and (Shift = [ssLeft, ssShift]) then begin if CurrentLayout.ElementAt(X, Y, aElement) then Selected.Switch(aElement); Update([brdInvalidate]); end else if (Button = mbRight) and (Shift = [ssRight]) then begin if CurrentLayout.ElementAt(X, Y, aElement) then ActiveElement := aElement; end end end; procedure TCustomBoard.MouseMove(Shift: TShiftState; X, Y: Integer); var aElement: TElement; begin inherited; if not CheckReciver or not Receiver.MouseMove(Shift, X, Y) then begin if (ActiveElement = nil) or not ActiveElement.MouseMove(Shift, X, Y) then Cursor := crDefault; end else Cursor := crDefault; end; procedure TCustomBoard.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; if not CheckReciver or not Receiver.MouseUp(Button, Shift, X, Y) then begin if ActiveElement <> nil then ActiveElement.MouseUp(Button, Shift, X, Y); end; end; function TCustomBoard.DoMouseWheel(Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint): Boolean; begin inherited; if not CheckReciver or not Receiver.MouseWheel(Shift, WheelDelta, MousePos) then begin Result := inherited DoMouseWheel(Shift, WheelDelta, MousePos); if WheelDelta < 0 then ScaleSize := ScaleSize - 1 else if WheelDelta > 0 then ScaleSize := ScaleSize + 1 end; end; procedure TCustomBoard.KeyDown(var Key: Word; Shift: TShiftState); var e: Integer; begin inherited; if not CheckReciver or not Receiver.KeyDown(Key, Shift) then begin if Shift = [] then case Key of VK_ESCAPE: ActiveElement := nil; VK_TAB: NextDesginElement; VK_DELETE: DeleteDesginElement; VK_1: begin BeginUpdate; try Offset := Point(0, 0); ScaleSize := 0; finally EndUpdate; end end; end else if Shift = [ssShift] then case Key of VK_TAB : PreviousDesginElement; end else if Shift = [ssCtrl] then case Key of VK_PRIOR : if ActiveElement <> nil then begin e := CurrentLayout.Elements.IndexOf(ActiveElement); if e < CurrentLayout.Elements.Count - 1 then CurrentLayout.Elements.Move(e, e + 1); Key := 0; Update([brdInvalidate]); end; VK_NEXT : if ActiveElement <> nil then begin e := CurrentLayout.Elements.IndexOf(ActiveElement); if e > 0 then CurrentLayout.Elements.Move(e - 1, e); Key := 0; Update([brdInvalidate]); end; end; end; end; //BasePaint procedure TCustomBoard.Paint; begin inherited; Canvas.Pen.Color := clBlack; Canvas.Pen.Style := psSolid; Canvas.Pen.Width := 1; Canvas.Brush.Color := Color; Canvas.Brush.Style := bsSolid; FLayouts.PaintBackground(Canvas); FLayouts.Paint(Canvas); end; procedure TCustomBoard.Reset; begin end; procedure TCustomBoard.PreviousDesginElement; var e: Integer; begin if CurrentLayout.Elements.Count > 0 then begin if ActiveElement = nil then ActiveElement := CurrentLayout.Elements[CurrentLayout.Elements.Count - 1] else begin e := CurrentLayout.Elements.IndexOf(ActiveElement); Selected.Clear; if e < 0 then ActiveElement := CurrentLayout.Elements[CurrentLayout.Elements.Count - 1] else if e > 0 then ActiveElement := CurrentLayout.Elements[e - 1] else ActiveElement := CurrentLayout.Elements[CurrentLayout.Elements.Count - 1] end; end; end; procedure TCustomBoard.NextDesginElement; var e: Integer; begin if CurrentLayout.Elements.Count > 0 then begin if ActiveElement = nil then ActiveElement := CurrentLayout.Elements[0] else begin e := CurrentLayout.Elements.IndexOf(ActiveElement); Selected.Clear; if e < 0 then ActiveElement := CurrentLayout.Elements[0] else if e < CurrentLayout.Elements.Count - 1 then ActiveElement := CurrentLayout.Elements[e + 1] else ActiveElement := CurrentLayout.Elements[0]; end; end; end; procedure TCustomBoard.DeleteDesginElement; begin if CurrentLayout.Elements.Count > 0 then begin BeginUpdate; try while Selected.Count > 0 do Selected[0].Free; Update([brdInvalidate]); finally EndUpdate; end; end; end; procedure TCustomBoard.BeginUpdate; begin CheckUpdate; FUpdateCount := FUpdateCount + 1; end; procedure TCustomBoard.Update(vStateUpdate: TBoardUpdate); begin FStateUpdate := FStateUpdate + vStateUpdate; CheckUpdate; end; procedure TCustomBoard.CheckUpdate; begin if FUpdateCount = 0 then begin if brdInvalidate in FStateUpdate then Invalidate; FStateUpdate := []; end; end; procedure TCustomBoard.EndUpdate; begin FUpdateCount := FUpdateCount - 1; if FUpdateCount < 0 then raise Exception.Create('Board: Update count less than 0'); CheckUpdate; end; procedure TCustomBoard.SizeChanged; begin end; function TCustomBoard.DoGetCreateElement(X, Y: Integer; out vElement: TElement): Boolean; begin vElement := nil; if Assigned(FOnGetCreateElement) then begin FOnGetCreateElement(Self, X, Y, vElement); end; Result := vElement <> nil; end; procedure TCustomBoard.Resize; begin inherited; FLayouts.BoundRect := ClientRect; if not (csLoading in ComponentState) then begin FLayouts.BoundRect := ClientRect; end; end; procedure TCustomBoard.SetCurrentLayout(const Value: TContainer); begin FCurrentLayout := Value; Update([brdInvalidate]); end; procedure TCustomBoard.SetOffset(AValue: TPoint); begin if (FOffset.X = AValue.X) and (FOffset.Y = AValue.Y) then Exit; FOffset := AValue; Update([brdInvalidate]); end; procedure TCustomBoard.SetScaleSize(AValue: Integer); begin if FScaleSize =AValue then Exit; FScaleSize := AValue; Update([brdInvalidate]); end; procedure TCustomBoard.SetScrollBars(AValue: TScrollStyle); begin if FScrollBars =AValue then Exit; FScrollBars :=AValue; end; procedure TCustomBoard.SetSnapSize(AValue: Integer); begin if FSnapSize =AValue then Exit; FSnapSize := AValue; Update([brdInvalidate]); end; procedure TCustomBoard.PostReceiver(AReceiver: TReceiver); begin if (Receiver = nil) or not Receiver.Finished then begin FreeAndNil(Receiver); Receiver := AReceiver; end else raise Exception.Create('You cant post receiver now'); end; function TCustomBoard.CheckReciver: Boolean; begin if (Receiver <> nil) and Receiver.Finished then FreeAndNil(Receiver); Result := Receiver <> nil; end; function TCustomBoard.MapToCanvas(P: TPoint): TPoint; begin P.x := P.x + Offset.x; P.y := P.y + Offset.y; Result := P; end; function TCustomBoard.MapToScreen(P: TPoint): TPoint; begin P.x := P.x - Offset.x; P.y := P.y - Offset.y; Result := P; end; procedure TCustomBoard.WMGetDlgCode(var message: TWMGetDlgCode); begin inherited; message.Result := message.Result or DLGC_WANTARROWS or DLGC_WANTTAB or DLGC_WANTALLKEYS; end; { TElements } function TElements.GetItem(Index: Integer): TElement; begin Result := TElement(inherited Items[Index]); end; procedure TElements.SetItem(Index: Integer; const Value: TElement); begin inherited Items[Index] := Value; end; { TElement } function TElement.IsOver(X, Y: Integer): Boolean; begin Result := False; end; procedure TElement.Update(Shift: TShiftState; X, Y: Integer); begin Updating; end; function TElement.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; begin Result := False; end; function TElement.MouseMove(Shift: TShiftState; X, Y: Integer): Boolean; begin Result := False; end; function TElement.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; begin Result := False; end; procedure TElement.Paint(vCanvas: TCanvas); begin end; procedure TElement.PaintFrames(vCanvas: TCanvas; Active: Boolean); begin end; { TCariesElement } procedure TCariesElement.AfterCreate(X, Y: Integer; Dummy: Boolean); begin inherited; SetLength(Polygon, 3); Polygon[0].X := 0; Polygon[0].Y := 0; Polygon[1].X := 30; Polygon[1].Y := 30; Polygon[2].X := -30; Polygon[2].Y := 30; end; procedure TCariesElement.Paint(vCanvas: TCanvas); begin inherited; vCanvas.Brush.Color := clGreen; vCanvas.Polygon(Polygon); end; { TSizableElement } procedure TSizableElement.CreateWedgeList; begin inherited; end; function TSizableElement.IsOver(X, Y: Integer): Boolean; begin if PtInRect(FBoundRect, Point(X, Y)) then Result := True else Result := False; end; function TSizableElement.GetHeight: Integer; begin Result := Bottom - Top; end; procedure TSizableElement.SetHeight(AValue: Integer); begin FBoundRect.Bottom := FBoundRect.Top + AValue; end; procedure TSizableElement.SetWidth(AValue: Integer); begin FBoundRect.Right := FBoundRect.Left + AValue; end; procedure TSizableElement.Update(Shift: TShiftState; X, Y: Integer); begin inherited; end; function TSizableElement.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; var i: Integer; begin inherited; if Container.Board.SizeWedges.FindAt(Self, Point(X, Y), i) then begin Result := True; end else begin if IsOver(X, Y) then begin Container.Board.PostReceiver(TMoveReceiver.Create(Container.Board, Self)); Container.Board.Receiver.MouseDown(Button, Shift, X, Y); Result := True; end else Result := False; end; end; function TSizableElement.MouseMove(Shift: TShiftState; X, Y: Integer): Boolean; var i: Integer; begin inherited; if Container.Board.SizeWedges.FindAt(Self, Point(X, Y), i) then begin Container.Cursor := cWedgeCursors[i];//use Wedget object, but now it is not permanent object :( Result := True; end else Result := False; end; function TSizableElement.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean; begin inherited; Result := False; //not sure end; function TSizableElement.GetWidth: Integer; begin Result := Right - Left; end; procedure TSizableElement.Paint(vCanvas: TCanvas); begin inherited; end; procedure TSizableElement.PaintFrames(vCanvas: TCanvas; Active: Boolean); begin inherited PaintFrames(vCanvas, Active); end; procedure TSizableElement.AfterCreate(X, Y: Integer; Dummy: Boolean); begin inherited; {if Dummy then begin FBoundRect := Rect(X, Y, X, Y); end else} FBoundRect := Rect(X, Y, X + 50, Y + 50); end; procedure TSizableElement.SetBoundRect(NewBounds: TRect); begin FBoundRect := NewBounds; end; procedure TSizableElement.CorrectSize; begin end; procedure TSizableElement.Move(DX, DY: Integer); begin inherited; OffsetRect(FBoundRect, DX, DY); Change; exit; case 0 of -1: begin OffsetRect(FBoundRect, DX, DY); end; 0: begin Inc(FBoundRect.Left, DX); Inc(FBoundRect.Top, DY); end; 1: begin Inc(FBoundRect.Top, DY); end; 2: begin Inc(FBoundRect.Top, DY); Inc(FBoundRect.Right, DX); end; 3: begin Inc(FBoundRect.Right, DX); end; 4: begin Inc(FBoundRect.Bottom, DY); Inc(FBoundRect.Right, DX); end; 5: begin Inc(FBoundRect.Bottom, DY); end; 6: begin Inc(FBoundRect.Bottom, DY); Inc(FBoundRect.Left, DX); end; 7: begin Inc(FBoundRect.Left, DX); end; end; Invalidate; end; procedure TSizableElement.Resize(DX1, DY1, DX2, DY2: Integer); begin end; procedure TSizableElement.Updating; begin inherited Updating; CreateWedgeList; end; procedure TSizableElement.EndUpdate; begin CorrectRect(FBoundRect); inherited; end; procedure TSizableElement.Change; begin inherited; CreateWedgeList; end; constructor TSizableElement.Create(AOwner: TContainer); begin inherited Create(AOwner); end; destructor TSizableElement.Destroy; begin inherited Destroy; end; { TContainer } destructor TContainer.Destroy; begin Elements.Clear; FreeAndNil(FElements); inherited; end; procedure TContainer.Paint(vCanvas: TCanvas); var i: Integer; begin for i := 0 to Elements.Count - 1 do begin Elements[i].Paint(vCanvas); end; end; function TContainer.ElementAt(X, Y: Integer; out vElement: TElement): Boolean; var i: Integer; begin Result := False; vElement := nil; for i := Elements.Count - 1 downto 0 do begin if Elements[i].IsOver(X, Y) then begin vElement := Elements[i]; Result := True; break; end; end; end; procedure TContainer.SetBoundRect(const Value: TRect); begin FBoundRect := Value; end; function TContainer.GetCursor: TCursor; begin Result := Board.Cursor; end; procedure TContainer.SetCursor(const Value: TCursor); begin Board.Cursor := Value; end; procedure TContainer.Invalidate; begin if Board <> nil then Board.Update([brdInvalidate]); end; procedure TCustomBoard.SetActiveElement(const Value: TElement); var i: Integer; begin if GetActiveElement <> Value then begin Selected.Clear; if Value <> nil then Selected.Add(Value); { i := Selected.IndexOf(Value); if i < 0 then Selected.Insert(0, Value) else Selected.Move(i, 0);} Update([brdInvalidate]); end; end; procedure TCustomBoard.SetBoardHeight(AValue: Integer); begin if FBoardHeight =AValue then Exit; FBoardHeight :=AValue; SizeChanged; end; function TCustomBoard.GetActiveElement: TElement; begin if Selected.Count > 0 then Result := Selected[0] else Result := nil; end; procedure TCustomBoard.SetBoardWidth(AValue: Integer); begin if FBoardWidth =AValue then Exit; FBoardWidth :=AValue; end; procedure TContainer.PaintBackground(vCanvas: TCanvas); var i: Integer; begin for i := 0 to Elements.Count - 1 do begin Elements[i].PaintBackground(vCanvas); end; end; constructor TContainer.Create(AOwner: TComponent); begin inherited Create(nil); FElements := TElements.Create; if (AOwner <> nil) then begin if (AOwner is TCustomBoard) then Board := AOwner as TCustomBoard else if (AOwner is TLayouts) then Board := (AOwner as TLayouts).Board; end; end; procedure TContainer.Change; begin Board.Change; Invalidate; end; procedure TContainer.Clear; begin Elements.Clear; end; function TContainer.GetHeight: Integer; begin Result := BoundRect.Bottom - BoundRect.Top; end; function TContainer.GetWidth: Integer; begin Result := BoundRect.Right - BoundRect.Left; end; function TContainer.GetLayoutByPoint(X, Y: Integer): TLayout; begin Result := nil; end; function TContainer.GetLayoutByIndex(vIndex: Integer): TLayout; begin Result := nil; end; procedure TContainer.Init; begin end; { TElement } constructor TElement.Create(AOwner: TContainer; X: Integer; Y: Integer); begin Create(AOwner); AfterCreate(X, Y, True); end; procedure TElement.AfterCreate(X, Y: Integer; Dummy: Boolean); begin end; procedure TElement.Invalidate; begin Container.Invalidate; end; procedure TElement.PaintBackground(vCanvas: TCanvas); begin end; function TElement.GetSelected: Boolean; begin if Container.Board <> nil then Result := Container.Board.ActiveElement = Self else Result := False; end; procedure TElement.SetSelected(const Value: Boolean); begin if Value and (Container.Board <> nil) then Container.Board.ActiveElement := Self else Container.Board.ActiveElement := nil; end; procedure TElement.BeginUpdate; begin FUpdateCount := FUpdateCount + 1; Invalidate; end; procedure TElement.Updating; begin Invalidate; end; procedure TElement.EndUpdate; begin FUpdateCount := FUpdateCount - 1; if FUpdateCount = 0 then begin Change; Invalidate; end; end; constructor TElement.Create(AOwner: TContainer); begin inherited Create; Container := AOwner as TContainer; //do not use FContainer end; procedure TElement.SetContainer(const Value: TContainer); begin if Value <> FContainer then begin if FContainer <> nil then FContainer.Elements.Extract(Self); FContainer := Value; if FContainer <> nil then FContainer.Elements.Add(Self); end; end; destructor TElement.Destroy; begin Container.Board.Selected.Remove(Self); Container := nil; //remove my self from elements list inherited; end; procedure TElement.Change; begin Container.Change; end; function TElement.ScalePoint(P: TPoint): TPoint; begin with Container.Board do begin P.x := P.x + P.x * ScaleSize; P.y := P.y + P.y * ScaleSize; end; Result := P; end; function TElement.ScaleRect(R: TRect): TRect; begin R.TopLeft := ScalePoint(R.TopLeft); R.BottomRight := ScalePoint(R.BottomRight); Result := R; end; function TElement.SnapPoint(P: TPoint): TPoint; begin with Container.Board do begin P.x := P.x div SnapSize * SnapSize; P.y := P.y div SnapSize * SnapSize; end; Result := P; end; function TElement.SnapRect(R: TRect): TRect; begin R.TopLeft := SnapPoint(R.TopLeft); R.BottomRight := SnapPoint(R.BottomRight); Result := R; end; procedure TElement.AfterConstruction; begin inherited; Change; end; { TEllipseElement } procedure TEllipseElement.AfterCreate(X, Y: Integer; Dummy: Boolean); begin inherited; if Dummy then else FBoundRect := Rect(X, Y, X + 10, Y + 10); end; procedure TEllipseElement.Paint(vCanvas: TCanvas); begin inherited; vCanvas.Pen.Color := clBlack; vCanvas.Brush.Color := Color; vCanvas.Ellipse(BoundRect); end; { TRectangleElement } constructor TRectangleElement.Create(AOwner: TContainer); begin inherited Create(AOwner); FColor := clGreen; end; procedure TRectangleElement.Paint(vCanvas: TCanvas); begin inherited; vCanvas.Pen.Color := clBlack; vCanvas.Pen.Width := 1; vCanvas.Brush.Color := Color; vCanvas.Brush.Style := bsSolid; vCanvas.Rectangle(FBoundRect); end; { TPolygonElement } procedure TPolygonElement.CreateWedgeList; var i: Integer; begin inherited; for i := 0 to Length(Polygon) -1 do begin //FWedges.Add(Polygon[i].x, Polygon[i].y); end end; procedure TPolygonElement.AfterCreate(X, Y: Integer; Dummy: Boolean); begin inherited; SetLength(Polygon, 1); Color := clRed; end; procedure TPolygonElement.Move(DX, DY: Integer); var i: Integer; begin inherited; for i := 0 to Length(Polygon) - 1 do begin Inc(Polygon[i].X, DX); Inc(Polygon[i].Y, DY); end; Invalidate; end; procedure TPolygonElement.Paint(vCanvas: TCanvas); begin inherited; end; { TDebateElement } procedure TDebateElement.AfterCreate(X, Y: Integer; Dummy: Boolean); begin inherited; SetLength(Polygon, 6); Polygon[0].X := 0; Polygon[0].Y := 0; Polygon[1].X := 30; Polygon[1].Y := 30; Polygon[2].X := 100; Polygon[2].Y := 30; Polygon[3].X := 100; Polygon[3].Y := 60; Polygon[4].X := 30; Polygon[4].Y := 60; Polygon[5].X := 30; Polygon[5].Y := 35; end; procedure TDebateElement.Paint(vCanvas: TCanvas); begin inherited; vCanvas.Brush.Color := clInfoBk; vCanvas.Polygon(Polygon); end; { THeavyElement } procedure THeavyElement.AfterCreate(X, Y: Integer; Dummy: Boolean); begin inherited; if Dummy then OffsetRect(DesignRect, X - (DesignRect.Right - DesignRect.Left) div 2, Y - (DesignRect.Bottom - DesignRect.Top) div 2); end; constructor THeavyElement.Create(AOwner: TContainer); begin if not (AOwner is TLayout) then raise Exception.Create('Must Create On Layout') else begin inherited; DesignRect := GetBounds; end; end; procedure THeavyElement.CreateWedgeList; begin inherited; with DesignRect do begin { FWedges.Add(Left, Top); FWedges.Add(Left + (Right - Left) div 2, Top); FWedges.Add(Right, Top); FWedges.Add(Right, Top + (Bottom - Top) div 2); FWedges.Add(Right, Bottom); FWedges.Add(Left + (Right - Left) div 2, Bottom); FWedges.Add(Left, Bottom); FWedges.Add(Left, Top + (Bottom - Top) div 2);} end; end; procedure THeavyElement.DoPaint(vCanvas: TCanvas); begin end; procedure THeavyElement.EndUpdate; begin Invalidate; DesignRect := GetBounds; inherited; end; function THeavyElement.GetBounds: TRect; begin Result := Container.BoundRect; end; function THeavyElement.IsOver(X, Y: Integer): Boolean; begin Result := PtInRect(GetBounds, Point(X, Y)); end; procedure THeavyElement.Move(DX, DY: Integer); begin inherited; Invalidate; OffsetRect(DesignRect, DX, DY); Invalidate; end; procedure THeavyElement.Paint(vCanvas: TCanvas); begin inherited; if Captured then begin vCanvas.Brush.Style := bsClear; vCanvas.Rectangle(DesignRect); end else DoPaint(vCanvas); end; { TLayout } constructor TLayout.Create(AOwner: TComponent); begin inherited; FEnabled := True; if AOwner is TLayouts then begin FLayouts := (AOwner as TLayouts); Index := FLayouts.FLayoutList.Add(Self); end; end; function TLayout.GetLayoutByIndex(vIndex: Integer): TLayout; begin Result := Self; end; function TLayout.GetLayoutByPoint(X, Y: Integer): TLayout; begin Result := Self; end; { TLayout } procedure TLayout.SetBoundRect(const Value: TRect); begin inherited; FBoundRect := Value; end; initialization ElementClasses := TList.Create; RegisterElements('', [TEllipseElement]); RegisterElements('', [TRectangleElement]); finalization FreeAndNil(ElementClasses); end.
unit DEBUGDLG; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TDebugForm = class(TForm) Memo1: TMemo; Button1: TButton; private { Private declarations } public { Public declarations } procedure Log(Msg : String); end; var DebugForm: TDebugForm; implementation {$R *.dfm} { TDebugForm } procedure TDebugForm.Log(Msg: String); begin Memo1.Lines.Add(msg); end; end.
unit UFaceBookAlbumDemo; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.ListView.Types, FMX.Edit, FMX.ListView, FMX.TMSCloudBase, FMX.TMSCloudFacebook, FMX.Layouts, FMX.ListBox, FMX.TMSCloudImage, FMX.Objects, FMX.TMSCloudBaseFMX, FMX.TMSCloudCustomFacebook, IOUtils; type TForm82 = class(TForm) ToolBar1: TToolBar; Button1: TButton; btRemove: TButton; TMSFMXCloudFaceBook1: TTMSFMXCloudFaceBook; Panel1: TPanel; btnLoad: TButton; ListView1: TListBox; btAdd: TButton; edAdd: TEdit; ListView2: TListBox; Label1: TLabel; TMSFMXCloudImage1: TTMSFMXCloudImage; procedure Button1Click(Sender: TObject); procedure btRemoveClick(Sender: TObject); procedure btnLoadClick(Sender: TObject); procedure btAddClick(Sender: TObject); procedure TMSFMXCloudFaceBook1ReceivedAccessToken(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ListView1Change(Sender: TObject); procedure ListView2Change(Sender: TObject); private { Private declarations } public { Public declarations } Connected: boolean; LVInit: boolean; procedure ToggleControls; procedure LoadAlbums; procedure LoadPictures; procedure Init; end; var Form82: TForm82; implementation {$R *.fmx} // PLEASE USE A VALID INCLUDE FILE THAT CONTAINS THE APPLICATION KEY & SECRET // FOR THE CLOUD STORAGE SERVICES YOU WANT TO USE // STRUCTURE OF THIS .INC FILE SHOULD BE // // const // FacebookAppkey = 'xxxxxxxxx'; // FacebookAppSecret = 'yyyyyyyy'; {$I APPIDS.INC} procedure TForm82.Button1Click(Sender: TObject); var acc: boolean; begin TMSFMXCloudFacebook1.App.Key := FacebookAppkey; TMSFMXCloudFacebook1.App.Secret := FacebookAppSecret; if TMSFMXCloudFacebook1.App.Key <> '' then begin TMSFMXCloudFacebook1.PersistTokens.Key := TPath.GetDocumentsPath + '/facebook.ini'; TMSFMXCloudFacebook1.PersistTokens.Section := 'tokens'; TMSFMXCloudFacebook1.LoadTokens; acc := TMSFMXCloudFacebook1.TestTokens; if not acc then begin TMSFMXCloudFacebook1.RefreshAccess; TMSFMXCloudFacebook1.DoAuth; end else Init; end else ShowMessage('Please provide a valid application ID for the client component'); end; procedure TForm82.btRemoveClick(Sender: TObject); begin TMSFMXCloudFacebook1.ClearTokens; Connected := false; ToggleControls; end; procedure TForm82.btnLoadClick(Sender: TObject); begin LoadAlbums; end; procedure TForm82.btAddClick(Sender: TObject); var fn: string; begin if MessageDlg('Do you want to upload a sample file?', TMsgDlgType.mtConfirmation,[TMsgDlgBtn.mbYes,TMsgDlgBtn.mbNo],0) = mrYes then begin fn := TPath.GetDocumentsPath + '/sample.jpg'; TMSFMXCloudFaceBook1.PostImage(edAdd.Text, fn, TFaceBookAlbum(ListView1.Items.Objects[ListView1.ItemIndex])); LoadPictures; end; end; procedure TForm82.FormCreate(Sender: TObject); begin {$IFDEF IOS} TFile.Copy(ExtractFilePath(Paramstr(0)) + 'sample.jpg', TPath.GetDocumentsPath + '/sample.jpg', True); {$ENDIF} LVInit := false; Connected := false; ToggleControls; end; procedure TForm82.Init; begin Connected := true; ToggleControls; TMSFMXCloudFaceBook1.GetUserInfo; LoadAlbums; end; procedure TForm82.ListView1Change(Sender: TObject); begin if LVInit then exit; LoadPictures; end; procedure TForm82.ListView2Change(Sender: TObject); var Picture: TFacebookPicture; begin if LVInit then exit; if ListView2.ItemIndex >= 0 then begin Picture := TFacebookPicture(ListView2.Items.Objects[ListView2.ItemIndex]); TMSFMXCloudImage1.URL := Picture.ImageURL; end; end; procedure TForm82.LoadAlbums; var I: integer; Profile: TFacebookProfile; begin LVInit := true; TMSFMXCloudFacebook1.GetAlbums(TMSFMXCloudFacebook1.Profile); ListView1.Items.Clear; Profile := TMSFMXCloudFacebook1.Profile; ListView1.BeginUpdate; for I := 0 to Profile.Albums.Count - 1 do ListView1.Items.AddObject(Profile.Albums[I].Title, Profile.Albums[I]); ListView1.EndUpdate; LVInit := false; end; procedure TForm82.LoadPictures; var AlbumItem: TFacebookAlbum; I: Integer; str: String; begin if ListView1.ItemIndex >= 0 then begin LVInit := true; edAdd.Enabled := true; btAdd.Enabled := true; AlbumItem := TFaceBookAlbum(ListView1.Items.Objects[ListView1.ItemIndex]); TMSFMXCloudImage1.URL := TMSFMXCloudFacebook1.GetImageURL(AlbumItem.CoverPhotoID); ListView2.Items.Clear; TMSFMXCloudFacebook1.GetPictures(AlbumItem); ListView2.BeginUpdate; for I := 0 to AlbumItem.Pictures.Count - 1 do begin str := AlbumItem.Pictures[I].Caption; if str = '' then str := AlbumItem.Pictures[I].ID; ListView2.Items.AddObject(str, AlbumItem.Pictures[I]); end; ListView2.EndUpdate; LVInit := false; end; end; procedure TForm82.TMSFMXCloudFaceBook1ReceivedAccessToken(Sender: TObject); begin TMSFMXCloudFacebook1.SaveTokens; Init; end; procedure TForm82.ToggleControls; begin Panel1.Enabled := Connected; btnLoad.Enabled := Connected; ListView2.Enabled := Connected; ListView1.Enabled := Connected; btRemove.Enabled := Connected; Button1.Enabled := not Connected; end; end.
unit DEX.Types; interface uses System.SysUtils, System.DateUtils, System.Math, System.Generics.Collections, System.Generics.Defaults; type TOfferDirection = (Buy=1,Sell=2); TOffer = record public Status: Integer; ID: Integer; AccountID: Int64; Direction: Integer; Symbol1: string; Symbol2: string; Ratio: Extended; StrtAmount: Extended; CrrntAmount: Extended; StartDate: TDateTime; LastDate: TDateTime; EndDate: TDateTime; class operator Implicit(const Offer: TOffer): string; end; TOffers = array of TOffer; TOffersHelper = record helper for TOffers function Copy: TOffers; function Sort: TOffers; function SortByStartDate(Asc: Boolean=True): TOffers; function SortByLastDate(Asc: Boolean=True): TOffers; function SortByRatio(Asc: Boolean=True): TOffers; function GroupByRatio: TOffers; end; TPair = record Symbol1: string; Symbol2: string; Ratio: Extended; Volume: Extended; LastDate: TDateTime; Ratio24hAgo: Extended; Percent: Extended; Low: Extended; High: Extended; class operator Implicit(const Pair: TPair): string; end; TPairs = array of TPair; TDataCandle = record DateTime: TDateTime; Min: Extended; Max: Extended; Open: Extended; Close: Extended; Volume: Extended; Time: Int64; class operator Implicit(const Candle: TDataCandle): string; end; TDataCandles = array of TDataCandle; TDataTrade = record Ratio: Extended; Volume: Extended; Date: TDateTime; Direction: Integer; class operator Implicit(const Trade: TDataTrade): string; end; TDataTrades = array of TDataTrade; TDataTradesHelper = record helper for TDataTrades function Copy: TDataTrades; function SortByDate(Asc: Boolean=True): TDataTrades; end; implementation function AmountToStr(Amount: Extended): string; begin Result:=FormatFloat('0.00######',Amount); end; class operator TOffer.Implicit(const Offer: TOffer): string; begin case Offer.Direction of 1: Result:='buy'; 2: Result:='sell'; else Result:=Offer.Direction.ToString; end; Result:= Offer.ID.ToString.PadRight(6)+ Offer.Status.ToString.PadRight(4)+ Offer.AccountID.ToString.PadRight(6)+ Result.PadRight(6)+ (Offer.Symbol1+'/'+Offer.Symbol2).PadRight(10)+ AmountToStr(Offer.CrrntAmount).PadRight(10)+ AmountToStr(Offer.Ratio).PadRight(10)+ DateTimeToStr(Offer.StartDate); end; function TOffersHelper.Copy: TOffers; begin SetLength(Result,Length(Self)); if Length(Self)>0 then TArray.Copy<TOffer>(Self,Result,Length(Self)); end; function TOffersHelper.Sort: TOffers; begin Result:=Copy; TArray.Sort<TOffer>(Result,TComparer<TOffer>.Construct( function(const Left,Right: TOffer): Integer begin Result:=CompareStr(Left.Symbol1,Right.Symbol1); if Result=0 then Result:=CompareText(Left.Symbol2,Right.Symbol2); if Result=0 then Result:=Right.Direction-Left.Direction; if Result=0 then Result:=-CompareValue(Left.Ratio,Right.Ratio); if Result=0 then begin Result:=CompareDateTime(Left.StartDate,Right.StartDate); if Left.Direction=2 then Result:=-Result; end; end)); end; function TOffersHelper.SortByStartDate(Asc: Boolean=True): TOffers; var A: Integer; begin Result:=Copy; if Asc then A:=+1 else A:=-1; TArray.Sort<TOffer>(Result,TComparer<TOffer>.Construct( function(const Left,Right: TOffer): Integer begin Result:=A*CompareDateTime(Left.StartDate,Right.StartDate); end)); end; function TOffersHelper.SortByLastDate(Asc: Boolean=True): TOffers; var A: Integer; begin Result:=Copy; if Asc then A:=+1 else A:=-1; TArray.Sort<TOffer>(Result,TComparer<TOffer>.Construct( function(const Left,Right: TOffer): Integer begin Result:=A*CompareDateTime(Left.LastDate,Right.LastDate); end)); end; function TOffersHelper.SortByRatio(Asc: Boolean=True): TOffers; var A: Integer; begin Result:=Copy; if Asc then A:=+1 else A:=-1; TArray.Sort<TOffer>(Result,TComparer<TOffer>.Construct( function(const Left,Right: TOffer): Integer begin if Left.Ratio*Right.Ratio=0 then Result:=CompareValue(Left.Ratio,Right.Ratio) else Result:=A*CompareValue(Left.Ratio,Right.Ratio); if Result=0 then Result:=CompareDateTime(Left.StartDate,Right.StartDate); end)); end; function TOffersHelper.GroupByRatio: TOffers; begin Result:=nil; for var Offer in Self do if (Length(Result)>0) and (Offer.Ratio=Result[High(Result)].Ratio) then begin Result[High(Result)].StrtAmount:=Result[High(Result)].StrtAmount+Offer.StrtAmount; Result[High(Result)].CrrntAmount:=Result[High(Result)].CrrntAmount+Offer.CrrntAmount; end else Result:=Result+[Offer]; end; class operator TPair.Implicit(const Pair: TPair): string; begin Result:= (Pair.Symbol1+'/'+Pair.Symbol2).PadRight(10)+ AmountToStr(Pair.Volume).PadRight(10)+ AmountToStr(Pair.Ratio).PadRight(10)+ FormatFloat('+0.0#%;-0.0#%',Pair.Percent).PadRight(9)+ DateTimeToStr(Pair.LastDate); end; class operator TDataCandle.Implicit(const Candle: TDataCandle): string; begin Result:= DateTimeToStr(Candle.DateTime).PadRight(22)+ AmountToStr(Candle.Open).PadRight(12)+ AmountToStr(Candle.Close).PadRight(12)+ AmountToStr(Candle.Min).PadRight(12)+ AmountToStr(Candle.Max).PadRight(12)+ AmountToStr(Candle.Volume).PadRight(12); end; class operator TDataTrade.Implicit(const Trade: TDataTrade): string; begin Result:= Trade.Direction.ToString.PadRight(5)+ AmountToStr(Trade.Volume).PadRight(10)+ AmountToStr(Trade.Ratio).PadRight(14)+ DateTimeToStr(Trade.Date); end; function TDataTradesHelper.Copy: TDataTrades; begin SetLength(Result,Length(Self)); if Length(Self)>0 then TArray.Copy<TDataTrade>(Self,Result,Length(Self)); end; function TDataTradesHelper.SortByDate(Asc: Boolean=True): TDataTrades; var A: Integer; begin Result:=Copy; if Asc then A:=+1 else A:=-1; TArray.Sort<TDataTrade>(Result,TComparer<TDataTrade>.Construct( function(const Left,Right: TDataTrade): Integer begin Result:=A*CompareDateTime(Left.Date,Right.Date); end)); end; end.
unit ServerHorse.Model.Entity.COMPANIES; interface uses SimpleAttributes; type [Tabela('Companies')] TCOMPANIES = class private FIDAREASEXPERTISE: String; FPICTURE: String; FCNPJ: String; FIDCITY: String; FCOMPANYNAME: String; FCEP: String; FCOMPLEMENT: String; FNUMBER: Integer; FGUUID: String; FNEIGHBORHOOD: String; FADDRESS: String; FLOGO: String; FIDSTATE: String; FIDCOUNTRY: String; procedure SetADDRESS(const Value: String); procedure SetCEP(const Value: String); procedure SetCNPJ(const Value: String); procedure SetCOMPANYNAME(const Value: String); procedure SetCOMPLEMENT(const Value: String); procedure SetGUUID(const Value: String); procedure SetIDAREASEXPERTISE(const Value: String); procedure SetIDCITY(const Value: String); procedure SetIDSTATE(const Value: String); procedure SetLOGO(const Value: String); procedure SetNEIGHBORHOOD(const Value: String); procedure SetNUMBER(const Value: Integer); procedure SetPICTURE(const Value: String); procedure SetIDCOUNTRY(const Value: String); public constructor Create; destructor Destroy; override; [Campo('GUUID'), Pk] property GUUID : String read FGUUID write SetGUUID; [Campo('COMPANYNAME')] property COMPANYNAME : String read FCOMPANYNAME write SetCOMPANYNAME; [Campo('CNPJ')] property CNPJ : String read FCNPJ write SetCNPJ; [Campo('IDAREASEXPERTISE')] property IDAREASEXPERTISE : String read FIDAREASEXPERTISE write SetIDAREASEXPERTISE; [Campo('IDCOUNTRY')] property IDCOUNTRY : String read FIDCOUNTRY write SetIDCOUNTRY; [Campo('IDSTATE')] property IDSTATE : String read FIDSTATE write SetIDSTATE; [Campo('IDCITY')] property IDCITY : String read FIDCITY write SetIDCITY; [Campo('LOGO')] property LOGO : String read FLOGO write SetLOGO; [Campo('CEP')] property CEP : String read FCEP write SetCEP; [Campo('ADDRESS')] property ADDRESS : String read FADDRESS write SetADDRESS; [Campo('NEIGHBORHOOD')] property NEIGHBORHOOD : String read FNEIGHBORHOOD write SetNEIGHBORHOOD; [Campo('NUMBER')] property NUMBER : Integer read FNUMBER write SetNUMBER; [Campo('COMPLEMENT')] property COMPLEMENT : String read FCOMPLEMENT write SetCOMPLEMENT; [Campo('PICTURE')] property PICTURE : String read FPICTURE write SetPICTURE; end; implementation { TCOMPANIES } constructor TCOMPANIES.Create; begin end; destructor TCOMPANIES.Destroy; begin inherited; end; procedure TCOMPANIES.SetADDRESS(const Value: String); begin FADDRESS := Value; end; procedure TCOMPANIES.SetCEP(const Value: String); begin FCEP := Value; end; procedure TCOMPANIES.SetCNPJ(const Value: String); begin FCNPJ := Value; end; procedure TCOMPANIES.SetCOMPANYNAME(const Value: String); begin FCOMPANYNAME := Value; end; procedure TCOMPANIES.SetCOMPLEMENT(const Value: String); begin FCOMPLEMENT := Value; end; procedure TCOMPANIES.SetGUUID(const Value: String); begin FGUUID := Value; end; procedure TCOMPANIES.SetIDAREASEXPERTISE(const Value: String); begin FIDAREASEXPERTISE := Value; end; procedure TCOMPANIES.SetIDCITY(const Value: String); begin FIDCITY := Value; end; procedure TCOMPANIES.SetIDCOUNTRY(const Value: String); begin FIDCOUNTRY := Value; end; procedure TCOMPANIES.SetIDSTATE(const Value: String); begin FIDSTATE := Value; end; procedure TCOMPANIES.SetLOGO(const Value: String); begin FLOGO := Value; end; procedure TCOMPANIES.SetNEIGHBORHOOD(const Value: String); begin FNEIGHBORHOOD := Value; end; procedure TCOMPANIES.SetNUMBER(const Value: Integer); begin FNUMBER := Value; end; procedure TCOMPANIES.SetPICTURE(const Value: String); begin FPICTURE := Value; end; end.
unit Lists; interface type pElem = ^Elem; Elem = record Data : integer; pnext : pElem; pprev : pElem; end; List = record pfirst : pElem; plast : pElem; end; procedure PushF(var s : List; const pnumber : pElem); procedure PushB(var s : List; const pnumber : pElem); procedure Print(var s : List); procedure DeleteList(var s : List); function Size(var s : List) : integer; function PopF(var s : List) : boolean; function PopB(var s : List) : boolean; implementation procedure PushF(var s : List; const pnumber : pElem); begin if (pnumber = nil) then exit; pnumber^.pnext := nil; pnumber^.pprev := nil; if (s.pfirst = nil) then begin s.pfirst := pnumber; s.plast := pnumber; end else begin pnumber^.pnext := s.pfirst; s.pfirst^.pprev := pnumber; s.pfirst := pnumber; end; end; procedure PushB(var s : List; const pnumber : pElem); begin if (pnumber = nil) then exit; pnumber^.pnext := nil; pnumber^.pprev := nil; if (s.pfirst = nil) then begin s.pfirst := pnumber; s.plast := pnumber; end else begin s.plast^.pnext := pnumber; pnumber^.pprev := s.plast; s.plast := pnumber; end; end; procedure Print(var s : List); var x : pElem; i : integer; begin x := s.pfirst; write('('); i := 0; while (x <> nil) do begin inc(i); if (i > 1) then write(', '); write(x^.Data); x := x^.pnext; end; writeln(')'); end; procedure DeleteList(var s : List); var next, del : pElem; begin if (s.pfirst = nil) then exit; next := s.pfirst; while (next <> nil) do begin del := next; next := next^.pnext; dispose(del); end; s.pfirst := nil; s.plast := nil; end; function GetElem(var s : List; const number : integer) : pElem; var i : integer; next, res : pElem; begin res := nil; i := 1; next := s.pfirst; while (i <= number) and (next <> nil) do begin if (i = number) then begin res := next; break; end; inc(i); next := next^.pnext; end; GetElem := res; end; function DelByPoint(var s : List; var pElement : pElem) : boolean; begin DelByPoint := false; if (pElement = nil) then exit; if (pElement = s.pfirst) then begin s.pfirst := pElement^.pnext; if (s.pfirst = nil) then s.plast := nil else s.pfirst^.pprev := nil; end else if (pElement = s.plast) then begin s.plast := pElement^.pprev; if (s.plast = nil) then s.pfirst := nil else s.plast^.pnext := nil; end else begin pElement^.pprev^.pnext := pElement^.pnext; pElement^.pnext^.pprev := pElement^.pprev; end; dispose(pElement); pElement := nil; DelByPoint := true; end; function PopF(var s : List) : boolean; var x : pElem; begin x := s.pfirst; PopF := DelByPoint(s, x); end; function PopB(var s : List) : boolean; var x : pElem; begin x := s.plast; PopB := DelByPoint(s, x); end; function Size(var s : List) : integer; var count : integer; pElement : pElem; begin count := 0; pElement := s.pfirst; while (pElement <> nil) do begin inc(count); pElement := pElement^.pnext; end; Size := count; end; end.
unit SyncIndex; interface uses Windows, Collection, Classes, SysUtils, CabUtils; const IgnoreDate : TFileTime = (dwLowDateTime : 0; dwHighDateTime : 0); type TSynchObjectKind = (sokArchive, sokFolder, sokSyncFolder); TCollection = Collection.TCollection; type TFolderIndexEntry = class; TFolderIndex = class; TFolderIndexEntry = class public constructor Create(aName : string; aDate : TFileTime; aSize : integer; aPckt : string; aKind : TSynchObjectKind); private fName : string; fDate : TFileTime; fSize : integer; fPckt : string; fKind : TSynchObjectKind; fFlag : boolean; public property Name : string read fName; property Date : TFileTime read fDate; property Size : integer read fSize; property Pckt : string read fPckt; property Kind : TSynchObjectKind read fKind; property Flag : boolean read fFlag; end; TFolderIndex = class public constructor Create; constructor Load(Stream : TStream); procedure Store(Stream : TStream); destructor Destroy; override; private fItems : TCollection; public procedure Add(Entry : TFolderIndexEntry); procedure AddCab(path : string; Info : TSearchRec); function FindFile(name : string; var Entry : TFolderIndexEntry) : boolean; private function Compare(Item1, Item2 : TObject) : integer; procedure AddCabInfo(cabfile : pchar; Info : PFileInCabinetInfo); function GetCount : integer; function GetEntry(index : integer) : TFolderIndexEntry; public property Count : integer read GetCount; property Entries[index : integer] : TFolderIndexEntry read GetEntry; default; end; TMasterIndex = class public constructor Create(aPath, aName : string; Synch : boolean); constructor Load(Stream : TStream); procedure Store(Stream : TStream); destructor Destroy; override; private fName : string; fFolderIndex : TFolderIndex; fSubFolders : TCollection; private function GetCount : integer; function GetItem(index : integer) : TMasterIndex; public property Name : string read fName; property FolderIndex : TFolderIndex read fFolderIndex; property Count : integer read GetCount; property Items[index : integer] : TMasterIndex read GetItem; default; end; const syncFolderFile = 'folders.sync'; syncIndexFile = 'index.sync'; syncMasterIndexFile = 'index.midx'; function CompareFolder(indexName, Folder : string; NewFiles, OldFiles, NewDirs, SyncDirs, OldDirs : TStringList; var count : integer; recurse : boolean) : TObject; // Returns a TFolderIndex or a TMasterIndex, just make sure you to release it yourself procedure CreateIndex(Folder, indexName : string; rec : boolean); procedure CreateMasterIndex(Folder, indexName : string); function ChangePath(path : string; fCh, tCh : char) : string; procedure ChangePaths(List : TStringList; fCh, tCh : char); implementation uses DelphiStreamUtils; function FileTimeToDateTime(FileTime : TFileTime) : TDateTime; var SysTime : TSystemTime; begin FileTimeToSystemTime(FileTime, SysTime); result := SystemTimeToDateTime(SysTime); end; function FileTimeToStr(FileTime : TFileTime) : string; begin result := DateTimeToStr(FileTimeToDateTime(FileTime)); end; // TFolderIndexEntry constructor TFolderIndexEntry.Create(aName : string; aDate : TFileTime; aSize : integer; aPckt : string; aKind : TSynchObjectKind); begin fName := aName; fDate := aDate; fSize := aSize; fPckt := aPckt; fKind := aKind; end; // TFolderIndex constructor TFolderIndex.Create; begin inherited Create; fItems := Collection.TSortedCollection.Create(0, rkBelonguer, Compare); end; constructor TFolderIndex.Load(Stream : TStream); var count : integer; i : integer; Entry : TFolderIndexEntry; name : string; date : TFileTime; size : integer; pck : string; kind : TSynchObjectKind; begin inherited Create; fItems := Collection.TCollection.Create(0, rkBelonguer); Stream.Read(count, sizeof(count)); for i := 0 to pred(count) do begin ReadString(Stream, name); Stream.Read(date, sizeof(date)); Stream.Read(size, sizeof(size)); ReadString(Stream, pck); Stream.Read(kind, sizeof(kind)); Entry := TFolderIndexEntry.Create(name, date, size, pck, kind); fItems.Insert(Entry); end; end; procedure TFolderIndex.Store(Stream : TStream); var count : integer; i : integer; begin count := fItems.Count; Stream.Write(count, sizeof(count)); for i := 0 to pred(count) do with TFolderIndexEntry(fItems[i]) do begin WriteString(Stream, fName); Stream.Write(fDate, sizeof(fDate)); Stream.Write(fSize, sizeof(fSize)); WriteString(Stream, fPckt); Stream.Write(fKind, sizeof(fKind)); end; end; destructor TFolderIndex.Destroy; begin fItems.Free; inherited; end; procedure TFolderIndex.Add(Entry : TFolderIndexEntry); var tmpEntry : TFolderIndexEntry; begin Entry.fName := lowercase(Entry.fName); if FindFile(Entry.fName, tmpEntry) then Entry.Free else fItems.Insert(Entry); end; procedure TFolderIndex.AddCabInfo(cabfile : pchar; Info : PFileInCabinetInfo); var name : string; Entry : TFolderIndexEntry; fltm : TFileTime; utcft : TFileTime; cbName : string; begin name := lowercase(Info.NameInCabinet); cbName := ExtractFileName(cabfile); DosDateTimeToFileTime(Info.DosDate, Info.DosTime, fltm); LocalFileTimeToFileTime(fltm, utcft); if FindFile(name, Entry) then begin Entry.fPckt := cbName; //Entry.fDate := utcft; end else begin Entry := TFolderIndexEntry.Create(name, utcft, Info.FileSize, cbName, sokArchive); fItems.Insert(Entry); end; end; procedure TFolderIndex.AddCab(path : string; Info : TSearchRec); var i : integer; begin ListCabFile(path, AddCabInfo); for i := 0 to pred(Count) do if Entries[i].Pckt = Info.Name then Entries[i].fSize := Info.Size; end; function TFolderIndex.FindFile(name : string; var Entry : TFolderIndexEntry) : boolean; var i : integer; begin i := 0; name := lowercase(name); while (i < Count) and (Entries[i].fName <> name) do inc(i); result := i < Count; if result then Entry := Entries[i] else Entry := nil; end; function TFolderIndex.Compare(Item1, Item2 : TObject) : integer; begin result := TFolderIndexEntry(Item1).fSize - TFolderIndexEntry(Item2).fSize; end; function TFolderIndex.GetCount : integer; begin result := fItems.Count; end; function TFolderIndex.GetEntry(index : integer) : TFolderIndexEntry; begin result := TFolderIndexEntry(fItems[index]); end; // TMasterIndex constructor TMasterIndex.Create(aPath, aName : string; Synch : boolean); var Stream : TStream; IdxName : string; i : integer; MstrIdx : TMasterIndex; begin inherited Create; fName := aName; fSubFolders := TCollection.Create(0, rkBelonguer); if aName <> '' then IdxName := aPath + aName + '\' + syncIndexFile else IdxName := aPath + syncIndexFile; if FileExists(IdxName) then begin Stream := TFileStream.Create(IdxName, fmOpenRead); fFolderIndex := TFolderIndex.Load(Stream); i := 0; while i < fFolderIndex.Count do begin if fFolderIndex[i].Kind = sokSyncFolder then begin MstrIdx := TMasterIndex.Create(ExtractFilePath(IdxName), fFolderIndex[i].fName, true); fSubFolders.Insert(MstrIdx); end; inc(i); end; end else IdxName := ''; end; constructor TMasterIndex.Load(Stream : TStream); var i : integer; c : integer; b : boolean; begin inherited Create; Stream.Read(b, sizeof(b)); if b then fFolderIndex := TFolderIndex.Load(Stream) else fFolderIndex := nil; ReadString(Stream, fName); Stream.Read(c, sizeof(c)); fSubFolders := TCollection.Create(0, rkBelonguer); for i := 0 to pred(c) do fSubFolders.Insert(TMasterIndex.Load(Stream)); end; procedure TMasterIndex.Store(Stream : TStream); var i : integer; c : integer; b : boolean; begin b := fFolderIndex <> nil; Stream.Write(b, sizeof(b)); if b then fFolderIndex.Store(Stream); WriteString(Stream, fName); c := Count; Stream.Write(c, sizeof(c)); for i := 0 to pred(c) do Items[i].Store(Stream); end; destructor TMasterIndex.Destroy; begin fFolderIndex.Free; fSubFolders.Free; inherited; end; function TMasterIndex.GetCount : integer; begin if fSubFolders <> nil then result := fSubFolders.Count else result := 0; end; function TMasterIndex.GetItem(index : integer) : TMasterIndex; begin if fSubFolders <> nil then result := TMasterIndex(fSubFolders[index]) else result := nil; end; // CompareFolders procedure BuildTree(Path : string; Dirs : TStringList); var Search : TSearchRec; begin Dirs.Add(Path); if FindFirst(Path + '*.*', faDirectory, Search) = 0 then repeat if (Search.Attr and faDirectory <> 0) and (Search.Name <> '.') and (Search.Name <> '..') then BuildTree(Path + Search.Name + '\' , Dirs); until FindNext(Search) <> 0; FindClose(Search); end; function DoCompareFolder(Dest, Prefix : string; Index : TFolderIndex; NewFiles, OldFiles, NewDirs, SyncDirs, OldDirs : TStringList; recurse : boolean) : integer; var Search : TSearchRec; Entry : TFolderIndexEntry; Tree : TStringList; i : integer; idxDate : string; curDate : string; newFile : string; CurPath : string; RelPath : string; DestLen : integer; begin result := 0; try DestLen := length(Dest); Tree := TStringList.Create; if recurse then BuildTree(Dest, Tree) else Tree.Add(Dest); while Tree.Count > 0 do begin CurPath := Tree[0]; Tree.Delete(0); //if FindFirst(Dest + '*.*', faArchive + faDirectory, Search) = 0 if FindFirst(CurPath + '*.*', faArchive + faDirectory, Search) = 0 then begin repeat if (Search.Name <> '.') and (Search.Name <> '..') then begin RelPath := copy(CurPath, DestLen + 1, length(CurPath) - DestLen); if Index.FindFile(RelPath + Search.Name, Entry) then begin Entry.fFlag := true; if Search.Attr and faDirectory <> 0 then case Entry.fKind of sokArchive : begin OldDirs.Add(Prefix + Search.Name); if Entry.fPckt <> '' then newFile := Prefix + Entry.fPckt else newFile := Prefix + Search.Name; if NewFiles.IndexOf(newFile) = -1 then begin NewFiles.AddObject(newFile, Index); inc(result, Entry.Size); end; end; sokSyncFolder : SyncDirs.Add(Prefix + Search.Name); end else begin if Entry.fKind = sokArchive then begin idxDate := FileTimeToStr(Entry.fDate); curDate := FileTimeToStr(Search.FindData.ftCreationTime) + '' + FileTimeToStr(Search.FindData.ftLastWriteTime); // >> ¿...? if CompareFileTime(Entry.fDate, Search.FindData.ftLastWriteTime) > 0 then begin if Entry.fPckt <> '' then newFile := Prefix + Entry.fPckt else newFile := Prefix + Entry.fName; if NewFiles.IndexOf(newFile) = -1 then begin NewFiles.AddObject(newFile, Index); inc(result, Entry.Size); end; end end else OldFiles.Add(Prefix + Entry.fName); end end else if Search.Attr and faArchive <> 0 then OldFiles.Add(Prefix + Search.Name) else if Search.Attr and faDirectory <> 0 then OldDirs.Add(Prefix + Search.Name); end; until FindNext(Search) <> 0; end; FindClose(Search); end; // Check for new files and folders for i := 0 to pred(Index.Count) do begin Entry := Index.Entries[i]; if not Entry.fFlag then case Entry.fKind of sokArchive : begin if Entry.fPckt <> '' then newFile := Prefix + Entry.fPckt else newFile := Prefix + Entry.fName; if NewFiles.IndexOf(newFile) = -1 then begin NewFiles.AddObject(newFile, Index); inc(result, Entry.Size); end; end; sokSyncFolder : begin SyncDirs.Add(Prefix + Entry.fName); NewDirs.Add(Prefix + Entry.fName); end; sokFolder : NewDirs.Add(Prefix + Entry.fName); end; end; finally //FindClose(Search); end; end; function CompareFolder(indexName, Folder : string; NewFiles, OldFiles, NewDirs, SyncDirs, OldDirs : TStringList; var count : integer; recurse : boolean) : TObject; // Returns a TFolderIndex or a TMasterIndex, just make sure you to release it yourself procedure CompareMasterIndex(Prefix : string; MasterIndex : TMasterIndex); var i : integer; NewPrf : string; begin count := count + DoCompareFolder(Folder + Prefix, Prefix, MasterIndex.FolderIndex, NewFiles, OldFiles, NewDirs, SyncDirs, OldDirs, recurse); for i := 0 to pred(MasterIndex.Count) do begin if Prefix <> '' then if MasterIndex[i].Name <> '' then NewPrf := Prefix + MasterIndex[i].Name + '\' else NewPrf := Prefix else if MasterIndex[i].Name <> '' then NewPrf := MasterIndex[i].Name + '\' else NewPrf := ''; CompareMasterIndex(NewPrf, MasterIndex[i]); end; end; var Index : TFolderIndex; Stream : TStream; MasterIndex : TMasterIndex; begin count := 0; if FileExists(Folder + indexName) then begin Stream := TFileStream.Create(Folder + indexName, fmOpenRead); try try if lowercase(ExtractFileExt(indexName)) = '.sync' then begin Index := TFolderIndex.Load(Stream); count := count + DoCompareFolder(Folder, '', Index, NewFiles, OldFiles, NewDirs, SyncDirs, OldDirs, recurse); result := Index; end else if lowercase(ExtractFileExt(indexName)) = '.midx' then begin MasterIndex := TMasterIndex.Load(Stream); CompareMasterIndex('', MasterIndex); result := MasterIndex; end else result := nil; finally Stream.Free; end; except result := nil; end; end else result := nil; end; procedure CreateIndex(Folder, indexName : string; rec : boolean); var SyncFolder : TStringList; Search : TSearchRec; Index : TFolderIndex; Stream : TStream; Entry : TFolderIndexEntry; FileExt : string; i : integer; begin try SyncFolder := TStringList.Create; if FileExists(Folder + syncFolderFile) then begin SyncFolder.LoadFromFile(Folder + syncFolderFile); for i := 0 to pred(SyncFolder.Count) do SyncFolder[i] := lowercase(SyncFolder[i]); end; Index := TFolderIndex.Create; try if FindFirst(Folder + '*.*', faArchive + faDirectory, Search) = 0 then repeat if Search.Attr and faArchive <> 0 then begin FileExt := UpperCase(ExtractFileExt(Search.Name)); if FileExt = '.CAB' then Index.AddCab(Folder + Search.Name, Search) else if (FileExt <> '.SYNC') and (FileExt <> '.BAT') and (FileExt <> '.MIDX') then if not Index.FindFile(Search.Name, Entry) then begin Entry := TFolderIndexEntry.Create( Search.Name, Search.FindData.ftLastWriteTime, // >> ¿...? Search.Size, '', sokArchive); Entry.fFlag := true; Index.Add(Entry); end else begin Entry.fDate := Search.FindData.ftLastWriteTime; Entry.fFlag := true; end; end else if (Search.Attr and faDirectory <> 0) and (Search.Name <> '.') and (Search.Name <> '..') then begin if SyncFolder.IndexOf(lowercase(Search.Name)) <> noIndex then Index.Add(TFolderIndexEntry.Create(Search.Name, IgnoreDate, 0, '', sokSyncFolder)) else Index.Add(TFolderIndexEntry.Create(Search.Name, IgnoreDate, 0, '', sokFolder)); if rec then CreateIndex(Folder + Search.Name + '\', indexName, true); end; until FindNext(Search) <> 0; Stream := TFileStream.Create(Folder + indexName, fmCreate); try Index.Store(Stream); finally Stream.Free; end; finally FindClose(Search); Index.Free; SyncFolder.Free; end; except end; end; procedure CreateMasterIndex(Folder, indexName : string); var MasterIndex : TMasterIndex; Stream : TStream; begin if (Folder <> '') and (Folder[length(Folder)] <> '\') then Folder := Folder + '\'; MasterIndex := TMasterIndex.Create(Folder, '', true); Stream := TFileStream.Create(Folder + IndexName, fmCreate); try MasterIndex.Store(Stream); finally Stream.Free; end; end; function ChangePath(path : string; fCh, tCh : char) : string; var i : integer; begin if path <> '' then begin SetLength(result, length(path)); for i := 1 to length(path) do if path[i] = fCh then result[i] := tCh else result[i] := path[i]; end else result := ''; end; procedure ChangePaths(List : TStringList; fCh, tCh : char); var i : integer; begin for i := 0 to pred(List.Count) do List[i] := ChangePath(List[i], fCh, tCh); end; end.
unit destListLevel; // Модуль: "w:\common\components\rtl\Garant\dd\destListLevel.pas" // Стереотип: "SimpleClass" // Элемент модели: "TdestListLevel" MUID: (51DD4CAB0089) {$Include w:\common\components\rtl\Garant\dd\ddDefine.inc} interface uses l3IntfUses , ddRTFdestination , rtfListTable , ddCustomRTFReader , ddRTFState , RTFtypes , l3Base ; type TdestListLevel = class(TddRTFDestination) private f_Level: TrtfListLevel; protected procedure Cleanup; override; {* Функция очистки полей объекта. } public procedure Close(aState: TddRTFState; aNewDest: TddRTFDestination); override; procedure WriteText(aRDS: TRDS; aText: Tl3String; aState: TddRTFState); override; procedure Clear; override; procedure ApplyProperty(propType: TPropType; What: TIProp; Value: LongInt; aState: TddRTFState); override; constructor Create(aRTFReader: TddCustomRTFReader); override; public property Level: TrtfListLevel read f_Level; end;//TdestListLevel implementation uses l3ImplUses , SysUtils , destList //#UC START# *51DD4CAB0089impl_uses* //#UC END# *51DD4CAB0089impl_uses* ; procedure TdestListLevel.Close(aState: TddRTFState; aNewDest: TddRTFDestination); //#UC START# *5461BEC2017D_51DD4CAB0089_var* //#UC END# *5461BEC2017D_51DD4CAB0089_var* begin //#UC START# *5461BEC2017D_51DD4CAB0089_impl* if (aNewDest.RDS = rdsList) then begin TdestList(aNewDest).AddLevel(Self); Clear; end; //#UC END# *5461BEC2017D_51DD4CAB0089_impl* end;//TdestListLevel.Close procedure TdestListLevel.WriteText(aRDS: TRDS; aText: Tl3String; aState: TddRTFState); //#UC START# *54E1F08400F9_51DD4CAB0089_var* //#UC END# *54E1F08400F9_51DD4CAB0089_var* begin //#UC START# *54E1F08400F9_51DD4CAB0089_impl* Assert(False); //#UC END# *54E1F08400F9_51DD4CAB0089_impl* end;//TdestListLevel.WriteText procedure TdestListLevel.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_51DD4CAB0089_var* //#UC END# *479731C50290_51DD4CAB0089_var* begin //#UC START# *479731C50290_51DD4CAB0089_impl* inherited Cleanup; FreeAndNil(f_Level); //#UC END# *479731C50290_51DD4CAB0089_impl* end;//TdestListLevel.Cleanup procedure TdestListLevel.Clear; //#UC START# *51D27A48038E_51DD4CAB0089_var* //#UC END# *51D27A48038E_51DD4CAB0089_var* begin //#UC START# *51D27A48038E_51DD4CAB0089_impl* with f_Level do begin CHP.Clear; Follow:= 0; Justify:= 0; LevelJC:= 0; LevelJCN:= 0; LevelNFC:= 0; LevelNFCN:= 0; Numbers:= ''; NumberType:= 0; StartAt:= 1; Text:= ''; end; //#UC END# *51D27A48038E_51DD4CAB0089_impl* end;//TdestListLevel.Clear procedure TdestListLevel.ApplyProperty(propType: TPropType; What: TIProp; Value: LongInt; aState: TddRTFState); //#UC START# *51D27EC50388_51DD4CAB0089_var* //#UC END# *51D27EC50388_51DD4CAB0089_var* begin //#UC START# *51D27EC50388_51DD4CAB0089_impl* case What of iproplevelfollow: Level.Follow:= Value; ipropLeveljc: Level.LevelJC:= Value; ipropleveljcn: Level.LevelJcn:= Value; iproplevelnfc: Level.LevelNFC:= Value; iproplevelnfcn: Level.LevelNFCN:= Value; iproplevelstartat: Level.StartAt:= Value; end; //#UC END# *51D27EC50388_51DD4CAB0089_impl* end;//TdestListLevel.ApplyProperty constructor TdestListLevel.Create(aRTFReader: TddCustomRTFReader); //#UC START# *51E7C9DB0213_51DD4CAB0089_var* //#UC END# *51E7C9DB0213_51DD4CAB0089_var* begin //#UC START# *51E7C9DB0213_51DD4CAB0089_impl* inherited Create(aRTFReader); f_Level := TrtfListLevel.Create(); //#UC END# *51E7C9DB0213_51DD4CAB0089_impl* end;//TdestListLevel.Create end.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } { Converted from org.apache.xml.security.c14n; } {* * Copyright 1999-2008 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *} { Author Christian Geuer-Pollmann geuer-pollmann@nue.et-inf.uni-siegen.de University of Siegen Institute for Data Communications Systems } unit clXmlCanonicalizerUtils; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, SysUtils, Windows, Variants, msxml{$IFDEF DELPHI2009}, WideStrings{$ENDIF}, {$ELSE} System.Classes, System.SysUtils, Winapi.Windows, System.Variants, Winapi.msxml, System.WideStrings, {$ENDIF} clUtils; type EclXmlCanonicalizeError = class(Exception) private FErrorCode: Integer; public constructor Create(const AErrorMsg: string; AErrorCode: Integer; ADummy: Boolean = False); property ErrorCode: Integer read FErrorCode; end; {** * A stack based Symble Table. * For speed reasons all the symbols are introduced in the same map, * and at the same time in a list so it can be removed when the frame is pop back. * @author Raul Benito **} TclNameSpaceSymbEntry = class(TPersistent) private FRendered: Boolean; FUri: WideString; FAttr: IXMLDOMAttribute; FPrefix: WideString; FLevel: Integer; FLastRendered: WideString; public constructor Create; overload; constructor Create(const AUri: WideString; const Attr: IXMLDOMAttribute; ARendered: Boolean; const APrefix: WideString); overload; procedure Assign(Source: TPersistent); override; property Uri: WideString read FUri; property Attr: IXMLDOMAttribute read FAttr; property Prefix: WideString read FPrefix; property Rendered: Boolean read FRendered write FRendered; property Level: Integer read FLevel write FLevel; property LastRendered: WideString read FLastRendered write FLastRendered; end; TclSymbMap = class(TPersistent) private FEntries: TWideStringList; function GetCount: Integer; function GetItem(Index: Integer): TclNameSpaceSymbEntry; procedure Clear; public constructor Create; destructor Destroy; override; procedure Assign(Source: TPersistent); override; procedure Put(const AKey: WideString; AValue: TclNameSpaceSymbEntry); function Get(const AKey: WideString): TclNameSpaceSymbEntry; property Count: Integer read GetCount; property Items[Index: Integer]: TclNameSpaceSymbEntry read GetItem; default; end; TclNameSpaceSymbTable = class private FNameSpaces: Integer; FLevel: TList; FSymb: TclSymbMap; FCloned: Boolean; procedure SetSymb(ASymb: TclSymbMap); procedure ClearLevel; procedure NeedsClone; procedure HandleParent(const AElement: IXMLDOMElement); public constructor Create; destructor Destroy; override; procedure GetParentNameSpaces(const AElement: IXMLDOMElement); function GetMappingWithoutRendered(const APrefix: WideString): IXMLDOMAttribute; function AddMappingAndRender(const APrefix, AUri: WideString; const Attr: IXMLDOMAttribute): IXMLDOMNode; function AddMapping(const APrefix, AUri: WideString; const Attr: IXMLDOMAttribute): Boolean; function GetMapping(const APrefix: WideString): IXMLDOMAttribute; procedure OutputNodePush; procedure OutputNodePop; procedure Push; procedure Pop; end; TclCanonicalizerUtfHelper = class public class procedure WriteCharToUtf8(C: WideChar; AOutput: TStream); class procedure WriteStringToUtf8(const AStr: WideString; AOutput: TStream); end; TclInclusiveNamespaces = class public class procedure PrefixStr2Set(const AInclusiveNamespaces: WideString; AInclusiveNSSet: TWideStringList); end; {** * Temporary swapped static functions from the normalizer Section * * @author Christian Geuer-Pollmann *} TclC14nHelper = class public class function NamespaceIsRelative(const ANamespaceValue: WideString): Boolean; class function NamespaceIsAbsolute(const ANamespaceValue: WideString): Boolean; end; {** * Compares two attributes based on the C14n specification. * * Namespace nodes have a lesser document order position than attribute * nodes. * An element's namespace nodes are sorted lexicographically by * local name (the default namespace node, if one exists, has no * local name and is therefore lexicographically least). * An element's attribute nodes are sorted lexicographically with * namespace URI as the primary key and local name as the secondary * key (an empty namespace URI is lexicographically least). * * @author Christian Geuer-Pollmann *} TclAttrCompare = class public function Compare(Obj0, Obj1: IInterface): Integer; end; const ALGO_ID_C14N_OMIT_COMMENTS = 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315'; ALGO_ID_C14N_WITH_COMMENTS = 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments'; ALGO_ID_C14N_EXCL_OMIT_COMMENTS = 'http://www.w3.org/2001/10/xml-exc-c14n#'; ALGO_ID_C14N_EXCL_WITH_COMMENTS = 'http://www.w3.org/2001/10/xml-exc-c14n#WithComments'; ALGO_ID_C14N11_OMIT_COMMENTS = 'http://www.w3.org/2006/12/xml-c14n11'; ALGO_ID_C14N11_WITH_COMMENTS = 'http://www.w3.org/2006/12/xml-c14n11#WithComments'; resourcestring XmlC14nBadNodeType = 'Illegal node type during traversal'; XmlC14nRelativeNamespace = 'Relative namespace found'; const XmlC14nBadNodeTypeCode = -10; XmlC14nRelativeNamespaceCode = -11; implementation uses clTranslator, clXmlUtils; { TclNameSpaceSymbTable } function TclNameSpaceSymbTable.AddMapping(const APrefix, AUri: WideString; const Attr: IXMLDOMAttribute): Boolean; var ob, ne: TclNameSpaceSymbEntry; begin ob := FSymb.Get(APrefix); if (ob <> nil) and (AUri = ob.Uri) then begin Result := False; Exit; end; ne := TclNameSpaceSymbEntry.Create(AUri, Attr, False, APrefix); if (ob <> nil) then begin ne.LastRendered := ob.LastRendered; if (ob.LastRendered = AUri) then begin ne.Rendered := True; end; end; NeedsClone(); FSymb.Put(APrefix, ne); Result := True; end; function TclNameSpaceSymbTable.AddMappingAndRender(const APrefix, AUri: WideString; const Attr: IXMLDOMAttribute): IXMLDOMNode; var ob, newOb, ne: TclNameSpaceSymbEntry; begin ob := FSymb.Get(APrefix); if ((ob <> nil) and (AUri = ob.Uri)) then begin if (not ob.Rendered) then begin newOb := TclNameSpaceSymbEntry.Create(); newOb.Assign(ob); NeedsClone(); FSymb.Put(APrefix, newOb); newOb.LastRendered := AUri; newOb.Rendered := True; Result := newOb.Attr; end else begin Result := nil; end; end else begin ne := TclNameSpaceSymbEntry.Create(AUri, Attr, True, APrefix); ne.LastRendered := AUri; if (ob <> nil) and (ob.LastRendered = AUri) then begin ne.Rendered := True; Result := nil; end else begin Result := ne.Attr; end; NeedsClone(); FSymb.Put(APrefix, ne); end; end; procedure TclNameSpaceSymbTable.ClearLevel; var i: Integer; begin for i := 0 to FLevel.Count - 1 do begin TObject(FLevel[i]).Free(); end; FLevel.Clear(); end; constructor TclNameSpaceSymbTable.Create; var ne: TclNameSpaceSymbEntry; begin inherited Create(); FLevel := TList.Create(); FSymb := TclSymbMap.Create(); FNameSpaces := 0; FCloned := True; ne := TclNameSpaceSymbEntry.Create('', nil, True, cXMLNS); FSymb.Put(cXMLNS, ne); end; destructor TclNameSpaceSymbTable.Destroy; begin SetSymb(nil); ClearLevel(); FLevel.Free(); inherited Destroy(); end; function TclNameSpaceSymbTable.GetMapping(const APrefix: WideString): IXMLDOMAttribute; var entry, newEntry: TclNameSpaceSymbEntry; begin entry := FSymb.Get(APrefix); if (entry = nil) then begin Result := nil; Exit; end; if (entry.Rendered) then begin Result := nil; Exit; end; newEntry := TclNameSpaceSymbEntry.Create(); newEntry.Assign(entry); NeedsClone(); FSymb.Put(APrefix, newEntry); newEntry.Rendered := True; newEntry.Level := FNameSpaces; newEntry.LastRendered := newEntry.Uri; Result := newEntry.Attr; end; function TclNameSpaceSymbTable.GetMappingWithoutRendered(const APrefix: WideString): IXMLDOMAttribute; var entry: TclNameSpaceSymbEntry; begin entry := FSymb.Get(APrefix); if (entry = nil) then begin Result := nil; end else if (entry.Rendered) then begin Result := nil; end else begin Result := entry.Attr; end; end; procedure TclNameSpaceSymbTable.GetParentNameSpaces(const AElement: IXMLDOMElement); var i: Integer; parents: TInterfaceList; parent, ele: IXMLDOMElement; nsprefix: IXMLDOMAttribute; begin parents := TInterfaceList.Create(); try if (AElement.parentNode = nil) or (AElement.parentNode.nodeType <> NODE_ELEMENT) then Exit; parent := AElement.parentNode as IXMLDOMElement; while (parent <> nil) do begin parents.Add(parent); if (parent.parentNode = nil) or (parent.parentNode.nodeType <> NODE_ELEMENT) then Break; parent := parent.parentNode as IXMLDOMElement; end; for i := parents.Count - 1 downto 0 do begin ele := parents[i] as IXMLDOMElement; HandleParent(ele); end; nsprefix := GetMappingWithoutRendered(cXMLNS); if (nsprefix <> nil) and (nsprefix.value = '') then begin AddMappingAndRender(cXMLNS, '', nil{TODO nullNode}); end; finally parents.Free(); end; end; procedure TclNameSpaceSymbTable.HandleParent(const AElement: IXMLDOMElement); var i: Integer; N: IXMLDOMAttribute; NName, NValue: WideString; begin for i := 0 to AElement.attributes.length - 1 do begin N := AElement.attributes.item[i] as IXMLDOMAttribute; if (cXMLNS_URI <> GetNamespaceURI(N)) then begin Continue; end; NName := GetAttributeLocalName(N); NValue := VarToWideStr(N.value); if (cXML = NName) and (cXML_LANG_URI = NValue) then begin Continue; end; AddMapping(NName, NValue, N); end; end; procedure TclNameSpaceSymbTable.NeedsClone; var newSymb: TclSymbMap; begin if (not FCloned) then begin newSymb := TclSymbMap.Create(); FLevel[FLevel.Count - 1] := newSymb; newSymb.Assign(FSymb); FCloned := True; end; end; procedure TclNameSpaceSymbTable.OutputNodePop; begin Dec(FNameSpaces); Pop(); end; procedure TclNameSpaceSymbTable.OutputNodePush; begin Inc(FNameSpaces); Push(); end; procedure TclNameSpaceSymbTable.Pop; var size: Integer; ob: TclSymbMap; begin size := FLevel.Count - 1; ob := TclSymbMap(FLevel[size]); FLevel.Delete(size); if (ob <> nil) then begin SetSymb(ob); if (size = 0) then begin FCloned := False; end else begin FCloned := (FLevel[size - 1] <> FSymb); //TODO possible bug, comparing of pointers, Delphi implementation has always different pointers - only nulls are equal end; end else begin FCloned := False; end; end; procedure TclNameSpaceSymbTable.Push; begin FLevel.Add(nil); FCloned := False; end; procedure TclNameSpaceSymbTable.SetSymb(ASymb: TclSymbMap); begin FSymb.Free(); FSymb := ASymb; end; { TclCanonicalizerUtfHelper } class procedure TclCanonicalizerUtfHelper.WriteCharToUtf8(C: WideChar; AOutput: TStream); begin WriteStringToUtf8(C, AOutput); end; class procedure TclCanonicalizerUtfHelper.WriteStringToUtf8(const AStr: WideString; AOutput: TStream); var buf: TclByteArray; begin buf := TclTranslator.GetUtf8Bytes(AStr); if (Length(buf) > 0) then begin AOutput.Write(buf[0], Length(buf)); end; end; { TclInclusiveNamespaces } class procedure TclInclusiveNamespaces.PrefixStr2Set(const AInclusiveNamespaces: WideString; AInclusiveNSSet: TWideStringList); var i: Integer; begin if (AInclusiveNamespaces = '') then Exit; SplitText(AInclusiveNamespaces, AInclusiveNSSet, [#9, #13, #10]); for i := 0 to AInclusiveNSSet.Count - 1 do begin if ('#default' = AInclusiveNSSet[i]) then begin AInclusiveNSSet[i] := cXMLNS; end; end; end; { TclC14nHelper } class function TclC14nHelper.NamespaceIsRelative(const ANamespaceValue: WideString): Boolean; begin Result := not NamespaceIsAbsolute(ANamespaceValue); end; class function TclC14nHelper.NamespaceIsAbsolute(const ANamespaceValue: WideString): Boolean; begin if (ANamespaceValue = '') then begin Result := True; end else begin Result := (system.Pos(':', ANamespaceValue) > 1); end; end; { TclSymbMap } procedure TclSymbMap.Assign(Source: TPersistent); var i: Integer; src: TclSymbMap; ent: TclNameSpaceSymbEntry; begin if (Source is TclSymbMap) then begin src := TclSymbMap(Source); FEntries.Clear(); for i := 0 to src.FEntries.Count - 1 do begin ent := TclNameSpaceSymbEntry.Create(); FEntries.AddObject(src.FEntries[i], ent); ent.Assign(TclNameSpaceSymbEntry(src.FEntries.Objects[i])); end; end else begin inherited Assign(Source); end; end; procedure TclSymbMap.Clear; var i: Integer; begin for i := 0 to FEntries.Count - 1 do begin GetItem(i).Free(); end; FEntries.Clear(); end; constructor TclSymbMap.Create; begin inherited Create(); FEntries := TWideStringList.Create(); end; destructor TclSymbMap.Destroy; begin Clear(); FEntries.Free(); inherited Destroy(); end; function TclSymbMap.Get(const AKey: WideString): TclNameSpaceSymbEntry; var ind: Integer; begin ind := FEntries.IndexOf(AKey); if (ind < 0) then begin Result := nil; end else begin Result := GetItem(ind); end; end; function TclSymbMap.GetCount: Integer; begin Result := FEntries.Count; end; function TclSymbMap.GetItem(Index: Integer): TclNameSpaceSymbEntry; begin Result := TclNameSpaceSymbEntry(FEntries.Objects[Index]); end; procedure TclSymbMap.Put(const AKey: WideString; AValue: TclNameSpaceSymbEntry); var ind: Integer; begin ind := FEntries.IndexOf(AKey); if (ind < 0) then begin FEntries.AddObject(AKey, AValue); end else begin FEntries.Objects[ind].Free(); FEntries.Objects[ind] := AValue; end; end; { TclNameSpaceSymbEntry } procedure TclNameSpaceSymbEntry.Assign(Source: TPersistent); var src: TclNameSpaceSymbEntry; begin if (Source is TclNameSpaceSymbEntry) then begin src := TclNameSpaceSymbEntry(Source); FUri := src.Uri; FAttr := src.Attr; FRendered := src.Rendered; FPrefix := src.Prefix; FLevel := src.Level; FLastRendered := src.LastRendered; end else begin inherited Assign(Source); end; end; constructor TclNameSpaceSymbEntry.Create(const AUri: WideString; const Attr: IXMLDOMAttribute; ARendered: Boolean; const APrefix: WideString); begin inherited Create(); FUri := AUri; FAttr := Attr; FRendered := ARendered; FPrefix := APrefix; FLevel := 0; FLastRendered := ''; end; constructor TclNameSpaceSymbEntry.Create; begin inherited Create(); end; { TclAttrCompare } function TclAttrCompare.Compare(Obj0, Obj1: IInterface): Integer; const ATTR0_BEFORE_ATTR1 = -1; ATTR1_BEFORE_ATTR0 = 1; var attr0, attr1: IXMLDOMAttribute; namespaceURI0, namespaceURI1, localname0, localname1, name0, name1: WideString; isNamespaceAttr0, isNamespaceAttr1: Boolean; a: Integer; begin attr0 := Obj0 as IXMLDOMAttribute; attr1 := Obj1 as IXMLDOMAttribute; namespaceURI0 := GetNamespaceURI(attr0); namespaceURI1 := GetNamespaceURI(attr1); isNamespaceAttr0 := (cXMLNS_URI = namespaceURI0); isNamespaceAttr1 := (cXMLNS_URI = namespaceURI1); if (isNamespaceAttr0) then begin if (isNamespaceAttr1) then begin localname0 := GetAttributeLocalName(attr0); localname1 := GetAttributeLocalName(attr1); if (cXMLNS = localname0) then begin localname0 := ''; end; if (cXMLNS = localname1) then begin localname1 := ''; end; Result := WideCompareText(localname0, localname1); Exit; end; Result := ATTR0_BEFORE_ATTR1; Exit; end; if (isNamespaceAttr1) then begin Result := ATTR1_BEFORE_ATTR0; Exit; end; if (namespaceURI0 = '') then begin if (namespaceURI1 = '') then begin name0 := attr0.name; name1 := attr1.name; Result := WideCompareText(name0, name1); Exit; end; Result := ATTR0_BEFORE_ATTR1; Exit; end; if (namespaceURI1 = '') then begin Result := ATTR1_BEFORE_ATTR0; Exit; end; a := WideCompareText(namespaceURI0, namespaceURI1); if (a <> 0) then begin Result := a; Exit; end; Result := WideCompareText(GetAttributeLocalName(attr0), GetAttributeLocalName(attr1)); end; { EclXmlCanonicalizeError } constructor EclXmlCanonicalizeError.Create(const AErrorMsg: string; AErrorCode: Integer; ADummy: Boolean); begin inherited Create(AErrorMsg); FErrorCode := AErrorCode; end; end.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clHttpUtils; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Classes; {$ELSE} System.Classes; {$ENDIF} const DefaultHttpPort = 80; DefaultHttpProxyPort = 8080; type TclAuthorizationType = (atBasic, atAutoDetect); TclHttpVersion = (hvHttp1_0, hvHttp1_1); TclHttpProxySettings = class(TPersistent) protected FAuthorizationType: TclAuthorizationType; FUserName: string; FPassword: string; FServer: string; FPort: Integer; public constructor Create; procedure Assign(Source: TPersistent); override; procedure Clear; published property AuthorizationType: TclAuthorizationType read FAuthorizationType write FAuthorizationType default atAutoDetect; property UserName: string read FUserName write FUserName; property Password: string read FPassword write FPassword; property Server: string read FServer write FServer; property Port: Integer read FPort write FPort default DefaultHttpProxyPort; end; resourcestring DefaultInternetAgent = 'Mozilla/4.0 (compatible; Clever Internet Suite)'; implementation { TclHttpProxySettings } procedure TclHttpProxySettings.Assign(Source: TPersistent); var Src: TclHttpProxySettings; begin if (Source is TclHttpProxySettings) then begin Src := (Source as TclHttpProxySettings); AuthorizationType := Src.AuthorizationType; UserName := Src.UserName; Password := Src.Password; Server := Src.Server; Port := Src.Port; end else begin inherited Assign(Source); end; end; procedure TclHttpProxySettings.Clear; begin FAuthorizationType := atAutoDetect; FPort := DefaultHttpProxyPort; FUserName := ''; FPassword := ''; FServer := ''; end; constructor TclHttpProxySettings.Create; begin inherited Create(); Clear(); end; end.
{ This is a personal project that I give to community under this licence: Copyright 2016 Eric Buso (Alias Caine_dvp) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. } unit UFiles; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface Uses Classes,SysUtils; Const InternalError = 'Erreur interne.'; AssignFileError = 'Erreur à l''assignation (%d) du fichier %s'; CreateFileError = 'Erreur à la création (%d) du nouveau fichier %s'; CreateOverrideError = 'Erreur (%d) fichier %s existant'; ReadFileError = 'Erreur de lecture (%d) du fichier %s'; WriteFileError = 'Erreur d''écriture (%d) du fichier %s'; ResetFileError = 'Erreur ouverture en lecture seule (%d) du fichier %s'; AppendFileError = 'Erreur ouverture en écriture seule (%d) du fichier %s'; NotFoundFileError = 'Erreur (%d) fichier %s attendue mais inexistant'; CloseFileError = ''; type TTextFiles = Class (TObject) private FFileName : String; FFile : TextFile; FError : Integer; FErrorStr : String; FAssigned : Boolean; FUnread : Boolean; FEOF : Boolean; function SetError(Const AFormatedError : String;Var ErrorStr : String): Boolean; function ReadEOF: Boolean; public constructor Create ( Const AFileName: String;Const NewFile: Boolean;Var ErrorStr : String); destructor Destroy;override; function ReadLine ( Var ALine : String; Var ErrorStr : String) : Boolean; function WriteLine ( Const ALine : String;Var ErrorStr : String) : Boolean; property IsEOF : Boolean read ReadEOF default False; End; implementation { TTextFiles } constructor TTextFiles.Create(const AFileName: String;Const NewFile: Boolean; var ErrorStr: String); begin FAssigned := False; FFileName := EmptyStr; FUnread := True; If Not NewFile Then Begin If Not FileExists(AFileName) { *Converted from FileExists* } Then Begin ErrorStr := Format(NotFoundFileError,[0,AFileName]); Exit; End; AssignFile(FFile,AFileName); If Not SetError(AssignFileError,ErrorStr) Then Begin FFileName := AFileName; FAssigned := True; End; Exit; End; If FileExists(AFileName) { *Converted from FileExists* } Then Begin FError := 0; ErrorStr := Format(CreateOverrideError,[-1,AFileName] ); Exit; End; AssignFile(FFile,AFileName); If Not SetError(AssignFileError,ErrorStr) Then Begin FFileName := AFileName; FAssigned := True; End; // NewFile est vrai, le fichier n'existe pas. ReWrite(FFile); SetError(CreateFileError,ErrorStr); CloseFile(FFile); // Supprimer l'écriture seule du Rewrite. FAssigned := False; FError := IOResult; If FError <> 0 Then Raise Exception.CreateFmt('Erreur de fichier inattendue (%d) sur (%s)',[FError,FFileName]); end; destructor TTextFiles.Destroy; begin If FAssigned Then CloseFile(FFile); inherited; end; function TTextFiles.ReadEOF: Boolean; Var mode : Integer; begin If Not FASSigned Then Raise Exception.Create(InternalError + ' lecture EOF avec un fichier non assigné'); Mode := TTextRec(FFile).Mode; If mode = 1 Then Raise Exception.Create(InternalError + ' lecture EOF sur un fichier en écriture'); Result := EOF(FFile) or FEOF; end; function TTextFiles.ReadLine(var ALine, ErrorStr: String): Boolean; begin Try Result := False; If Not FAssigned Then Begin //Raise Exception.Create(InternalError); AssignFile(FFile,FFileName); If Not SetError(AssignFileError,ErrorStr) Then Begin FAssigned := True; End; End; FileMode := 0; // Lecture seule. If FUnread Then Reset(FFile); If SetError(ResetFileError,ErrorStr) Then Begin ErrorStr := FErrorStr; Exit End; ReadLn(FFile,ALine); If Not SetError(ReadFileError,ErrorStr) Then Begin FUnread := False; Result := True; End; Finally End; end; function TTextFiles.SetError(Const AFormatedError: String;Var ErrorStr : String) : Boolean; begin Result := FError <> 0; If Result Then Exit; // Une erreur est déjà en cours. FError := IOresult; If FError <> 0 Then Begin FErrorStr := Format(AFormatedError,[FError,FFileName]); ErrorStr := FErrorStr; Result := True; FEOF := True; End end; function TTextFiles.WriteLine(const ALine: String; var ErrorStr: String): Boolean; begin Try Result := False; If Not FAssigned Then Begin //Raise Exception.Create(InternalError); AssignFile(FFile,FFileName); If Not SetError(AssignFileError,ErrorStr) Then Begin FAssigned := True; End; End; Append(FFile); SetError(AppendFileError,ErrorStr); WriteLn(FFile,ALine); Result := Not SetError(WriteFileError,ErrorStr); Finally //Sleep(5); //CloseFile(FFile); End; end; end.
unit define_dealsimulation; interface uses define_dealItem, define_price; type TDealDirection = ( dealBuy, dealSale, dealMoneyIn, // 存款进入 dealMoneyOut // 取款 ); TRT_DealAction = packed record DealDirection : TDealDirection; StockCode : TDealCodePack; Price : TRT_PricePack; Num : Integer; DealTime : Word; end; PDealActionNode = ^TDealActionNode; TDealActionNode = packed record PrevSibling : PDealActionNode; NextSibling : PDealActionNode; DealAction : TRT_DealAction; end; TRT_DealActions = packed record FirstActionNode : PDealActionNode; LastActionNode : PDealActionNode; end; TRT_DealItemHoldItem = packed record StockCode : TDealCodePack; Num : Integer; DealDate : Word; DealTime : Word; Cost : TRT_PricePack// 成本价 end; PDealItemHoldItemNode = ^TDealItemHoldItemNode; TDealItemHoldItemNode = packed record PrevSibling : PDealItemHoldItemNode; NextSibling : PDealItemHoldItemNode; HoldItem : TRT_DealItemHoldItem; end; TRT_DealItemHoldItems = packed record FirstHoldItemNode : PDealItemHoldItemNode; LastHoldItemNode : PDealItemHoldItemNode; end; // 交易结算 PRT_DealSettlement = ^TRT_DealSettlement; TRT_DealSettlement = packed record Date : Word; MoneyAvailable : integer; // 现金 MoneyLocked : integer; // 现金 HoldItems : TRT_DealItemHoldItems; // 持仓 end; TRT_DealDaySettlement = packed record Date : Word; DealSettlement : TRT_DealSettlement; DealRequests : TRT_DealActions; // 交易请求 DealActions : TRT_DealActions; // 交易成交 end; PDealHistoryDayNode = ^TDealHistoryDayNode; TDealHistoryDayNode = record PrevSibling : PDealHistoryDayNode; NextSibling : PDealHistoryDayNode; DealSimulationDay : TRT_DealDaySettlement; end; PRT_DealHistorys = ^TRT_DealHistorys; TRT_DealHistorys = packed record FirstDealHistoryDay : PDealHistoryDayNode; LastDealHistoryDay : PDealHistoryDayNode; end; // 交易模拟 Session PRT_DealAccount = ^TRT_DealAccount; TRT_DealAccount = record StartMoney : Integer; EndAsset : Integer; // 当日结算 CurrentSettlement : TRT_DealDaySettlement; // 交易历史 DealHistorys : TRT_DealHistorys; end; PDealAccountNode = ^TDealAccountNode; TDealAccountNode = record PrevSibling : PDealAccountNode; NextSibling : PDealAccountNode; DealAccount : TRT_DealAccount; end; TRT_DealAccounts = record FirstDealAccount : PDealAccountNode; LastDealAccount : PDealAccountNode; end; PRT_DealHistorySession = ^TRT_DealHistorySession; TRT_DealHistorySession = packed record StartDate : Word; EndDate : Word; DealAccounts : TRT_DealAccounts; end; implementation end.
unit PrimShutDown_sftNone_UserType; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "View" // Автор: Люлин А.В. // Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/View/PrimCommon/Forms/PrimShutDown_sftNone_UserType.pas" // Начат: 21.08.2009 21:18 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<UserType::Class>> F1 Базовые определения предметной области::F1 Application Template::View::PrimCommon::PrimShutDown::sftNone // // Предупреждение о закрытии приложения // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface uses Classes {$If not defined(NoVCM)} , vcmUserControls {$IfEnd} //not NoVCM {$If not defined(NoScripts)} , tfwInteger {$IfEnd} //not NoScripts ; const { Константы для типа формы sftNone } sftNoneName = 'sftNone'; { Строковый идентификатор пользовательского типа "Предупреждение о закрытии приложения" } sftNone = TvcmUserType(0); { Предупреждение о закрытии приложения } type Tkw_FormUserType_sftNone = class(TtfwInteger) {* Слово словаря для типа формы sftNone } protected // overridden protected methods {$If not defined(NoScripts)} function GetInteger: Integer; override; {$IfEnd} //not NoScripts end;//Tkw_FormUserType_sftNone implementation // start class Tkw_FormUserType_sftNone {$If not defined(NoScripts)} function Tkw_FormUserType_sftNone.GetInteger: Integer; {-} begin Result := sftNone; end;//Tkw_FormUserType_sftNone.GetInteger {$IfEnd} //not NoScripts initialization // Регистрация Tkw_FormUserType_sftNone Tkw_FormUserType_sftNone.Register('тип_формы::sftNone'); end.
unit Control.EnderecosEmpresa; interface uses System.SysUtils, FireDAC.Comp.Client, Forms, Windows, Common.ENum, Model.EnderecosEmpresa, Control.Sistema; type TEnderecosEmpresasControl = class private FEnderecos : TEnderecosEmpresa; public constructor Create; destructor Destroy; override; property Enderecos: TEnderecosEmpresa read FEnderecos write FEnderecos; function GetID(iID: Integer): Integer; function Localizar(aParam: array of variant): TFDQuery; function Gravar(): Boolean; function ValidaCampos(): Boolean; end; implementation { TEnderecosEmpresasControl } uses Common.Utils; constructor TEnderecosEmpresasControl.Create; begin FEnderecos := TEnderecosEmpresa.Create; end; destructor TEnderecosEmpresasControl.Destroy; begin FEnderecos.Free; inherited; end; function TEnderecosEmpresasControl.GetID(iID: Integer): Integer; begin Result := FEnderecos.GetID(FEnderecos.ID); end; function TEnderecosEmpresasControl.Gravar: Boolean; begin Result := False; if Fenderecos.Acao = tacIncluir then begin if not ValidaCampos() then Exit; end; Result := FEnderecos.Gravar; end; function TEnderecosEmpresasControl.Localizar(aParam: array of variant): TFDQuery; begin Result := FEnderecos.Localizar(aParam); end; function TEnderecosEmpresasControl.ValidaCampos: Boolean; var FDQuery : TFDQuery; aParam: Array of variant; begin try Result := False; FDQuery := TSistemaControl.GetInstance.Conexao.ReturnQuery; if FEnderecos.ID = 0 then begin Application.MessageBox('Informe o ID do cadastro!', 'Atenção', MB_OK + MB_ICONWARNING); Exit; end; if FEnderecos.Acao <> tacIncluir then begin if FEnderecos.Sequencia = 0 then begin Application.MessageBox('Informe a sequência do endereço!', 'Atenção', MB_OK + MB_ICONWARNING); Exit; end; end; if FEnderecos.Tipo.IsEmpty then begin Application.MessageBox('Informe o tipo de endereço!', 'Atenção', MB_OK + MB_ICONWARNING); Exit; end; if not FEnderecos.CNPJ.IsEmpty then begin if not TUtils.CNPJ(FEnderecos.CNPJ) then begin Application.MessageBox('Número do CNPJ do endereço é inválido!', 'Atenção', MB_OK + MB_ICONWARNING); Exit; end; SetLength(aParam,2); aParam[0] := 'CNPJ'; aParam[1] := FEnderecos.CNPJ; FDQuery := FEnderecos.Localizar(aParam); Finalize(aParam); if FDQuery.RecordCount >= 1 then begin if FEnderecos.Acao = tacIncluir then begin Application.MessageBox('Endereço com este CNPJ já cadastrado!', 'Atenção', MB_OK + MB_ICONWARNING); FDQuery.Close; Exit; end; end; end; Result := True; finally FDQuery.Free; end; end; end.
PROGRAM d2a; FUNCTION answer(filename:string) : integer; TYPE guide_line = array[1..3] of char; FUNCTION score(guide_l:guide_line) : integer; CONST YOU_ROCK = 'X'; YOU_PAPER = 'Y'; YOU_SCISSORS = 'Z'; OPPONENT_ROCK = 'A'; OPPONENT_PAPER = 'B'; OPPONENT_SCISSORS = 'C'; BEGIN score := 0; {Score of the shape you selected} IF guide_l[3] = YOU_ROCK THEN score += 1 ELSE IF guide_l[3] = YOU_PAPER THEN score += 2 ELSE IF guide_l[3] = YOU_SCISSORS THEN score += 3; {Plus the score for the outcome of the round} {0 if you lost, 3 if draw, 6 if you won} IF (guide_l[3] = YOU_ROCK) AND (guide_l[1] = OPPONENT_ROCK) THEN score += 3 ELSE IF (guide_l[3] = YOU_ROCK) AND (guide_l[1] = OPPONENT_PAPER) THEN score += 0 ELSE IF (guide_l[3] = YOU_ROCK) AND (guide_l[1] = OPPONENT_SCISSORS) THEN score += 6 ELSE IF (guide_l[3] = YOU_PAPER) AND (guide_l[1] = OPPONENT_ROCK) THEN score += 6 ELSE IF (guide_l[3] = YOU_PAPER) AND (guide_l[1] = OPPONENT_PAPER) THEN score += 3 ELSE IF (guide_l[3] = YOU_PAPER) AND (guide_l[1] = OPPONENT_SCISSORS) THEN score += 0 ELSE IF (guide_l[3] = YOU_SCISSORS) AND (guide_l[1] = OPPONENT_ROCK) THEN score += 0 ELSE IF (guide_l[3] = YOU_SCISSORS) AND (guide_l[1] = OPPONENT_PAPER) THEN score += 6 ELSE IF (guide_l[3] = YOU_SCISSORS) AND (guide_l[1] = OPPONENT_SCISSORS) THEN score += 3; END; VAR f: text; guide: ARRAY[1..2500] OF guide_line; i: integer; totscore: integer = 0; BEGIN assign(f, filename); reset(f); i := 1; WHILE not eof(f) DO BEGIN readln(f, guide[i]); i :=+ 1; totscore += score(guide[i]); END; close(f); answer := totscore; END; CONST testfile = 'd2.test.1'; filename = 'd2.input'; VAR a : integer; BEGIN{d2a} assert(answer(testfile) = 15, 'test faal'); a := answer(filename); writeln(''); writeln('answer: ', a); writeln('klaar'); END.
unit BaiduMapAPI.PoiSearchService.Android; //author:Xubzhlin //Email:371889755@qq.com //百度地图API Poi搜索服务 单元 //官方链接:http://lbsyun.baidu.com/ //TAndroidBaiduMapPoiSearchService 百度地图 安卓Poi搜索服务 interface uses System.Classes, System.Types, FMX.Maps, Androidapi.JNI.JavaTypes, Androidapi.JNI.Embarcadero, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNIBridge, System.Generics.Collections, Androidapi.JNI.baidu.mapapi.search, Androidapi.JNI.baidu.mapapi.model, BaiduMapAPI.Search.CommTypes, BaiduMapAPI.PoiSearchService; type TAndroidBaiduMapPoiSearchService = class; TOnGetPoiSearchResultListener = class(TJavaLocal, JOnGetPoiSearchResultListener) private [weak] FPoiSearchService: TAndroidBaiduMapPoiSearchService; function JPoiInfoToPoiInfo(Info:JPoiInfo):TPoiInfo; function JCityInfoToCityInfo(Info:JCityInfo):TCityInfo; function JPoiAddrInfoToPoiAddrInfo(Info:JPoiAddrInfo):TPoiAddrInfo; function JPoiIndoorInfoToPoiIndoorInfo(Info:JPoiIndoorInfo):TPoiIndoorInfo; public procedure onGetPoiResult(P1: JPoiResult); cdecl; procedure onGetPoiDetailResult(P1: JPoiDetailResult); cdecl; procedure onGetPoiIndoorResult(P1: JPoiIndoorResult); cdecl; constructor Create(PoiSearchService: TAndroidBaiduMapPoiSearchService); end; TAndroidBaiduMapPoiSearchService = class(TBaiduMapPoiSearchService) private FPoiSearch: JPoiSearch; FResultListener: TOnGetPoiSearchResultListener; function DoBoundSearch(Option: TPoiBoundSearchOption): Boolean; function DoCitySearch(Option: TPoiCitySearchOption): Boolean; function DoNearbySearch(Option: TPoiNearbySearchOption): Boolean; protected function DoPoiSearch(Option: TPoiSearchrOption): Boolean; override; function DoSearchPoiDetail(Uid: string): Boolean; override; public constructor Create; destructor Destroy; override; end; //Poi 类型转换 function CreatePoiType(AType:JPoiInfo_POITYPE):TPoiType; implementation uses Androidapi.Helpers; function CreatePoiType(AType:JPoiInfo_POITYPE):TPoiType; begin if AType = TJPoiInfo_POITYPE.JavaClass.POINT then Result:=TPoiType.POINT else if AType = TJPoiInfo_POITYPE.JavaClass.BUS_STATION then Result:=TPoiType.BUS_STATION else if AType = TJPoiInfo_POITYPE.JavaClass.BUS_LINE then Result:=TPoiType.BUS_LINE else if AType = TJPoiInfo_POITYPE.JavaClass.SUBWAY_STATION then Result:=TPoiType.SUBWAY_STATION else if AType = TJPoiInfo_POITYPE.JavaClass.SUBWAY_LINE then Result:=TPoiType.SUBWAY_LINE end; { TAndroidBaiduMapPoiSearchService } constructor TAndroidBaiduMapPoiSearchService.Create; begin inherited; FPoiSearch := TJPoiSearch.JavaClass.newInstance; FResultListener := TOnGetPoiSearchResultListener.Create(Self); FPoiSearch.setOnGetPoiSearchResultListener(FResultListener); end; destructor TAndroidBaiduMapPoiSearchService.Destroy; begin FResultListener.Free; FPoiSearch := nil; inherited; end; function TAndroidBaiduMapPoiSearchService.DoBoundSearch (Option: TPoiBoundSearchOption): Boolean; var Bounds: JLatLngBounds; SearchOption: JPoiBoundSearchOption; begin Bounds := TJLatLngBounds_Builder.JavaClass.init.build; Bounds.northeast := TJLatLng.JavaClass.init(Option.northeast.Latitude, Option.northeast.Longitude); Bounds.southwest := TJLatLng.JavaClass.init(Option.southwest.Latitude, Option.southwest.Longitude); SearchOption := TJPoiBoundSearchOption.JavaClass.init; SearchOption.keyword(StringToJString(Option.keyword)).bound(Bounds) .pageNum(Option.pageNum).pageCapacity(Option.pageCapacity); Result := FPoiSearch.searchInBound(SearchOption); end; function TAndroidBaiduMapPoiSearchService.DoCitySearch (Option: TPoiCitySearchOption): Boolean; var SearchOption: JPoiCitySearchOption; begin SearchOption := TJPoiCitySearchOption.JavaClass.init; SearchOption.city(StringToJString(Option.city)) .keyword(StringToJString(Option.keyword)).pageNum(Option.pageNum) .pageCapacity(Option.pageCapacity).isReturnAddr(Option.isReturnAddr); Result := FPoiSearch.searchInCity(SearchOption); end; function TAndroidBaiduMapPoiSearchService.DoNearbySearch (Option: TPoiNearbySearchOption): Boolean; var Location:JLatLng; PoiSortType: JPoiSortType; SearchOption: JPoiNearbySearchOption; begin case Option.sortType of comprehensive: PoiSortType := TJPoiSortType.JavaClass.comprehensive; distance_from_near_to_far: PoiSortType := TJPoiSortType.JavaClass.distance_from_near_to_far; end; Location:=TJLatLng.JavaClass.init(Option.Location.Latitude, Option.Location.Longitude); SearchOption := TJPoiNearbySearchOption.JavaClass.init; SearchOption.keyword(StringToJString(Option.keyword)).location(Location) .sortType(PoiSortType).radius(Option.radius).pageNum(Option.pageNum) .pageCapacity(Option.pageCapacity); Result := FPoiSearch.searchNearby(SearchOption); end; function TAndroidBaiduMapPoiSearchService.DoPoiSearch (Option: TPoiSearchrOption): Boolean; begin if Option is TPoiBoundSearchOption then begin Result := DoBoundSearch(TPoiBoundSearchOption(Option)); end else if Option is TPoiCitySearchOption then begin Result := DoCitySearch(TPoiCitySearchOption(Option)); end else if Option is TPoiNearbySearchOption then begin Result := DoNearbySearch(TPoiNearbySearchOption(Option)); end; end; function TAndroidBaiduMapPoiSearchService.DoSearchPoiDetail (Uid: string): Boolean; var SearchOption: JPoiDetailSearchOption; begin SearchOption := TJPoiDetailSearchOption.JavaClass.init; SearchOption.poiUid(StringToJString(Uid)); Result := FPoiSearch.searchPoiDetail(SearchOption); end; { TOnGetPoiSearchResultListener } constructor TOnGetPoiSearchResultListener.Create(PoiSearchService : TAndroidBaiduMapPoiSearchService); begin inherited Create; FPoiSearchService := PoiSearchService; end; function TOnGetPoiSearchResultListener.JCityInfoToCityInfo( Info: JCityInfo): TCityInfo; begin Result.city:=JStringToString(Info.city); Result.num:=Info.num; end; function TOnGetPoiSearchResultListener.JPoiAddrInfoToPoiAddrInfo( Info: JPoiAddrInfo): TPoiAddrInfo; begin Result.address:=JStringToString(Info.address); Result.location:=TMapCoordinate.Create(Info.location.latitude, Info.location.longitude); Result.name:=JStringToString(Info.name); end; function TOnGetPoiSearchResultListener.JPoiIndoorInfoToPoiIndoorInfo( Info: JPoiIndoorInfo): TPoiIndoorInfo; begin Result.address:=JStringToString(Info.address); Result.bid:=JStringToString(Info.bid); Result.floor:=JStringToString(Info.floor); Result.name:=JStringToString(Info.name); Result.phone:=JStringToString(Info.phone); Result.price:=Info.price; Result.latLng:=TMapCoordinate.Create(Info.latLng.latitude, Info.latLng.longitude); Result.starLevel:=Info.starLevel; Result.isGroup:=Info.isGroup; Result.isTakeOut:=Info.isTakeOut; Result.isWaited:=Info.isWaited; Result.uid:=JStringToString(Info.uid); Result.tag:=JStringToString(Info.tag); Result.groupNum:=Info.groupNum; end; function TOnGetPoiSearchResultListener.JPoiInfoToPoiInfo( Info: JPoiInfo): TPoiInfo; begin Result.name:=JStringToString(Info.name); Result.uid:=JStringToString(Info.uid); Result.address:=JStringToString(Info.address); Result.city:=JStringToString(Info.city); Result.phoneNum:=JStringToString(Info.phoneNum); Result.postCode:=JStringToString(Info.postCode); Result.&type:=CreatePoiType(Info.&type); Result.location:=TMapCoordinate.Create(Info.location.latitude, Info.location.longitude); Result.isPano:=Info.isPano; end; procedure TOnGetPoiSearchResultListener.onGetPoiDetailResult (P1: JPoiDetailResult); var DetailResult:TPoiDetailResult; begin if FPoiSearchService <> nil then begin DetailResult:=TPoiDetailResult.Create; DetailResult.error:=CreateErrorNo(P1.error); if DetailResult.error = TSearchResult_ErrorNo.NO_ERROR then begin DetailResult.name:=JStringToString(P1.getName); DetailResult.location:=TMapCoordinate.Create(P1.getLocation.latitude, P1.getLocation.longitude); DetailResult.address:=JStringToString(P1.getAddress); DetailResult.telephone:=JStringToString(P1.getTelephone); DetailResult.uid:=JStringToString(P1.getUid); DetailResult.tag:=JStringToString(P1.getTag); DetailResult.detailUrl:=JStringToString(P1.getDetailUrl); DetailResult.&type:= JStringToString(P1.getType); DetailResult.price:=P1.getPrice; DetailResult.overallRating:=P1.getOverallRating; DetailResult.tasteRating:=P1.getTasteRating; DetailResult.serviceRating:=P1.getServiceRating; DetailResult.environmentRating:=P1.getEnvironmentRating; DetailResult.facilityRating:=P1.getFacilityRating; DetailResult.hygieneRating:=P1.getHygieneRating; DetailResult.technologyRating:=P1.getTechnologyRating; DetailResult.imageNum:=P1.getImageNum; DetailResult.grouponNum:=P1.getGrouponNum; DetailResult.commentNum:=P1.getCommentNum; DetailResult.favoriteNum:=P1.getFavoriteNum; DetailResult.checkinNum:=P1.getCheckinNum; DetailResult.shopHours:=JStringToString(P1.getShopHours); end; FPoiSearchService.GetPoiDetailResult(DetailResult); end; end; procedure TOnGetPoiSearchResultListener.onGetPoiIndoorResult (P1: JPoiIndoorResult); var PoiIndoorResult:TPoiIndoorResult; i:Integer; PoiIndoorInfo:JPoiIndoorInfo; List:JList; begin if FPoiSearchService <> nil then begin PoiIndoorResult:=TPoiIndoorResult.Create; PoiIndoorResult.error:=CreateErrorNo(P1.error); if PoiIndoorResult.error = TSearchResult_ErrorNo.NO_ERROR then begin List:=P1.getmArrayPoiInfo; for i := 0 to List.size - 1 do begin PoiIndoorInfo:=TJPoiIndoorInfo.Wrap(List.get(i)); PoiIndoorResult.PoiIndoorsInfo.Add(JPoiIndoorInfoToPoiIndoorInfo(PoiIndoorInfo)); end; PoiIndoorResult.CurrentPageNum:=P1.getPageNum; PoiIndoorResult.CurrentPageCapacity:=List.size; PoiIndoorResult.TotalPoiNum:=P1.getPoiNum; end; FPoiSearchService.GetPoiIndoorResult(PoiIndoorResult); end; end; procedure TOnGetPoiSearchResultListener.onGetPoiResult(P1: JPoiResult); var PoiResult:TPoiResult; i:Integer; PoiInfo:JPoiInfo; CityInfo:JCityInfo; AddrInfo:JPoiAddrInfo; List:JList; begin if FPoiSearchService <> nil then begin PoiResult:=TPoiResult.Create; PoiResult.error:=CreateErrorNo(P1.error); case PoiResult.error of TSearchResult_ErrorNo.NO_ERROR: begin List:=P1.getAllPoi; for i := 0 to List.size - 1 do begin PoiInfo:=TJPoiInfo.Wrap(List.get(i)); PoiResult.PoisInfo.Add(JPoiInfoToPoiInfo(PoiInfo)); end; if P1.isHasAddrInfo then begin List:=P1.getAllAddr; for i := 0 to List.size - 1 do begin AddrInfo:=TJPoiAddrInfo.Wrap(List.get(i)); PoiResult.PoiAddrsInfo.Add(JPoiAddrInfoToPoiAddrInfo(AddrInfo)); end; end; PoiResult.CurrentPageCapacity:=P1.getCurrentPageCapacity; PoiResult.CurrentPageNum:=P1.getCurrentPageNum; PoiResult.TotalPageNum:=P1.getTotalPageNum; PoiResult.TotalPoiNum:=P1.getTotalPoiNum; PoiResult.isHasAddrInfo:=P1.isHasAddrInfo; end; TSearchResult_ErrorNo.AMBIGUOUS_KEYWORD: begin List:=P1.getSuggestCityList; for i := 0 to List.size - 1 do begin CityInfo:=TJCityInfo.Wrap(List.get(i)); PoiResult.CitysInfo.Add(JCityInfoToCityInfo(CityInfo)); end; end; end; FPoiSearchService.GetPoiResult(PoiResult); end; end; end.
unit MFichas.Model.Produto.Metodos.Cadastrar; interface uses System.SysUtils, MFichas.Model.Produto.Interfaces, MFichas.Controller.Types; type TModelProdutoMetodosCadastrar = class(TInterfacedObject, iModelProdutoMetodosCadastrar) private [weak] FParent : iModelProduto; FDescricao: String; FValor : Currency; FGrupo : String; constructor Create(AParent: iModelProduto); procedure Gravar; public destructor Destroy; override; class function New(AParent: iModelProduto): iModelProdutoMetodosCadastrar; function Descricao(ADescricao: String): iModelProdutoMetodosCadastrar; function Valor(AValor: Currency) : iModelProdutoMetodosCadastrar; function Grupo(AGrupo: String) : iModelProdutoMetodosCadastrar; function &End : iModelProdutoMetodos; end; implementation { TModelProdutoMetodosCadastrar } function TModelProdutoMetodosCadastrar.&End: iModelProdutoMetodos; begin //TODO: IMPLEMENTAR METODO DE CADASTRAR PRODUTO. Result := FParent.Metodos; Gravar; end; procedure TModelProdutoMetodosCadastrar.Gravar; begin FParent.Entidade.DESCRICAO := FDescricao; FParent.Entidade.PRECO := FValor; FParent.Entidade.STATUS := Integer(saiAtivo); FParent.Entidade.GRUPO := FGrupo; FParent.DAO.Insert(FParent.Entidade); end; constructor TModelProdutoMetodosCadastrar.Create(AParent: iModelProduto); begin FParent := AParent; end; function TModelProdutoMetodosCadastrar.Descricao( ADescricao: String): iModelProdutoMetodosCadastrar; begin Result := Self; if ADescricao.IsNullOrWhiteSpace(ADescricao) then raise Exception.Create( 'Não é possível cadastrar este produto sem um Nome/Descrição.' ); FDescricao := ADescricao.ToUpper; end; destructor TModelProdutoMetodosCadastrar.Destroy; begin inherited; end; function TModelProdutoMetodosCadastrar.Grupo( AGrupo: String): iModelProdutoMetodosCadastrar; begin Result := Self; if AGrupo.IsNullOrWhiteSpace(AGrupo) then raise Exception.Create( 'Não é possível cadastrar este produto sem adicioná-lo a um grupo.' ); FGrupo := AGrupo; end; class function TModelProdutoMetodosCadastrar.New(AParent: iModelProduto): iModelProdutoMetodosCadastrar; begin Result := Self.Create(AParent); end; function TModelProdutoMetodosCadastrar.Valor( AValor: Currency): iModelProdutoMetodosCadastrar; begin Result := Self; if AValor <= 0 then raise Exception.Create( 'Não é possível cadastrar este produto com o valor de venda igual a 0.' ); FValor := AValor; end; end.
unit Model.Modulos; interface uses Common.ENum, FireDAC.Comp.Client; type TModulos = class private FAcao: TAcao; FDescricao: String; FCodigo: Integer; FSistema: Integer; public property Sistema: Integer read FSistema write FSistema; property Codigo: Integer read FCodigo write FCodigo; property Descricao: String read FDescricao write FDescricao; property Acao: TAcao read FAcao write FAcao; function Localizar(aParam: array of variant): TFDQuery; function Gravar(): Boolean; end; implementation { TModulos } uses DAO.Modulos; function TModulos.Gravar: Boolean; var modulosdDAO : TModulosDAO; begin try Result := False; modulosdDAO := TModulosDAO.Create; case FAcao of Common.ENum.tacIncluir: Result := modulosdDAO.Inserir(Self); Common.ENum.tacAlterar: Result := modulosdDAO.Alterar(Self); Common.ENum.tacExcluir: Result := modulosdDAO.Excluir(Self); end; finally modulosdDAO.Free; end; end; function TModulos.Localizar(aParam: array of variant): TFDQuery; var modulosDAO : TModulosDAO; begin try modulosDAO := TModulosDAO.Create; Result := modulosDAO.Pesquisar(aParam); finally modulosDAO.Free; end; end; end.
unit daArchiUser; // Модуль: "w:\common\components\rtl\Garant\DA\daArchiUser.pas" // Стереотип: "SimpleClass" // Элемент модели: "TdaArchiUser" MUID: (57234C2903E3) {$Include w:\common\components\rtl\Garant\DA\daDefine.inc} interface uses l3IntfUses , l3ProtoObject , daTypes , Classes ; type TdaArchiUser = class(Tl3ProtoObject) private f_ID: TdaUserID; f_Active: Boolean; f_HasAdminRights: Boolean; f_ExportPriority: TdaPriority; f_ImportPriority: TdaPriority; f_IP: AnsiString; f_LoginDate: TDateTime; f_LoginName: AnsiString; f_Password: AnsiString; f_UserName: AnsiString; protected procedure ClearFields; override; public procedure Load(aStream: TStream); procedure Save(aStream: TStream); public property ID: TdaUserID read f_ID write f_ID; property Active: Boolean read f_Active write f_Active; property HasAdminRights: Boolean read f_HasAdminRights write f_HasAdminRights; property ExportPriority: TdaPriority read f_ExportPriority write f_ExportPriority; property ImportPriority: TdaPriority read f_ImportPriority write f_ImportPriority; property IP: AnsiString read f_IP write f_IP; property LoginDate: TDateTime read f_LoginDate write f_LoginDate; property LoginName: AnsiString read f_LoginName write f_LoginName; property Password: AnsiString read f_Password write f_Password; property UserName: AnsiString read f_UserName write f_UserName; end;//TdaArchiUser implementation uses l3ImplUses ; procedure TdaArchiUser.Load(aStream: TStream); //#UC START# *57234C5B02CA_57234C2903E3_var* //#UC END# *57234C5B02CA_57234C2903E3_var* begin //#UC START# *57234C5B02CA_57234C2903E3_impl* !!! Needs to be implemented !!! //#UC END# *57234C5B02CA_57234C2903E3_impl* end;//TdaArchiUser.Load procedure TdaArchiUser.Save(aStream: TStream); //#UC START# *57234C6E01C3_57234C2903E3_var* //#UC END# *57234C6E01C3_57234C2903E3_var* begin //#UC START# *57234C6E01C3_57234C2903E3_impl* !!! Needs to be implemented !!! //#UC END# *57234C6E01C3_57234C2903E3_impl* end;//TdaArchiUser.Save procedure TdaArchiUser.ClearFields; begin IP := ''; LoginName := ''; Password := ''; UserName := ''; inherited; end;//TdaArchiUser.ClearFields end.
program TESTSTR1 ( OUTPUT ) ; //********************************************************************** //$A+ //********************************************************************** type TRANSLATE_TAB = array [ 1 .. 128 ] of CHAR ; var S : STRING ( 20 ) ; C : CHAR ( 20 ) ; I : INTEGER ; C1 : CHAR ; C2 : CHAR ; C20 : CHAR ( 20 ) ; C20A : CHAR ( 20 ) ; VC20 : STRING ( 20 ) ; VC200 : STRING ( 200 ) ; VC2000 : STRING ( 2000 ) ; X : BOOLEAN ; P1 : STRING ( 20 ) ; P2 : STRING ( 200 ) ; COUNT : INTEGER ; TTAB : STRING ( 256 ) ; const IDENT_T1 : TRANSLATE_TAB = ( X'00' , X'01' , X'02' , X'03' , X'04' , X'05' , X'06' , X'07' , X'08' , X'09' , X'0a' , X'0b' , X'0c' , X'0d' , X'0e' , X'0f' , X'10' , X'11' , X'12' , X'13' , X'14' , X'15' , X'16' , X'17' , X'18' , X'19' , X'1a' , X'1b' , X'1c' , X'1d' , X'1e' , X'1f' , X'20' , X'21' , X'22' , X'23' , X'24' , X'25' , X'26' , X'27' , X'28' , X'29' , X'2a' , X'2b' , X'2c' , X'2d' , X'2e' , X'2f' , X'30' , X'31' , X'32' , X'33' , X'34' , X'35' , X'36' , X'37' , X'38' , X'39' , X'3a' , X'3b' , X'3c' , X'3d' , X'3e' , X'3f' , X'40' , X'41' , X'42' , X'43' , X'44' , X'45' , X'46' , X'47' , X'48' , X'49' , X'4a' , X'4b' , X'4c' , X'4d' , X'4e' , X'4f' , X'50' , X'51' , X'52' , X'53' , X'54' , X'55' , X'56' , X'57' , X'58' , X'59' , X'5a' , X'5b' , X'5c' , X'5d' , X'5e' , X'5f' , X'60' , X'61' , X'62' , X'63' , X'64' , X'65' , X'66' , X'67' , X'68' , X'69' , X'6a' , X'6b' , X'6c' , X'6d' , X'6e' , X'6f' , X'70' , X'71' , X'72' , X'73' , X'74' , X'75' , X'76' , X'77' , X'78' , X'79' , X'7a' , X'7b' , X'7c' , X'7d' , X'7e' , X'7f' ) ; IDENT_T2 : TRANSLATE_TAB = ( X'80' , X'81' , X'82' , X'83' , X'84' , X'85' , X'86' , X'87' , X'88' , X'89' , X'8a' , X'8b' , X'8c' , X'8d' , X'8e' , X'8f' , X'90' , X'91' , X'92' , X'93' , X'94' , X'95' , X'96' , X'97' , X'98' , X'99' , X'9a' , X'9b' , X'9c' , X'9d' , X'9e' , X'9f' , X'a0' , X'a1' , X'a2' , X'a3' , X'a4' , X'a5' , X'a6' , X'a7' , X'a8' , X'a9' , X'aa' , X'ab' , X'ac' , X'ad' , X'ae' , X'af' , X'b0' , X'b1' , X'b2' , X'b3' , X'b4' , X'b5' , X'b6' , X'b7' , X'b8' , X'b9' , X'ba' , X'bb' , X'bc' , X'bd' , X'be' , X'bf' , X'c0' , X'c1' , X'c2' , X'c3' , X'c4' , X'c5' , X'c6' , X'c7' , X'c8' , X'c9' , X'ca' , X'cb' , X'cc' , X'cd' , X'ce' , X'cf' , X'd0' , X'd1' , X'd2' , X'd3' , X'd4' , X'd5' , X'd6' , X'd7' , X'd8' , X'd9' , X'da' , X'db' , X'dc' , X'dd' , X'de' , X'df' , X'e0' , X'e1' , X'e2' , X'e3' , X'e4' , X'e5' , X'e6' , X'e7' , X'e8' , X'e9' , X'ea' , X'eb' , X'ec' , X'ed' , X'ee' , X'ef' , X'f0' , X'f1' , X'f2' , X'f3' , X'f4' , X'f5' , X'f6' , X'f7' , X'f8' , X'f9' , X'fa' , X'fb' , X'fc' , X'fd' , X'fe' , X'ff' ) ; function MEMCMPX ( X : ANYPTR ; Y : ANYPTR ; L : INTEGER ) : INTEGER ; var PLINKS : -> CHAR ; PRECHTS : -> CHAR ; PLIMIT : -> CHAR ; RESULT : INTEGER ; begin (* MEMCMPX *) PLINKS := X ; PRECHTS := Y ; PLIMIT := PTRADD ( PLINKS , L ) ; RESULT := 0 ; while PTRDIFF ( PLIMIT , PLINKS ) > 0 do begin if PLINKS -> < PRECHTS -> then begin RESULT := - 1 ; break end (* then *) else if PLINKS -> > PRECHTS -> then begin RESULT := 1 ; break end (* then *) else begin PLINKS := PTRADD ( PLINKS , 1 ) ; PRECHTS := PTRADD ( PRECHTS , 1 ) ; end (* else *) end (* while *) ; MEMCMPX := RESULT end (* MEMCMPX *) ; procedure TEIL1 ; begin (* TEIL1 *) C := 'Bernd' ; WRITELN ( 'c = ' , C ) ; S := 'Oppolzer' ; WRITELN ( 'maxlength = ' , MAXLENGTH ( S ) ) ; WRITELN ( 'length = ' , LENGTH ( S ) ) ; C := S ; WRITELN ( 'c = ' , C ) ; for I := 1 to LENGTH ( S ) do WRITE ( S [ I ] , ' ' ) ; WRITELN ; //***************************************************************** // tests aus testvarc //***************************************************************** C1 := 'A' ; C2 := C1 ; C20 := 'Test' ; VC20 := STR ( 'A' ) ; WRITE ( 'VC20 nach Zuweisung STR (''A'') ........: ' ) ; WRITELN ( '<' , VC20 , '>' ) ; VC20 := STR ( C1 ) ; WRITE ( 'VC20 nach Zuweisung STR (C1) .........: ' ) ; WRITELN ( '<' , VC20 , '>' ) ; VC20 := 'A' ; WRITE ( 'VC20 nach Zuweisung ''A'' ..............: ' ) ; WRITELN ( '<' , VC20 , '>' ) ; VC20 := 'Test Varchar' ; WRITE ( 'VC20 nach Zuweisung const char array .: ' ) ; WRITELN ( '<' , VC20 , '>' ) ; //***************************************************************** // ist nicht zulaessig, muss Konstante sein oder Funktion STR //***************************************************************** // VC20 := C20 ; /* sollte Fehler sein */ //***************************************************************** // so korrekt //***************************************************************** VC20 := STR ( C20 ) ; WRITE ( 'VC20 nach Zuweisung STR (C20) ........: ' ) ; WRITELN ( '<' , VC20 , '>' ) ; //***************************************************************** // muss erlaubt sein, mit Blanks auffuellen wie gehabt ... //***************************************************************** VC20 := 'Bernd' ; WRITE ( 'VC20 nach Zuweisung Bernd ............: ' ) ; WRITELN ( '<' , VC20 , '>' ) ; C20 := VC20 ; WRITELN ( 'C20 nach Zuweisung VC20 ..............: ' , C20 ) ; C20 := 'Bernd ' || 'Oppolzer' ; WRITELN ( 'C20 nach Zuweisung String Expression .: ' , C20 ) ; //***************************************************************** // Verkettung usw. //***************************************************************** VC200 := VC20 || VC20 ; WRITE ( 'VC200 nach Verkettung ................: ' ) ; WRITELN ( '<' , VC200 , '>' ) ; VC200 := VC20 || ' Oppolzer' ; WRITE ( 'VC200 nach Verkettung ................: ' ) ; WRITELN ( '<' , VC200 , '>' ) ; VC200 := VC20 || ' Oppolzer' || ' Leinfelden' ; WRITE ( 'VC200 nach Verkettung ................: ' ) ; WRITELN ( '<' , VC200 , '>' ) ; VC200 := VC20 || ( ' Oppolzer' || ' Leinfelden' ) ; WRITE ( 'VC200 nach Verkettung (Klammer hinten): ' ) ; WRITELN ( '<' , VC200 , '>' ) ; VC200 := ( VC20 || ' Oppolzer' ) || ' Leinfelden' ; WRITE ( 'VC200 nach Verkettung ................: ' ) ; WRITELN ( '<' , VC200 , '>' ) ; VC200 := ( ( VC20 || ' Oppolzer' ) || ' Leinfelden' ) ; WRITE ( 'VC200 nach Verkettung ................: ' ) ; WRITELN ( '<' , VC200 , '>' ) ; VC200 := VC20 || STR ( ' Oppolzer' ) || STR ( ' Leinfelden' ) ; WRITE ( 'VC200 nach Verkettung (mit STR Funk.).: ' ) ; WRITELN ( '<' , VC200 , '>' ) ; VC200 := VC20 || ' ' || VC20 ; WRITE ( 'VC200 nach Verkettung (mit Blank) ....: ' ) ; WRITELN ( '<' , VC200 , '>' ) ; VC200 := VC20 || ' dazwischen ' || VC20 ; WRITE ( 'VC200 nach Verkettung ................: ' ) ; WRITELN ( '<' , VC200 , '>' ) ; VC200 := VC20 || ' dazwischen ' || STR ( C20 ) ; WRITE ( 'VC200 nach Verkettung ................: ' ) ; WRITELN ( '<' , VC200 , '>' ) ; VC200 := STR ( C20 ) || ' dazwischen ' || VC20 ; WRITE ( 'VC200 nach Verkettung ................: ' ) ; WRITELN ( '<' , VC200 , '>' ) ; //***************************************************************** // Zuweisungen einfach oder Expression //***************************************************************** VC20 := 'Test-String' ; WRITE ( 'VC20 nach Zuweisung Konstante ........: ' ) ; WRITELN ( '<' , VC20 , '>' ) ; VC200 := VC20 ; WRITE ( 'VC200 nach Zuweisung VC20 ............: ' ) ; WRITELN ( '<' , VC200 , '>' ) ; VC200 := VC20 || ' mit Verkettung' ; WRITE ( 'VC200 nach Zuweisung Expression ......: ' ) ; WRITELN ( '<' , VC200 , '>' ) ; VC20 := 'Bernd' ; end (* TEIL1 *) ; procedure TEIL2 ; var ZZ : STRING ( 20 ) ; begin (* TEIL2 *) //************************************************************ // Vergleiche von Strings //************************************************************ X := C20 = 'Bernd Oppolzer' ; WRITELN ( 'c20 = ''Bernd Oppolzer'' ...............: ' , X ) ; X := C20 = 'Bernd' ; WRITELN ( 'c20 = ''Bernd'' ........................: ' , X ) ; X := C20 = 'Bernd ' ; WRITELN ( 'c20 = ''Bernd '' ..................: ' , X ) ; ZZ := 'Bernd' ; WRITELN ( 'vc20 = <' , VC20 , '>' ) ; WRITELN ( 'zz = <' , ZZ , '>' ) ; X := VC20 = ZZ ; WRITELN ( 'vc20 = zz ............................: ' , X ) ; ZZ := 'Bornd' ; WRITELN ( 'vc20 = <' , VC20 , '>' ) ; WRITELN ( 'zz = <' , ZZ , '>' ) ; X := VC20 = ZZ ; WRITELN ( 'vc20 = zz ............................: ' , X ) ; X := VC20 = 'Bernd' ; WRITELN ( 'vc20 = ''Bernd'' .......................: ' , X ) ; X := VC20 = 'Berndx' ; WRITELN ( 'vc20 = ''Berndx'' ......................: ' , X ) ; X := VC20 = 'Bornd' ; WRITELN ( 'vc20 = ''Bornd'' .......................: ' , X ) ; X := ( VC20 = 'Bernd' ) ; WRITELN ( 'vc20 = ''Bernd'' .......................: ' , X ) ; X := VC20 || ' ' = 'Bernd' || ' ' ; WRITELN ( 'vc20 = ''Bernd'' .......................: ' , X ) ; X := VC20 = 'Bernd ' ; WRITELN ( 'vc20 = ''Bernd '' ......................: ' , X ) ; X := C20 = 'Bernd' ; WRITELN ( 'c20 = ''Bernd'' ........................: ' , X ) ; X := C20 = 'Bernd ' ; WRITELN ( 'c20 = ''Bernd '' ..................: ' , X ) ; C20A := 'Oppolzer' ; WRITELN ( 'c20 = ................................: ' , C20 ) ; WRITELN ( 'c20A = ...............................: ' , C20A ) ; WRITELN ( 'VC20 = ...............................: ' , VC20 ) ; X := C20A > C20 ; WRITELN ( 'c20a > c20 ...........................: ' , X ) ; X := C20A < C20 ; WRITELN ( 'c20a < c20 ...........................: ' , X ) ; X := STR ( C20 ) > VC20 ; WRITELN ( 'c20 > vc20 ...........................: ' , X ) ; X := STR ( C20 ) < VC20 ; WRITELN ( 'c20 < vc20 ...........................: ' , X ) ; X := VC20 < C20 ; WRITELN ( 'c20 > vc20 ??? .......................: ' , X ) ; X := VC20 > C20 ; WRITELN ( 'c20 < vc20 ??? .......................: ' , X ) ; X := VC20 = C20 ; WRITELN ( 'c20 = vc20 ...........................: ' , X ) ; X := STR ( C20A ) > VC20 ; WRITELN ( 'c20a > vc20 ..........................: ' , X ) ; X := STR ( C20A ) < VC20 ; WRITELN ( 'c20a < vc20 ..........................: ' , X ) ; X := VC20 < C20A ; WRITELN ( 'c20a > vc20 ..........................: ' , X ) ; X := VC20 > C20A ; WRITELN ( 'c20a < vc20 ..........................: ' , X ) ; if VC20 || ' ' = 'Bernd' || ' ' then WRITELN ( 'success !!' ) ; end (* TEIL2 *) ; procedure STRPROC ( X : STRING ( 20 ) ; var Y : STRING ; A : STRING ( 200 ) ; var B : STRING ) ; begin (* STRPROC *) if TRUE then begin WRITELN ( 'maxlength (x) = ' , MAXLENGTH ( X ) ) ; WRITELN ( 'maxlength (y) = ' , MAXLENGTH ( Y ) ) ; WRITELN ( 'maxlength (a) = ' , MAXLENGTH ( A ) ) ; WRITELN ( 'maxlength (b) = ' , MAXLENGTH ( B ) ) ; end (* then *) ; B := X || ' Oppolzer' ; Y := A ; WRITELN ( 'In STRPROC - X = <' , X , '>' ) ; WRITELN ( 'In STRPROC - Y = <' , Y , '>' ) ; WRITELN ( 'In STRPROC - A = <' , A , '>' ) ; WRITELN ( 'In STRPROC - B = <' , B , '>' ) ; end (* STRPROC *) ; function STRFUNC ( X : STRING ( 20 ) ; Y : STRING ( 20 ) ) : STRING ; begin (* STRFUNC *) STRFUNC := X || '/' || Y ; end (* STRFUNC *) ; function IFUNC ( X : STRING ( 20 ) ; Y : STRING ( 20 ) ) : INTEGER ; begin (* IFUNC *) IFUNC := LENGTH ( X || '/' || Y ) ; end (* IFUNC *) ; function STRFUNC2 ( const X : STRING ; const Y : STRING ) : STRING ; var P : ANYPTR ; PDUMP : -> ANYPTR ; begin (* STRFUNC2 *) WRITELN ( 'strfunc2: addr stack = ' , ADDR ( P ) ) ; P := ADDR ( X ) ; PDUMP := P ; WRITELN ( 'strfunc2: addr (x) = ' , PDUMP ) ; WRITE ( 'strfunc2: x = ' , PDUMP -> ) ; PDUMP := PTRADD ( PDUMP , 4 ) ; WRITELN ( ' ' , PDUMP -> ) ; P := ADDR ( Y ) ; PDUMP := P ; WRITELN ( 'strfunc2: addr (y) = ' , PDUMP ) ; WRITE ( 'strfunc2: y = ' , PDUMP -> ) ; PDUMP := PTRADD ( PDUMP , 4 ) ; WRITELN ( ' ' , PDUMP -> ) ; WRITELN ( 'strfunc2: x = <' , X , '>' ) ; WRITELN ( 'strfunc2: y = <' , Y , '>' ) ; STRFUNC2 := X || '/' || Y ; end (* STRFUNC2 *) ; function STRFUNC3 ( var X : STRING ; var Y : STRING ) : STRING ; var ERG : STRING ( 200 ) ; begin (* STRFUNC3 *) WRITELN ( 'strfunc3: x = <' , X , '>' ) ; WRITELN ( 'strfunc3: y = <' , Y , '>' ) ; ERG := X || '/' || Y ; WRITELN ( 'strfunc3: erg = <' , ERG , '>' ) ; STRFUNC3 := ERG ; end (* STRFUNC3 *) ; function STRFUNC5 ( var X : STRING ; var Y : STRING ) : STRING ; begin (* STRFUNC5 *) STRFUNC5 := STRFUNC3 ( X , Y ) ; end (* STRFUNC5 *) ; procedure TESTSTR ( X : STRING ( 20 ) ; var Y : STRING ; const Z : STRING ) ; type LENGTHF = - 1 .. 32767 ; CHARPTR = -> CHAR ; var CP : -> CHAR ; LF : -> LENGTHF ; LEN : LENGTHF ; CPP : -> CHARPTR ; begin (* TESTSTR *) LF := ADDR ( X ) ; WRITELN ( 'lf 1 von x = ' , LF -> ) ; LEN := LF -> ; LF := PTRADD ( LF , 2 ) ; WRITELN ( 'lf 2 von x = ' , LF -> ) ; CP := PTRADD ( LF , 2 ) ; if LEN < 0 then begin CPP := PTRADD ( CP , 0 ) ; CP := CPP -> end (* then *) ; WRITELN ( '1. byte von x = ' , ORD ( CP -> ) ) ; WRITELN ( 'x [1] = ' , X [ 1 ] ) ; WRITELN ( 'x [4] = ' , X [ 4 ] ) ; //************************************************************ // y genauer anschauen //************************************************************ LF := ADDR ( Y ) ; WRITELN ( 'lf 1 von y = ' , LF -> ) ; LEN := LF -> ; LF := PTRADD ( LF , 2 ) ; WRITELN ( 'lf 2 von y = ' , LF -> ) ; CP := PTRADD ( LF , 2 ) ; if LEN < 0 then begin CPP := PTRADD ( CP , 0 ) ; CP := CPP -> end (* then *) ; WRITELN ( '1. byte von y = ' , ORD ( CP -> ) ) ; WRITELN ( 'y [1] = ' , Y [ 1 ] ) ; WRITELN ( 'y [4] = ' , Y [ 4 ] ) ; Y := 'Oppolzer' ; Y [ 5 ] := 'S' ; //************************************************************ // z genauer anschauen //************************************************************ LF := ADDR ( Z ) ; WRITELN ( 'lf 1 von z = ' , LF -> ) ; LEN := LF -> ; LF := PTRADD ( LF , 2 ) ; WRITELN ( 'lf 2 von z = ' , LF -> ) ; CP := PTRADD ( LF , 2 ) ; if LEN < 0 then begin CPP := PTRADD ( CP , 0 ) ; CP := CPP -> end (* then *) ; WRITELN ( '1. byte von z = ' , ORD ( CP -> ) ) ; WRITELN ( 'z [1] = ' , Z [ 1 ] ) ; WRITELN ( 'z [4] = ' , Z [ 4 ] ) ; //************************************************************ // Z := 'Oppolzer' ; // Z [ 5 ] := 'S' ; //************************************************************ end (* TESTSTR *) ; function SUBSTR1 ( const SOURCE : STRING ; START : INTEGER ; LEN : INTEGER ) : STRING ; type LENGTHF = 0 .. 32767 ; var X : INTEGER ; Z : STRING ( 100 ) ; P : ANYPTR ; Q : ANYPTR ; PLF : -> LENGTHF ; begin (* SUBSTR1 *) WRITELN ( 'substr1 - source: <' , SOURCE , '>' ) ; WRITELN ( 'substr1 - start = ' , START ) ; WRITELN ( 'substr1 - len = ' , LEN ) ; if LEN < 0 then begin if START > LENGTH ( SOURCE ) then EXIT ( 1201 ) ; LEN := LENGTH ( SOURCE ) - START + 1 ; end (* then *) else begin X := START + LEN - 1 ; if X > LENGTH ( SOURCE ) then EXIT ( 1201 ) ; end (* else *) ; if LEN > 100 then EXIT ( 1202 ) ; Z := '' ; P := ADDR ( Z ) ; P := PTRADD ( P , 2 ) ; PLF := P ; P := PTRADD ( P , 2 ) ; Q := ADDR ( SOURCE [ START ] ) ; PLF -> := LEN ; MEMCPY ( P , Q , LEN ) ; SUBSTR1 := Z ; end (* SUBSTR1 *) ; function SUBSTR2 ( const SOURCE : STRING ; START : INTEGER ; LEN : INTEGER ) : STRING ; type LENGTHF = 0 .. 32767 ; var X : INTEGER ; P : ANYPTR ; Q : ANYPTR ; begin (* SUBSTR2 *) if LEN < 0 then begin if START > LENGTH ( SOURCE ) then EXIT ( 1201 ) ; LEN := LENGTH ( SOURCE ) - START + 1 ; end (* then *) else begin X := START + LEN - 1 ; if X > LENGTH ( SOURCE ) then EXIT ( 1201 ) ; end (* else *) ; SUBSTR2 := REPEATSTR ( ' ' , LEN ) ; P := STRRESULTP ; Q := ADDR ( SOURCE [ START ] ) ; MEMCPY ( P , Q , LEN ) ; end (* SUBSTR2 *) ; procedure TEIL3 ; begin (* TEIL3 *) //************************************************************ // verkettung direkt in Writeln ... //************************************************************ //****** //************************************************************ VC200 := VC20 || VC20 ; WRITE ( 'VC200 nach Verkettung ................: ' ) ; WRITELN ( '<' , VC200 , '>' ) ; WRITE ( 'Verkettung direkt ausgeben ...........: ' ) ; WRITELN ( '<' , VC20 || VC20 , '>' ) ; WRITE ( 'Verkettung nochmal direkt ausgeben ...: ' ) ; WRITELN ( '<' , VC20 || ' ' || C20A , '>' ) ; //***************************************************************** //* // tests mit prozeduren, call by value und by reference //***************************************************************** //* WRITELN ( 'Aufruf STRPROC' ) ; STRPROC ( 'Bernd' , P1 , 'xxxxxxxxxxxxxxx' , P2 ) ; WRITELN ( 'zurck von STRPROC' ) ; WRITE ( 'P1 nach STRPROC ......................: ' ) ; WRITELN ( '<' , P1 , '>' ) ; WRITE ( 'P2 nach STRPROC ......................: ' ) ; WRITELN ( '<' , P2 , '>' ) ; //***************************************************************** //* // noch ein Test, unpassende var-Parameter //***************************************************************** //* WRITELN ( 'Aufruf STRPROC' ) ; STRPROC ( 'Bernd' , P2 , 'xxxxxxxxxxxxxxx' , P1 ) ; WRITELN ( 'zurck von STRPROC' ) ; WRITE ( 'P1 nach STRPROC ......................: ' ) ; WRITELN ( '<' , P1 , '>' ) ; WRITE ( 'P2 nach STRPROC ......................: ' ) ; WRITELN ( '<' , P2 , '>' ) ; //***************************************************************** //* // length und maxlength ausprobieren //***************************************************************** //* WRITE ( 'maxlength von einfachem char .........: ' ) ; WRITELN ( MAXLENGTH ( 'a' ) ) ; WRITE ( 'maxlength von char-Konstante .........: ' ) ; WRITELN ( MAXLENGTH ( 'Bernd' ) ) ; WRITE ( 'maxlength von char-Variable ..........: ' ) ; WRITELN ( MAXLENGTH ( C1 ) ) ; WRITE ( 'maxlength von char-array .............: ' ) ; WRITELN ( MAXLENGTH ( C20A ) ) ; WRITE ( 'maxlength von string .................: ' ) ; WRITELN ( MAXLENGTH ( VC20 ) ) ; WRITE ( 'maxlength von string-Expression ......: ' ) ; WRITELN ( MAXLENGTH ( VC20 || ' ' || VC20 ) ) ; WRITE ( 'length von einfachem char ............: ' ) ; WRITELN ( LENGTH ( 'a' ) ) ; WRITE ( 'length von char-konstante ............: ' ) ; WRITELN ( LENGTH ( 'bernd' ) ) ; WRITE ( 'length von char-variable .............: ' ) ; WRITELN ( LENGTH ( C1 ) ) ; WRITE ( 'length von char-array ................: ' ) ; WRITELN ( LENGTH ( C20A ) ) ; WRITE ( 'length von string ....................: ' ) ; WRITELN ( LENGTH ( VC20 ) ) ; WRITE ( 'length von string-expression .........: ' ) ; WRITELN ( LENGTH ( VC20 || ' ' || VC20 ) ) ; //***************************************************************** //* // Funktion mit string ergebnis ausprobieren //***************************************************************** //* P1 := 'Oppolzer' ; I := IFUNC ( VC20 , P1 ) ; WRITE ( 'funktion mit Integer Ergebnis ........: ' ) ; WRITELN ( I ) ; P1 := 'Oppolzer' ; P2 := STRFUNC ( VC20 , P1 ) ; WRITE ( 'p2 = funktion mit String Ergebnis ....: ' ) ; WRITELN ( '<' , P2 , '>' ) ; P2 := 'Test ' || STRFUNC ( VC20 , P1 ) || ' nochmal Test' ; WRITE ( 'p2 = kombiniert mit Funktion .........: ' ) ; WRITELN ( '<' , P2 , '>' ) ; WRITE ( 'String Ergebnis direkt ...............: ' ) ; WRITELN ( '<' , STRFUNC ( VC20 , P1 ) , '>' ) ; WRITE ( 'String Ergebnis mit Konstanten .......: ' ) ; WRITELN ( '<' , STRFUNC ( 'Bernd ' , ' Oppolzer' ) , '>' ) ; //***************************************************************** //* // test Funktion mit const String parametern //***************************************************************** //* P1 := 'Oppolzer' ; P2 := STRFUNC3 ( VC20 , P1 ) ; WRITE ( 'p2 = funktion mit var String .........: ' ) ; WRITELN ( '<' , P2 , '>' ) ; P1 := 'Oppolzer' ; P2 := STRFUNC5 ( VC20 , P1 ) ; WRITE ( 'p2 = funktion mit var String (2 mal) .: ' ) ; WRITELN ( '<' , P2 , '>' ) ; WRITELN ( 'Test Funktionsaufruf mit const Parm zwei Vars' ) ; P1 := 'Oppolzer' ; WRITELN ( 'addr(s) vor strfunc2 = ' , ADDR ( S ) ) ; P2 := STRFUNC2 ( VC20 , P1 ) ; WRITELN ( 'addr(s) nach strfunc2 = ' , ADDR ( S ) ) ; WRITE ( 'p2 = funktion mit const String .......: ' ) ; WRITELN ( '<' , P2 , '>' ) ; WRITELN ( 'Test Funktionsaufruf mit const Parm zwei Expr' ) ; P1 := 'Oppolzer' ; WRITELN ( 'addr(s) vor strfunc2 = ' , ADDR ( S ) ) ; P2 := STRFUNC2 ( VC20 || ' ' , ' ' || P1 ) ; WRITELN ( 'addr(s) nach strfunc2 = ' , ADDR ( S ) ) ; WRITE ( 'p2 = funktion mit const String .......: ' ) ; WRITELN ( '<' , P2 , '>' ) ; WRITELN ( 'Test Funktionsaufruf mit const Parm zwei Const' ) ; WRITELN ( 'addr(s) vor strfunc2 = ' , ADDR ( S ) ) ; P2 := STRFUNC2 ( 'Bernd' , ' Oppolzer' ) ; WRITELN ( 'addr(s) nach strfunc2 = ' , ADDR ( S ) ) ; WRITE ( 'p2 = funktion mit const String .......: ' ) ; WRITELN ( '<' , P2 , '>' ) ; WRITELN ( 'Test Funktionsaufruf mit const Parm Expr + Const' ) ; WRITELN ( 'addr(s) vor strfunc2 = ' , ADDR ( S ) ) ; P2 := STRFUNC2 ( VC20 || ' ' , ' Oppolzer' ) ; WRITELN ( 'addr(s) nach strfunc2 = ' , ADDR ( S ) ) ; WRITE ( 'p2 = funktion mit const String .......: ' ) ; WRITELN ( '<' , P2 , '>' ) ; end (* TEIL3 *) ; function CHECKF : STRING ; var X : ANYPTR ; CH : CHAR ; COUNT : INTEGER ; S : STRING ( 20 ) ; begin (* CHECKF *) CH := '*' ; S := REPEATSTR ( CH , 10 ) ; WRITELN ( 'test repeatstr = <' , S , '>' ) ; CH := '*' ; COUNT := 15 ; S := REPEATSTR ( CH , COUNT ) ; WRITELN ( 'test repeatstr = <' , S , '>' ) ; X := NIL ; WRITELN ( 'strresultp = ' , X ) ; X := STRRESULTP ; WRITELN ( 'strresultp = ' , X ) ; WRITELN ( 'strresultp = ' , STRRESULTP ) ; CHECKF := 'Bernd Oppolzer' ; WRITELN ( 'strresultp = ' , STRRESULTP ) ; WRITELN ( 'length (result) = ' , LENGTH ( STRRESULT ) ) ; CHECKF := 'Bernd Oppolzer' || STRRESULT ; WRITELN ( 'strresultp = ' , STRRESULTP ) ; WRITELN ( 'length (result) = ' , LENGTH ( STRRESULT ) ) ; CHECKF := REPEATSTR ( '*' , 1000 ) ; WRITELN ( 'strresultp = ' , STRRESULTP ) ; WRITELN ( 'length (result) = ' , LENGTH ( STRRESULT ) ) ; end (* CHECKF *) ; procedure TEIL4 ; begin (* TEIL4 *) //************************************************************ // test SUBSTR1 - einfache Variante //************************************************************ P1 := 'Oppolzer' ; P2 := 'Oppolzer' ; WRITELN ( 'TESTSTR Variante 1 - ueberall Variable' ) ; TESTSTR ( P1 , P2 , P1 ) ; WRITELN ( 'TESTSTR Variante 2 - Konstante byvalue' ) ; TESTSTR ( 'Oppolzer' , P2 , P1 ) ; WRITELN ( 'TESTSTR Variante 3 - Konstante byconst' ) ; TESTSTR ( P1 , P2 , 'Oppolzer' ) ; WRITE ( 'P1 nach Aufruf TESTSTR ...............: ' ) ; WRITELN ( '<' , P1 , '>' ) ; WRITE ( 'P2 nach Aufruf TESTSTR ...............: ' ) ; WRITELN ( '<' , P2 , '>' ) ; P1 := 'Oppolzer' ; WRITE ( 'Zugriff auf String ueber Index .......: ' ) ; WRITELN ( P1 [ 1 ] ) ; WRITE ( 'Zugriff auf String ueber Index .......: ' ) ; WRITELN ( P1 [ 5 ] ) ; P2 := SUBSTR1 ( P1 , 3 , 4 ) ; WRITE ( 'p2 = Ergebnis von SUBSTR1 ............: ' ) ; WRITELN ( '<' , P2 , '>' ) ; P2 := SUBSTR1 ( 'Bernd ' || 'Oppolzer' , 5 , 7 ) ; WRITE ( 'p2 = Ergebnis von SUBSTR1 ............: ' ) ; WRITELN ( '<' , P2 , '>' ) ; P2 := SUBSTR1 ( 'Bernd ' || 'Oppolzer' , 5 , - 1 ) ; WRITE ( 'p2 = Ergebnis von SUBSTR1 ............: ' ) ; WRITELN ( '<' , P2 , '>' ) ; //************************************************************ // ... geht nur in Funktion mit String Result !! // WRITE ( 'Testausgabe STRRESULT ................: ' ) ; // WRITELN ( STRRESULT ) ; // WRITE ( 'Testausgabe STRRESULTP ...............: ' ) ; // WRITELN ( STRRESULTP ) ; //************************************************************ VC2000 := CHECKF ; WRITE ( 'Laenge des Ergebnisses von CHECKF ....: ' ) ; WRITELN ( LENGTH ( VC2000 ) ) ; WRITE ( 'Test REPEATSTR .......................: ' ) ; WRITELN ( REPEATSTR ( 'Bernd ' , 5 ) ) ; P1 := 'Oppolzer ' ; WRITE ( 'Test REPEATSTR .......................: ' ) ; WRITELN ( REPEATSTR ( P1 , 5 ) ) ; COUNT := 6 ; WRITE ( 'Test REPEATSTR .......................: ' ) ; WRITELN ( REPEATSTR ( 'Bernd ' , COUNT ) ) ; WRITE ( 'Test REPEATSTR .......................: ' ) ; WRITELN ( REPEATSTR ( P1 , COUNT ) ) ; //************************************************************ // test SUBSTR2 - korrekte Variante mit STRRESULTP usw. //************************************************************ P1 := 'Oppolzer' ; P2 := SUBSTR2 ( P1 , 3 , 4 ) ; WRITE ( 'p2 = Ergebnis von SUBSTR2 ............: ' ) ; WRITELN ( '<' , P2 , '>' ) ; P2 := SUBSTR2 ( 'Bernd ' || 'Oppolzer' , 5 , 7 ) ; WRITE ( 'p2 = Ergebnis von SUBSTR2 ............: ' ) ; WRITELN ( '<' , P2 , '>' ) ; P2 := SUBSTR2 ( 'Bernd ' || 'Oppolzer' , 5 , - 1 ) ; WRITE ( 'p2 = Ergebnis von SUBSTR2 ............: ' ) ; WRITELN ( '<' , P2 , '>' ) ; //************************************************************ // test SUBSTR //************************************************************ P1 := 'Oppolzer' ; P2 := SUBSTR ( P1 , 3 , 4 ) ; WRITE ( 'p2 = Ergebnis von SUBSTR .............: ' ) ; WRITELN ( '<' , P2 , '>' ) ; WRITE ( 'P1 nach SUBSTR (should not change) ...: ' ) ; WRITELN ( '<' , P1 , '>' ) ; P2 := SUBSTR ( 'Bernd ' || 'Oppolzer' , 5 , 7 ) ; WRITE ( 'p2 = Ergebnis von SUBSTR .............: ' ) ; WRITELN ( '<' , P2 , '>' ) ; P2 := SUBSTR ( 'Bernd ' || 'Oppolzer' , 5 ) ; WRITE ( 'p2 = Ergebnis von SUBSTR .............: ' ) ; WRITELN ( '<' , P2 , '>' ) ; //************************************************************ // test DELETE //************************************************************ P1 := 'Oppolzer' ; P2 := DELETE ( P1 , 3 , 4 ) ; WRITE ( 'p2 = Ergebnis von DELETE .............: ' ) ; WRITELN ( '<' , P2 , '>' ) ; WRITE ( 'P1 nach DELETE (should not change) ...: ' ) ; WRITELN ( '<' , P1 , '>' ) ; P2 := DELETE ( 'Bernd ' || 'Oppolzer' , 5 , 7 ) ; WRITE ( 'p2 = Ergebnis von DELETE .............: ' ) ; WRITELN ( '<' , P2 , '>' ) ; P2 := DELETE ( 'Bernd ' || 'Oppolzer' , 5 ) ; WRITE ( 'p2 = Ergebnis von DELETE .............: ' ) ; WRITELN ( '<' , P2 , '>' ) ; //************************************************************ // test RTRIM und LTRIM, TRIM und COMPRESS //************************************************************ P1 := ' Bernd Oppolzer ' ; P2 := RTRIM ( P1 ) ; WRITE ( 'p2 = Ergebnis von RTRIM ..............: ' ) ; WRITELN ( '<' , P2 , '>' ) ; WRITE ( 'P1 nach RTRIM (should not change) ....: ' ) ; WRITELN ( '<' , P1 , '>' ) ; WRITE ( 'p2 = Ergebnis von RTRIM ..............: ' ) ; WRITELN ( '<' , RTRIM ( ' a b ' ) , '>' ) ; WRITE ( 'p2 = Ergebnis von RTRIM ..............: ' ) ; WRITELN ( '<' , RTRIM ( ' ' ) , '>' ) ; P1 := ' Bernd Oppolzer ' ; P2 := LTRIM ( P1 ) ; WRITE ( 'p2 = Ergebnis von LTRIM ..............: ' ) ; WRITELN ( '<' , P2 , '>' ) ; WRITE ( 'P1 nach LTRIM (should not change) ....: ' ) ; WRITELN ( '<' , P1 , '>' ) ; WRITE ( 'p2 = Ergebnis von LTRIM ..............: ' ) ; WRITELN ( '<' , LTRIM ( ' a b ' ) , '>' ) ; WRITE ( 'p2 = Ergebnis von LTRIM ..............: ' ) ; WRITELN ( '<' , LTRIM ( ' ' ) , '>' ) ; P1 := ' Bernd Oppolzer ' ; P2 := TRIM ( P1 ) ; WRITE ( 'p2 = Ergebnis von TRIM ...............: ' ) ; WRITELN ( '<' , P2 , '>' ) ; WRITE ( 'P1 nach TRIM (should not change) .....: ' ) ; WRITELN ( '<' , P1 , '>' ) ; WRITE ( 'p2 = Ergebnis von TRIM ...............: ' ) ; WRITELN ( '<' , TRIM ( ' a b ' ) , '>' ) ; WRITE ( 'p2 = Ergebnis von TRIM ...............: ' ) ; WRITELN ( '<' , TRIM ( ' ' ) , '>' ) ; end (* TEIL4 *) ; function TESTCONST ( const S : STRING ) : STRING ; //********************************************************************** // checkout problem with const strings //********************************************************************** var CP : -> CHAR ; begin (* TESTCONST *) TESTCONST := S ; CP := STRRESULTP ; CP -> := 'A' ; end (* TESTCONST *) ; begin (* HAUPTPROGRAMM *) TEIL1 ; TEIL2 ; TEIL3 ; TEIL4 ; //************************************************************ // XP := RESULTP ; ... not allowed here //************************************************************ P1 := ' Bernd Oppolzer ' ; P2 := COMPRESS ( P1 ) ; WRITE ( 'p2 = Ergebnis von COMPRESS ...........: ' ) ; WRITELN ( '<' , P2 , '>' ) ; WRITE ( 'P1 nach COMPRESS (should not change) .: ' ) ; WRITELN ( '<' , P1 , '>' ) ; WRITE ( 'p2 = Ergebnis von COMPRESS ...........: ' ) ; WRITELN ( '<' , COMPRESS ( ' a b ' ) , '>' ) ; WRITE ( 'p2 = Ergebnis von COMPRESS ...........: ' ) ; WRITELN ( '<' , COMPRESS ( ' ' ) , '>' ) ; //****************************************************************** // test INDEX //****************************************************************** P1 := ' Bernd Oppolzer ' ; I := INDEX ( P1 , 'pol' ) ; WRITE ( 'Ergebnis von INDEX ...................: ' ) ; WRITELN ( I : 5 ) ; P1 := ' Bernd Oppolzer ' ; I := INDEX ( TRIM ( P1 ) , 'pol' ) ; WRITE ( 'Ergebnis von INDEX ...................: ' ) ; WRITELN ( I : 5 ) ; WRITE ( 'P1 nach TRIM (should not change) .....: ' ) ; WRITELN ( '<' , P1 , '>' ) ; WRITE ( 'Ergebnis von INDEX (3) ...............: ' ) ; WRITELN ( INDEX ( 'Oppolzer' , 'pol' ) : 5 ) ; WRITE ( 'Ergebnis von INDEX (0) ...............: ' ) ; WRITELN ( INDEX ( 'Oppolzer' , 'polizei' ) : 5 ) ; WRITE ( 'Ergebnis von INDEX (1) ...............: ' ) ; WRITELN ( INDEX ( 'Oppolzer' , 'Oppolzer' ) : 5 ) ; WRITE ( 'Ergebnis von INDEX (0) ...............: ' ) ; WRITELN ( INDEX ( 'Oppolzer' , 'Oppolzer1' ) : 5 ) ; WRITE ( 'Ergebnis von INDEX (1) ...............: ' ) ; WRITELN ( INDEX ( 'Oppolzer' , 'Oppo' ) : 5 ) ; WRITE ( 'Ergebnis von INDEX (6) ...............: ' ) ; WRITELN ( INDEX ( 'Oppolzer' , 'zer' ) : 5 ) ; //****************************************************************** // test VERIFY //****************************************************************** P1 := ' Bernd Oppolzer ' ; I := VERIFY ( P1 , 'Berndpol ' ) ; WRITE ( 'Ergebnis von VERIFY (9) ..............: ' ) ; WRITELN ( I : 5 ) ; P1 := '1256735473645' ; I := VERIFY ( P1 , '0123456789' ) ; WRITE ( 'Ergebnis von VERIFY (0) ..............: ' ) ; WRITELN ( I : 5 ) ; P1 := '125673547E645' ; I := VERIFY ( P1 , '0123456789' ) ; WRITE ( 'Ergebnis von VERIFY (10) .............: ' ) ; WRITELN ( I : 5 ) ; P1 := '125 73547E645' ; I := VERIFY ( P1 , '0123456789' ) ; WRITE ( 'Ergebnis von VERIFY (4) ..............: ' ) ; WRITELN ( I : 5 ) ; P1 := '1234567890123456789 ' ; I := VERIFY ( P1 , '0123456789' ) ; WRITE ( 'Ergebnis von VERIFY (20) .............: ' ) ; WRITELN ( I : 5 ) ; //****************************************************************** // test TRANSLATE //****************************************************************** P1 := ' Bernd Oppolzer ' ; WRITE ( 'P1 before testconst ..................: ' ) ; WRITELN ( '<' , P1 , '>' ) ; P2 := TESTCONST ( P1 ) ; WRITE ( 'P2 after testconst ...................: ' ) ; WRITELN ( '<' , P2 , '>' ) ; WRITE ( 'P1 after testconst (should not change): ' ) ; WRITELN ( '<' , P1 , '>' ) ; P1 := ' Bernd Oppolzer ' ; P2 := TRANSLATE ( P1 , 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' , 'abcdefghijklmnopqrstuvwxyz' ) ; WRITE ( 'Ergebnis von TRANSLATE ...............: ' ) ; WRITELN ( '<' , P2 , '>' ) ; WRITE ( 'P1 nach TRANSLATE (should not change) : ' ) ; WRITELN ( '<' , P1 , '>' ) ; P1 := ' Bernd Oppolzer ' ; P2 := TRANSLATE ( P1 , 'y' , 'z' ) ; WRITE ( 'Ergebnis von TRANSLATE ...............: ' ) ; WRITELN ( '<' , P2 , '>' ) ; WRITE ( 'P1 nach TRANSLATE (should not change) : ' ) ; WRITELN ( '<' , P1 , '>' ) ; P1 := ' Bernd Oppolzer ' ; WRITE ( 'Ergebnis von TRANSLATE ...............: ' ) ; WRITELN ( '<' , TRANSLATE ( P1 , 'CAyx' , 'BOze' ) , '>' ) ; WRITE ( 'P1 nach TRANSLATE (should not change) : ' ) ; WRITELN ( '<' , P1 , '>' ) ; P1 := ' Bernd Oppolzer ' ; WRITE ( 'Ergebnis von TRANSLATE ...............: ' ) ; WRITELN ( '<' , TRANSLATE ( P1 , 'x' , ' ' ) , '>' ) ; WRITE ( 'P1 nach TRANSLATE ....................: ' ) ; WRITELN ( '<' , P1 , '>' ) ; if TRUE then begin TTAB := IDENT_T1 || IDENT_T2 ; TTAB [ ORD ( ' ' ) + 1 ] := 'y' ; P1 := ' Bernd Oppolzer ' ; P2 := TRANSLATE ( P1 , TTAB , '' ) ; WRITE ( 'Ergebnis von TRANSLATE (3. P. leer) ..: ' ) ; WRITELN ( '<' , P2 , '>' ) ; WRITE ( 'Ergebnis von TRANSLATE (3. P. leer) ..: ' ) ; WRITELN ( '<' , TRANSLATE ( P1 , TTAB , '' ) , '>' ) ; WRITE ( 'P1 nach TRANSLATE (should not change) : ' ) ; WRITELN ( '<' , P1 , '>' ) ; P1 := ' Bernd Oppolzer ' ; P2 := TRANSLATE ( P1 , TTAB ) ; WRITE ( 'Ergebnis von TRANSLATE (3. P. n.vorh.): ' ) ; WRITELN ( '<' , P2 , '>' ) ; WRITE ( 'Ergebnis von TRANSLATE (3. P. n.vorh.): ' ) ; WRITELN ( '<' , TRANSLATE ( P1 , TTAB ) , '>' ) ; WRITE ( 'P1 nach TRANSLATE (should not change) : ' ) ; WRITELN ( '<' , P1 , '>' ) ; end (* then *) //****************************************************************** // Ende aller Tests //****************************************************************** end (* HAUPTPROGRAMM *) .
{$include lem_directives.inc} unit GameSound; interface uses Windows, Classes, Contnrs, SysUtils, GameModPlay, Dialogs, LemTypes; const DEFAULT_CHANNELS = 4; type TAbstractSound = class private fStream: TMemoryStream; fResourceDataType: TLemDataType; protected public constructor Create; destructor Destroy; override; procedure LoadFromFileName(const aFileName: string); procedure LoadFromStream(aStream: TStream); // procedure Play; virtual; abstract; // procedure Stop; virtual; abstract; end; TSound = class(TAbstractSound) private protected public constructor Create; // procedure Play; override; // procedure Stop; override; end; TMusic = class(TAbstractSound) private protected public constructor Create; // procedure Play; override; // procedure Stop; override; end; TSoundList = class(TObjectList) private function GetItem(Index: Integer): TSound; protected public function Add(Item: TSound): Integer; procedure Insert(Index: Integer; Item: TSound); property Items[Index: Integer]: TSound read GetItem; default; published end; TMusicList = class(TObjectList) private function GetItem(Index: Integer): TMusic; protected public function Add(Item: TMusic): Integer; procedure Insert(Index: Integer; Item: TMusic); property Items[Index: Integer]: TMusic read GetItem; default; published end; TSoundMgr = class private fMusics: TMusicList; fSounds: TList; fAvailableChannels : Integer; fBrickSound : Integer; fActiveSounds : array[0..255] of Boolean; fPlayingSounds : array[0..255] of Integer; protected public constructor Create; destructor Destroy; override; { sounds } function AddSoundFromFileName(const aFileName: string): Integer; procedure PlaySound(Index: Integer); procedure StopSound(Index: Integer); //procedure MarkChannelFree(handle: HSYNC; channel, data: DWORD; user: POINTER); stdcall; { musics } function AddMusicFromFileName(const aFileName: string): Integer; procedure PlayMusic(Index: Integer); procedure StopMusic(Index: Integer); procedure CheckFreeChannels; property Musics: TMusicList read fMusics; property Sounds: TList read fSounds; property AvailableChannels: Integer read fAvailableChannels write fAvailableChannels; property BrickSound: Integer read fBrickSound write fBrickSound; end; (* TWavePlayerEx = class(TWavePlayer) private // Ix: Integer; protected public end; *) TSoundSystem = class private fMusicRef : HMUSIC; //fWinampPlugin : HPLUGIN; //fVgmPlugin : DWORD; //fWavePlayer: TWavePlayerEx;//array[0..2] of TWavePlayerEx; // procedure WavePlayer_Finished(Sender: TObject); protected public constructor Create; destructor Destroy; override; procedure InitWav; function PlayWav(S: TMemoryStream): Integer; procedure StopWav(S: TMemoryStream); procedure PlayMusic(S: TMemoryStream); procedure StopMusic(S: TMemoryStream); end; implementation uses MMSystem; var _SoundSystem: TSoundSystem; function SoundSystem: TSoundSystem; begin if _SoundSystem = nil then _SoundSystem := TSoundSystem.Create; Result := _SoundSystem; end; { TAbstractSound } constructor TAbstractSound.Create; begin inherited Create; fStream := TMemoryStream.Create; end; destructor TAbstractSound.Destroy; begin fStream.Free; inherited; end; procedure TAbstractSound.LoadFromFileName(const aFileName: string); {------------------------------------------------------------------------------- Loads from file or archive file in resource -------------------------------------------------------------------------------} var F: TStream; begin {$ifdef external} if FileExists(aFileName + '.ogg') then F := TFileStream.Create(aFileName + '.ogg', fmOpenRead) else if FileExists(aFileName + '.it') then F := TFileStream.Create(aFileName + '.it', fmOpenRead) else {$endif} F := CreateDataStream(aFileName, fResourceDataType); try LoadFromStream(F); finally F.Free; end; end; procedure TAbstractSound.LoadFromStream(aStream: TStream); begin fStream.LoadFromStream(aStream); end; { TSound } constructor TSound.Create; begin inherited Create; fResourceDataType := ldtSound; end; { TMusic } constructor TMusic.Create; begin inherited; fResourceDataType := ldtMusic; end; (* procedure TSound.Play; begin SoundSystem.PlayWav(fStream); end; procedure TSound.Stop; begin SoundSystem.StopWav(fStream); end; procedure TMusic.Play; begin SoundSystem.PlayMusic(fStream); end; procedure TMusic.Stop; begin SoundSystem.StopMusic(fStream); end; *) { TSoundList } function TSoundList.Add(Item: TSound): Integer; begin Result := inherited Add(Item); end; function TSoundList.GetItem(Index: Integer): TSound; begin Result := inherited Get(Index); end; procedure TSoundList.Insert(Index: Integer; Item: TSound); begin inherited Insert(Index, Item); end; { TMusicList } function TMusicList.Add(Item: TMusic): Integer; begin Result := inherited Add(Item); end; function TMusicList.GetItem(Index: Integer): TMusic; begin Result := inherited Get(Index); end; procedure TMusicList.Insert(Index: Integer; Item: TMusic); begin inherited Insert(Index, Item); end; { TSoundMgr } function TSoundMgr.AddMusicFromFileName(const aFileName: string): Integer; var M: TMusic; begin M := TMusic.Create; Result := Musics.Add(M); M.LoadFromFileName(aFileName); end; function TSoundMgr.AddSoundFromFileName(const aFileName: string): Integer; var S: TMemoryStream; begin S := TMemoryStream(CreateDataStream(aFileName, ldtSound)); //S.SaveToFile('test.wav'); Result := Sounds.Add(Pointer(BASS_SampleLoad(true, S.Memory, 0, S.Size, 65535, 0))); //S.LoadFromFileName(aFileName); end; constructor TSoundMgr.Create; var i: Integer; begin inherited Create; if not BASS_Init(-1, 44100, 0, 0, nil) then BASS_Free; fSounds := TList.Create; fMusics := TMusicList.Create; fAvailableChannels := DEFAULT_CHANNELS; for i := 0 to 255 do fPlayingSounds[i] := -1; end; destructor TSoundMgr.Destroy; begin StopSound(0); StopMusic(0); fSounds.Free; fMusics.Free; inherited Destroy; end; procedure TSoundMgr.CheckFreeChannels; var i : integer; begin for i := 0 to fAvailableChannels-1 do begin //if fPlayingSounds[i] < 0 then Continue; if (BASS_ChannelIsActive(fPlayingSounds[i]) <> BASS_ACTIVE_PLAYING) or (BASS_ChannelGetPosition(fPlayingSounds[i], BASS_POS_BYTE) >= BASS_ChannelGetLength(fPlayingSounds[i], BASS_POS_BYTE)) then begin fActiveSounds[i] := false; fPlayingSounds[i] := -1; Continue; end; if BASS_ChannelGetPosition(fPlayingSounds[i], BASS_POS_BYTE) >= BASS_ChannelSeconds2Bytes(fPlayingSounds[i], 0.5) then fActiveSounds[i] := false; end; end; procedure TSoundMgr.PlaySound(Index: Integer); var i{, i2} : Integer; c : HCHANNEL; LPosBytes : Integer; begin CheckFreeChannels; if Index = fBrickSound then begin if fPlayingSounds[0] >= 0 then BASS_ChannelStop(fPlayingSounds[0]); c := BASS_SampleGetChannel(Integer(Sounds[Index]), true); BASS_ChannelPlay(c, true); {BASS_ChannelSetSync(c, BASS_SYNC_POS or BASS_SYNC_MIXTIME, BASS_ChannelSeconds2Bytes(c, 0.5), BASS_MarkChannelFree, @fActiveSounds[0]); BASS_ChannelSetSync(c, BASS_SYNC_END or BASS_SYNC_MIXTIME, 0, BASS_MarkChannelFree, @fActiveSounds[0]); BASS_ChannelSetSync(c, BASS_SYNC_END or BASS_SYNC_MIXTIME, 0, BASS_WipeChannel, @fPlayingSounds[0]);} fPlayingSounds[0] := c; fActiveSounds[0] := true; Exit; end; if Index >= 0 then if Index < Sounds.Count then //Sounds[Index].Play; for i := 1 to (fAvailableChannels - 1) do begin if not fActiveSounds[i] then begin //c := (Sounds[Index]); if fPlayingSounds[i] >= 0 then BASS_ChannelStop(fPlayingSounds[i]); c := BASS_SampleGetChannel(Integer(Sounds[Index]), true); {i2 := BASS_ErrorGetCode; if i2 <> 0 then messagedlg(inttostr(i2), mtcustom, [mbok], 0);} BASS_ChannelPlay(c, true); {BASS_ChannelSetSync(c, BASS_SYNC_POS or BASS_SYNC_MIXTIME, BASS_ChannelSeconds2Bytes(c, 0.5), BASS_MarkChannelFree, @fActiveSounds[i]); BASS_ChannelSetSync(c, BASS_SYNC_END or BASS_SYNC_MIXTIME, 0, BASS_MarkChannelFree, @fActiveSounds[i]); BASS_ChannelSetSync(c, BASS_SYNC_END or BASS_SYNC_MIXTIME, 0, BASS_WipeChannel, @fPlayingSounds[i]);} fPlayingSounds[i] := c; fActiveSounds[i] := true; Exit; end; end; end; procedure TSoundMgr.PlayMusic(Index: Integer); begin if Index >= 0 then if Index < Musics.Count then // Musics[Index].Play; SoundSystem.PlayMusic(Musics[Index].fStream) end; procedure TSoundMgr.StopSound(Index: Integer); begin // if Index >= 0 then // if Index < SoundSystem.StopWav(nil); end; procedure TSoundMgr.StopMusic(Index: Integer); begin if Index >= 0 then if Index < Musics.Count then //Musics[Index].Stop; SoundSystem.StopMusic(nil); end; { TSoundSystem } constructor TSoundSystem.Create; //var //i: Integer; begin inherited Create; //if not BASS_Init(-1, 44100, 0, 0, nil) then // BASS_Free; InitWav; end; destructor TSoundSystem.Destroy; //var //i: Integer; begin BASS_Free; // for i := 0 to 2 do // fWavePlayer.Free; inherited; end; procedure TSoundSystem.InitWav; begin PlaySound(nil, HINSTANCE, SND_ASYNC + SND_MEMORY); end; procedure TSoundSystem.PlayMusic(S: TMemoryStream); const MusicFlags = BASS_MUSIC_LOOP or BASS_MUSIC_RAMPS or BASS_MUSIC_SURROUND or BASS_MUSIC_POSRESET or BASS_SAMPLE_SOFTWARE; var i, v : Integer; begin BASS_StreamFree(fMusicRef); BASS_MusicFree(fMusicRef); fMusicRef := 0; if S.Size > 0 then fMusicRef := BASS_StreamCreateFile(true, S.Memory, 0, S.Size, MusicFlags); if fMusicRef = 0 then begin fMusicRef := BASS_MusicLoad(true, S.Memory, 0, S.Size, MusicFlags, 1); BASS_ChannelSetAttribute(fMusicRef, BASS_ATTRIB_MUSIC_AMPLIFY, 30); end else BASS_LoadLoopData(fMusicRef); if fMusicRef <> 0 then BASS_ChannelPlay(fMusicRef, false); end; function TSoundSystem.PlayWav(S: TMemoryStream): Integer; //var //i: Integer; begin (* // for i := 0 to 2 do begin with fWavePlayer do begin // if State = wpPlaying then // Stop; // if State <> wpPlaying then begin Source := S; Play; // Exit; end; end; end; *) PlaySound(S.Memory, HINSTANCE, SND_ASYNC + SND_MEMORY); end; procedure TSoundSystem.StopMusic(S: TMemoryStream); begin BASS_ChannelStop(fMusicRef); //BASS_StreamFree(fMusicRef); end; procedure TSoundSystem.StopWav(S: TMemoryStream); begin PlaySound(nil, HINSTANCE, SND_ASYNC + SND_MEMORY); end; initialization finalization _SoundSystem.Free; _SoundSystem := nil; end.
unit StreamToStr; interface uses Classes; function StreamToString( Stream : TStream ) : string; procedure StringToStream( str : string; Stream : TStream ); implementation uses SysUtils, CompStringsParser; const ByteSep = ':'; function StreamToString( Stream : TStream ) : string; var b : byte; begin result := ''; Stream.Position := 0; while Stream.Position < Stream.Size do begin Stream.ReadBuffer( b, sizeof(b) ); result := result + IntToStr(b) + ByteSep; end; end; procedure StringToStream( str : string; Stream : TStream ); var token : string; p : integer; b : byte; begin try p := 1; repeat token := GetNextStringUpTo( str, p, ByteSep ); if token <> '' then begin b := StrToInt( token ); Stream.WriteBuffer( b, sizeof(b) ); end; until token = ''; except end; end; end.
unit UDMCliente; interface uses System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client,uCliente, FireDAC.Stan.StorageBin; type TDMCliente = class(TDataModule) cdsEndereco: TFDMemTable; cdsCliente: TFDMemTable; cdsClientenome: TStringField; cdsClienteIdentidade: TStringField; cdsClienteCPF: TStringField; cdsClientetelefone: TStringField; cdsClienteemail: TStringField; cdsClienteid: TIntegerField; cdsEnderecocep: TStringField; cdsEnderecoLogradouro: TStringField; cdsEnderecoBairro: TStringField; cdsEnderecoComplemento: TStringField; cdsEnderecoCidade: TStringField; cdsEnderecoEstado: TStringField; cdsEnderecopais: TStringField; cdsEnderecoIDCliente: TIntegerField; cdsEnderecoNumero: TStringField; private { Private declarations } public { Public declarations } function GerarID: Integer; procedure InserirCliente(oCliente: TCliente); procedure InserirEndereco(oCliente: TCliente); function RetornaDadosCliente: IFDDataSetReference; function RetornaDadosEndereco: IFDDataSetReference; end; var DMCliente: TDMCliente; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} { TDataModule1 } function TDMCliente.GerarID: Integer; begin Result := cdsCliente.RecordCount + 1; end; procedure TDMCliente.InserirCliente(oCliente: TCliente); begin cdsCliente.Insert; with oCliente do begin cdsClienteid.AsInteger := GerarID; cdsClientenome.AsString := Nome; cdsClienteIdentidade.AsString := Identidade; cdsClientecpf.AsString := CPF; cdsClientetelefone.AsString := Telefone; cdsClienteemail.AsString := Email; end; try cdsCliente.Post; except on e: Exception do begin raise Exception.Create(e.Message); end; end; end; procedure TDMCliente.InserirEndereco(oCliente: TCliente); var I: integer; begin cdsEndereco.Insert; try with oCliente do begin for I := 0 to Endereco.Count -1 do begin cdsEndereco.Insert; cdsEnderecoIDCliente.AsInteger := Endereco.Items[i].IdCliente; cdsEnderecocep.AsString := Endereco.Items[i].Cep; cdsEnderecoLogradouro.AsString := Endereco.Items[i].Logradouro; cdsEnderecoNumero.AsString := Endereco.Items[i].Numero; cdsEnderecoBairro.AsString := Endereco.Items[i].Bairro; cdsEnderecoComplemento.AsString := Endereco.Items[i].Complemento; cdsEnderecoCidade.AsString := Endereco.Items[i].Localidade; cdsEnderecoEstado.AsString := Endereco.Items[i].Uf; cdsEnderecopais.AsString := Endereco.Items[i].Pais; cdsEndereco.Post; end; end; except on e: Exception do begin raise Exception.Create('Erro ao inserir Endereco para o Cliente: ' + oCliente.Nome); end; end; end; function TDMCliente.RetornaDadosCliente: IFDDataSetReference; begin Result := self.cdsCliente.Data; end; function TDMCliente.RetornaDadosEndereco: IFDDataSetReference; begin Result := self.cdsEndereco.Data; end; end.
{ CoreGraphics - CGFont.h * Copyright (c) 1999-2003 Apple Computer, Inc. * All rights reserved. } { Pascal Translation Updated: Peter N Lewis, <peter@stairways.com.au>, August 2005 } { Modified for use with Free Pascal Version 210 Please report any bugs to <gpc@microbizz.nl> } {$mode macpas} {$packenum 1} {$macro on} {$inline on} {$calling mwpascal} unit CGFont; interface {$setc UNIVERSAL_INTERFACES_VERSION := $0342} {$setc GAP_INTERFACES_VERSION := $0210} {$ifc not defined USE_CFSTR_CONSTANT_MACROS} {$setc USE_CFSTR_CONSTANT_MACROS := TRUE} {$endc} {$ifc defined CPUPOWERPC and defined CPUI386} {$error Conflicting initial definitions for CPUPOWERPC and CPUI386} {$endc} {$ifc defined FPC_BIG_ENDIAN and defined FPC_LITTLE_ENDIAN} {$error Conflicting initial definitions for FPC_BIG_ENDIAN and FPC_LITTLE_ENDIAN} {$endc} {$ifc not defined __ppc__ and defined CPUPOWERPC} {$setc __ppc__ := 1} {$elsec} {$setc __ppc__ := 0} {$endc} {$ifc not defined __i386__ and defined CPUI386} {$setc __i386__ := 1} {$elsec} {$setc __i386__ := 0} {$endc} {$ifc defined __ppc__ and __ppc__ and defined __i386__ and __i386__} {$error Conflicting definitions for __ppc__ and __i386__} {$endc} {$ifc defined __ppc__ and __ppc__} {$setc TARGET_CPU_PPC := TRUE} {$setc TARGET_CPU_X86 := FALSE} {$elifc defined __i386__ and __i386__} {$setc TARGET_CPU_PPC := FALSE} {$setc TARGET_CPU_X86 := TRUE} {$elsec} {$error Neither __ppc__ nor __i386__ is defined.} {$endc} {$setc TARGET_CPU_PPC_64 := FALSE} {$ifc defined FPC_BIG_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := TRUE} {$setc TARGET_RT_LITTLE_ENDIAN := FALSE} {$elifc defined FPC_LITTLE_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := FALSE} {$setc TARGET_RT_LITTLE_ENDIAN := TRUE} {$elsec} {$error Neither FPC_BIG_ENDIAN nor FPC_LITTLE_ENDIAN are defined.} {$endc} {$setc ACCESSOR_CALLS_ARE_FUNCTIONS := TRUE} {$setc CALL_NOT_IN_CARBON := FALSE} {$setc OLDROUTINENAMES := FALSE} {$setc OPAQUE_TOOLBOX_STRUCTS := TRUE} {$setc OPAQUE_UPP_TYPES := TRUE} {$setc OTCARBONAPPLICATION := TRUE} {$setc OTKERNEL := FALSE} {$setc PM_USE_SESSION_APIS := TRUE} {$setc TARGET_API_MAC_CARBON := TRUE} {$setc TARGET_API_MAC_OS8 := FALSE} {$setc TARGET_API_MAC_OSX := TRUE} {$setc TARGET_CARBON := TRUE} {$setc TARGET_CPU_68K := FALSE} {$setc TARGET_CPU_MIPS := FALSE} {$setc TARGET_CPU_SPARC := FALSE} {$setc TARGET_OS_MAC := TRUE} {$setc TARGET_OS_UNIX := FALSE} {$setc TARGET_OS_WIN32 := FALSE} {$setc TARGET_RT_MAC_68881 := FALSE} {$setc TARGET_RT_MAC_CFM := FALSE} {$setc TARGET_RT_MAC_MACHO := TRUE} {$setc TYPED_FUNCTION_POINTERS := TRUE} {$setc TYPE_BOOL := FALSE} {$setc TYPE_EXTENDED := FALSE} {$setc TYPE_LONGLONG := TRUE} uses MacTypes,CFBase,CFData,CFDictionary,CFArray,CGBase; {$ALIGN POWER} { The type used to represent a CoreGraphics font. } type CGFontRef = ^SInt32; { an opaque 32-bit type } { A type to represent indexes in a CGFontRef. } type CGFontIndex = UInt16; { A type to represent glyph identifiers in a CGFontRef. } type CGGlyph = CGFontIndex; CGGlyphPtr = ^CGGlyph; { The format of a PostScript font subset. Type1 is documented in the * "Adobe Type 1 Font Format"; Type3 in the "PostScript Language Reference, * 3rd ed." and Type42 in "Adobe Technical Note 5012, The Type 42 Font * Format Specification". } type CGFontPostScriptFormat = SInt32; const kCGFontPostScriptFormatType1 = 1; kCGFontPostScriptFormatType3 = 3; kCGFontPostScriptFormatType42 = 42; const { The maximum allowed value of a CGFontIndex. Always <= USHRT_MAX - 1. } kCGFontIndexMax = (1 shl 16) - 2; { A value representing an invalid CGFontIndex. Always <= USHRT_MAX. } kCGFontIndexInvalid = (1 shl 16) - 1; { The maximum allowed value of a CGGlyph. } kCGGlyphMax = kCGFontIndexMax; { Return the CFTypeID for CGFontRefs. } function CGFontGetTypeID: CFTypeID; external name '_CGFontGetTypeID'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { Create a CGFontRef using `platformFontReference', a pointer to a * platform-specific font reference. For MacOS X, `platformFontReference' * should be a pointer to an ATSFontRef. } function CGFontCreateWithPlatformFont( platformFontReference: UnivPtr ): CGFontRef; external name '_CGFontCreateWithPlatformFont'; { Return a font based on `font' with the variation specification * dictionary `variations' applied to `font'. A variation specification * dictionary contains keys corresponding the variation axis names of the * font. Each key is a variation axis name; the value for each key is the * value specified for that particular variation axis represented as a * CFNumberRef. If a variation axis name is not specified in `variations', * then the current value from `font' is used. } function CGFontCreateCopyWithVariations( font: CGFontRef; variations: CFDictionaryRef ): CGFontRef; external name '_CGFontCreateCopyWithVariations'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { Equivalent to `CFRetain(font)', except it doesn't crash (as CFRetain * does) if `font' is NULL. } function CGFontRetain( font: CGFontRef ): CGFontRef; external name '_CGFontRetain'; { Equivalent to `CFRelease(font)', except it doesn't crash (as CFRelease * does) if `font' is NULL. } procedure CGFontRelease( font: CGFontRef ); external name '_CGFontRelease'; { Return the PostScript name of `font'. } function CGFontCopyPostScriptName( font: CGFontRef ): CFStringRef; external name '_CGFontCopyPostScriptName'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { Return an array of the variation axis dictionaries for `font'. Each * variation axis dictionary contains values for the variation axis keys * listed below. This function returns NULL if `font' doesn't support * variations. } function CGFontCopyVariationAxes( font: CGFontRef ): CFArrayRef; external name '_CGFontCopyVariationAxes'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { Return the variation specification dictionary from `font'. This * dictionary contains keys corresponding the variation axis names of the * font. Each key is a variation axis name; the value for each key is the * value specified for that particular variation axis represented as a * CFNumberRef. This function returns NULL if `font' doesn't support * variations. } function CGFontCopyVariations( font: CGFontRef ): CFDictionaryRef; external name '_CGFontCopyVariations'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { Return true if a subset in the PostScript format `format' can be created * for `font'; false otherwise. } function CGFontCanCreatePostScriptSubset( font: CGFontRef; format: CGFontPostScriptFormat ): CBool; external name '_CGFontCanCreatePostScriptSubset'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { Create a subset of `font' named `subsetName' in the PostScript format * `format'. The subset will contain the glyphs specified by `glyphs', an * array of `count' CGGlyphs. If non-NULL, `encoding' specifies the * default encoding for the subset. } type CGGlyph256Array = array[0..255] of CGGlyph; function CGFontCreatePostScriptSubset( font: CGFontRef; subsetName: CFStringRef; format: CGFontPostScriptFormat; {const} glyphs: {variable-size-array} CGGlyphPtr; count: size_t; const (*var*) encoding: CGGlyph256Array ): CFDataRef; external name '_CGFontCreatePostScriptSubset'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { Return a PostScript encoding of `font' containing glyphs in `encoding'. } function CGFontCreatePostScriptEncoding( font: CGFontRef; const (*var*) encoding: CGGlyph256Array ): CFDataRef; external name '_CGFontCreatePostScriptEncoding'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) {** Keys for the font variation axis dictionary. **} { The key used to obtain the variation axis name from a variation axis * dictionary. The value obtained with this key is a CFStringRef specifying * the name of the variation axis. } var kCGFontVariationAxisName: CFStringRef; external name '_kCGFontVariationAxisName'; (* attribute const *) (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { The key used to obtain the minimum variation axis value from a variation * axis dictionary. The value obtained with this key is a CFNumberRef * specifying the minimum value of the variation axis. } var kCGFontVariationAxisMinValue: CFStringRef; external name '_kCGFontVariationAxisMinValue'; (* attribute const *) (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { The key used to obtain the maximum variation axis value from a variation * axis dictionary. The value obtained with this key is a CFNumberRef * specifying the maximum value of the variation axis. } var kCGFontVariationAxisMaxValue: CFStringRef; external name '_kCGFontVariationAxisMaxValue'; (* attribute const *) (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { The key used to obtain the default variation axis value from a variation * axis dictionary. The value obtained with this key is a CFNumberRef * specifying the default value of the variation axis. } var kCGFontVariationAxisDefaultValue: CFStringRef; external name '_kCGFontVariationAxisDefaultValue'; (* attribute const *) (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { Obsolete; don't use these. } const CGGlyphMin = 0; CGGlyphMax = kCGGlyphMax; end.
// Upgraded to Delphi 2009: Sebastian Zierer (* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is TurboPower SysTools * * The Initial Developer of the Original Code is * TurboPower Software * * Portions created by the Initial Developer are Copyright (C) 1996-2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** *) {*********************************************************} {* SysTools: StNetPfm.pas 4.04 *} {*********************************************************} {* SysTools: Net Performance Class *} {*********************************************************} {$I StDefine.inc} {$H+} {Huge strings} unit StNetPfm; interface uses Windows, Classes, StBase; type TStCPFlags = (cpfForNetCard, cpfNotRouted, cpfSlowLink, cpfDynamic); TStCPFlagsSet = set of TStCPFlags; TStNetPerformance = class(TStComponent) private { Private Methods/Properties } FGotData : Boolean; { Input } FLocalName : string; FRemoteName : string; FProviderName: string; { Output } FFlags : TStCPFlagsSet; FSpeed : DWord; FDelay : DWord; FOptDataSize : DWord; protected { Protected Methods/Properties } function GetFlags: TStCPFlagsSet; function GetSpeed: DWord; function GetDelay: DWord; function GetOptDataSize : DWord; procedure SetLocalName(Value: string); procedure SetRemoteName(Value: string); procedure SetProviderName(Value: string); public { Public Methods/Properties } procedure QueryPerformance; property Flags: TStCPFlagsSet read GetFlags; property Speed: DWord read GetSpeed; property Delay: DWord read GetDelay; property OptDataSize: DWord read GetOptDataSize; published { Published Methods/Properties } property LocalName: string read FLocalName write SetLocalName; property RemoteName: string read FRemoteName write SetRemoteName; property ProviderName: string read FProviderName write SetProviderName; end; implementation uses SysUtils {$IFDEF FPC} , Delphi.Windows {$ENDIF} ; procedure TStNetPerformance.QueryPerformance; var Err : DWord; NR : TNetResource; CI : TNetConnectInfoStruct; begin FillChar(NR, SizeOf(NR), 0); FillChar(CI, SizeOf(CI), 0); if FLocalName <> '' then NR.lpLocalName := PChar(FLocalName) else NR.lpRemoteName := PChar(FRemoteName); if Length(FProviderName) > 0 then NR.lpProvider := PChar(FProviderName); CI.cbStructure := SizeOf(CI); Err := MultinetGetConnectionPerformance(@NR, @CI); if Err = NO_ERROR then begin FFlags := []; if (CI.dwFlags and WNCON_FORNETCARD) = WNCON_FORNETCARD then Include(FFlags, cpfForNetCard); if (CI.dwFlags and WNCON_NOTROUTED) = WNCON_NOTROUTED then Include(FFlags, cpfNotRouted); if (CI.dwFlags and WNCON_SLOWLINK) = WNCON_SLOWLINK then Include(FFlags, cpfSlowLink); if (CI.dwFlags and WNCON_DYNAMIC) = WNCON_DYNAMIC then Include(FFlags, cpfDynamic); FSpeed := CI.dwSpeed; FDelay := CI.dwDelay; FOptDataSize := CI.dwOptDataSize; FGotData := True; end else RaiseStWin32Error(EStNetException, Err); end; function TStNetPerformance.GetFlags: TStCPFlagsSet; begin if not FGotData then QueryPerformance; Result := FFlags; end; function TStNetPerformance.GetSpeed: DWord; begin if not FGotData then QueryPerformance; Result := FSpeed; end; function TStNetPerformance.GetDelay: DWord; begin if not FGotData then QueryPerformance; Result := FDelay; end; function TStNetPerformance.GetOptDataSize : DWord; begin if not FGotData then QueryPerformance; Result := FOptDataSize; end; procedure TStNetPerformance.SetLocalName(Value: string); begin if Value <> FLocalName then begin FLocalName := Value; FGotData := False; end; end; procedure TStNetPerformance.SetRemoteName(Value: string); begin if Value <> FRemoteName then begin FRemoteName := Value; FGotData := False; end; end; procedure TStNetPerformance.SetProviderName(Value: string); begin if Value <> FProviderName then begin FProviderName := Value; FGotData := False; end; end; end.
unit AddressBookParametersUnit; interface uses HttpQueryMemberAttributeUnit, JSONNullableAttributeUnit, NullableBasicTypesUnit, GenericParametersUnit; type TAddressBookParameters = class(TGenericParameters) private [HttpQueryMember('address_id')] [Nullable] FAddressId: NullableString; [HttpQueryMember('limit')] [Nullable] FLimit: NullableInteger; [HttpQueryMember('offset')] [Nullable] FOffset: NullableInteger; [HttpQueryMember('start')] [Nullable] FStart: NullableInteger; [HttpQueryMember('query')] [Nullable] FQuery: NullableString; [HttpQueryMember('fields')] [Nullable] FFields: NullableString; [HttpQueryMember('display')] [Nullable] FDisplay: NullableString; public constructor Create; overload; override; constructor Create(Limit: integer; Offset: integer); reintroduce; overload; property AddressId: NullableString read FAddressId write FAddressId; property Limit: NullableInteger read FLimit write FLimit; property Offset: NullableInteger read FOffset write FOffset; property Start: NullableInteger read FStart write FStart; property Query: NullableString read FQuery write FQuery; property Fields: NullableString read FFields write FFields; property Display: NullableString read FDisplay write FDisplay; end; implementation { TAddressBookParameters } constructor TAddressBookParameters.Create(Limit: integer; Offset: integer); begin Create; FLimit := Limit; FOffset := Offset; end; constructor TAddressBookParameters.Create; begin Inherited Create; FAddressId := NullableString.Null; FLimit := NullableInteger.Null; FOffset := NullableInteger.Null; FStart := NullableInteger.Null; FQuery := NullableString.Null; FFields := NullableString.Null; FDisplay := NullableString.Null; end; end.
unit nevVirtualDrawView; // Модуль: "w:\common\components\gui\Garant\Everest\new\nevVirtualDrawView.pas" // Стереотип: "SimpleClass" // Элемент модели: "TnevVirtualDrawView" MUID: (481213C903A2) {$Include w:\common\components\gui\Garant\Everest\evDefine.inc} interface uses l3IntfUses , nevBaseDetachedView , evdStyles , nevBase , nevTools ; type TnevVirtualDrawView = class(TnevBaseDetachedView) private f_IsWebStyle: Boolean; f_ShowDocumentParts: Boolean; f_ShowSpecial: Boolean; f_HiddenStyles: TevStandardStyles; f_ParentFI: TnevFormatInfoPrim; f_AllowRubberTables: TnevRubberTablesMode; protected procedure Cleanup; override; {* Функция очистки полей объекта. } function GetIsWebStyle: Boolean; override; function GetShowDocumentParts: Boolean; override; function GetShowSpecial: Boolean; override; function GetHiddenStyles: TevStandardStyles; override; function GetRootFormatInfo: TnevFormatInfoPrim; override; function GetAllowRubberTables: TnevRubberTablesMode; override; public constructor Create(const aText: InevObject; aParentFI: TnevFormatInfoPrim; const aCanvas: InevCanvas; const aViewMetrics: InevViewMetrics); reintroduce; class function Make(const aText: InevObject; aParentFI: TnevFormatInfoPrim; const aCanvas: InevCanvas; const aViewMetrics: InevViewMetrics): InevView; reintroduce; end;//TnevVirtualDrawView implementation uses l3ImplUses //#UC START# *481213C903A2impl_uses* //#UC END# *481213C903A2impl_uses* ; constructor TnevVirtualDrawView.Create(const aText: InevObject; aParentFI: TnevFormatInfoPrim; const aCanvas: InevCanvas; const aViewMetrics: InevViewMetrics); //#UC START# *4CB5BE9803DF_481213C903A2_var* //#UC END# *4CB5BE9803DF_481213C903A2_var* begin //#UC START# *4CB5BE9803DF_481213C903A2_impl* inherited Create(aText, aCanvas); f_ParentFI := aParentFI; if (aViewMetrics <> nil) then with aViewMetrics do begin f_IsWebStyle := IsWebStyle; f_AllowRubberTables := AllowRubberTables; f_ShowDocumentParts := ShowDocumentParts; f_ShowSpecial := ShowSpecial; f_HiddenStyles := HiddenStyles; f_LimitWidth := LimitWidth; end;//with aViewMetrics //#UC END# *4CB5BE9803DF_481213C903A2_impl* end;//TnevVirtualDrawView.Create class function TnevVirtualDrawView.Make(const aText: InevObject; aParentFI: TnevFormatInfoPrim; const aCanvas: InevCanvas; const aViewMetrics: InevViewMetrics): InevView; var l_Inst : TnevVirtualDrawView; begin l_Inst := Create(aText, aParentFI, aCanvas, aViewMetrics); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TnevVirtualDrawView.Make procedure TnevVirtualDrawView.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_481213C903A2_var* //#UC END# *479731C50290_481213C903A2_var* begin //#UC START# *479731C50290_481213C903A2_impl* f_ParentFI := nil; inherited; //#UC END# *479731C50290_481213C903A2_impl* end;//TnevVirtualDrawView.Cleanup function TnevVirtualDrawView.GetIsWebStyle: Boolean; //#UC START# *48120CED0107_481213C903A2_var* //#UC END# *48120CED0107_481213C903A2_var* begin //#UC START# *48120CED0107_481213C903A2_impl* Result := f_IsWebStyle; //#UC END# *48120CED0107_481213C903A2_impl* end;//TnevVirtualDrawView.GetIsWebStyle function TnevVirtualDrawView.GetShowDocumentParts: Boolean; //#UC START# *48120D0300D4_481213C903A2_var* //#UC END# *48120D0300D4_481213C903A2_var* begin //#UC START# *48120D0300D4_481213C903A2_impl* Result := f_ShowDocumentParts; //#UC END# *48120D0300D4_481213C903A2_impl* end;//TnevVirtualDrawView.GetShowDocumentParts function TnevVirtualDrawView.GetShowSpecial: Boolean; //#UC START# *48120D270114_481213C903A2_var* //#UC END# *48120D270114_481213C903A2_var* begin //#UC START# *48120D270114_481213C903A2_impl* Result := f_ShowSpecial; //#UC END# *48120D270114_481213C903A2_impl* end;//TnevVirtualDrawView.GetShowSpecial function TnevVirtualDrawView.GetHiddenStyles: TevStandardStyles; //#UC START# *48120D32035F_481213C903A2_var* //#UC END# *48120D32035F_481213C903A2_var* begin //#UC START# *48120D32035F_481213C903A2_impl* Result := f_HiddenStyles; //#UC END# *48120D32035F_481213C903A2_impl* end;//TnevVirtualDrawView.GetHiddenStyles function TnevVirtualDrawView.GetRootFormatInfo: TnevFormatInfoPrim; //#UC START# *481DA04D0324_481213C903A2_var* //#UC END# *481DA04D0324_481213C903A2_var* begin //#UC START# *481DA04D0324_481213C903A2_impl* if (f_ParentFI = nil) then // - эта проверка нужна например для TnscSimpleEditor.AdjustHeightByText Result := inherited GetRootFormatInfo else Result := f_ParentFI.InfoForChild(Self.Shape); //#UC END# *481DA04D0324_481213C903A2_impl* end;//TnevVirtualDrawView.GetRootFormatInfo function TnevVirtualDrawView.GetAllowRubberTables: TnevRubberTablesMode; //#UC START# *4BED6EF003DD_481213C903A2_var* //#UC END# *4BED6EF003DD_481213C903A2_var* begin //#UC START# *4BED6EF003DD_481213C903A2_impl* Result := f_AllowRubberTables; //#UC END# *4BED6EF003DD_481213C903A2_impl* end;//TnevVirtualDrawView.GetAllowRubberTables end.
{ ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: QuickReport 6.0 for Delphi and C++Builder :: :: :: :: QRSubReport TQRSubReport control :: :: :: :: Copyright (c) 2013 QBS Software :: :: All Rights Reserved :: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::} unit QRSubReport; interface uses Messages, Windows, Classes, Controls, StdCtrls, SysUtils, Graphics, Forms, ExtCtrls, Dialogs, Printers, ComCtrls, QRPrntr, QuickRpt, Qr5Const, qrctrls; type TQRDisplayMode = (executeOnPrint, executeOnce); TQRSubRepImageMode = ( storeMetafile, storeXML); TQRGetSubRepEvent = procedure (sender : TObject; var subrep : TCustomQuickrep) of object; TQRSubReport = class(TQRPrintable) private FPicture: TPicture; //FUseXML : boolean; FDisplayMode : TQRDisplayMode; FImageMode : TQRSubRepImageMode; FReportControl : TCustomQuickrep; FReportPagecount : integer; FGetSubRep : TQRGetSubRepEvent; FBeforePrint : TQRGetSubRepEvent; FPagelist : TStringlist; FXMLStream : TMemorystream; procedure GetXMLPageItems( inxml : TMemoryStream; outList : TStringlist; pagenum, OfsX, OfsY : integer); Procedure FillPagelist; protected procedure Prepare; override; procedure Paint; override; procedure Print(OfsX, OfsY : integer); override; public currentPage : integer; constructor Create(AOwner: TComponent); override; destructor Destroy; override; function GetCanvas: TCanvas; published //property UseXML : boolean read FUseXML write FUseXML; property GetSubRep : TQRGetSubRepEvent read FGetSubRep write FGetSubRep; property BeforePrint : TQRGetSubRepEvent read FBeforePrint write FBeforePrint; property DisplayMode : TQRDisplayMode read FDisplayMode write FDisplayMode; property Visible; property XLColumn; property Transparent; property Color; end; function copyBackToChar( s : string; start : integer; ToChar : char; var lastPos : integer ): string; function copyToChar( s : string; start : integer; ToChar : char; var lastPos : integer ): string; implementation uses QRXMLSFilt; var subxmlfilt : TQRXDocumentFilter; constructor TQRSubReport.Create(AOwner: TComponent); begin inherited create(AOwner); FReportControl := nil; FPicture := TPicture.Create; subxmlfilt := nil; FPagelist := TStringlist.Create; FXMLStream := TMemorystream.Create; end; destructor TQRSubReport.Destroy; var k : integer; begin FPicture.Free; //if subxmlfilt <> nil then subxmlfilt.Free; for k:=0 to FPagelist.Count-1 do TMetafile(FPagelist.Objects[k]).Free; FPagelist.Free; FXMLStream.Free; inherited Destroy; end; function TQRSubReport.GetCanvas: TCanvas; begin result := TQuickrep(parentreport).QRPrinter.Canvas; end; Procedure TQRSubReport.FillPagelist; var k : integer; begin for k := 1 to FReportControl.QRPrinter.Pagecount do FPagelist.AddObject(inttostr(k),FReportControl.QRPrinter.PageList.GetPage(k)); end; procedure TQRSubReport.Prepare; begin inherited Prepare; if assigned(GetSubRep) then GetSubRep(self,FReportControl); if FReportControl= nil then exit; FReportControl.ShowProgress := false; if FDisplayMode=executeOnce then begin FReportControl.Prepare; FillPagelist; FReportPagecount := FPagelist.Count; FReportControl.QRPrinter.Free; FReportControl.QRPrinter := nil; if parentreport.Exporting and ( parentreport.ExportFilter is TQRXDocumentFilter) then begin subxmlfilt := TQRXDocumentFilter.Create(''); FReportControl.ExportToFilter(subxmlfilt); subxmlfilt.stream.Position := 0; FXMLStream.LoadFromStream(subxmlfilt.stream); subxmlfilt.Free; end; end; end; procedure TQRSubReport.Paint; begin if csDesigning in ComponentState then with inherited Canvas do begin Pen.Style := psSolid; Brush.Style := bsClear; Rectangle(0, 0, Width, Height); end; end; procedure TQRSubReport.GetXMLPageItems( inxml : TMemoryStream; outList : TStringlist; pagenum, OfsX, OfsY : integer); const inItem = 0; inOther = 1; var inlist : TStringlist; k ,p, cp, cstate : integer; np : double; tstr, tstr2, intext : string; pixTomm : extended; begin pixTomm := 25.4/screen.PixelsPerInch; inlist := TStringlist.Create; inlist.LoadFromStream(inXml); outlist.Clear; // find the page k := 0; p := 0; while (k<inlist.Count) and (p<pagenum) do begin if pos('<Page',inlist[k])>0 then inc(p); inc(k); end; if p<>pagenum then exit; // look for '<item' p := inlist.Count-1; cstate := InOther; while (k<inlist.Count) do begin if pos('<Item',inlist[k])>0 then begin if pos('</Item',inlist[k])=0 then cstate := inItem; intext := inlist[k]; cp := pos(' X=',intext); if cp >0 then begin tstr := copyToChar(inlist[k], cp+1, ' ', p); tstr2 := copyToChar(inlist[k], cp+3, ' ', p); tstr2 := copy(tstr2,2,length(tstr2)-2); np := strtofloat(trim(tstr2)); np := np + (Ofsx/10.0) + (Left*pixTomm); tstr2 := ' X="'+trim(format('%-5.2f',[np]))+'"'; intext := stringreplace(intext,tstr,tstr2,[rfReplaceAll]); end; cp := pos(' Y=',inlist[k]); if cp >0 then begin tstr := copyToChar(inlist[k], cp+1, ' ', p); tstr2 := copyToChar(inlist[k], cp+3, ' ', p); tstr2 := copy(tstr2,2,length(tstr2)-2); np := strtofloat(trim(tstr2)); np := np + (OfsY/10) + (Top*pixTomm);; tstr2 := ' Y="'+trim(format('%-5.2f',[np]))+'"'; intext := stringreplace(intext,tstr,tstr2,[rfReplaceAll]); end; cp := pos(' CID=',inlist[k]); if cp >0 then begin tstr := copyToChar(inlist[k], cp+1, ' ', p); tstr2 := copyToChar(inlist[k], cp+5, ' ', p); tstr2 := copy(tstr2,2,length(tstr2)-2); tstr2 := ' CID="'+self.Name+'.'+tstr2+'"'; intext := stringreplace(intext,tstr,tstr2,[rfReplaceAll]); end; outlist.Add(intext); inc(k); continue; end; if (pos('</Item',inlist[k])>0) and (cstate=inItem) then begin outlist.Add(inlist[k]); cstate := inOther; end else if cstate=inItem then outlist.Add(inlist[k]); inc(k); end; //outlist.SaveToFile('xmlout.txt'); inlist.Free; end; procedure TQRSubReport.Print(OfsX, OfsY : integer); var gcanvas : TCanvas; CanvasRect : TRect ; cRgn : HRGN ; expimg : TQRImage; expshp : TQRShape; pageMetafile : TMetafile; xmlItems : TStringlist; //xmlStream : TMemoryStream; begin if parentreport.Exporting and ( parentreport.ExportFilter is TQRXDocumentFilter) then self.FImageMode := storeXml else FImagemode := TQRSubRepImagemode.storeMetafile; // determine the rectangle of the canvas of this control: CanvasRect.left := QRPrinter.XPos(OfsX + Size.Left); CanvasRect.top := QRPrinter.YPos(OfsY + Size.Top); CanvasRect.right := QRPrinter.XPos(OfsX + Size.Left + Size.Width); CanvasRect.bottom := QRPrinter.YPos(OfsY + Size.Top + Size.Height); gcanvas := TQuickrep(parentreport).QRPrinter.Canvas; if FReportControl = nil then begin gcanvas.TextOut( canvasrect.left + 10,canvasrect.Top+20,'No QuickRep assigned'); exit; end; cRgn := CreateRectRgn(CanvasRect.left-1,CanvasRect.top-1,CanvasRect.right+1,CanvasRect.bottom+1); SelectClipRgn(QRPrinter.Canvas.Handle,cRgn); if gcanvas = nil then exit; if assigned(FBeforePrint) then BeforePrint( self,FReportControl); if not transparent then begin gcanvas.Brush.Color := color; gcanvas.Brush.Style := bsSolid; gcanvas.Pen.Color := color; gcanvas.Pen.Style := psSolid; gcanvas.Rectangle(CanvasRect.left, CanvasRect.top, CanvasRect.right, CanvasRect.bottom); if parentreport.Exporting then begin expshp := TQRShape.Create(parentreport); expshp.Top := top; expshp.Left := left; expshp.Width := width; expshp.Height := height; expshp.Shape := qrsRectangle; expshp.Brush.Style := bsSolid; expshp.Brush.Color := self.color; expshp.Pen.Style := psClear; parentreport.ExportFilter.AcceptGraphic(CanvasRect.left,CanvasRect.top, expshp); expshp.Free; end; end; if FDisplaymode = TQRDisplaymode.executeOnPrint then begin FReportControl.Prepare; FReportPagecount := FReportControl.QRPrinter.PageCount; if FImageMode=storeXML then begin subxmlfilt := TQRXDocumentFilter.Create(''); FReportControl.ExportToFilter(subxmlfilt); subxmlfilt.stream.Position := 0; FXMLStream.LoadFromStream(subxmlfilt.stream); subxmlfilt.Free; end; end; pagemetafile := nil; if (currentPage > 0) and (currentPage<=FReportPagecount) then begin if FDisplaymode = TQRDisplaymode.executeOnPrint then pagemetafile := FReportControl.QRPrinter.PageList.GetPage(CurrentPage) else if FDisplaymode = TQRDisplaymode.executeOnce then begin pagemetafile := TMetafile.Create; pagemetafile.Assign(TMetafile(FPagelist.Objects[CurrentPage-1])); end; if pagemetafile <> nil then begin gcanvas.Draw(canvasrect.Left,canvasrect.Top, pagemetafile); if not parentreport.Exporting then pagemetafile.Free; end; end; if FDisplaymode = TQRDisplaymode.executeOnPrint then begin FReportControl.QRPrinter.Free; FReportControl.QRPrinter := nil; end; SelectClipRgn(QRPrinter.Canvas.Handle,0); deleteObject(cRgn); // exporting if not parentreport.Exporting then exit; if (FImageMode=storeXML) and (parentreport.ExportFilter is TQRXDocumentfilter) then begin xmlItems := TStringlist.Create; FXMLStream.Position := 0; GetXMLPageItems( FXMLStream , xmlItems, currentPage, OfsX, OfsY ); TQRXDocumentfilter(parentreport.ExportFilter).AddToStream(xmlItems); if pagemetafile <> nil then pagemetafile.Free; xmlitems.Free; exit; end; expimg := TQRImage.Create(parentreport); expimg.Top := top; expimg.Left := left; expimg.width := width; expimg.height := height; expimg.Picture.Bitmap.Width := self.Width; expimg.Picture.Bitmap.Height := Height; if not transparent then begin expimg.Picture.Bitmap.Canvas.Pen.Style := psClear; expimg.Picture.Bitmap.Canvas.brush.Style := bsSolid; expimg.Picture.Bitmap.Canvas.brush.Color := color; expimg.Picture.Bitmap.Canvas.Rectangle(0,0,width+1, height+1); end; if pagemetafile <> nil then begin expimg.Picture.Bitmap.Canvas.Draw(0,0,pagemetafile); pagemetafile.Free; end; parentreport.ExportFilter.AcceptGraphic(CanvasRect.left,CanvasRect.top, expimg); expimg.Free; end; {-------------------------------- utilities -----------------------------} function copyToChar( s : string; start : integer; ToChar : char; var lastPos : integer ): string; var k : integer; begin result := ''; lastPos := -1; for k := start to length(s) do begin lastPos := k; if s[k]='>' then break; if s[k]=''+ ToChar then break; result := result + s[k]; end; result := trim(result); end; function copyBackToChar( s : string; start : integer; ToChar : char; var lastPos : integer ): string; var k : integer; begin result := ''; lastPos := -1; for k := start downto 1 do begin lastPos := k; if s[k]=''+ ToChar then break; result := s[k] + result; end; result := trim(result); end; end.
unit MultEdit; interface uses System.SysUtils, System.Classes, System.UITypes, Vcl.Controls, Vcl.StdCtrls, Vcl.Mask, Vcl.Graphics, VCL.Dialogs; type TEditType = (etNone, etEmail, etURL, etPhone, etCPF, etCNPJ, etCEP); TOnValidate = procedure(Sender: TObject; AValid: Boolean; AMessage: string) of object; TMultEdit = class(TMaskEdit) private FEditType : TEditType; FColorValid : TColor; FColorInvalid: TColor; FValid : Boolean; FOnValidate : TOnValidate; FVersion : string; FMessage : string; procedure SetMask(const Value: TEditType); procedure SetEditType(const Value: TEditType); function GetValidationSize: Integer; protected procedure KeyPress(var Key: Char); override; procedure CheckIsValid(const AText: string); function isValid(const AText: string): Boolean; public constructor Create(AOwner: TComponent); override; procedure ResetDefaults; property Valid: Boolean read FValid; procedure Test; procedure TestInput; procedure ShowResultValidation; published property ColorInvalid : TColor read FColorInvalid write FColorInvalid; property ColorValid : TColor read FColorValid write FColorValid; property EditType : TEditType read FEditType write SetEditType default etNone; property Version : string read FVersion; property OnValidate : TOnValidate read FOnValidate write FOnValidate; end; procedure Register; implementation uses MultEdit.Helpers, System.RegularExpressions; procedure Register; begin RegisterComponents('MeusComponentes', [TMultEdit]); end; procedure TMultEdit.CheckIsValid(const AText: string); begin if isValid(AText) then begin Self.Color := Self.ColorValid; FMessage := MSG_VALID; end else begin Self.Color := Self.ColorInvalid; FMessage := MSG_INVALID; end; if Assigned(FOnValidate) then FOnValidate(Self, FValid, FMessage); end; constructor TMultEdit.Create(AOwner: TComponent); begin inherited Create(AOwner); FVersion := VERSION_NUMBER; ResetDefaults; end; function TMultEdit.GetValidationSize: Integer; begin case Self.EditType of etNone : Result := Self.MaxLength; etEmail: Result := VALIDATION_SIZE_EMAIL; etURL : Result := VALIDATION_SIZE_URL; else Result := string(Self.EditMask).CountChar(MASK_KEY_NUMBERS); end; end; function TMultEdit.isValid(const AText: string): Boolean; begin case Self.EditType of etEmail : Result := TRegEx.IsMatch(AText, REGEX_MAIL); etURL : Result := TRegEx.IsMatch(AText, REGEX_URL); etPhone : Result := TRegEx.IsMatch(AText, REGEX_PHONE); etCPF : Result := CPFValid(AText); etCNPJ : Result := CNPJValid(AText); etCEP : Result := CEPValid(AText); else Result := True; end; FValid := Result; end; procedure TMultEdit.KeyPress(var Key: Char); begin FValid := True; if Self.EditType <> etNone then begin FValid := False; if not (Self.EditType in [etEmail, etURL]) then if not CharInSet(Key, NUMBERS) then Key := #0; if Length(Trim(Self.Text) + Key) >= GetValidationSize then CheckIsValid(Trim(Self.Text) + Key); end; inherited; end; procedure TMultEdit.ResetDefaults; begin FColorValid := COLOR_VALID; FColorInvalid := COLOR_INVALID; Self.Color := clWindow; FEditType := etNone; end; procedure TMultEdit.SetEditType(const Value: TEditType); begin FEditType := Value; SetMask(Value); if Value in [etURL, etEmail] then Self.CharCase := ecLowerCase else Self.CharCase := ecNormal; end; procedure TMultEdit.SetMask(const Value: TEditType); begin case Value of etPhone : Self.EditMask := MASK_PHONE; etCPF : Self.EditMask := MASK_CPF; etCNPJ : Self.EditMask := MASK_CNPJ; etCEP : Self.EditMask := MASK_CEP; else Self.EditMask := EmptyStr; end; end; procedure TMultEdit.ShowResultValidation; begin if Self.Valid then MessageDlg(Self.FMessage, mtInformation, [mbOk], 0) else MessageDlg(Self.FMessage, mtError, [mbOk], 0); end; procedure TMultEdit.Test; begin if FEditType = etNone then Exit; CheckIsValid(Self.Text); ShowResultValidation; end; procedure TMultEdit.TestInput; var FText: string; begin if FEditType = etNone then Exit; FText := InputBox('Validation', 'Text', Self.Text); Self.Text := FText; CheckIsValid(Self.Text); ShowResultValidation; end; end.
inherited dmCidades: TdmCidades OldCreateOrder = True inherited qryManutencao: TIBCQuery SQLInsert.Strings = ( 'INSERT INTO STWOPETCID' ' (CIDADE, ESTADO, FILIAL, GRANDE_REGIAO, COD_SEFAZ, DT_ALTERACA' + 'O, OPERADOR, ISS_ALIQUOTA, ISS_FATOR, ISS_REDUTOR, COD_MUNICIPIO' + ', COD_UF, COD_FEDERAL, COD_DIPAM, PADRAO_NFSE, ATENDIDA)' 'VALUES' ' (:CIDADE, :ESTADO, :FILIAL, :GRANDE_REGIAO, :COD_SEFAZ, :DT_AL' + 'TERACAO, :OPERADOR, :ISS_ALIQUOTA, :ISS_FATOR, :ISS_REDUTOR, :CO' + 'D_MUNICIPIO, :COD_UF, :COD_FEDERAL, :COD_DIPAM, :PADRAO_NFSE, :A' + 'TENDIDA)') SQLDelete.Strings = ( 'DELETE FROM STWOPETCID' 'WHERE' ' CIDADE = :Old_CIDADE AND ESTADO = :Old_ESTADO') SQLUpdate.Strings = ( 'UPDATE STWOPETCID' 'SET' ' CIDADE = :CIDADE, ESTADO = :ESTADO, FILIAL = :FILIAL, GRANDE_R' + 'EGIAO = :GRANDE_REGIAO, COD_SEFAZ = :COD_SEFAZ, DT_ALTERACAO = :' + 'DT_ALTERACAO, OPERADOR = :OPERADOR, ISS_ALIQUOTA = :ISS_ALIQUOTA' + ', ISS_FATOR = :ISS_FATOR, ISS_REDUTOR = :ISS_REDUTOR, COD_MUNICI' + 'PIO = :COD_MUNICIPIO, COD_UF = :COD_UF, COD_FEDERAL = :COD_FEDER' + 'AL, COD_DIPAM = :COD_DIPAM, PADRAO_NFSE = :PADRAO_NFSE, ATENDIDA' + ' = :ATENDIDA' 'WHERE' ' CIDADE = :Old_CIDADE AND ESTADO = :Old_ESTADO') SQLRefresh.Strings = ( 'SELECT CIDADE, ESTADO, FILIAL, GRANDE_REGIAO, COD_SEFAZ, DT_ALTE' + 'RACAO, OPERADOR, ISS_ALIQUOTA, ISS_FATOR, ISS_REDUTOR, COD_MUNIC' + 'IPIO, COD_UF, COD_FEDERAL, COD_DIPAM, PADRAO_NFSE, ATENDIDA FROM' + ' STWOPETCID' 'WHERE' ' CIDADE = :Old_CIDADE AND ESTADO = :Old_ESTADO') SQLLock.Strings = ( 'SELECT NULL FROM STWOPETCID' 'WHERE' 'CIDADE = :Old_CIDADE AND ESTADO = :Old_ESTADO' 'FOR UPDATE WITH LOCK') SQLRecCount.Strings = ( 'SELECT COUNT(*) FROM (' 'SELECT 1 AS C FROM STWOPETCID' '' ') q') SQL.Strings = ( 'SELECT' ' CID.CIDADE,' ' CID.ESTADO,' ' CID.FILIAL,' ' CID.GRANDE_REGIAO,' ' CID.COD_SEFAZ,' ' CID.DT_ALTERACAO,' ' CID.OPERADOR,' ' CID.ISS_ALIQUOTA,' ' CID.ISS_FATOR,' ' CID.ISS_REDUTOR,' ' CID.COD_MUNICIPIO,' ' CID.COD_UF,' ' CID.COD_FEDERAL,' ' CID.COD_DIPAM,' ' CID.PADRAO_NFSE,' ' CID.ATENDIDA,' ' FIL.nome NM_FILIAL' 'FROM STWOPETCID CID' 'LEFT JOIN stwopetfil FIL ON FIL.filial = CID.filial') object qryManutencaoCIDADE: TStringField FieldName = 'CIDADE' Required = True Size = 60 end object qryManutencaoESTADO: TStringField FieldName = 'ESTADO' Required = True Size = 2 end object qryManutencaoFILIAL: TStringField FieldName = 'FILIAL' Size = 3 end object qryManutencaoGRANDE_REGIAO: TStringField FieldName = 'GRANDE_REGIAO' Size = 1 end object qryManutencaoCOD_SEFAZ: TStringField FieldName = 'COD_SEFAZ' Size = 5 end object qryManutencaoDT_ALTERACAO: TDateTimeField FieldName = 'DT_ALTERACAO' end object qryManutencaoOPERADOR: TStringField FieldName = 'OPERADOR' end object qryManutencaoISS_ALIQUOTA: TFloatField FieldName = 'ISS_ALIQUOTA' end object qryManutencaoISS_FATOR: TFloatField FieldName = 'ISS_FATOR' end object qryManutencaoISS_REDUTOR: TFloatField FieldName = 'ISS_REDUTOR' end object qryManutencaoCOD_MUNICIPIO: TIntegerField FieldName = 'COD_MUNICIPIO' end object qryManutencaoCOD_UF: TIntegerField FieldName = 'COD_UF' end object qryManutencaoCOD_FEDERAL: TIntegerField FieldName = 'COD_FEDERAL' end object qryManutencaoNM_FILIAL: TStringField FieldName = 'NM_FILIAL' ReadOnly = True Size = 40 end object qryManutencaoCOD_DIPAM: TIntegerField FieldName = 'COD_DIPAM' end object qryManutencaoPADRAO_NFSE: TStringField FieldName = 'PADRAO_NFSE' end object qryManutencaoATENDIDA: TStringField FieldName = 'ATENDIDA' Size = 1 end end inherited qryLocalizacao: TIBCQuery SQLInsert.Strings = ( 'INSERT INTO STWOPETCID' ' (CIDADE, ESTADO, FILIAL, GRANDE_REGIAO, COD_SEFAZ, DT_ALTERACA' + 'O, OPERADOR, ISS_ALIQUOTA, ISS_FATOR, ISS_REDUTOR, COD_MUNICIPIO' + ', COD_UF, COD_FEDERAL, COD_DIPAM, PADRAO_NFSE, ATENDIDA)' 'VALUES' ' (:CIDADE, :ESTADO, :FILIAL, :GRANDE_REGIAO, :COD_SEFAZ, :DT_AL' + 'TERACAO, :OPERADOR, :ISS_ALIQUOTA, :ISS_FATOR, :ISS_REDUTOR, :CO' + 'D_MUNICIPIO, :COD_UF, :COD_FEDERAL, :COD_DIPAM, :PADRAO_NFSE, :A' + 'TENDIDA)') SQLDelete.Strings = ( 'DELETE FROM STWOPETCID' 'WHERE' ' CIDADE = :Old_CIDADE AND ESTADO = :Old_ESTADO') SQLUpdate.Strings = ( 'UPDATE STWOPETCID' 'SET' ' CIDADE = :CIDADE, ESTADO = :ESTADO, FILIAL = :FILIAL, GRANDE_R' + 'EGIAO = :GRANDE_REGIAO, COD_SEFAZ = :COD_SEFAZ, DT_ALTERACAO = :' + 'DT_ALTERACAO, OPERADOR = :OPERADOR, ISS_ALIQUOTA = :ISS_ALIQUOTA' + ', ISS_FATOR = :ISS_FATOR, ISS_REDUTOR = :ISS_REDUTOR, COD_MUNICI' + 'PIO = :COD_MUNICIPIO, COD_UF = :COD_UF, COD_FEDERAL = :COD_FEDER' + 'AL, COD_DIPAM = :COD_DIPAM, PADRAO_NFSE = :PADRAO_NFSE, ATENDIDA' + ' = :ATENDIDA' 'WHERE' ' CIDADE = :Old_CIDADE AND ESTADO = :Old_ESTADO') SQLRefresh.Strings = ( 'SELECT CIDADE, ESTADO, FILIAL, GRANDE_REGIAO, COD_SEFAZ, DT_ALTE' + 'RACAO, OPERADOR, ISS_ALIQUOTA, ISS_FATOR, ISS_REDUTOR, COD_MUNIC' + 'IPIO, COD_UF, COD_FEDERAL, COD_DIPAM, PADRAO_NFSE, ATENDIDA FROM' + ' STWOPETCID' 'WHERE' ' CIDADE = :CIDADE AND ESTADO = :ESTADO') SQLLock.Strings = ( 'SELECT NULL FROM STWOPETCID' 'WHERE' 'CIDADE = :Old_CIDADE AND ESTADO = :Old_ESTADO' 'FOR UPDATE WITH LOCK') SQLRecCount.Strings = ( 'SELECT COUNT(*) FROM (' 'SELECT 1 AS C FROM STWOPETCID' '' ') q') SQL.Strings = ( 'SELECT' ' CID.CIDADE,' ' CID.ESTADO,' ' CID.FILIAL,' ' CID.GRANDE_REGIAO,' ' CID.COD_SEFAZ,' ' CID.DT_ALTERACAO,' ' CID.OPERADOR,' ' CID.ISS_ALIQUOTA,' ' CID.ISS_FATOR,' ' CID.ISS_REDUTOR,' ' CID.COD_MUNICIPIO,' ' CID.COD_UF,' ' CID.COD_FEDERAL,' ' CID.COD_DIPAM,' ' CID.PADRAO_NFSE,' ' CID.ATENDIDA,' ' FIL.nome NM_FILIAL' 'FROM STWOPETCID CID' 'LEFT JOIN stwopetfil FIL ON FIL.filial = CID.filial') object qryLocalizacaoCIDADE: TStringField FieldName = 'CIDADE' Required = True Size = 30 end object qryLocalizacaoESTADO: TStringField FieldName = 'ESTADO' Required = True Size = 2 end object qryLocalizacaoFILIAL: TStringField FieldName = 'FILIAL' Size = 3 end object qryLocalizacaoGRANDE_REGIAO: TStringField FieldName = 'GRANDE_REGIAO' Size = 1 end object qryLocalizacaoCOD_SEFAZ: TStringField FieldName = 'COD_SEFAZ' Size = 5 end object qryLocalizacaoDT_ALTERACAO: TDateTimeField FieldName = 'DT_ALTERACAO' end object qryLocalizacaoOPERADOR: TStringField FieldName = 'OPERADOR' end object qryLocalizacaoISS_ALIQUOTA: TFloatField FieldName = 'ISS_ALIQUOTA' end object qryLocalizacaoISS_FATOR: TFloatField FieldName = 'ISS_FATOR' end object qryLocalizacaoISS_REDUTOR: TFloatField FieldName = 'ISS_REDUTOR' end object qryLocalizacaoCOD_MUNICIPIO: TIntegerField FieldName = 'COD_MUNICIPIO' end object qryLocalizacaoCOD_UF: TIntegerField FieldName = 'COD_UF' end object qryLocalizacaoCOD_FEDERAL: TIntegerField FieldName = 'COD_FEDERAL' end object qryLocalizacaoNM_FILIAL: TStringField FieldName = 'NM_FILIAL' ReadOnly = True Size = 40 end object qryLocalizacaoCOD_DIPAM: TIntegerField FieldName = 'COD_DIPAM' end object qryLocalizacaoPADRAO_NFSE: TStringField FieldName = 'PADRAO_NFSE' end object qryLocalizacaoATENDIDA: TStringField FieldName = 'ATENDIDA' Size = 1 end end end
unit kwPopEditorSelectAll; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "ScriptEngine" // Автор: Люлин А.В. // Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwPopEditorSelectAll.pas" // Начат: 14.06.2011 17:05 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<ScriptKeyword::Class>> Shared Delphi Scripting::ScriptEngine::EditorFromStackKeyWords::pop_editor_SelectAll // // pop:editor:SelectAll. Выделяет весь документ в редакторе. // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\ScriptEngine\seDefine.inc} interface {$If not defined(NoScripts)} uses evCustomEditorWindow, tfwScriptingInterfaces, Controls, Classes ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type {$Include ..\ScriptEngine\kwEditorFromStackWord.imp.pas} TkwPopEditorSelectAll = class(_kwEditorFromStackWord_) {* pop:editor:SelectAll. Выделяет весь документ в редакторе. } protected // realized methods procedure DoWithEditor(const aCtx: TtfwContext; anEditor: TevCustomEditorWindow); override; public // overridden public methods class function GetWordNameForRegister: AnsiString; override; end;//TkwPopEditorSelectAll {$IfEnd} //not NoScripts implementation {$If not defined(NoScripts)} uses evTypes, tfwAutoregisteredDiction, tfwScriptEngine, Windows, afwFacade, Forms ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type _Instance_R_ = TkwPopEditorSelectAll; {$Include ..\ScriptEngine\kwEditorFromStackWord.imp.pas} // start class TkwPopEditorSelectAll procedure TkwPopEditorSelectAll.DoWithEditor(const aCtx: TtfwContext; anEditor: TevCustomEditorWindow); //#UC START# *4F4CB81200CA_4DF75C6902E6_var* //#UC END# *4F4CB81200CA_4DF75C6902E6_var* begin //#UC START# *4F4CB81200CA_4DF75C6902E6_impl* anEditor.Select(ev_stDocument); //#UC END# *4F4CB81200CA_4DF75C6902E6_impl* end;//TkwPopEditorSelectAll.DoWithEditor class function TkwPopEditorSelectAll.GetWordNameForRegister: AnsiString; {-} begin Result := 'pop:editor:SelectAll'; end;//TkwPopEditorSelectAll.GetWordNameForRegister {$IfEnd} //not NoScripts initialization {$If not defined(NoScripts)} {$Include ..\ScriptEngine\kwEditorFromStackWord.imp.pas} {$IfEnd} //not NoScripts end.
unit UMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.ListView.Types, Data.DB, Datasnap.DBClient, FMX.ListView, System.Rtti, System.Bindings.Outputs, Fmx.Bind.Editors, Data.Bind.EngExt, Fmx.Bind.DBEngExt, Data.Bind.Components, Data.Bind.DBScope, FMX.Objects; type TForm9 = class(TForm) ToolBar1: TToolBar; Label1: TLabel; ListView1: TListView; ClientDataSet1: TClientDataSet; BindSourceDB1: TBindSourceDB; BindingsList1: TBindingsList; LinkFillControlToField1: TLinkFillControlToField; Image1: TImage; procedure ListView1UpdateObjects(const Sender: TObject; const AItem: TListViewItem); procedure LinkFillControlToField1FilledListItem(Sender: TObject; const AEditor: IBindListEditorItem); private { Private declarations } public { Public declarations } end; var Form9: TForm9; implementation {$R *.fmx} procedure TForm9.LinkFillControlToField1FilledListItem(Sender: TObject; const AEditor: IBindListEditorItem); var AListItem : TListViewItem; AItemText : TListItemText; AItemImage : TListItemImage; AField : TField; begin // Otro Evento que debo implementar if(AEditor.CurrentIndex >= 0)then begin AListItem := ListView1.Items[AEditor.CurrentIndex]; AItemText := AListItem.Objects.FindObject('Salary') as TListItemText; AField := BindSourceDB1.DataSet.FieldByName('Salary'); if(AItemText <> nil) and (AField <> nil)then begin AItemText.Text := 'Bs. ' + FormatFloat('#,#00.00', AField.AsFloat); if(AField.AsFloat >= 45000)then begin AItemText.TextColor := TAlphaColorRec.Blue; end else begin AItemText.TextColor := TAlphaColorRec.Red; end; end; AItemText := AListItem.Objects.FindObject('HireDate') as TListItemText; AField := BindSourceDB1.DataSet.FieldByName('HireDate'); if(AItemText <> nil) and (AField <> nil)then begin AItemText.Text := FormatDateTime('dd/MM/yyy', AField.AsDateTime); end; AItemImage := AListItem.Objects.FindObject('MiImagen') as TListItemImage; AItemImage.Bitmap := Image1.Bitmap; end; end; procedure TForm9.ListView1UpdateObjects(const Sender: TObject; const AItem: TListViewItem); var AItemText : TListItemText; AItemImage : TListItemImage; begin // Uno de los Eventos dque debo implementar AItemText := AItem.Objects.FindObject('Salary') as TListItemText; if(AItemText = nil)then begin AItemText := TListItemText.Create(AItem); AItemText.Name := 'Salary'; AItemText.Align := TListItemAlign.Trailing; AItemText.PlaceOffset.X := -30; AItemText.Width := 120; end; AItemText := AItem.Objects.FindObject('HireDate') as TListItemText; if(AItemText = nil)then begin AItemText := TListItemText.Create(AItem); AItemText.Name := 'HireDate'; AItemText.Align := TListItemAlign.Trailing; AItemText.PlaceOffset.X := -30; AItemText.PlaceOffset.Y := 20; AItemText.Width := 120; end; AItemImage := AItem.Objects.FindObject('MiImagen') as TListItemImage; if(AItemImage = nil)then begin AItemImage := TListItemImage.Create(AItem); AItemImage.Name := 'MiImagen'; AItemImage.Align := TListItemAlign.Trailing; AItemImage.VertAlign := TListItemAlign.Center; AItemImage.PlaceOffset.X := -200; AItemImage.ScalingMode := TImageScalingMode.Stretch; AItemImage.Width := 24; AItemImage.Height := 24; end; end; end.
unit mod_samecomputer; {$mode objfpc}{$H+} interface uses Classes, SysUtils, StdCtrls, Forms, Controls, chessmodules; type { TSameComputerChessModule } TSameComputerChessModule = class(TChessModule) private textSecondPlayerName: TStaticText; editSecondPlayerName: TEdit; public SecondPlayerName: string; constructor Create(); override; procedure CreateUserInterface(); override; procedure ShowUserInterface(AParent: TWinControl); override; procedure HideUserInterface(); override; procedure FreeUserInterface(); override; procedure PrepareForGame(); override; function IsMovingAllowedNow(): Boolean; override; function GetSecondPlayerName(): string; override; procedure HandleOnMove(AFrom, ATo: TPoint); override; end; implementation { TSameComputerChessModule } constructor TSameComputerChessModule.Create; begin inherited Create; Name := 'mod_samecomputer.pas'; SelectionDescription := 'Play against a friend in the same computer'; PlayingDescription := 'Playing against a friend in the same computer'; Kind := cmkSameComputer; end; procedure TSameComputerChessModule.CreateUserInterface; begin textSecondPlayerName := TStaticText.Create(nil); textSecondPlayerName.SetBounds(20, 20, 180, 50); textSecondPlayerName.Caption := 'Name of the second player'; editSecondPlayerName := TEdit.Create(nil); editSecondPlayerName.SetBounds(200, 20, 150, 50); editSecondPlayerName.Text := 'Second player'; end; procedure TSameComputerChessModule.ShowUserInterface(AParent: TWinControl); begin textSecondPlayerName.Parent := AParent; editSecondPlayerName.Parent := AParent; end; procedure TSameComputerChessModule.HideUserInterface(); begin textSecondPlayerName.Parent := nil; editSecondPlayerName.Parent := nil; end; procedure TSameComputerChessModule.FreeUserInterface(); begin textSecondPlayerName.Free; editSecondPlayerName.Free; end; procedure TSameComputerChessModule.PrepareForGame; begin SecondPlayerName := editSecondPlayerName.Text; end; function TSameComputerChessModule.IsMovingAllowedNow: Boolean; begin Result := True; end; function TSameComputerChessModule.GetSecondPlayerName: string; begin Result := SecondPlayerName; end; procedure TSameComputerChessModule.HandleOnMove(AFrom, ATo: TPoint); begin end; initialization RegisterChessModule(TSameComputerChessModule.Create); end.
{ Subroutine SST_R_SYO_COMMAND (STAT) * * Process COMMAND syntax. This is the top level SYN file syntax. } module sst_r_syo_command; define sst_r_syo_command; %include 'sst_r_syo.ins.pas'; procedure sst_r_syo_command ( {process COMMAND syntax} out stat: sys_err_t); {completion status code} var tag: sys_int_machine_t; {tag from syntax tree} str_h: syo_string_t; {handle to string from input file} begin sys_error_none (stat); {init to no errors} syo_level_down; {down into COMMAND syntax level} syo_get_tag_msg (tag, str_h, 'sst_syo_read', 'syerr_command', nil, 0); case tag of { * End of input data. } 1: begin sys_stat_set (sst_subsys_k, sst_stat_eod_k, stat); {indicate EOD} end; { * Syntax definition. } 2: begin sst_r_syo_define; {process DEFINE syntax} end; { * Symbol declaration. } 3: begin sst_r_syo_declare; {process DECLARE syntax} end; otherwise syo_error_tag_unexp (tag, str_h); end; {end of top level tag cases} syo_level_up; {back up from COMMAND syntax level} end;
unit Unit1; { DEMO 2 for Delphi Zip by Eric W. Engler } (************************************************************************ Copyright (C) 2009, 2010 by Russell J. Peters, Roger Aelbrecht, Eric W. Engler and Chris Vleghert. This file is part of TZipMaster Version 1.9. TZipMaster is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. TZipMaster 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with TZipMaster. If not, see <http://www.gnu.org/licenses/>. contact: problems@delphizip.org (include ZipMaster in the subject). updates: http://www.delphizip.org DelphiZip maillist subscribe at http://www.freelists.org/list/delphizip ************************************************************************) interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ZipMstr19; type TForm1 = class(TForm) ZipBut: TButton; UnzipBut: TButton; ExitBut: TButton; DelBut: TButton; VersionBut: TButton; ZipMaster1: TZipMaster19; procedure ZipButClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ExitButClick(Sender: TObject); procedure ZipMaster1Message(Sender: TObject; ErrCode: Integer; Message: string); procedure UnzipButClick(Sender: TObject); procedure DelButClick(Sender: TObject); procedure VersionButClick(Sender: TObject); procedure FormDestroy(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.DFM} procedure TForm1.FormCreate(Sender: TObject); begin { SetCurrentDir('C:\ZIP\DEMO2'); } Caption:='ZIP Demo 2 - ' + GetCurrentDir; ZipMaster1.ZipFileName:='test.zip'; ZipMaster1.Dll_Load := true; end; { Add one file to the zipfile } procedure TForm1.ZipButClick(Sender: TObject); begin if not FileExists('TEST.DAT') then begin ShowMessage('Error - test.dat not found'); Exit; end; ZipMaster1.FSpecArgs.Add('TEST.DAT'); ZipMaster1.Add; ShowMessage('Files added = ' + IntToStr(ZipMaster1.SuccessCnt)); end; { expand all files from the zipfile } procedure TForm1.UnzipButClick(Sender: TObject); begin with ZipMaster1 do begin if Count = 0 then begin ShowMessage('Error - no files in the Zip file'); Exit; end; { If we don't specify filenames, we will extract them all. } { Of course, in this little demo there is only 1 file in the ZIP. } FSpecArgs.Add('*.*'); ExtrBaseDir:=GetCurrentDir; { if the file to be extracted already exists, overwrite it } ExtrOptions:=ExtrOptions+[ExtrOverwrite]; Extract; ShowMessage('Files extracted = ' + IntToStr(SuccessCnt)); end; end; { delete one file from the zipfile } procedure TForm1.DelButClick(Sender: TObject); begin ZipMaster1.FSpecArgs.Add('TEST.DAT'); ZipMaster1.Delete; ShowMessage('Files deleted = ' + IntToStr(ZipMaster1.SuccessCnt)); end; procedure TForm1.VersionButClick(Sender: TObject); begin ShowMessage('DelZip190.DLL version: ' + ZipMaster1.Dll_Version + #13#10 + 'Loaded from: ' + ZipMaster1.Dll_Path + #13#10 + 'ZipMaster version: ' + ZipMaster1.Version);//Info); end; procedure TForm1.ExitButClick(Sender: TObject); begin Close; end; { This procedure displays messages received from the DLLs. If you really want to minimize the amount of messages you show the user, you don't even need to assign this event handler. However, I'd still recommend that you assign this to catch errors. You can test the ErrCode before you display the message - if ErrCode is non-zero, make sure you display the message. If it's 0, then you can ignore the message. Also, if ZipMaster1's "Verbose" property is true, you'll get more informational message callbacks here. By default, it's false to minimize user messages. } procedure TForm1.ZipMaster1Message(Sender: TObject; ErrCode: Integer; Message: string); begin { if ErrCode <> 0 then } { uncomment this line to show errors ONLY } ShowMessage(Message); end; procedure TForm1.FormDestroy(Sender: TObject); begin ZipMaster1.Dll_Load := false; end; end.