text
stringlengths
14
6.51M
unit MedicFirmListKeywordsPack; {* Набор слов словаря для доступа к экземплярам контролов формы MedicFirmList } // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\Inpharm\Forms\MedicFirmListKeywordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "MedicFirmListKeywordsPack" MUID: (4AB9E69C0243_Pack) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3IntfUses ; {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL) implementation {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3ImplUses , MedicFirmList_Form , tfwPropertyLike , vtPanel , tfwScriptingInterfaces , TypInfo , tfwTypeInfo {$If Defined(Nemesis)} , nscContextFilter {$IfEnd} // Defined(Nemesis) , nscTreeViewWithAdapterDragDrop , tfwControlString , kwBynameControlPush , TtfwClassRef_Proxy , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes //#UC START# *4AB9E69C0243_Packimpl_uses* //#UC END# *4AB9E69C0243_Packimpl_uses* ; type TkwEnMedicFirmListBackgroundPanel = {final} class(TtfwPropertyLike) {* Слово скрипта .Ten_MedicFirmList.BackgroundPanel } private function BackgroundPanel(const aCtx: TtfwContext; aen_MedicFirmList: Ten_MedicFirmList): TvtPanel; {* Реализация слова скрипта .Ten_MedicFirmList.BackgroundPanel } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnMedicFirmListBackgroundPanel TkwEnMedicFirmListContextFilter = {final} class(TtfwPropertyLike) {* Слово скрипта .Ten_MedicFirmList.ContextFilter } private function ContextFilter(const aCtx: TtfwContext; aen_MedicFirmList: Ten_MedicFirmList): TnscContextFilter; {* Реализация слова скрипта .Ten_MedicFirmList.ContextFilter } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnMedicFirmListContextFilter TkwEnMedicFirmListListTree = {final} class(TtfwPropertyLike) {* Слово скрипта .Ten_MedicFirmList.ListTree } private function ListTree(const aCtx: TtfwContext; aen_MedicFirmList: Ten_MedicFirmList): TnscTreeViewWithAdapterDragDrop; {* Реализация слова скрипта .Ten_MedicFirmList.ListTree } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnMedicFirmListListTree Tkw_Form_MedicFirmList = {final} class(TtfwControlString) {* Слово словаря для идентификатора формы MedicFirmList ---- *Пример использования*: [code]форма::MedicFirmList TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Form_MedicFirmList Tkw_MedicFirmList_Control_BackgroundPanel = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола BackgroundPanel ---- *Пример использования*: [code]контрол::BackgroundPanel TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_MedicFirmList_Control_BackgroundPanel Tkw_MedicFirmList_Control_BackgroundPanel_Push = {final} class(TkwBynameControlPush) {* Слово словаря для контрола BackgroundPanel ---- *Пример использования*: [code]контрол::BackgroundPanel:push pop:control:SetFocus ASSERT[code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_MedicFirmList_Control_BackgroundPanel_Push Tkw_MedicFirmList_Control_ContextFilter = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола ContextFilter ---- *Пример использования*: [code]контрол::ContextFilter TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_MedicFirmList_Control_ContextFilter Tkw_MedicFirmList_Control_ContextFilter_Push = {final} class(TkwBynameControlPush) {* Слово словаря для контрола ContextFilter ---- *Пример использования*: [code]контрол::ContextFilter:push pop:control:SetFocus ASSERT[code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_MedicFirmList_Control_ContextFilter_Push Tkw_MedicFirmList_Control_ListTree = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола ListTree ---- *Пример использования*: [code]контрол::ListTree TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_MedicFirmList_Control_ListTree Tkw_MedicFirmList_Control_ListTree_Push = {final} class(TkwBynameControlPush) {* Слово словаря для контрола ListTree ---- *Пример использования*: [code]контрол::ListTree:push pop:control:SetFocus ASSERT[code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_MedicFirmList_Control_ListTree_Push function TkwEnMedicFirmListBackgroundPanel.BackgroundPanel(const aCtx: TtfwContext; aen_MedicFirmList: Ten_MedicFirmList): TvtPanel; {* Реализация слова скрипта .Ten_MedicFirmList.BackgroundPanel } begin Result := aen_MedicFirmList.BackgroundPanel; end;//TkwEnMedicFirmListBackgroundPanel.BackgroundPanel class function TkwEnMedicFirmListBackgroundPanel.GetWordNameForRegister: AnsiString; begin Result := '.Ten_MedicFirmList.BackgroundPanel'; end;//TkwEnMedicFirmListBackgroundPanel.GetWordNameForRegister function TkwEnMedicFirmListBackgroundPanel.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtPanel); end;//TkwEnMedicFirmListBackgroundPanel.GetResultTypeInfo function TkwEnMedicFirmListBackgroundPanel.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnMedicFirmListBackgroundPanel.GetAllParamsCount function TkwEnMedicFirmListBackgroundPanel.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Ten_MedicFirmList)]); end;//TkwEnMedicFirmListBackgroundPanel.ParamsTypes procedure TkwEnMedicFirmListBackgroundPanel.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству BackgroundPanel', aCtx); end;//TkwEnMedicFirmListBackgroundPanel.SetValuePrim procedure TkwEnMedicFirmListBackgroundPanel.DoDoIt(const aCtx: TtfwContext); var l_aen_MedicFirmList: Ten_MedicFirmList; begin try l_aen_MedicFirmList := Ten_MedicFirmList(aCtx.rEngine.PopObjAs(Ten_MedicFirmList)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aen_MedicFirmList: Ten_MedicFirmList : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(BackgroundPanel(aCtx, l_aen_MedicFirmList)); end;//TkwEnMedicFirmListBackgroundPanel.DoDoIt function TkwEnMedicFirmListContextFilter.ContextFilter(const aCtx: TtfwContext; aen_MedicFirmList: Ten_MedicFirmList): TnscContextFilter; {* Реализация слова скрипта .Ten_MedicFirmList.ContextFilter } begin Result := aen_MedicFirmList.ContextFilter; end;//TkwEnMedicFirmListContextFilter.ContextFilter class function TkwEnMedicFirmListContextFilter.GetWordNameForRegister: AnsiString; begin Result := '.Ten_MedicFirmList.ContextFilter'; end;//TkwEnMedicFirmListContextFilter.GetWordNameForRegister function TkwEnMedicFirmListContextFilter.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TnscContextFilter); end;//TkwEnMedicFirmListContextFilter.GetResultTypeInfo function TkwEnMedicFirmListContextFilter.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnMedicFirmListContextFilter.GetAllParamsCount function TkwEnMedicFirmListContextFilter.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Ten_MedicFirmList)]); end;//TkwEnMedicFirmListContextFilter.ParamsTypes procedure TkwEnMedicFirmListContextFilter.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству ContextFilter', aCtx); end;//TkwEnMedicFirmListContextFilter.SetValuePrim procedure TkwEnMedicFirmListContextFilter.DoDoIt(const aCtx: TtfwContext); var l_aen_MedicFirmList: Ten_MedicFirmList; begin try l_aen_MedicFirmList := Ten_MedicFirmList(aCtx.rEngine.PopObjAs(Ten_MedicFirmList)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aen_MedicFirmList: Ten_MedicFirmList : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(ContextFilter(aCtx, l_aen_MedicFirmList)); end;//TkwEnMedicFirmListContextFilter.DoDoIt function TkwEnMedicFirmListListTree.ListTree(const aCtx: TtfwContext; aen_MedicFirmList: Ten_MedicFirmList): TnscTreeViewWithAdapterDragDrop; {* Реализация слова скрипта .Ten_MedicFirmList.ListTree } begin Result := aen_MedicFirmList.ListTree; end;//TkwEnMedicFirmListListTree.ListTree class function TkwEnMedicFirmListListTree.GetWordNameForRegister: AnsiString; begin Result := '.Ten_MedicFirmList.ListTree'; end;//TkwEnMedicFirmListListTree.GetWordNameForRegister function TkwEnMedicFirmListListTree.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TnscTreeViewWithAdapterDragDrop); end;//TkwEnMedicFirmListListTree.GetResultTypeInfo function TkwEnMedicFirmListListTree.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnMedicFirmListListTree.GetAllParamsCount function TkwEnMedicFirmListListTree.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Ten_MedicFirmList)]); end;//TkwEnMedicFirmListListTree.ParamsTypes procedure TkwEnMedicFirmListListTree.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству ListTree', aCtx); end;//TkwEnMedicFirmListListTree.SetValuePrim procedure TkwEnMedicFirmListListTree.DoDoIt(const aCtx: TtfwContext); var l_aen_MedicFirmList: Ten_MedicFirmList; begin try l_aen_MedicFirmList := Ten_MedicFirmList(aCtx.rEngine.PopObjAs(Ten_MedicFirmList)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aen_MedicFirmList: Ten_MedicFirmList : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(ListTree(aCtx, l_aen_MedicFirmList)); end;//TkwEnMedicFirmListListTree.DoDoIt function Tkw_Form_MedicFirmList.GetString: AnsiString; begin Result := 'en_MedicFirmList'; end;//Tkw_Form_MedicFirmList.GetString class procedure Tkw_Form_MedicFirmList.RegisterInEngine; begin inherited; TtfwClassRef.Register(Ten_MedicFirmList); end;//Tkw_Form_MedicFirmList.RegisterInEngine class function Tkw_Form_MedicFirmList.GetWordNameForRegister: AnsiString; begin Result := 'форма::MedicFirmList'; end;//Tkw_Form_MedicFirmList.GetWordNameForRegister function Tkw_MedicFirmList_Control_BackgroundPanel.GetString: AnsiString; begin Result := 'BackgroundPanel'; end;//Tkw_MedicFirmList_Control_BackgroundPanel.GetString class procedure Tkw_MedicFirmList_Control_BackgroundPanel.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtPanel); end;//Tkw_MedicFirmList_Control_BackgroundPanel.RegisterInEngine class function Tkw_MedicFirmList_Control_BackgroundPanel.GetWordNameForRegister: AnsiString; begin Result := 'контрол::BackgroundPanel'; end;//Tkw_MedicFirmList_Control_BackgroundPanel.GetWordNameForRegister procedure Tkw_MedicFirmList_Control_BackgroundPanel_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('BackgroundPanel'); inherited; end;//Tkw_MedicFirmList_Control_BackgroundPanel_Push.DoDoIt class function Tkw_MedicFirmList_Control_BackgroundPanel_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::BackgroundPanel:push'; end;//Tkw_MedicFirmList_Control_BackgroundPanel_Push.GetWordNameForRegister function Tkw_MedicFirmList_Control_ContextFilter.GetString: AnsiString; begin Result := 'ContextFilter'; end;//Tkw_MedicFirmList_Control_ContextFilter.GetString class procedure Tkw_MedicFirmList_Control_ContextFilter.RegisterInEngine; begin inherited; TtfwClassRef.Register(TnscContextFilter); end;//Tkw_MedicFirmList_Control_ContextFilter.RegisterInEngine class function Tkw_MedicFirmList_Control_ContextFilter.GetWordNameForRegister: AnsiString; begin Result := 'контрол::ContextFilter'; end;//Tkw_MedicFirmList_Control_ContextFilter.GetWordNameForRegister procedure Tkw_MedicFirmList_Control_ContextFilter_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('ContextFilter'); inherited; end;//Tkw_MedicFirmList_Control_ContextFilter_Push.DoDoIt class function Tkw_MedicFirmList_Control_ContextFilter_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::ContextFilter:push'; end;//Tkw_MedicFirmList_Control_ContextFilter_Push.GetWordNameForRegister function Tkw_MedicFirmList_Control_ListTree.GetString: AnsiString; begin Result := 'ListTree'; end;//Tkw_MedicFirmList_Control_ListTree.GetString class procedure Tkw_MedicFirmList_Control_ListTree.RegisterInEngine; begin inherited; TtfwClassRef.Register(TnscTreeViewWithAdapterDragDrop); end;//Tkw_MedicFirmList_Control_ListTree.RegisterInEngine class function Tkw_MedicFirmList_Control_ListTree.GetWordNameForRegister: AnsiString; begin Result := 'контрол::ListTree'; end;//Tkw_MedicFirmList_Control_ListTree.GetWordNameForRegister procedure Tkw_MedicFirmList_Control_ListTree_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('ListTree'); inherited; end;//Tkw_MedicFirmList_Control_ListTree_Push.DoDoIt class function Tkw_MedicFirmList_Control_ListTree_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::ListTree:push'; end;//Tkw_MedicFirmList_Control_ListTree_Push.GetWordNameForRegister initialization TkwEnMedicFirmListBackgroundPanel.RegisterInEngine; {* Регистрация en_MedicFirmList_BackgroundPanel } TkwEnMedicFirmListContextFilter.RegisterInEngine; {* Регистрация en_MedicFirmList_ContextFilter } TkwEnMedicFirmListListTree.RegisterInEngine; {* Регистрация en_MedicFirmList_ListTree } Tkw_Form_MedicFirmList.RegisterInEngine; {* Регистрация Tkw_Form_MedicFirmList } Tkw_MedicFirmList_Control_BackgroundPanel.RegisterInEngine; {* Регистрация Tkw_MedicFirmList_Control_BackgroundPanel } Tkw_MedicFirmList_Control_BackgroundPanel_Push.RegisterInEngine; {* Регистрация Tkw_MedicFirmList_Control_BackgroundPanel_Push } Tkw_MedicFirmList_Control_ContextFilter.RegisterInEngine; {* Регистрация Tkw_MedicFirmList_Control_ContextFilter } Tkw_MedicFirmList_Control_ContextFilter_Push.RegisterInEngine; {* Регистрация Tkw_MedicFirmList_Control_ContextFilter_Push } Tkw_MedicFirmList_Control_ListTree.RegisterInEngine; {* Регистрация Tkw_MedicFirmList_Control_ListTree } Tkw_MedicFirmList_Control_ListTree_Push.RegisterInEngine; {* Регистрация Tkw_MedicFirmList_Control_ListTree_Push } TtfwTypeRegistrator.RegisterType(TypeInfo(Ten_MedicFirmList)); {* Регистрация типа Ten_MedicFirmList } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtPanel)); {* Регистрация типа TvtPanel } {$If Defined(Nemesis)} TtfwTypeRegistrator.RegisterType(TypeInfo(TnscContextFilter)); {* Регистрация типа TnscContextFilter } {$IfEnd} // Defined(Nemesis) TtfwTypeRegistrator.RegisterType(TypeInfo(TnscTreeViewWithAdapterDragDrop)); {* Регистрация типа TnscTreeViewWithAdapterDragDrop } {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL) end.
program Ordenar; const maximo : Integer = 100; const maxVal : Integer= 3000; var datos: array[1..maximo] of integer; var i: integer; procedure swap(var a : integer; var b: integer); var tmp: integer; begin tmp := a; a := b; b := tmp; end; procedure generaNumeros(); { Genera números aleatorios } begin writeln(''); writeln('Generando números...'); for i := 1 to maximo do begin datos[i] := maximo - i * i ; end; end; procedure muestraNumeros(); { Muestra los núms almacenados } begin writeln(''); writeln('Los números son...'); for i := 1 to maximo do begin write(datos[i], ' '); end; end; procedure Burbuja(); { Ordena según burbuja } var cambiado: boolean; var temp : Integer; begin writeln(''); writeln('Ordenando mediante burbuja...'); repeat cambiado := false; { No cambia nada aún } for i := maximo downto 2 do begin { De final a principio } if (datos[i]) < (datos[i-1]) then { Si está colocado al revés } begin temp := datos[i]; datos[i] := datos[i-1]; { Le da la vuelta } datos[i-1] := temp; cambiado := true; { Y habrá que seguir mirando } end; end; until (not (cambiado)); { Hasta q nada se haya cambiado } end; procedure Sort(var l : Integer;var r: Integer); { Esta es la parte recursiva } var i, j, x, y, temp: integer; begin i := l; j := r; { Límites por los lados } x := datos[((l+r) DIV 2)]; { Centro de la comparaciones } repeat while ((datos[i]) < x) do i := i + 1;; { Salta los ya colocados } while (x < (datos[j])) do j := j - 1;; { en ambos lados } if (i <= j) then { Si queda alguno sin colocar } begin temp := datos[i]; datos[i] := datos[j]; { Le da la vuelta } datos[j] := temp; { Los cambia de lado } i := i + 1; j := j - 1; { Y sigue acercándose al centro } end; until (i > j); { Hasta que lo pasemos } if (l < j) then begin Sort(l, j);end; { Llamadas recursivas por cada } if (i < r) then begin Sort(i, r);end; { lado } end; procedure QuickSort(); { Ordena según Quicksort } begin writeln(''); writeln('Ordenando mediante QuickSort...'); Sort(1,Maximo); end; generaNumeros(); muestraNumeros(); Burbuja(); muestraNumeros(); generaNumeros(); muestraNumeros(); QuickSort(); muestraNumeros();
unit MSObjectCacher; interface uses SysUtils, CacheAgent, CacheCommon; // RegisterCacher must be call to register a functions which knows how to // cache an instance of ClassName. By registering a Cacher for a particular // class it ensures that any instance of that class or of any class // descending from that class will be cached using this function. procedure RegisterCacher(const ClassName : string; Agent : CCacheAgent); // GetObjectPath returns the relative path this object has within its world. function GetObjectPath(Obj : TObject; kind, info : integer) : string; // Call this method to create the cache of an object in the Web Serever Cache. // It doesn't matters if there is no cacher registered for its class, in // this case Obj is ignored. Use Action to specify the actual action to be // taken on the cache. function CacheObject(Obj : TObject; kind, info : integer) : boolean; // The only differce between CacheObject and CacheMetaObject is that // MetaObjects are shared by all the running world around the Cache // Sever. function CacheMetaObject(Obj : TObject; kind, info : integer) : boolean; // Call this methods to eliminate an object in the Web Serever Cache. // It doesen't matters if there is no cacher registered for its class, in // this case Obj is ignored. Use Action to specify the actual action to be // taken on the cache. function UncacheObject(Obj : TObject; kind, info : integer) : boolean; function UncacheObjectByPath(path : string) : boolean; // Call this methods to eliminate a meta object in the Web Serever Cache. // It doesen't matters if there is no cacher registered for its class, in // this case Obj is ignored. Use Action to specify the actual action to be // taken on the cache. function UncacheMetaObject(Obj : TObject; kind, info : integer) : boolean; // Call this method to update the cache of an object in the Web Serever Cache. // It doesn't matters if there is no cacher registered for its class, in // this case Obj is ignored. Use Action to specify the actual action to be // taken on the cache. // UpdateObjectCache is always applied to Objects, never to MetaObjects. function UpdateObjectCache(Obj : TObject; kind, info : integer) : boolean; // Initialize the module procedure InitCachers; // Unitialize the module procedure DoneCachers; // GetWorldName function GetWorldName : string; // SetWorldName procedure SetWorldName(aName : string); // GetGlobalPath function GetGlobalPath(const path : string) : string; // CreateMapLink function CreateMapLink(X, Y : integer; const path : string) : string; // CreateOutputLink function CreateOutputLink(X, Y, K, P, C : integer; const Output, Town, Company, Utility, Circuits : string; Role : TFacilityRole) : string; // CreateInputLink function CreateInputLink(X, Y, Capacity, SupLevel : integer; const Input, Town, Company, Utility, Circuits : string; Role : TFacilityRole) : string; // Set Version procedure SetMSVersion(ver : integer); // UpdateObjectCacheEx function UpdateObjectCacheEx(Obj : TObject; kind, info : integer; update : boolean) : TObjectCache; // Save Cache function SaveImage(Obj : TObjectCache) : boolean; // Invalidate Cache function InvalidateCache(Obj : TObject; MetaObject : boolean) : boolean; // InvalidateObjectByPath function InvalidateObjectByPath(path : string) : boolean; // CacheObjectLinks procedure CacheObjectLinks(path, links : string); var MSVersion : integer = 0; type EMSObjectCacherError = class(Exception); EMSCacheRDOError = class(Exception); implementation uses Windows, ComObj, SpecialChars, MSCacher, MSCacheSpool, Registry, CacheRegistryKeys, CacheObjects, DataRegistry, CacheNameUtils, Logs; // Aux class type TCacheRegistryEntry = class public constructor Create(anAgent : CCacheAgent); private fAgent : CCacheAgent; public property Agent : CCacheAgent read fAgent; end; constructor TCacheRegistryEntry.Create(anAgent : CCacheAgent); begin inherited Create; fAgent := anAgent; end; // MSObjectCacher instance var RegisteredCachers : TDataRegistry = nil; ObjectCacher : TMSCacher = nil; WorldName : string = ''; procedure RegisterCacher(const ClassName : string; Agent : CCacheAgent); begin RegisteredCachers.Add(ClassName, TCacheRegistryEntry.Create(Agent)) end; function GetCacheAgent(ObjClass : TClass) : CCacheAgent; var aux : TObject; begin aux := nil; while (aux = nil) and (ObjClass <> nil) do begin aux := RegisteredCachers[ObjClass.ClassName]; ObjClass := ObjClass.ClassParent; end; if aux <> nil then result := TCacheRegistryEntry(aux).Agent else result := nil; end; function CacheAnyObject(Obj : TObject; MetaObject : boolean; kind, info : integer) : boolean; var Cacher : CCacheAgent; Cache : TObjectCache; Name : string; begin try if Obj <> nil then begin Name := Obj.ClassName; Cacher := GetCacheAgent(Obj.ClassType); if Cacher <> nil then begin try Cache := Cacher.GetCache(Obj, kind, info, true); except on E : Exception do begin E.Message := E.Message + 'Internal error caching class: ' + Name; raise E; end; end; if Cache <> nil then try if MetaObject then Cache.Path := 'Classes\' + Cache.Path else begin Cache.Path := 'Worlds\' + WorldName + '\' + Cache.Path; if Cache.Properties[ppTTL] <> '' then Cache.WriteString(ppLastMod, DateTimeToStr(Now)); end; Cache.WriteInteger(ppVersion, MSVersion); Cache.Action := caCreate; ObjectCacher.CacheObject(Cache, false); result := true; finally Cache.Free; end else result := false; end else result := false; end else result := false; except on E : Exception do begin result := false; logs.log('Survival', DateTimeToStr(Now) + ' Error caching object ' + E.Message); end; end; end; function GetObjectPath(Obj : TObject; kind, info : integer) : string; var CacheAgent : CCacheAgent; begin CacheAgent := GetCacheAgent(Obj.ClassType); if CacheAgent <> nil then result := CacheAgent.GetPath(Obj, kind, info) else result := ''; end; function CacheObject(Obj : TObject; kind, info : integer) : boolean; begin result := CacheAnyObject(Obj, false, kind, info); end; function CacheMetaObject(Obj : TObject; kind, info : integer) : boolean; begin result := CacheAnyObject(Obj, true, kind, info); end; function UpdateObjectCache(Obj : TObject; kind, info : integer) : boolean; var Cacher : CCacheAgent; Cache : TObjectCache; begin try if Obj <> nil then begin Cacher := GetCacheAgent(Obj.ClassType); if Cacher <> nil then begin Cache := Cacher.UpdateCache(Obj, kind, info, false); try if Cache[ppTTL] <> '' then Cache.WriteString(ppLastMod, DateTimeToStr(Now)); // >> Use UTC? Cache.Path := 'Worlds\' + WorldName + '\' + Cache.Path; Cache.Action := caCreate; Cache.WriteInteger(ppVersion, MSVersion); ObjectCacher.CacheObject(Cache, false); result := true; finally Cache.Free; end; end else result := false; end else result := false; except result := false; end; end; function UpdateObjectCacheEx(Obj : TObject; kind, info : integer; update : boolean) : TObjectCache; var Cacher : CCacheAgent; Cache : TObjectCache; begin try if Obj <> nil then begin Cacher := GetCacheAgent(Obj.ClassType); if Cacher <> nil then begin Cache := Cacher.UpdateCache(Obj, kind, info, update); try if Cache[ppTTL] <> '' then Cache.WriteString(ppLastMod, DateTimeToStr(Now)); // >> Use UTC? Cache.Path := 'Worlds\' + WorldName + '\' + Cache.Path; Cache.Action := caCreate; Cache.WriteInteger(ppVersion, MSVersion); result := Cache; finally //Cache.Free; end; end else result := nil; end else result := nil; except result := nil; end; end; function UncacheObjectAnyObject(Obj : TObject; MetaObject : boolean; kind, info : integer) : boolean; var Cacher : CCacheAgent; Cache : TObjectCache; begin try if Obj <> nil then begin Cacher := GetCacheAgent(Obj.ClassType); if Assigned(Cacher) then begin Cache := TObjectCache.Create; try //Logs.Log('Survival', 'before getPath ' + IntToStr(integer(Obj))); if MetaObject then Cache.Path := 'Classes\' + Cacher.GetPath(Obj, kind, info) else Cache.Path := 'Worlds\' + WorldName + '\' + Cacher.GetPath(Obj, kind, info); //Logs.Log('Survival', 'after getPath and before Uncache' + IntToStr(integer(Obj))); Cache.Action := caDelete; ObjectCacher.CacheObject(Cache, false); //Logs.Log('Survival', 'after Uncache' + IntToStr(integer(Obj))); result := true; finally Cache.Free; end; end else result := false; end else result := false; except result := false; end; end; function UncacheObject(Obj : TObject; kind, info : integer) : boolean; begin result := UncacheObjectAnyObject(Obj, false, kind, info); end; function UncacheObjectByPath(path : string) : boolean; begin result := ObjectCacher.RemoveCache('Worlds\' + WorldName + '\' + path); end; function UncacheMetaObject(Obj : TObject; kind, info : integer) : boolean; begin result := UncacheObjectAnyObject(Obj, true, kind, info); end; procedure InitCachers; begin RegisteredCachers := TDataRegistry.Create; ObjectCacher := TMSCacher.Create; MSCacheSpool.Init; end; procedure DoneCachers; begin RegisteredCachers.Free; ObjectCacher.Free; MSCacheSpool.Done; end; function GetWorldName : string; begin result := WorldName; end; procedure SetWorldName(aName : string); begin WorldName := aName; end; function GetGlobalPath(const path : string) : string; begin result := 'Worlds\' +WorldName + '\' + path; end; function CreateMapLink(X, Y : integer; const path : string) : string; const ClearMask = integer(not((1 shl 6) - 1)); var aux : string; i : integer; begin if Path <> '' then begin SetLength(aux, length(path)); for i := 0 to pred(length(path)) do if pchar(path)[i] = '\' then pchar(aux)[i] := BackslashChar else pchar(aux)[i] := pchar(path)[i]; //result := 'Worlds\' + WorldName + '\Map\' + IntToStr(X and ClearMask) + BackslashChar + IntToStr(Y and ClearMask) + '\' + IntToStr(X) + BackslashChar + IntToStr(Y) + BackslashChar + aux; result := 'Worlds\' + WorldName + '\Map\' + IntToStr(X and ClearMask) + BackslashChar + IntToStr(Y and ClearMask) + '\MAP' + IntToStr(X) + BackslashChar + IntToStr(Y) + BackslashChar + aux; end else result := ''; end; function GetLinkFirstChar(Role : TFacilityRole) : string; begin case Role of rolNeutral, rolProducer : result := 'P'; rolDistributer : result := 'D'; rolBuyer : result := 'B'; rolImporter : result := 'I'; rolCompExport : result := 'X'; rolCompInport : result := 'N'; else result := ''; end; end; function CreateOutputLink(X, Y, K, P, C : integer; const Output, Town, Company, Utility, Circuits : string; Role : TFacilityRole) : string; begin result := 'Worlds\' + WorldName + '\Outputs\' + Output + '\' + GetLinkFirstChar(Role) + IntToStr(X) + BackslashChar + IntToStr(Y) + BackslashChar + IntToStr(K) + BackslashChar + IntToStr(P) + BackslashChar + IntToStr(C) + BackslashChar + Town + BackslashChar + Company + BackslashChar + Utility + BackslashChar + Circuits; end; function CreateInputLink(X, Y, Capacity, SupLevel : integer; const Input, Town, Company, Utility, Circuits : string; Role : TFacilityRole) : string; begin result := 'Worlds\' + WorldName + '\Inputs\' + Input + '\' + GetLinkFirstChar(Role) + IntToStr(X) + BackslashChar + IntToStr(Y) + BackslashChar + IntToStr(Capacity) + BackslashChar + IntToStr(SupLevel) + BackslashChar + Town + BackslashChar + Company + BackslashChar + Utility + BackslashChar + Circuits; end; procedure SetMSVersion(ver : integer); begin MSVersion := ver; end; function SaveImage(Obj : TObjectCache) : boolean; begin try ObjectCacher.CacheObject(Obj, false); result := true; except result := false; end; end; function InvalidateCache(Obj : TObject; MetaObject : boolean) : boolean; var Cacher : CCacheAgent; Path : string; begin try if Obj <> nil then begin Cacher := GetCacheAgent(Obj.ClassType); if Assigned(Cacher) then begin if MetaObject then Path := 'Classes\' + Cacher.GetPath(Obj, noKind, noInfo) else Path := 'Worlds\' + WorldName + '\' + Cacher.GetPath(Obj, noKind, noInfo); result := ObjectCacher.InvalidateCache(Path); end else result := false; end else result := false; except result := false; end; end; function InvalidateObjectByPath(path : string) : boolean; begin result := ObjectCacher.InvalidateCache('Worlds\' + WorldName + '\' + path); end; procedure CacheObjectLinks(path, links : string); begin ObjectCacher.CacheObjectLinks(path, links); end; end.
{********************************************************************** This small program tests the use of type definitions of arrays, booleans, and integers. It also tests the use of forward declarations of functions, etc. **********************************************************************} program foo; type b1 = boolean; index = integer; vector = array [1..10] of integer; var i:index; x,y:vector; function f2 (x,y,z:boolean; a,b:vector):integer; forward; function f1 (w,x,y,z:b1; a,b,c:vector):integer; var i:index; result:vector; sum:integer; begin for i:=1 to 10 do if i mod 2 = 1 then result [i] := f2 (w,x,y,a,b) else result [i] := f2 (x,y,z,b,c); for i:= 1 to 10 do sum := sum + result[i]; f1:=sum end; { Note that I changed the parameter names from the forward declaration } function f2 (a,b,c:boolean; x,y:vector):integer; var i:index; result:vector; sum:integer; begin for i:=1 to 10 do if a or b and c then result[i]:=f1(a,a,b,c,x,x,y) else result[i]:=f1(a,b,c,c,x,y,y); for i:=1 to 10 do sum := sum + result[i]; f2:=sum end; begin for i:=1 to 10 do begin x[i]:=i; y[i]:=i end end.
unit xBevel; interface uses SysUtils, Classes, Controls, ExtCtrls, Graphics, xGradient; type TxBevelStyle = (bsLowered, bsRaised, bsSingle); TxBevelEdge = (beLeft, beRight, beTop, beBottom); TxBevelEdges = set of TxBevelEdge; TxBevel = class(TGraphicControl) private FShape: TBevelShape; FStyle: TxBevelStyle; FColorInner: TColor; FColorOuter: TColor; FCaption: TCaption; FAlignment: TAlignment; FGradient: TxGradient; FEdges: TxBevelEdges; procedure SetShape(const Value: TBevelShape); procedure SetStyle(const Value: TxBevelStyle); procedure SetColorInner(const Value: TColor); procedure SetColorOuter(const Value: TColor); procedure SetCaption(const Value: TCaption); procedure SetAlignment(const Value: TAlignment); procedure SetEdges(const Value: TxBevelEdges); procedure SetGradient(const Value: TxGradient); protected procedure Paint; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property Align; property Alignment: TAlignment read FAlignment write SetAlignment; property Anchors; property Caption: TCaption read FCaption write SetCaption; property ColorInner: TColor read FColorInner write SetColorInner; property ColorOuter: TColor read FColorOuter write SetColorOuter; property Constraints; property Edges: TxBevelEdges read FEdges write SetEdges; property Font; property Gradient: TxGradient read FGradient write SetGradient; property ParentShowHint; property Shape: TBevelShape read FShape write SetShape default bsBox; property ShowHint; property Style: TxBevelStyle read FStyle write SetStyle default bsLowered; property Visible; end; implementation uses Types, Windows; constructor TxBevel.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := ControlStyle + [csReplicatable]; FStyle := bsLowered; FShape := bsBox; FColorInner:=clBtnShadow; FColorOuter:=clBtnHighlight; Width := 50; Height := 50; FGradient := TxGradient.Create(Self); with FGradient do begin ColorBegin:=clBtnFace; ColorEnd:=clBtnFace; end; end; destructor TxBevel.Destroy; begin FGradient.Free; inherited; end; procedure TxBevel.Paint; const XorColor = $00FFD8CE; Alignments: array[TAlignment] of Longint = (DT_LEFT, DT_RIGHT, DT_CENTER); var Color1, Color2: TColor; Temp: TColor; {tx, ty, }th, tw: integer; R: TRect; Flags: Longint; procedure BevelRect(const R: TRect); begin with Canvas do begin Pen.Color := Color1; PolyLine([Point(R.Left, R.Bottom), Point(R.Left, R.Top), Point(R.Right, R.Top)]); Pen.Color := Color2; PolyLine([Point(R.Right, R.Top), Point(R.Right, R.Bottom), Point(R.Left, R.Bottom)]); end; end; procedure BevelLine(C: TColor; X1, Y1, X2, Y2: Integer); begin with Canvas do begin Pen.Color := C; MoveTo(X1, Y1); LineTo(X2, Y2); end; end; begin R:=ClientRect; with Canvas do begin if FGradient.Enabled then FGradient.GradientFill; tw := TextWidth(FCaption); th := TextHeight(FCaption); if (csDesigning in ComponentState) then begin if (FShape = bsSpacer) then begin Pen.Style := psDot; Pen.Mode := pmXor; Pen.Color := XorColor; Brush.Style := bsClear; Rectangle(0, 0, ClientWidth, ClientHeight); end else begin Pen.Style := psSolid; Pen.Mode := pmCopy; Pen.Color := clBlack; Brush.Style := bsSolid; end; end; Pen.Width := 1; if FStyle = bsLowered then begin Color1 := FColorInner; Color2 := FColorOuter; end else begin Color1 := FColorOuter; Color2 := FColorInner; end; case FShape of bsBox: BevelRect(Rect(0, 0, Width - 1, Height - 1)); bsFrame: begin Temp := Color1; Color1 := Color2; BevelRect(Rect(1, 1, Width - 1, Height - 1)); Color2 := Temp; Color1 := Temp; BevelRect(Rect(0, 0, Width - 2, Height - 2)); end; bsTopLine: begin BevelLine(Color1, 0, 0, Width, 0); if FStyle <> bsSingle then BevelLine(Color2, 0, 1, Width, 1); end; bsBottomLine: begin BevelLine(Color1, 0, Height - 2, Width, Height - 2); if FStyle <> bsSingle then BevelLine(Color2, 0, Height - 1, Width, Height - 1); end; bsLeftLine: begin BevelLine(Color1, 0, 0, 0, Height); if FStyle <> bsSingle then BevelLine(Color2, 1, 0, 1, Height); end; bsRightLine: begin BevelLine(Color1, Width - 2, 0, Width - 2, Height); if FStyle <> bsSingle then BevelLine(Color2, Width - 1, 0, Width - 1, Height); end; end; Font:=Self.Font; Brush.Style:=bsClear; with R do begin Top := ((Bottom + Top) - th) div 2; Bottom := Top + th; Left:=Left+2; Right:=Right-2; end; Flags := DT_EXPANDTABS or DT_VCENTER or Alignments[Alignment]; Flags := DrawTextBiDiModeFlags(Flags); DrawText(Handle, PChar(FCaption), -1, R, Flags); end; end; procedure TxBevel.SetAlignment(const Value: TAlignment); begin FAlignment := Value; Invalidate; end; procedure TxBevel.SetCaption(const Value: TCaption); begin FCaption := Value; Invalidate; end; procedure TxBevel.SetColorInner(const Value: TColor); begin if Value <> FColorInner then begin FColorInner := Value; Invalidate; end; end; procedure TxBevel.SetColorOuter(const Value: TColor); begin if Value <> FColorOuter then begin FColorOuter := Value; Invalidate; end; end; procedure TxBevel.SetEdges(const Value: TxBevelEdges); begin FEdges := Value; Invalidate; end; procedure TxBevel.SetGradient(const Value: TxGradient); begin FGradient.Assign(Value); end; procedure TxBevel.SetShape(const Value: TBevelShape); begin if Value <> FShape then begin FShape := Value; Invalidate; end; end; procedure TxBevel.SetStyle(const Value: TxBevelStyle); begin if Value <> FStyle then begin FStyle := Value; Invalidate; end; end; end.
unit ConsolProjectOptionsUnit; interface uses {$IFDEF LINUX} Libc, QDialogs, {$ENDIF} {$IFDEF MSWINDOWS} Windows, ShellAPI, {$ENDIF} SysUtils, Classes, JclSysUtils; type TLineBreakQuality = (lbqStrict, lbqSloppy); TOutputType = (otWebPage, otHtmlHelp, otLatex, otLatex2Rtf); TLatexGraphicsPackage = (ltmNone, ltmPDF, ltmDVI); TSortOption = (soStructures, soConstants, soFunctions, soTypes, soVariables, soUsesClauses, soRecordFields, soNonRecordFields, soMethods, soProperties); TSortOptions = set of TSortOption; TCustomHelpOptions = class(TComponent) protected FFileDirectory: string; procedure Initialize; virtual; public procedure ReadFromComponentFile(const FileName: string); procedure SaveToComponentFile(const FileName: string); end; TConsolHelpProjectOptions = class(TCustomHelpOptions) private // function GetVisibilities: TVisibilities; protected FSourceFiles: TStrings; function GetChanged: boolean; virtual; abstract; function GetConclusion: string; virtual; abstract; function GetDirectives: TSTrings; virtual; abstract; function GetFooter: TStrings; virtual; abstract; function GetGraphVizDotLocation: string; virtual; abstract; function GetHeader: TStrings; virtual; abstract; function GetHtmlHelpContents: string; virtual; abstract; // function GetHtmlDocGeneratorComponent: THtmlDocGenerator; virtual; // abstract; // function GetHTMLHelpDocGeneratorComponent: THTMLHelpDocGenerator; // virtual; abstract; function GetHyphenatedWords: TStrings; virtual; abstract; function GetIncludeAutomated: boolean; virtual; abstract; function GetIncludeDirectories: TStrings; virtual; abstract; function GetIncludeImplicit: boolean; virtual; abstract; function GetIncludeStrictPrivate: boolean; virtual; abstract; function GetIncludePrivate: boolean; virtual; abstract; function GetIncludeStrictProtected: boolean; virtual; abstract; function GetIncludeProtected: boolean; virtual; abstract; function GetIncludePublic: boolean; virtual; abstract; function GetIncludePublished: boolean; virtual; abstract; function GetIntroduction: string; virtual; abstract; function GetLanguageString: string; virtual; abstract; function GetLatexGraphicsPackage: TLatexGraphicsPackage; virtual; abstract; function GetLineBreakQuality: TLineBreakQuality; virtual; abstract; function GetOutputDirectory: string; virtual; abstract; function GetOutputType: TOutputType; virtual; abstract; // function GetPasDocComponent: TPasDoc; virtual; abstract; function GetProjectName: string; virtual; abstract; function GetSourceFiles: TStrings; virtual; abstract; function GetSortOptions: TSortOptions; virtual; abstract; function GetSpellChecking: boolean; virtual; abstract; function GetSpellCheckIgnoreWords: TStrings; virtual; abstract; function GetSpellCheckLanguage: string; virtual; abstract; function GetSpellCheckLanguageCode: string; virtual; abstract; // function GetTexDocGeneratorComponent: TTexDocGenerator; virtual; // abstract; function GetTitle: string; virtual; abstract; function GetUseGraphVizClasses: boolean; virtual; abstract; function GetUseGraphVizUses: boolean; virtual; abstract; function GetVerbosity: integer; virtual; abstract; procedure Initialize; override; procedure Loaded; override; procedure SetChanged(const Value: boolean); virtual; abstract; procedure SetConclusion(const Value: string); virtual; abstract; procedure SetDefaultActivePage; virtual; abstract; procedure SetDirectives(const Value: TSTrings); virtual; abstract; procedure SetFooter(const Value: TStrings); virtual; abstract; procedure SetGraphVizDotLocation(const Value: string); virtual; abstract; procedure SetHeader(const Value: TStrings); virtual; abstract; procedure SetHtmlHelpContents(const AValue: string); virtual; abstract; procedure SetHyphenatedWords(const Value: TStrings); virtual; abstract; procedure SetIncludeAutomated(const Value: boolean); virtual; abstract; procedure SetIncludeDirectories(const Value: TStrings); virtual; abstract; procedure SetIncludeImplicit(const Value: boolean); virtual; abstract; procedure SetIncludeStrictPrivate(const Value: boolean); virtual; abstract; procedure SetIncludePrivate(const Value: boolean); virtual; abstract; procedure SetIncludeStrictProtected(const Value: boolean); virtual; abstract; procedure SetIncludeProtected(const Value: boolean); virtual; abstract; procedure SetIncludePublic(const Value: boolean); virtual; abstract; procedure SetIncludePublished(const Value: boolean); virtual; abstract; procedure SetIntroduction(const Value: string); virtual; abstract; procedure SetLanguageString(const Value: string); virtual; abstract; procedure SetLatexGraphicsPackage(const Value: TLatexGraphicsPackage); virtual; abstract; procedure SetLineBreakQuality(const Value: TLineBreakQuality); virtual; abstract; procedure SetOutputDirectory(const Value: string); virtual; abstract; procedure SetOutputType(const Value: TOutputType); virtual; abstract; procedure SetProjectName(const Value: string); virtual; abstract; procedure SetSortOptions(Const Value: TSortOptions); virtual; abstract; procedure SetSourceFiles(const Value: TStrings); virtual; abstract; procedure SetSpellChecking(const Value: boolean); virtual; abstract; procedure SetSpellCheckIgnoreWords(const Value: TStrings); virtual; abstract; procedure SetSpellCheckLanguage(const Value: string); virtual; abstract; procedure SetTitle(const Value: string); virtual; abstract; procedure SetUseGraphVizClasses(const Value: boolean); virtual; abstract; procedure SetUseGraphVizUses(const Value: boolean); virtual; abstract; procedure SetVerbosity(const Value: integer); virtual; abstract; function GetPasDocConsoleLocation: string; virtual; abstract; public class procedure DefaultDefines(Defines: TStrings); constructor Create(AOwner: TComponent); override; destructor Destroy; override; function FullFileName(FileName: string): string; function RelativeFileName(FileName: string): string; procedure RunPasDocConsol(OutputLineCallback: TTextHandler); procedure RunProgram(AProgram: string; Arguments: TStringList); procedure RunVizGraph(OutputLineCallback: TTextHandler); procedure SetDefaults; property Changed: boolean read GetChanged write SetChanged; { property HtmlDocGeneratorComponent: THtmlDocGenerator read GetHtmlDocGeneratorComponent; property HTMLHelpDocGeneratorComponent: THTMLHelpDocGenerator read GetHTMLHelpDocGeneratorComponent; property PasDocComponent: TPasDoc read GetPasDocComponent; property TexDocGeneratorComponent: TTexDocGenerator read GetTexDocGeneratorComponent; } // property Visibilities: TVisibilities read GetVisibilities; published property ConclusionFileName: string read GetConclusion write SetConclusion stored True; property Directives: TSTrings read GetDirectives write SetDirectives stored True; property Footer: TStrings read GetFooter write SetFooter stored True; property GraphVizDotLocation: string read GetGraphVizDotLocation write SetGraphVizDotLocation stored False; property Header: TStrings read GetHeader write SetHeader stored True; property HtmlHelpContents: string read GetHtmlHelpContents write SetHtmlHelpContents stored True; property HyphenatedWords: TStrings read GetHyphenatedWords write SetHyphenatedWords stored True; property IncludeAutomated: boolean read GetIncludeAutomated write SetIncludeAutomated stored True; property IncludeDirectories: TStrings read GetIncludeDirectories write SetIncludeDirectories stored True; property IncludeStrictPrivate: boolean read GetIncludeStrictPrivate write SetIncludeStrictPrivate; property IncludePrivate: boolean read GetIncludePrivate write SetIncludePrivate stored True; property IncludeStrictProtected: boolean read GetIncludeStrictProtected write SetIncludeStrictProtected; property IncludeProtected: boolean read GetIncludeProtected write SetIncludeProtected stored True; property IncludePublic: boolean read GetIncludePublic write SetIncludePublic stored True; property IncludePublished: boolean read GetIncludePublished write SetIncludePublished stored True; property IncludeImplicit: boolean read GetIncludeImplicit write SetIncludeImplicit; property IntroductionFileName: string read GetIntroduction write SetIntroduction stored True; property LanguageString: string read GetLanguageString write SetLanguageString stored True; property LatexGraphicsPackage: TLatexGraphicsPackage read GetLatexGraphicsPackage write SetLatexGraphicsPackage stored True; property LineBreakQuality: TLineBreakQuality read GetLineBreakQuality write SetLineBreakQuality stored True; property OutputDirectory: string read GetOutputDirectory write SetOutputDirectory stored True; property OutputType: TOutputType read GetOutputType write SetOutputType stored True; property ProjectName: string read GetProjectName write SetProjectName stored True; property SortOptions: TSortOptions read GetSortOptions write SetSortOptions; property SourceFiles: TStrings read GetSourceFiles write SetSourceFiles stored True; property SpellChecking: boolean read GetSpellChecking write SetSpellChecking; property SpellCheckIgnoreWords: TStrings read GetSpellCheckIgnoreWords write SetSpellCheckIgnoreWords; property SpellCheckLanguage: string read GetSpellCheckLanguage write SetSpellCheckLanguage; property SpellCheckLanguageCode: string read GetSpellCheckLanguageCode; property Title: string read GetTitle write SetTitle stored True; property UseGraphVizClasses: boolean read GetUseGraphVizClasses write SetUseGraphVizClasses stored True; property UseGraphVizUses: boolean read GetUseGraphVizUses write SetUseGraphVizUses stored True; property Verbosity: integer read GetVerbosity write SetVerbosity stored True; end; TCustomIniFile = class(TCustomHelpOptions) private protected function GetGraphVizDotLocation: string; virtual; abstract; procedure SetGraphVizDotLocation(const Value: string); virtual; abstract; function GetBrowserLocation: string; virtual; abstract; procedure SetBrowserLocation(const Value: string); virtual; abstract; function GetPasDocConsoleLocation: string; virtual; abstract; procedure SetPasDocConsoleLocation(const Value: string); virtual; abstract; procedure Initialize; override; published property GraphVizDotLocation: string read GetGraphVizDotLocation write SetGraphVizDotLocation stored True; property BrowserLocation: string read GetBrowserLocation write SetBrowserLocation stored True; property PasDocConsoleLocation: string read GetPasDocConsoleLocation write SetPasDocConsoleLocation stored True; end; TIniFileClass = class of TCustomIniFile; procedure GetVisibilityNames(Names: TStrings); function IniFileName: string; procedure ReadIniFile(IniClass: TIniFileClass); procedure WriteIniFile(IniClass: TIniFileClass); const {$IFDEF MSWINDOWS} ReadWritePermissions = 0; {$ELSE} ReadWritePermissions = S_IREAD or S_IWRITE or S_IRGRP or S_IWGRP or S_IROTH; {$ENDIF} const GVUses = 'GVUses'; GVClasses = 'GVClasses'; GVImageExtension = 'png'; type LanguageRecord = record Name: string; Abbreviation: string; end; const MaxLanguages = 20; Languages : array[0..MaxLanguages] of LanguageRecord = ( (Name: 'Bosnian (Codepage 1250)'; Abbreviation: 'ba'), (Name: 'Brasilian'; Abbreviation: 'br'), (Name: 'Catalan'; Abbreviation: 'ct'), (Name: 'Chinese (Codepage 950)'; Abbreviation: 'big5'), (Name: 'Danish'; Abbreviation: 'dk'), (Name: 'Dutch'; Abbreviation: 'nl'), (Name: 'English'; Abbreviation: 'en'), (Name: 'French'; Abbreviation: 'fr'), (Name: 'German'; Abbreviation: 'de'), (Name: 'Hungarian (Codepage 1250)'; Abbreviation: 'hu.1250'), (Name: 'Indonesian'; Abbreviation: 'id'), (Name: 'Italian'; Abbreviation: 'it'), (Name: 'Javanese'; Abbreviation: 'jv'), (Name: 'Polish (Codepage CP1250)'; Abbreviation: ' pl.cp1250'), (Name: 'Polish (Codepage ISO 8859-2)'; Abbreviation: 'pl.iso-8859-2'), (Name: 'Russian (Codepage 1251)'; Abbreviation: 'ru.1251'), (Name: 'Russian (Codepage 866)'; Abbreviation: 'ru.866'), (Name: 'Russian (KOI-8)'; Abbreviation: 'ru.KOI8'), (Name: 'Spanish'; Abbreviation: 'es'), (Name: 'Swedish'; Abbreviation: 'se'), (Name: 'Slovak'; Abbreviation: 'sk') ); resourcestring kPublished = 'Published'; kPublic = 'Public'; kProtected = 'Protected'; kStrictProtected = 'Strict Protected'; kPrivate = 'Private'; kStrictPrivate = 'Strict Private'; kAutomated = 'Automated'; kImplicit = 'Implicit'; implementation uses StrUtils; procedure GetVisibilityNames(Names: TStrings); begin Names.Clear; // hard code names Names.Add(kPublished); Names.Add(kPublic); Names.Add(kProtected); Names.Add(kStrictProtected); Names.Add(kPrivate); Names.Add(kStrictPrivate); Names.Add(kAutomated); Names.Add(kImplicit); end; function IniFileName: string; const IniName = 'HelpGenerator.ini'; begin result := ExtractFileDir(ParamStr(0)) + PathDelim + IniName; end; procedure ReadIniFile(IniClass: TIniFileClass); var Ini: TCustomIniFile; FileName: string; begin FileName := IniFileName; Ini := IniClass.Create(nil); try if FileExists(FileName) then begin Ini.ReadFromComponentFile(FileName); end else begin FileName := ParamStr(0); FileName := ExpandFileName(FileName); FileName := ExtractFileDir(FileName) + PathDelim; {$IFDEF LINUX} FileName := FileName + 'pasdoc'; {$ELSE} FileName := FileName + 'pasdoc.exe'; {$ENDIF} Ini.PasDocConsoleLocation := FileName; end; finally Ini.Free; end; end; procedure WriteIniFile(IniClass: TIniFileClass); var Ini: TCustomIniFile; begin Ini := IniClass.Create(nil); try Ini.SaveToComponentFile(IniFileName); finally Ini.Free; end; end; { TCustomHelpOptions } procedure TCustomHelpOptions.Initialize; begin // do nothing end; procedure TCustomHelpOptions.ReadFromComponentFile(const FileName: string); var FileStream: TFileStream; BinaryStream: TMemoryStream; ObjectStream: TMemoryStream; begin FFileDirectory := ExtractFileDir(FileName) + PathDelim; try Initialize; FileStream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite, ReadWritePermissions); try FileStream.Position := 0; BinaryStream := TMemoryStream.Create; ObjectStream := TMemoryStream.Create; try BinaryStream.CopyFrom(FileStream, FileStream.Size); BinaryStream.Position := 0; ObjectTextToBinary(BinaryStream, ObjectStream); ObjectStream.Position := 0; ObjectStream.ReadComponent(self); finally BinaryStream.Free; ObjectStream.Free; end; finally FileStream.Free; end; finally FFileDirectory := ''; end; end; procedure TCustomHelpOptions.SaveToComponentFile(const FileName: string); var FileStream: TFileStream; BinaryStream: TMemoryStream; ObjectStream: TMemoryStream; begin FFileDirectory := ExtractFileDir(FileName) + PathDelim; try BinaryStream := TMemoryStream.Create; ObjectStream := TMemoryStream.Create; try BinaryStream.WriteComponent(self); BinaryStream.Position := 0; ObjectBinaryToText(BinaryStream, ObjectStream); FileStream := TFileStream.Create(FileName, fmCreate or fmShareDenyWrite, ReadWritePermissions); try ObjectStream.Position := 0; FileStream.CopyFrom(ObjectStream, ObjectStream.Size) finally FileStream.Free; end; finally BinaryStream.Free; ObjectStream.Free; end; finally FFileDirectory := ''; end; end; { TConsolHelpProjectOptions } constructor TConsolHelpProjectOptions.Create(AOwner: TComponent); begin inherited; FSourceFiles := TStringList.Create; end; class procedure TConsolHelpProjectOptions.DefaultDefines( Defines: TStrings); begin Defines.Clear; {$IFDEF LINUX} Defines.Add('LINUX'); {$ENDIF} {$IFDEF DEBUG} Defines.Add('DEBUG'); {$ENDIF} {$IFDEF VER130} Defines.Add('VER130'); {$ENDIF} {$IFDEF VER140} Defines.Add('VER140'); {$ENDIF} {$IFDEF VER150} Defines.Add('VER150'); {$ENDIF} {$IFDEF VER160} Defines.Add('VER160'); {$ENDIF} {$IFDEF VER170} Defines.Add('VER170'); {$ENDIF} {$IFDEF MSWINDOWS} Defines.Add('MSWINDOWS'); {$ENDIF} {$IFDEF WIN32} Defines.Add('WIN32'); {$ENDIF} {$IFDEF CPU386} Defines.Add('CPU386'); {$ENDIF} {$IFDEF CONDITIONALEXPRESSIONS} Defines.Add('CONDITIONALEXPRESSIONS'); {$ENDIF} end; destructor TConsolHelpProjectOptions.Destroy; begin FSourceFiles.Free; inherited; end; function TConsolHelpProjectOptions.FullFileName(FileName: string): string; const WrongPathDelim = {$IFDEF MSWINDOWS} '/' {$ELSE} '\' {$ENDIF}; begin if FileName = '' then begin result := ''; end else begin result := ExpandFileName(AnsiReplaceStr(FileName, WrongPathDelim, PathDelim)); end; end; procedure TConsolHelpProjectOptions.Initialize; begin SpellCheckIgnoreWords.Clear; SpellCheckLanguage := ''; ConclusionFileName := ''; Directives.Clear; Footer.Clear; Header.Clear; HtmlHelpContents := ''; IncludeDirectories.Clear; IntroductionFileName := ''; OutputDirectory := ''; ProjectName := ''; SourceFiles.Clear; HyphenatedWords.Clear; Title := ''; end; procedure TConsolHelpProjectOptions.Loaded; var Index: integer; SpellWords : TStringList; begin inherited; for Index := 0 to SourceFiles.Count - 1 do begin SourceFiles[Index] := FullFileName(SourceFiles[Index]); end; ConclusionFileName := FullFileName(ConclusionFileName); IntroductionFileName := FullFileName(IntroductionFileName); for Index := 0 to IncludeDirectories.Count - 1 do begin IncludeDirectories[Index] := FullFileName(IncludeDirectories[Index]); end; OutputDirectory := FullFileName(OutputDirectory); SpellWords := TStringList.Create; try SpellWords.Duplicates := dupIgnore; SpellWords.CaseSensitive := True; SpellWords.AddStrings(SpellCheckIgnoreWords); for Index := 0 to SpellWords.Count -1 do begin SpellWords[Index] := Trim(SpellWords[Index]); end; SpellWords.Sorted := True; for Index := SpellWords.Count -2 downto 0 do begin if SpellWords[Index] = SpellWords[Index+1] then begin SpellWords.Delete(Index); end; end; SpellCheckIgnoreWords := SpellWords; finally SpellWords.Free; end; end; function TConsolHelpProjectOptions.RelativeFileName( FileName: string): string; begin if FileName = '' then begin result := ''; end else begin result := ExtractRelativePath(FFileDirectory, FileName); end; end; procedure TConsolHelpProjectOptions.RunPasDocConsol( OutputLineCallback: TTextHandler); var Options: TStringList; OutputDir: string; Conditionals: TStringList; ConditionalPath: string; Index: integer; SourceFiles: TStringList; SourcePath: string; FooterFile: TStringList; FooterPath: string; HeaderFile: TStringList; HeaderPath: string; Lang: string; Abbreviation: string; VisibilityString: string; LatexHead: TStringList; LatexHeadPath: string; OptionString: string; CommandLine: string; CommandFile: TStringList; CommandFilePath: string; SpellCheckIgnoreWordsPath: string; begin Options := TStringList.Create; try OutputDir := OutputDirectory; Assert(OutputDir <> ''); if not DirectoryExists(OutputDir) then begin Assert(ForceDirectories(OutputDir)); end; // --version option is not appropriate here so it isn't used. // --source option SourceFiles := TStringList.Create; try SourceFiles.Assign(self.SourceFiles); SourcePath := OutputDir + PathDelim + 'Sources.txt'; SourceFiles.SaveToFile(SourcePath); finally SourceFiles.Free; end; SourcePath := '"' + SourcePath + '"'; Options.Add('--source=' + SourcePath); // --output option Options.Add('--output=' + '"' + OutputDirectory + '"'); // --verbosity option Options.Add('--verbosity=' + IntToStr(self.Verbosity)); // --define option not used because --conditionals option used instead // --conditionals option if Directives.Count > 0 then begin Conditionals := TStringList.Create; try Conditionals.Assign(Directives); ConditionalPath := OutputDir + PathDelim + 'Conditionals.txt'; Conditionals.SaveToFile(ConditionalPath); finally Conditionals.Free; end; ConditionalPath := '"' + ConditionalPath + '"'; Options.Add('--conditionals=' + ConditionalPath); end; // --description option not supported because it is broken. // --include option for Index := 0 to IncludeDirectories.Count -1 do begin Options.Add('--include=' + '"' + IncludeDirectories[Index] + '"'); end; // html-help-contents if (OutputType = otHtmlHelp) and (HtmlHelpContents <> '') then begin Options.Add('--html-help-contents=' + '"' + HtmlHelpContents + '"'); end; // --name option if ProjectName <> '' then begin Options.Add('--name=' + '"' + ProjectName + '"'); end; // --title option if Title <> '' then begin Options.Add('--title=' + '"' + Title + '"'); end; if OutputType in [otWebPage, otHtmlHelp] then begin // --footer option if Footer.Count > 0 then begin // Set the footer file. FooterFile := TStringList.Create; try FooterFile.Assign(self.Footer); FooterPath := OutputDir + PathDelim + 'Footer.txt'; FooterFile.SaveToFile(FooterPath); finally FooterFile.Free; end; FooterPath := '"' + FooterPath + '"'; Options.Add('--footer=' + FooterPath); end; // --header option if Header.Count > 0 then begin // Set the footer file. HeaderFile := TStringList.Create; try HeaderFile.Assign(self.Header); HeaderPath := OutputDir + PathDelim + 'Header.txt'; HeaderFile.SaveToFile(HeaderPath); finally HeaderFile.Free; end; HeaderPath := '"' + HeaderPath + '"'; Options.Add('--header=' + HeaderPath); end; end; // --format option case OutputType of otWebPage: begin Options.Add('--format=' + 'html'); end; otHtmlHelp: begin Options.Add('--format=' + 'htmlhelp'); end; otLatex: begin Options.Add('--format=' + 'latex'); end; otLatex2Rtf: begin Options.Add('--format=' + 'latex2rtf'); end; else Assert(False); end; // --exclude-generator option not supported. // --language option Abbreviation := ''; Lang := self.LanguageString; for Index := 0 to Length(Languages) -1 do begin if Languages[Index].Name = Lang then begin Abbreviation := Languages[Index].Abbreviation; break; end; end; Assert(Abbreviation <> ''); Options.Add('--language=' + Abbreviation); // --staronly option not supported. // --marker option not supported. // --marker-optional option not supported. // --numericfilenames option not supported. // --visible-members VisibilityString := ''; if self.IncludePublished then begin VisibilityString := VisibilityString + 'published,'; end; if self.IncludePublic then begin VisibilityString := VisibilityString + 'public,'; end; if self.IncludeProtected then begin VisibilityString := VisibilityString + 'protected,'; end; if self.IncludeStrictProtected then begin VisibilityString := VisibilityString + 'strictprotected,'; end; if self.IncludePrivate then begin VisibilityString := VisibilityString + 'private,'; end; if self.IncludeStrictPrivate then begin VisibilityString := VisibilityString + 'strictprivate,'; end; if self.IncludeAutomated then begin VisibilityString := VisibilityString + 'automated,'; end; // not included in released version. if self.IncludeImplicit then begin VisibilityString := VisibilityString + 'implicit,'; end; if Length(VisibilityString) > 0 then begin SetLength(VisibilityString, Length(VisibilityString) -1); end; Options.Add('--visible-members ' + VisibilityString); // --write-uses-list option always included Options.Add('--write-uses-list '); // --graphviz-uses and --link-gv-uses options if self.UseGraphVizUses then begin Options.Add('--graphviz-uses '); // only png format supported here. // dot can also make jpg files. Options.Add('--link-gv-uses png '); end; // --graphviz-classes and --link-gv-classes options if self.UseGraphVizClasses then begin Options.Add('--graphviz-classes '); // only png format supported here. // dot can also make jpg files. Options.Add('--link-gv-classes png '); end; // --abbreviations option not supported. // --aspell option not supported - not implemented in Delphi. // --spell-check-ignore-words option not supported if SpellChecking then begin Options.Add('--aspell=' + SpellCheckLanguageCode); if SpellCheckIgnoreWords.Count > 0 then begin SpellCheckIgnoreWordsPath := OutputDir + PathDelim + 'ASpellIgnoreWords.txt'; SpellCheckIgnoreWords.SaveToFile(SpellCheckIgnoreWordsPath); Options.Add('--spell-check-ignore-words=' + '"' + SpellCheckIgnoreWordsPath + '"'); end; end; // --cache-dir option not supported // --link-look=stripped option set by default Options.Add('--link-look=stripped '); // --full-link option is deprecated // --auto-abstract option set by default Options.Add('--auto-abstract '); // --css option not supported. // --use-tipue-search is set by default for html output if self.OutputType = otWebPage then begin Options.Add('--use-tipue-search '); end; // --sort option not supported. // --introduction option if self.IntroductionFileName <> '' then begin Options.Add('--introduction=' + '"' + IntroductionFileName + '"'); end; // --conclusion option if self.ConclusionFileName <> '' then begin Options.Add('--conclusion=' + '"' + ConclusionFileName + '"'); end; // --latex-head option if self.OutputType in [otLatex, otLatex2Rtf] then begin LatexHead:= TStringList.Create; try if LineBreakQuality = lbqSloppy then begin LatexHead.Add('\sloppy'); end; if HyphenatedWords.Count > 0 then begin LatexHead.Add('\hyphenation{'); for Index := 0 to HyphenatedWords.Count - 1 do begin LatexHead.Add(HyphenatedWords[Index]); end; LatexHead.Add('}'); end; case LatexGraphicsPackage of ltmNone: begin // do nothing end; ltmPDF: begin LatexHead.Add('\usepackage[pdftex]{graphicx}'); end; ltmDVI: begin LatexHead.Add('\usepackage[dvips]{graphicx}'); end; else Assert(False); end; if LatexHead.Count > 0 then begin LatexHeadPath := OutputDir + PathDelim + 'LatexHead.txt'; LatexHead.SaveToFile(LatexHeadPath); Options.Add('--latex-head ' + '"' + LatexHeadPath + '"'); end; finally LatexHead.Free; end; end; // --implicit-visibility=implicit option set by default Options.Add('--implicit-visibility=implicit '); OptionString := ''; for Index := 0 to Options.Count -1 do begin OptionString := OptionString + Options[Index] + ' '; end; CommandLine := GetPasDocConsoleLocation; if CommandLine = '' then begin OutputLineCallback('Error: PasDoc console not specified'); Exit; end; CommandLine := '"' + CommandLine + '"' + ' ' + OptionString; CommandFile := TStringList.Create; try CommandFile.Add(CommandLine); {$IFDEF WIN32} CommandFilePath := OutputDir + PathDelim + 'pasdoc.bat'; {$ELSE} CommandFilePath := OutputDir + PathDelim + 'pasdoc.sh'; {$ENDIF} CommandFile.SaveToFile(CommandFilePath); finally CommandFile.Free; end; Execute(CommandFilePath, OutputLineCallback); // Execute(CommandLine, OutputLineCallback); finally Options.Free; end; end; procedure TConsolHelpProjectOptions.RunProgram(AProgram: string; Arguments: TStringList); var {$IFDEF WIN32} Index: integer; ParamString: string; {$ELSE} NewProcess: pid_t; open_max: Longint; i: Longint; {$ENDIF} begin {$IFDEF WIN32} ParamString := ''; for Index := 0 to Arguments.Count - 1 do begin ParamString := ParamString + Arguments[Index] + ' '; end; ParamString := Trim(ParamString); ShellExecute(0, 'open', PChar(AProgram), PChar(ParamString), nil, SW_SHOWNORMAL); {$ELSE} { TODO : Test this } NewProcess := fork; case NewProcess of -1: begin raise Exception.Create('fork failed'); end; 0: begin open_max := sysconf(_SC_OPEN_MAX); for i := Succ(STDERR_FILENO) to open_max do begin fcntl(i, F_SETFD, FD_CLOEXEC); end; // Yes, I know there is a better way to do this. case Arguments.Count of 0: begin execlp(PChar(AProgram), nil); end; 1: begin execlp(PChar(AProgram), PChar(Arguments[0]), nil); end; 2: begin execlp(PChar(AProgram), PChar(Arguments[0]), PChar(Arguments[1]), nil); end; 3: begin execlp(PChar(AProgram), PChar(Arguments[0]), PChar(Arguments[1]), PChar(Arguments[2]), nil); end; 4: begin execlp(PChar(AProgram), PChar(Arguments[0]), PChar(Arguments[1]), PChar(Arguments[2]), PChar(Arguments[3]), nil); end; else begin Assert(False); end; end; end; end; {$ENDIF} end; procedure TConsolHelpProjectOptions.RunVizGraph(OutputLineCallback: TTextHandler); var GVInputFile: string; GVOutputFile: string; GVLocation: string; Arguments: TStringList; OptionString: string; Index: integer; CommandLine: string; begin if (UseGraphVizUses or UseGraphVizClasses) and FileExists(GraphVizDotLocation) then begin OutputLineCallback(''); OutputLineCallback('Starting GraphViz'); { $IFDEF LINUX} // ShowMessage('You will have to run the GraphViz "dot" program from the ' // + 'command line outside of Help Generator.'); { $ELSE} GVLocation := '"' + GraphVizDotLocation + '"'; Arguments := TStringList.Create; try if UseGraphVizUses then begin OutputLineCallback('Creating "Uses" diagram.'); GVInputFile := OutputDirectory + PathDelim + GVUses + '.dot'; GVOutputFile := '"' + OutputDirectory + PathDelim + GVUses + '.' + GVImageExtension + '"'; if FileExists(GVInputFile) then begin GVInputFile := '"' + GVInputFile + '"'; Arguments.Add('-T' + GVImageExtension); Arguments.Add(GVInputFile); Arguments.Add('-o'); Arguments.Add(GVOutputFile); OptionString := ''; for Index := 0 to Arguments.Count -1 do begin OptionString := OptionString + Arguments[Index] + ' '; end; if Length(OptionString) > 0 then begin SetLength(OptionString, Length(OptionString)-1); end; CommandLine := GVLocation + ' ' + OptionString; Execute(CommandLine, OutputLineCallback); //RunProgram(GVLocation, Arguments); end; end; if UseGraphVizClasses then begin OutputLineCallback('Creating "Classes" diagram.'); GVInputFile := OutputDirectory + PathDelim + GVClasses + '.dot'; GVOutputFile := '"' + OutputDirectory + PathDelim + GVClasses + '.' + GVImageExtension + '"'; if FileExists(GVInputFile) then begin GVInputFile := '"' + GVInputFile + '"'; Arguments.Clear; Arguments.Add('-T' + GVImageExtension); Arguments.Add(GVInputFile); Arguments.Add('-o'); Arguments.Add(GVOutputFile); OptionString := ''; for Index := 0 to Arguments.Count -1 do begin OptionString := OptionString + Arguments[Index] + ' '; end; if Length(OptionString) > 0 then begin SetLength(OptionString, Length(OptionString)-1); end; CommandLine := GVLocation + ' ' + OptionString; Execute(CommandLine, OutputLineCallback); end; end; finally Arguments.Free; end; { $ENDIF} end; end; procedure TConsolHelpProjectOptions.SetDefaults; begin IncludePublished := True; IncludePublic := True; IncludeProtected := False; IncludePrivate := False; IncludeAutomated := False; IncludeImplicit := True; LanguageString := 'English'; SetDefaultActivePage; Changed := False; SortOptions := [soStructures, soConstants, soFunctions, soTypes, soVariables, soNonRecordFields, soMethods, soProperties] end; { TCustomIniFile } procedure TCustomIniFile.Initialize; begin GraphVizDotLocation := ''; BrowserLocation := ''; end; end.
unit TTSPLDGTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TTTSPLDGRecord = record PLenderNum: String[4]; PLoanNum: String[20]; PCollNum: Integer; PXLoanNum: String[20]; PXCollNum: Integer; End; TTTSPLDGBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TTTSPLDGRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEITTSPLDG = (TTSPLDGPrimaryKey, TTSPLDGByCross, TTSPLDGByLoanColl); TTTSPLDGTable = class( TDBISAMTableAU ) private FDFLenderNum: TStringField; FDFLoanNum: TStringField; FDFCollNum: TIntegerField; FDFXLoanNum: TStringField; FDFXCollNum: TIntegerField; procedure SetPLenderNum(const Value: String); function GetPLenderNum:String; procedure SetPLoanNum(const Value: String); function GetPLoanNum:String; procedure SetPCollNum(const Value: Integer); function GetPCollNum:Integer; procedure SetPXLoanNum(const Value: String); function GetPXLoanNum:String; procedure SetPXCollNum(const Value: Integer); function GetPXCollNum:Integer; procedure SetEnumIndex(Value: TEITTSPLDG); function GetEnumIndex: TEITTSPLDG; protected procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TTTSPLDGRecord; procedure StoreDataBuffer(ABuffer:TTTSPLDGRecord); property DFLenderNum: TStringField read FDFLenderNum; property DFLoanNum: TStringField read FDFLoanNum; property DFCollNum: TIntegerField read FDFCollNum; property DFXLoanNum: TStringField read FDFXLoanNum; property DFXCollNum: TIntegerField read FDFXCollNum; property PLenderNum: String read GetPLenderNum write SetPLenderNum; property PLoanNum: String read GetPLoanNum write SetPLoanNum; property PCollNum: Integer read GetPCollNum write SetPCollNum; property PXLoanNum: String read GetPXLoanNum write SetPXLoanNum; property PXCollNum: Integer read GetPXCollNum write SetPXCollNum; published property Active write SetActive; property EnumIndex: TEITTSPLDG read GetEnumIndex write SetEnumIndex; end; { TTTSPLDGTable } procedure Register; implementation procedure TTTSPLDGTable.CreateFields; begin FDFLenderNum := CreateField( 'LenderNum' ) as TStringField; FDFLoanNum := CreateField( 'LoanNum' ) as TStringField; FDFXLoanNum := CreateField( 'XLoanNum' ) as TStringField; FDFXCollNum := CreateField( 'XCollNum' ) as TIntegerField; FDFCollNum := CreateField( 'CollNum' ) as TIntegerField; end; { TTTSPLDGTable.CreateFields } procedure TTTSPLDGTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TTTSPLDGTable.SetActive } procedure TTTSPLDGTable.SetPLenderNum(const Value: String); begin DFLenderNum.Value := Value; end; function TTTSPLDGTable.GetPLenderNum:String; begin result := DFLenderNum.Value; end; procedure TTTSPLDGTable.SetPLoanNum(const Value: String); begin DFLoanNum.Value := Value; end; function TTTSPLDGTable.GetPLoanNum:String; begin result := DFLoanNum.Value; end; procedure TTTSPLDGTable.SetPCollNum(const Value: Integer); begin DFCollNum.Value := Value; end; function TTTSPLDGTable.GetPCollNum:Integer; begin result := DFCollNum.Value; end; procedure TTTSPLDGTable.SetPXLoanNum(const Value: String); begin DFXLoanNum.Value := Value; end; function TTTSPLDGTable.GetPXLoanNum:String; begin result := DFXLoanNum.Value; end; procedure TTTSPLDGTable.SetPXCollNum(const Value: Integer); begin DFXCollNum.Value := Value; end; function TTTSPLDGTable.GetPXCollNum:Integer; begin result := DFXCollNum.Value; end; procedure TTTSPLDGTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('LenderNum, String, 4, N'); Add('LoanNum, String, 20, N'); Add('XLoanNum, String, 20, N'); Add('XCollNum, Integer, 0, N'); Add('CollNum, Integer, 0, N'); end; end; procedure TTTSPLDGTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, LenderNum;LoanNum;XLoanNum;XCollNum, Y, Y, N, N'); Add('ByCross, LenderNum;XLoanNum;XCollNum, N, N, N, N'); Add('ByLoanColl, LenderNum;LoanNum;CollNum, N, N, N, N'); end; end; procedure TTTSPLDGTable.SetEnumIndex(Value: TEITTSPLDG); begin case Value of TTSPLDGPrimaryKey : IndexName := ''; TTSPLDGByCross : IndexName := 'ByCross'; TTSPLDGBYLoanColl : IndexName := 'ByLoanColl'; end; end; function TTTSPLDGTable.GetDataBuffer:TTTSPLDGRecord; var buf: TTTSPLDGRecord; begin fillchar(buf, sizeof(buf), 0); buf.PLenderNum := DFLenderNum.Value; buf.PLoanNum := DFLoanNum.Value; buf.PXLoanNum := DFXLoanNum.Value; buf.PXCollNum := DFXCollNum.Value; buf.PCollNum := DFCollNum.Value; result := buf; end; procedure TTTSPLDGTable.StoreDataBuffer(ABuffer:TTTSPLDGRecord); begin DFLenderNum.Value := ABuffer.PLenderNum; DFLoanNum.Value := ABuffer.PLoanNum; DFXLoanNum.Value := ABuffer.PXLoanNum; DFXCollNum.Value := ABuffer.PXCollNum; DFCollNum.Value := ABuffer.PCollNum; end; function TTTSPLDGTable.GetEnumIndex: TEITTSPLDG; var iname : string; begin result := TTSPLDGPrimaryKey; iname := uppercase(indexname); if iname = '' then result := TTSPLDGPrimaryKey; if iname = 'BYCROSS' then result := TTSPLDGByCross; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'TTS Tables', [ TTTSPLDGTable, TTTSPLDGBuffer ] ); end; { Register } function TTTSPLDGBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..5] of string = ('LENDERNUM','LOANNUM','XLOANNUM','XCOLLNUM','COLLNUM' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 5) and (flist[x] <> s) do inc(x); if x <= 5 then result := x else result := 0; end; function TTTSPLDGBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftString; 4 : result := ftInteger; 5 : result := ftInteger; end; end; function TTTSPLDGBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PLenderNum; 2 : result := @Data.PLoanNum; 3 : result := @Data.PXLoanNum; 4 : result := @Data.PXCollNum; 5 : result := @Data.PCollNum; end; end; end.
{ Double Commander ------------------------------------------------------------------------- Take a single file and split it in part based on few parameters. Copyright (C) 2018 Alexander Koblov (alexx2000@mail.ru) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Original comment: ----------------- Seksi Commander ---------------------------- Licence : GNU GPL v 2.0 Author : Pavel Letko (letcuv@centrum.cz) File splitter contributors: Radek Cervinka } unit fSplitter; {$mode objfpc}{$H+} interface uses //Lazarus, Free-Pascal, etc. SysUtils, Classes, Controls, Forms, Dialogs, StdCtrls, Buttons, Menus, //DC uFileSource, uFile; type { TfrmSplitter } TfrmSplitter = class(TForm) teNumberParts: TEdit; grbxFile: TGroupBox; edFileSource: TEdit; lblNumberParts: TLabel; lbFileSource: TLabel; edDirTarget: TEdit; lbDirTarget: TLabel; btnFTChoice: TButton; grbxSize: TGroupBox; cmbxSize: TComboBox; btnOK: TButton; btnCancel: TButton; rbtnKiloB: TRadioButton; rbtnMegaB: TRadioButton; rbtnGigaB: TRadioButton; rbtnByte: TRadioButton; btnRelativeFTChoice: TSpeedButton; cbRequireACRC32VerificationFile: TCheckBox; pmPathHelper: TPopupMenu; procedure btnFTChoiceClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure SetNumberOfPart; procedure SetSizeOfPart; procedure cmbxSizeChange(Sender: TObject); procedure btnRelativeFTChoiceClick(Sender: TObject); procedure rbtnByteChange(Sender: TObject); procedure teNumberPartsChange(Sender: TObject); procedure btnOKClick(Sender: TObject); procedure FormClose(Sender: TObject; var {%H-}CloseAction: TCloseAction); private { Private declarations } MyModalResult: integer; function StrConvert(sExpression: String): Int64; public { Public declarations } iVolumeNumber: Integer; iVolumeSize: int64; end; { ShowSplitterFileForm: "TMainCommands.cm_FileSpliter" function from "uMainCommands.pas" is calling this routine.} function ShowSplitterFileForm(aFileSource: IFileSource; var aFile: TFile; const TargetPath: String): Boolean; implementation {$R *.lfm} uses //Lazarus, Free-Pascal, etc. LazUTF8, LCLType, LCLProc, //DC uTypes, DCStrUtils, uLng, uFileProcs, uOperationsManager, uFileSourceSplitOperation, uShowMsg, DCOSUtils, uGlobs, uSpecialDir, uDCUtils; { ShowSplitterFileForm: "TMainCommands.cm_FileSpliter" function from "uMainCommands.pas" is calling this routine.} function ShowSplitterFileForm(aFileSource: IFileSource; var aFile: TFile; const TargetPath: String): Boolean; var Operation: TFileSourceSplitOperation = nil; frmSplitter:TfrmSplitter; begin frmSplitter:=TfrmSplitter.Create(Application); //Did not use the "with..." here to make absolutely sure of what is referenced in the following. try frmSplitter.edFileSource.Text:= aFile.FullPath; frmSplitter.edDirTarget.Text:= TargetPath; frmSplitter.SetNumberOfPart; // Show form Result:= (frmSplitter.ShowModal = mrOK); if Result then begin try Operation:= aFileSource.CreateSplitOperation(aFile, frmSplitter.edDirTarget.Text) as TFileSourceSplitOperation; if Assigned(Operation) then begin Operation.VolumeSize:= frmSplitter.iVolumeSize; Operation.VolumeNumber:= frmSplitter.iVolumeNumber; Operation.RequireACRC32VerificationFile:= frmSplitter.cbRequireACRC32VerificationFile.Checked; Operation.AutomaticSplitMode:=(frmSplitter.cmbxSize.ItemIndex=0); OperationsManager.AddOperation(Operation); end; finally FreeThenNil(aFile); end; end; finally frmSplitter.Free; end; end; { TfrmSplitter.SetNumberOfPart } procedure TfrmSplitter.SetNumberOfPart; begin if cmbxSize.ItemIndex<>0 then begin if StrConvert(cmbxSize.Text)>0 then begin if mbFileSize(edFileSource.Text) mod StrConvert(cmbxSize.Text)>0 then teNumberParts.Text:= IntToStr( (mbFileSize(edFileSource.Text) div StrConvert(cmbxSize.Text)) +1) else teNumberParts.Text:= IntToStr(mbFileSize(edFileSource.Text) div StrConvert(cmbxSize.Text)); end else begin teNumberParts.Text:=rsSimpleWordError; end; end else begin teNumberParts.Text:=rsMSgUndeterminedNumberOfFile; end; end; { TfrmSplitter.SetSizeOfPart } procedure TfrmSplitter.SetSizeOfPart; begin if StrToInt64Def(teNumberParts.Text,0)>0 then begin if mbFileSize(edFileSource.Text) mod StrToInt64Def(teNumberParts.Text,0)>0 then cmbxSize.Text := IntToStr(mbFileSize(edFileSource.Text) div StrToInt64Def(teNumberParts.Text, 0) + 1) else cmbxSize.Text := IntToStr(mbFileSize(edFileSource.Text) div StrToInt64Def(teNumberParts.Text, 0)); rbtnByte.Checked := True; rbtnByte.Enabled := True; rbtnKiloB.Enabled := True; rbtnMegaB.Enabled := True; rbtnGigaB.Enabled := True; end else begin cmbxSize.Text:=rsSimpleWordError; end; end; { TfrmSplitter.btnFTChoiceClick } procedure TfrmSplitter.btnFTChoiceClick(Sender: TObject); var sDir: string; begin if SelectDirectory(rsSplitSelDir, edDirTarget.Text, sDir) then // Select directory: // must change on linux!!! begin edDirTarget.Text:= sDir; end; end; { TfrmSplitter.StrConvert } //Let's do a basic conversion that maybe is not a full idiot-proof, but versatile and simple enough to fit in a few lines. function TfrmSplitter.StrConvert(sExpression:string):int64; var iMult: int64 = 1; bUseRadioButtons: boolean = True; procedure CheckIfMemSizeAndSetMultiplicator(sExpressionToCheck:string; iMultiplicatorToSetIfAny:int64); var iSeekPos: integer; begin iSeekPos := pos(UTF8LowerCase(sExpressionToCheck), sExpression); if iSeekPos <> 0 then begin iMult := iMultiplicatorToSetIfAny; sExpression := UTF8LeftStr(sExpression, pred(iSeekPos)); bUseRadioButtons := False; end; end; begin //1.Let's place string in lowercase to avoid any later problem. sExpression := UTF8LowerCase(sExpression); //2.Let's check first if we have the personalized unit in the expression. // We check first since they may include spaces and byte suffix. CheckIfMemSizeAndSetMultiplicator(gSizeDisplayUnits[fsfPersonalizedByte], 1); CheckIfMemSizeAndSetMultiplicator(gSizeDisplayUnits[fsfPersonalizedKilo], 1024); CheckIfMemSizeAndSetMultiplicator(gSizeDisplayUnits[fsfPersonalizedMega], 1024*1024); CheckIfMemSizeAndSetMultiplicator(gSizeDisplayUnits[fsfPersonalizedGiga], 1024*1024*1024); //4.Let's check if there are single letter multiplier or byte suffix. CheckIfMemSizeAndSetMultiplicator(rsLegacyOperationByteSuffixLetter, 1); CheckIfMemSizeAndSetMultiplicator(rsLegacyDisplaySizeSingleLetterKilo, 1024); CheckIfMemSizeAndSetMultiplicator(rsLegacyDisplaySizeSingleLetterMega, 1024*1024); CheckIfMemSizeAndSetMultiplicator(rsLegacyDisplaySizeSingleLetterGiga, 1024*1024*1024); //5. Well... It looks like the pre-defined disk size strings has not been translated in all languages so let's simplify with english values... //NO NEED TO TRANSLATE THESE ONES! Either translate all disk size strings and/or accept that english abbreviation always work here. CheckIfMemSizeAndSetMultiplicator('B', 1); CheckIfMemSizeAndSetMultiplicator('K', 1024); CheckIfMemSizeAndSetMultiplicator('M', 1024*1024); CheckIfMemSizeAndSetMultiplicator('G', 1024*1024*1024); //5.We remove the spaces since they are irrevelant. sExpression := UTF8StringReplace(sExpression, ' ', '', [rfReplaceAll]); //6.If we return a number here, let's disable the unit selector below. if cmbxSize.Focused then begin rbtnByte.Enabled := bUseRadioButtons; rbtnKiloB.Enabled := bUseRadioButtons; rbtnMegaB.Enabled := bUseRadioButtons; rbtnGigaB.Enabled := bUseRadioButtons; end; //7.If we return a number here, let's disable the unit selector below. if bUseRadioButtons then begin if rbtnKiloB.Checked then iMult:=1024; if rbtnMegaB.Checked then iMult:=1024*1024; if rbtnGigaB.Checked then iMult:=1024*1024*1024; end; //7.Since we're now supposed to have just numbers in our string, we should be ready to do our conversion. result := StrToInt64Def(sExpression, 0) * iMult; end; { TfrmSplitter.FormCreate } procedure TfrmSplitter.FormCreate(Sender: TObject); begin InitPropStorage(Self); // Initialize property storage MyModalResult:=mrCancel; gSpecialDirList.PopulateMenuWithSpecialDir(pmPathHelper,mp_PATHHELPER,nil); ParseLineToList(rsSplitPreDefinedSizes, cmbxSize.Items); end; { TfrmSplitter.rbtnByteChange } procedure TfrmSplitter.rbtnByteChange(Sender: TObject); const sDigits:string='0123456789'; var iFirstNonDigit: integer = 0; iIndex: integer; sExpression, sSanitize: string; begin if rbtnByte.focused OR rbtnKiloB.focused OR rbtnMegaB.focused OR rbtnGigaB.focused then begin if TRadioButton(Sender).Checked then begin sExpression := UTF8StringReplace(cmbxSize.Text, ' ', '', [rfIgnoreCase , rfReplaceAll]); sSanitize := ''; iFirstNonDigit := 0; for iIndex := 1 to UTF8Length(sExpression) do begin if (UTF8Pos(UTF8Copy(sExpression, iIndex, 1), sDigits) = 0) then begin if iFirstNonDigit = 0 then iFirstNonDigit := iIndex; end else begin if iIndex=UTF8Length(sExpression) then iFirstNonDigit := succ(iIndex); end; end; if iFirstNonDigit <> 0 then sSanitize:=UTF8LeftStr(sExpression, pred(iFirstNonDigit)); cmbxSize.Text := sSanitize; SetNumberOfPart; end; end; end; { TfrmSplitter.btnRelativeFTChoiceClick } procedure TfrmSplitter.btnRelativeFTChoiceClick(Sender: TObject); begin edDirTarget.SetFocus; gSpecialDirList.SetSpecialDirRecipientAndItsType(edDirTarget,pfPATH); pmPathHelper.PopUp(Mouse.CursorPos.X, Mouse.CursorPos.Y); end; { TfrmSplitter.cmbxSizeChange } procedure TfrmSplitter.cmbxSizeChange(Sender: TObject); begin if cmbxSize.Focused then //Do the function ONLY-IF it's the result of someone typing in the field begin if cmbxSize.ItemIndex<>0 then begin SetNumberOfPart; end else begin teNumberParts.Text:=''; if teNumberParts.CanFocus then teNumberParts.SetFocus; SetSizeOfPart; end; end; end; { TfrmSplitter.teNumberPartsChange } procedure TfrmSplitter.teNumberPartsChange(Sender: TObject); begin if teNumberParts.Focused then SetSizeOfPart; //Do the function ONLY-IF it's the result of someone typing in the field end; { TfrmSplitter.btnOKClick } procedure TfrmSplitter.btnOKClick(Sender: TObject); var isTooManyFiles: boolean; begin if cmbxSize.ItemIndex<>0 then iVolumeSize:= StrConvert(cmbxSize.Text) else iVolumeSize:=0; if (iVolumeSize <= 0) AND (cmbxSize.ItemIndex<>0) then begin ShowMessageBox(rsSplitErrFileSize, rsSimpleWordError+'!', MB_OK or MB_ICONERROR); //Incorrect file size format! (Used "ShowMessageBox" instead of "MsgError" 'cause with "MsgError", user can still click on the frmSplitter form and type in it). end else begin if not mbForceDirectory(IncludeTrailingPathDelimiter(mbExpandFileName(edDirTarget.Text))) then begin ShowMessageBox(rsSplitErrDirectory, rsSimpleWordError+'!', MB_OK or MB_ICONERROR); //Unable to create target directory! end else begin if teNumberParts.Text <> rsMSgUndeterminedNumberOfFile then iVolumeNumber := StrToInt(teNumberParts.Text) else iVolumeNumber := 0; if (iVolumeNumber < 1) AND (teNumberParts.Text <> rsMSgUndeterminedNumberOfFile) then begin ShowMessageBox(rsSplitErrSplitFile, rsSimpleWordError+'!', MB_OK or MB_ICONERROR); //Unable to split the file! end else begin isTooManyFiles:=(iVolumeNumber > 100); if isTooManyFiles then isTooManyFiles:=(MessageDlg(Caption, rsSplitMsgManyParts, mtWarning, mbYesNo, 0) <> mrYes); if not isTooManyFiles then begin MyModalResult:=mrOk; close; end; //if isTooManyFiles then end; //if (iVolumeNumber = 0) then end; //if not mbForceDirectory(edDirTarget.Text) then end; //if iVolumeSize <= 0 then end; { TfrmSplitter.FormClose } procedure TfrmSplitter.FormClose(Sender: TObject; var CloseAction: TCloseAction); begin modalResult := MyModalResult; end; end.
unit ExcelSaver; interface uses DataFileSaver, Classes, DB, System.StrUtils; const MAX_ROW_PER_FILE = 50;//65530; type TExcelSaver = class(TAbsFileSaver) private // CXlsBof: array[0..5] of Word; // CXlsEof: array[0..1] of Word; // CXlsLabel: array[0..5] of Word; // CXlsNumber: array[0..4] of Word; // CXlsRk: array[0..4] of Word; FStream: TStream; FDataSet: TDataSet; FCurrPage: Integer; protected procedure XlsBeginStream(XlsStream: TStream; const BuildNumber: Word); procedure XlsEndStream(XlsStream: TStream); procedure XlsWriteCellRk(XlsStream: TStream; const ACol, ARow: Word; const AValue: Integer); procedure XlsWriteCellNumber(XlsStream: TStream; const ACol, ARow: Word; const AValue: Double); procedure XlsWriteCellLabel(XlsStream: TStream; const ACol, ARow: Word; const AValue: string); function WideStringToString(const ws: WideString; codePage: Word): AnsiString; function IsStringType( fieldType: TFieldType ): Boolean; function IsDoubleType( fieldType: TFieldType ): Boolean; function IsIntegerType( fieldType: TFieldType ): Boolean; function IsTimeType( fieldType: TFieldType ): Boolean; function GetFieldType( fieldType: TFieldType ): TFieldType; procedure AppendColumnName; procedure AppendStrField(colNum: Integer); procedure AppendDblField(colNum: Integer); procedure AppendIntField(colNum: Integer); procedure AppendTimeField(colNum: Integer); public constructor Create(); function SaveTo(data: TDataSet; filePath: String): Boolean; overload; override; function SaveTo(dataIter: IDataSetIterator; filePath: String): Integer; overload; override; function SaveToMulti(data: TDataSet; filePath: String): Boolean; end; implementation uses Windows, System.Variants, SysUtils; var CXlsBof: array[0..5] of Word = ($809, 8, 00, $10, 0, 0); CXlsEof: array[0..1] of Word = ($0A, 00); CXlsLabel: array[0..5] of Word = ($204, 0, 0, 0, 0, 0); CXlsNumber: array[0..4] of Word = ($203, 14, 0, 0, 0); CXlsRk: array[0..4] of Word = ($27E, 10, 0, 0, 0); { TExcelSaver } function TExcelSaver.SaveTo(data: TDataSet; filePath: String): Boolean; var bRet: Boolean; i: Integer; fieldType: TFieldType; begin FCurrPage := 0; bRet := true; FDataSet := data; FStream := TFileStream.Create( filePath, fmCreate ); try XlsBeginStream( FStream, 0 ); AppendColumnName; for i := 0 to FDataSet.FieldCount - 1 do begin fieldType := GetFieldType( FDataSet.Fields[ i ].DataType ); case fieldType of ftFloat: AppendDblField( i ); ftInteger: AppendIntField( i ); ftString: AppendStrField( i ); ftTime: AppendTimeField( i ); end; end; // for I := 0 to 99 do // for J := 0 to 99 do // begin //// XlsWriteCellNumber(FStream, I, J, 34.34); // // XlsWriteCellRk(FStream, I, J, 3434); //// XlsWriteCellLabel(FStream, I, J, Format('Cell: %d,%d', [I, J])); // end; XlsEndStream( FStream ); except bRet := false; end; FStream.Free; result := bRet; end; function TExcelSaver.SaveTo(dataIter: IDataSetIterator; filePath: String): Integer; var iRet: Integer; bSaveResult: Boolean; sFilePath: String; begin iRet := 0; while dataIter.MoveNext do begin sFilePath := StringReplace( filePath, '.xls', '_' + dataIter.CurName + '.xls', [ rfIgnoreCase ] ); bSaveResult := SaveTo( dataIter.CurData, sFilePath ); if bSaveResult = true then Inc( iRet ); end; dataIter.MoveFirst; result := iRet; end; function TExcelSaver.SaveToMulti(data: TDataSet; filePath: String): Boolean; var bRet: Boolean; i: Integer; fieldType: TFieldType; iFileCount: Integer; iFileMax: Integer; begin bRet := true; FDataSet := data; iFileCount := 0; iFileMax := data.RecordCount div MAX_ROW_PER_FILE; for iFileCount := 0 to iFileMax do begin FStream := TFileStream.Create( StringReplace( filePath, '.xls', IntToStr( iFileCount ) + '.xls', [rfReplaceAll] ), fmCreate ); try XlsBeginStream( FStream, 0 ); AppendColumnName; for i := 0 to FDataSet.FieldCount - 1 do begin fieldType := GetFieldType( FDataSet.Fields[ i ].DataType ); case fieldType of ftFloat: AppendDblField( i ); ftInteger: AppendIntField( i ); ftString: AppendStrField( i ); ftTime: AppendTimeField( i ); end; FDataSet.MoveBy( iFileCount * MAX_ROW_PER_FILE ) end; // for I := 0 to 99 do // for J := 0 to 99 do // begin //// XlsWriteCellNumber(FStream, I, J, 34.34); // // XlsWriteCellRk(FStream, I, J, 3434); //// XlsWriteCellLabel(FStream, I, J, Format('Cell: %d,%d', [I, J])); // end; XlsEndStream( FStream ); FDataSet.MoveBy( ( iFileCount + 1 ) * MAX_ROW_PER_FILE ) except bRet := false; end; end; FStream.Free; result := bRet; end; procedure TExcelSaver.AppendTimeField(colNum: Integer); var iRow: Integer; field: TField; sValue: String; begin iRow := 1; field := FDataSet.Fields[ colNum ]; while FDataSet.Eof = false do begin sValue := VarToStr( field.Value ); sValue := ReplaceStr( sValue, '¿ÀÀü', 'AM' ); sValue := ReplaceStr( sValue, '¿ÀÈÄ', 'PM' ); XlsWriteCellLabel( FStream, colNum, iRow, sValue ); FDataSet.Next; Inc( iRow ); end; FDataSet.First; end; procedure TExcelSaver.AppendColumnName; var i: Integer; begin for i := 0 to FDataSet.FieldCount - 1 do begin XlsWriteCellLabel( Fstream, i, 0, FDataSet.Fields[ i ].FieldName ); end; end; procedure TExcelSaver.AppendDblField(colNum: Integer); var iRow: Integer; field: TField; begin iRow := 1; field := FDataSet.Fields[ colNum ]; while FDataSet.Eof = false do begin XlsWriteCellNumber( FStream, colNum, iRow, field.Value ); FDataSet.Next; Inc( iRow ); end; FDataSet.First; end; procedure TExcelSaver.AppendIntField(colNum: Integer); var iRow: Integer; field: TField; begin iRow := 1; field := FDataSet.Fields[ colNum ]; while FDataSet.Eof = false do begin XlsWriteCellRk( FStream, colNum, iRow, field.Value ); FDataSet.Next; Inc( iRow ); end; FDataSet.First; end; procedure TExcelSaver.AppendStrField(colNum: Integer); var iRow: Integer; field: TField; begin iRow := 1; field := FDataSet.Fields[ colNum ]; while FDataSet.Eof = false do begin XlsWriteCellLabel( FStream, colNum, iRow, field.Value ); FDataSet.Next; Inc( iRow ); end; FDataSet.First; end; constructor TExcelSaver.Create; begin inherited; end; function TExcelSaver.GetFieldType(fieldType: TFieldType): TFieldType; begin if IsDoubleType( fieldType ) = true then result := ftFloat else if IsIntegerType( fieldType ) = true then result := ftInteger else if IsStringType( fieldType ) = true then result := ftString else if IsTimeType( fieldType ) = true then result := ftTime else result := ftString; end; function TExcelSaver.IsDoubleType(fieldType: TFieldType): Boolean; begin result := ( fieldType = ftFloat ) or ( fieldType = ftSingle ); end; function TExcelSaver.IsIntegerType(fieldType: TFieldType): Boolean; begin result := ( fieldType = ftSmallint ) or ( fieldType = ftInteger ) or ( fieldType = ftWord ) or ( fieldType = ftBytes ) or ( fieldType = ftLargeint ); end; function TExcelSaver.IsStringType(fieldType: TFieldType): Boolean; begin result := ( fieldType = ftDate ) or ( fieldType = ftString ) or ( fieldType = ftMemo ); end; function TExcelSaver.IsTimeType(fieldType: TFieldType): Boolean; begin result := ( fieldType = ftDateTime ) or ( fieldType = ftTime ) or ( fieldType = ftTimeStamp ); end; procedure TExcelSaver.XlsBeginStream(XlsStream: TStream; const BuildNumber: Word); begin CXlsBof[4] := BuildNumber; XlsStream.WriteBuffer(CXlsBof, SizeOf(CXlsBof)); end; procedure TExcelSaver.XlsEndStream(XlsStream: TStream); begin XlsStream.WriteBuffer(CXlsEof, SizeOf(CXlsEof)); end; procedure TExcelSaver.XlsWriteCellRk(XlsStream: TStream; const ACol, ARow: Word; const AValue: Integer); var V: Integer; begin CXlsRk[2] := ARow; CXlsRk[3] := ACol; XlsStream.WriteBuffer(CXlsRk, SizeOf(CXlsRk)); V := (AValue shl 2) or 2; XlsStream.WriteBuffer(V, 4); end; procedure TExcelSaver.XlsWriteCellNumber(XlsStream: TStream; const ACol, ARow: Word; const AValue: Double); begin CXlsNumber[2] := ARow; CXlsNumber[3] := ACol; XlsStream.WriteBuffer(CXlsNumber, SizeOf(CXlsNumber)); XlsStream.WriteBuffer(AValue, 8); end; procedure TExcelSaver.XlsWriteCellLabel(XlsStream: TStream; const ACol, ARow: Word; const AValue: string); var L: Word; begin L := Length(AValue); CXlsLabel[1] := 8 + L; CXlsLabel[2] := ARow; CXlsLabel[3] := ACol; CXlsLabel[5] := L; XlsStream.WriteBuffer(CXlsLabel, SizeOf(CXlsLabel)); XlsStream.WriteBuffer(Pointer( WideStringToString(AValue, CP_OEMCP) )^, L); end; function TExcelSaver.WideStringToString(const ws: WideString; codePage: Word): AnsiString; var l: integer; begin if ws = '' then Result := '' else begin l := WideCharToMultiByte(codePage, WC_COMPOSITECHECK or WC_DISCARDNS or WC_SEPCHARS or WC_DEFAULTCHAR, @ws[1], - 1, nil, 0, nil, nil); SetLength(Result, l - 1); if l > 1 then WideCharToMultiByte(codePage, WC_COMPOSITECHECK or WC_DISCARDNS or WC_SEPCHARS or WC_DEFAULTCHAR, @ws[1], - 1, @Result[1], l - 1, nil, nil); end; end; { WideStringToString } end.
unit nsDataExchangeProxy; // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\Search\nsDataExchangeProxy.pas" // Стереотип: "SimpleClass" // Элемент модели: "TnsDataExchangeProxy" MUID: (54FEC834013B) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If NOT Defined(Admin)} uses l3IntfUses , l3ProtoDataContainer , DynamicDocListUnit , bsTypes ; type TnsDataExchangeProxy = class; InsDataExchangeSubscriber = interface ['{20C77FB9-BA8F-42A3-8DA2-CA5B86F19816}'] procedure MakeAndOpenList(const aList: IDynList; aOpenFrom: TbsListOpenFrom = bsTypes.lofNone); end;//InsDataExchangeSubscriber TnsDataExchangeProxy = class(Tl3ProtoDataContainer) private f_Subscriber: InsDataExchangeSubscriber; protected procedure pm_SetSubscriber(const aValue: InsDataExchangeSubscriber); procedure Cleanup; override; {* Функция очистки полей объекта. } procedure ClearFields; override; public procedure MakeAndOpenList(const aList: IDynList; aOpenFrom: TbsListOpenFrom = bsTypes.lofNone); class function Instance: TnsDataExchangeProxy; {* Метод получения экземпляра синглетона TnsDataExchangeProxy } class function Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } public property Subscriber: InsDataExchangeSubscriber read f_Subscriber write pm_SetSubscriber; end;//TnsDataExchangeProxy {$IfEnd} // NOT Defined(Admin) implementation {$If NOT Defined(Admin)} uses l3ImplUses , SysUtils , l3Base //#UC START# *54FEC834013Bimpl_uses* //#UC END# *54FEC834013Bimpl_uses* ; var g_TnsDataExchangeProxy: TnsDataExchangeProxy = nil; {* Экземпляр синглетона TnsDataExchangeProxy } procedure TnsDataExchangeProxyFree; {* Метод освобождения экземпляра синглетона TnsDataExchangeProxy } begin l3Free(g_TnsDataExchangeProxy); end;//TnsDataExchangeProxyFree procedure TnsDataExchangeProxy.pm_SetSubscriber(const aValue: InsDataExchangeSubscriber); //#UC START# *54FEC8BB0295_54FEC834013Bset_var* //#UC END# *54FEC8BB0295_54FEC834013Bset_var* begin //#UC START# *54FEC8BB0295_54FEC834013Bset_impl* if Assigned(f_Subscriber) and Assigned(aValue) and (f_Subscriber <> aValue) then Assert(False); f_Subscriber := aValue; //#UC END# *54FEC8BB0295_54FEC834013Bset_impl* end;//TnsDataExchangeProxy.pm_SetSubscriber procedure TnsDataExchangeProxy.MakeAndOpenList(const aList: IDynList; aOpenFrom: TbsListOpenFrom = bsTypes.lofNone); //#UC START# *54FEC90002B4_54FEC834013B_var* //#UC END# *54FEC90002B4_54FEC834013B_var* begin //#UC START# *54FEC90002B4_54FEC834013B_impl* if Assigned(f_Subscriber) then f_Subscriber.MakeAndOpenList(aList, aOpenFrom); //#UC END# *54FEC90002B4_54FEC834013B_impl* end;//TnsDataExchangeProxy.MakeAndOpenList class function TnsDataExchangeProxy.Instance: TnsDataExchangeProxy; {* Метод получения экземпляра синглетона TnsDataExchangeProxy } begin if (g_TnsDataExchangeProxy = nil) then begin l3System.AddExitProc(TnsDataExchangeProxyFree); g_TnsDataExchangeProxy := Create; end; Result := g_TnsDataExchangeProxy; end;//TnsDataExchangeProxy.Instance class function TnsDataExchangeProxy.Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } begin Result := g_TnsDataExchangeProxy <> nil; end;//TnsDataExchangeProxy.Exists procedure TnsDataExchangeProxy.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_54FEC834013B_var* //#UC END# *479731C50290_54FEC834013B_var* begin //#UC START# *479731C50290_54FEC834013B_impl* f_Subscriber := nil; inherited; //#UC END# *479731C50290_54FEC834013B_impl* end;//TnsDataExchangeProxy.Cleanup procedure TnsDataExchangeProxy.ClearFields; begin Subscriber := nil; inherited; end;//TnsDataExchangeProxy.ClearFields {$IfEnd} // NOT Defined(Admin) end.
unit vg_canvas_cairo; {$ALIGN ON} {$MINENUMSIZE 4} {$I vg_define.inc} {.$DEFINE FLATTEN} {$DEFINE TEXTFLATTEN} interface uses {$IFDEF LINUX} cairo, cairoXlib, xlib, x,xutil, gtk2def, gtk2proc, gtk2, gdk2, gdk2x, gdk2pixbuf, glib2, pango, {$ENDIF} {$IFDEF WIN32} Cairo, {$ENDIF} {$IFDEF FPC} LCLProc, {$ENDIF} Graphics, Classes, SysUtils, Math, vg_scene; const merge3 = 0; {$IFDEF LINUX} {$ifdef win32} {$define pangowin} pangocairolib = 'libpangocairo-1.0-0.dll'; {$IFDEF FPC} {$ifndef NO_SMART_LINK} {$smartlink on} {$endif} {$ENDIF} {$else} {$ifdef UseCustomLibs} pangocairolib = ''; {$else} pangocairolib = 'libpangocairo-1.0.so.0'; gdkcairolib = 'libgdkcairo-1.0.so.0'; {$endif} {$endif} {$IFDEF LINUX} type PGInputStream = Pointer; function g_memory_input_stream_new_from_data(const Data: Pointer; size: gssize; Notify: Pointer): PGInputStream; cdecl; external gliblib; procedure gdk_cairo_set_source_pixbuf(cr: Pcairo_t; const Pb: PGdkPixbuf; const x, y: double); cdecl; external LIB_CAIRO; function gdk_pixbuf_get_file_info(filename:Pchar; var width, height: gint): integer; cdecl; external gdkpixbuflib; function gdk_pixbuf_new_from_stream(stream: PGInputStream; Cancelable: pointer; error:PPGError):PGdkPixbuf; cdecl; external gdkpixbuflib; function gdk_pixbuf_save_to_buffer(pb: PGdkPixbuf; var bug: PByte; var Len: gsize; const typ: PChar; Error: Pointer): gboolean; cdecl; external gdkpixbuflib; function gdk_pixbuf_save_to_bufferv(pb: PGdkPixbuf; var bug: PByte; var Len: gsize; const typ: PChar; option_keys:PPchar; option_values:PPchar; Error: Pointer): gboolean; cdecl; external gdkpixbuflib; function gdk_screen_get_rgba_colormap(const screen: PGdkScreen): PGdkColormap; cdecl; external gdklib; procedure gdk_window_set_composited(window: PGdkWindow; Composited: gboolean); cdecl; external gdklib; procedure cairo_path_extents(cr: Pcairo_t; var x1, y1, x2, y2: double); cdecl; external LIB_CAIRO; function gdk_cairo_create(drawable: PGdkDrawable): Pcairo_t; cdecl; external LIB_CAIRO; function pango_cairo_create_context(cr: Pcairo_t): PPangoContext; cdecl; external pangocairolib; function pango_cairo_create_layout(cr: Pcairo_t): PPangoLayout; cdecl; external pangocairolib; procedure pango_cairo_update_layout(cr: Pcairo_t; layout: PPangoLayout); cdecl; external pangocairolib; procedure pango_cairo_show_layout(cr: Pcairo_t; layout: PPangoLayout); cdecl; external pangocairolib; procedure pango_cairo_layout_path(cr: Pcairo_t; layout: PPangoLayout); cdecl; external pangocairolib; procedure pango_layout_set_height(layout:PPangoLayout; height:longint); cdecl; external pangolib; {$ENDIF} {$ENDIF} implementation {===============================================================} {$IFDEF LINUX} type { TvgFilterGtk } TvgFilterGtk = class(TvgFilter) private public published class function GetFileTypes: string; override; class function GetImageSize(const AFileName: string): TvgPoint; override; function LoadFromFile(const AFileName: string; const Rotate: single; var Bitmap: TvgBitmap): boolean; override; function LoadThumbnailFromFile(const AFileName: string; const AFitWidth, AFitHeight: single; const UseEmbedded: boolean;var Bitmap: TvgBitmap): boolean; override; function SaveToFile(const AFileName: string; var Bitmap: TvgBitmap; const Params: string = ''): boolean; override; function LoadFromStream(const AStream: TStream; var Bitmap: TvgBitmap): boolean; override; function SaveToStream(const AStream: TStream; var Bitmap: TvgBitmap; const Format: string; const Params: string = ''): boolean; override; end; { TvgCanvasCairo } TvgCanvasCairo = class(TvgCanvas) private grad: Pcairo_pattern_t; sr: Pcairo_surface_t; memcr: Pcairo_t; memsr: Pcairo_surface_t; memlayout: PPangoLayout; protected procedure ApplyFill(ARect: TvgRect; const AOpacity: single); procedure DeapplyFill; procedure ApplyStroke(ARect: TvgRect; const AOpacity: single); procedure FontChanged(Sender: TObject); override; procedure UpdateBitmap(ABitmap: TvgBitmap); procedure DoDestroyBitmap(Sender: TObject); class function GetBitmapScanline(Bitmap: TvgBitmap; y: integer): PvgColorArray; override; public constructor Create(const AWidth, AHeight: integer); override; constructor CreateFromBitmap(const ABitmap: TvgBitmap); override; destructor Destroy; override; { buffer } procedure FreeBuffer; override; procedure ResizeBuffer(const AWidth, AHeight: integer); override; procedure FlushBuffer(const X, Y: integer; const DC: Cardinal); override; procedure FlushBufferRect(const X, Y: integer; const DC: Cardinal; const ARect: TvgRect); override; procedure Clear(const Color: cardinal); override; procedure ClearRect(const ARect: TvgRect; const AColor: TvgColor = 0); override; { matrix } procedure SetMatrix(const M: TvgMatrix); override; procedure MultyMatrix(const M: TvgMatrix); override; { cliping } function SaveCanvas: cardinal; override; procedure RestoreCanvas(const AState: cardinal); override; procedure SetClipRects(const ARects: array of TvgRect); override; procedure IntersectClipRect(const ARect: TvgRect); override; procedure ExcludeClipRect(const ARect: TvgRect); override; procedure ResetClipRect; override; { drawing } procedure DrawLine(const APt1, APt2: TvgPoint; const AOpacity: single); override; procedure FillRect(const ARect: TvgRect; const xRadius, yRadius: single; const ACorners: TvgCorners; const AOpacity: single; const ACornerType: TvgCornerType = vgCornerRound); override; procedure DrawRect(const ARect: TvgRect; const xRadius, yRadius: single; const ACorners: TvgCorners; const AOpacity: single; const ACornerType: TvgCornerType = vgCornerRound); override; procedure FillEllipse(const ARect: TvgRect; const AOpacity: single); override; procedure DrawEllipse(const ARect: TvgRect; const AOpacity: single); override; procedure FillText(const ARect, AClipRect: TvgRect; const AText: WideString; const WordWrap: boolean; const AOpacity: single; const ATextAlign: TvgTextAlign; const AVTextAlign: TvgTextAlign = vgTextAlignCenter); override; procedure MeasureText(var ARect: TvgRect; AClipRect: TvgRect; const AText: WideString; const WordWrap: boolean; const ATextAlign: TvgTextAlign; const AVTextAlign: TvgTextAlign = vgTextAlignCenter); override; function PtInPath(const APoint: TvgPoint; const ARect: TvgRect; const APath: TvgPathData): boolean; override; procedure FillPath(const APath: TvgPathData; const ARect: TvgRect; const AOpacity: single); override; procedure DrawPath(const APath: TvgPathData; const ARect: TvgRect; const AOpacity: single); override; procedure DrawBitmap(const ABitmap: TvgBitmap; const SrcRect, DstRect: TvgRect; const AOpacity: single; const HighSpeed: boolean = false); override; procedure DrawThumbnail(const ABitmap: TvgBitmap; const Width, Height: single); override; function TextToPath(Path: TvgPathData; const ARect: TvgRect; const AText: WideString; const WordWrap: boolean; const ATextAlign: TvgTextAlign; const AVTextAlign: TvgTextAlign = vgTextAlignCenter): boolean; override; published end; procedure SwapRB(const Buf: Pointer; const Size: integer); var i: integer; b: byte; begin for i := 0 to Size - 1 do begin b := PvgColorRecArray(Buf)[i].R; PvgColorRecArray(Buf)[i].R := PvgColorRecArray(Buf)[i].B; PvgColorRecArray(Buf)[i].B := b; end; end; { TvgFilterGtk } class function TvgFilterGtk.GetFileTypes: string; begin Result := '*.jpg;*.jpeg;*.gif;*.tif;*.tiff;*.png;*.bmp;*.JPG;*.JPEG;*.GIF;*.TIF;*.TIFF;*.PNG;*.BMP'; end; class function TvgFilterGtk.GetImageSize(const AFileName: string): TvgPoint; var W, H: gint; begin Result := vgPoint(0, 0); if gdk_pixbuf_get_file_info(PChar(AFileName), W, H) <> 0 then Result := vgPoint(W, H); end; function TvgFilterGtk.LoadFromStream(const AStream: TStream; var Bitmap: TvgBitmap): boolean; var GS: PGInputStream; res, pb: PGdkPixbuf; MS: TMemoryStream; begin Result := false; if AStream.Size = 0 then Exit; MS := TMemoryStream.Create; MS.CopyFrom(AStream, AStream.Size); GS := g_memory_input_stream_new_from_data(MS.Memory, MS.Size, nil); if GS <> nil then begin pb := gdk_pixbuf_new_from_stream(GS, nil, nil); if pb <> nil then begin Bitmap.SetSize(gdk_pixbuf_get_width(pb), gdk_pixbuf_get_Height(pb)); res := gdk_pixbuf_new_from_data(Pguchar(Bitmap.StartLine), GDK_COLORSPACE_RGB, true, 8, gdk_pixbuf_get_width(pb), gdk_pixbuf_get_Height(pb), gdk_pixbuf_get_width(pb) * 4, nil, nil); if res <> nil then begin gdk_pixbuf_copy_area(pb, 0, 0, gdk_pixbuf_get_width(pb), gdk_pixbuf_get_Height(pb), res, 0, 0); g_object_unref(res); { swap } SwapRB(Bitmap.Startline, Bitmap.Width * Bitmap.Height); Result := true; end; g_object_unref(pb); end; g_object_unref(GS); end; MS.Free; end; function TvgFilterGtk.SaveToStream(const AStream: TStream; var Bitmap: TvgBitmap; const Format: string; const Params: string = ''): boolean; var pb: PGdkPixbuf; buf: PByte; size: gsize; k, o: array [0..10] of PChar; param, name, value, S, encoderType, opts, keys: string; i: integer; begin Result := false; encoderType := 'png'; if (LowerCase(Format) = 'jpg') or (LowerCase(Format) = 'jpeg') then encoderType := 'jpeg'; if (LowerCase(Format) = 'bmp') then encoderType := 'bmp'; if (LowerCase(Format) = 'png') then encoderType := 'png'; if (LowerCase(Format) = 'tif') or (LowerCase(Format) = 'tiff') then encoderType := 'tif'; if (LowerCase(Format) = 'gif') then encoderType := 'gif'; pb := gdk_pixbuf_new_from_data(Pguchar(Bitmap.StartLine), GDK_COLORSPACE_RGB, true, 8, Bitmap.Width, Bitmap.Height, Bitmap.Width * 4, nil, nil); if pb <> nil then begin opts := ''; keys := ''; i := 0; if Params <> '' then begin S := Params; while S <> '' do begin param := vgGetToken(S, ' '); name := vgGetToken(param, '='); value := vgGetToken(param, ''); if CompareText(name, 'quality') = 0 then begin o[i] := PChar('quality'); k[i] := PChar(value); inc(i); end; end; o[i] := nil; k[i] := nil; SwapRB(Bitmap.Startline, Bitmap.Width * Bitmap.Height); if gdk_pixbuf_save_to_bufferv(pb, buf, size, PChar(encoderType), @o[0], @k[0], nil) then begin AStream.Write(buf^, size); g_free(buf); Result := true; end; SwapRB(Bitmap.Startline, Bitmap.Width * Bitmap.Height); end else begin SwapRB(Bitmap.Startline, Bitmap.Width * Bitmap.Height); if gdk_pixbuf_save_to_buffer(pb, buf, size, PChar(encoderType), nil) then begin AStream.Write(buf^, size); g_free(buf); Result := true; end; SwapRB(Bitmap.Startline, Bitmap.Width * Bitmap.Height); end; g_object_unref(pb); end; end; function TvgFilterGtk.LoadFromFile(const AFileName: string; const Rotate: single; var Bitmap: TvgBitmap): boolean; var res, pb: PGdkPixbuf; begin pb := gdk_pixbuf_new_from_file(PChar(AFileName), nil); if pb <> nil then begin Bitmap.SetSize(gdk_pixbuf_get_width(pb), gdk_pixbuf_get_Height(pb)); res := gdk_pixbuf_new_from_data(Pguchar(Bitmap.StartLine), GDK_COLORSPACE_RGB, true, 8, gdk_pixbuf_get_width(pb), gdk_pixbuf_get_Height(pb), gdk_pixbuf_get_width(pb) * 4, nil, nil); if res <> nil then begin gdk_pixbuf_copy_area(pb, 0, 0, gdk_pixbuf_get_width(pb), gdk_pixbuf_get_Height(pb), res, 0, 0); g_object_unref(res); SwapRB(Bitmap.Startline, Bitmap.Width * Bitmap.Height); Result := true; end; g_object_unref(pb); end else Result := false; end; function TvgFilterGtk.LoadThumbnailFromFile(const AFileName: string; const AFitWidth, AFitHeight: single; const UseEmbedded: boolean; var Bitmap: TvgBitmap): boolean; var res, pb: PGdkPixbuf; begin pb := gdk_pixbuf_new_from_file_at_scale(PChar(AFileName), round(AFitWidth), round(AFitHeight), true, nil); if pb <> nil then begin Bitmap.SetSize(gdk_pixbuf_get_width(pb), gdk_pixbuf_get_Height(pb)); res := gdk_pixbuf_new_from_data(Pguchar(Bitmap.StartLine), GDK_COLORSPACE_RGB, true, 8, gdk_pixbuf_get_width(pb), gdk_pixbuf_get_Height(pb), gdk_pixbuf_get_width(pb) * 4, nil, nil); if res <> nil then begin gdk_pixbuf_copy_area(pb, 0, 0, gdk_pixbuf_get_width(pb), gdk_pixbuf_get_Height(pb), res, 0, 0); g_object_unref(res); SwapRB(Bitmap.Startline, Bitmap.Width * Bitmap.Height); Result := true; end; g_object_unref(pb); end else Result := false; end; function TvgFilterGtk.SaveToFile(const AFileName: string; var Bitmap: TvgBitmap; const Params: string = ''): boolean; var pb: PGdkPixbuf; param, name, value, S, encoderType, opts, keys: string; i: integer; k, o: array [0..10] of PChar; begin Result := false; encoderType := 'png'; if (LowerCase(ExtractFileExt(AFileName)) = '.jpg') or (LowerCase(ExtractFileExt(AFileName)) = '.jpeg') then encoderType := 'jpeg'; if (LowerCase(ExtractFileExt(AFileName)) = '.bmp') then encoderType := 'bmp'; if (LowerCase(ExtractFileExt(AFileName)) = '.png') then encoderType := 'png'; if (LowerCase(ExtractFileExt(AFileName)) = '.tif') or (LowerCase(ExtractFileExt(AFileName)) = '.tiff') then encoderType := 'tiff'; if (LowerCase(ExtractFileExt(AFileName)) = '.gif') then encoderType := 'gif'; if encoderType = '' then Exit; pb := gdk_pixbuf_new_from_data(Pguchar(Bitmap.StartLine), GDK_COLORSPACE_RGB, true, 8, Bitmap.Width, Bitmap.Height, Bitmap.Width * 4, nil, nil); if pb <> nil then begin opts := ''; keys := ''; i := 0; if Params <> '' then begin S := Params; while S <> '' do begin param := vgGetToken(S, ' '); name := vgGetToken(param, '='); value := vgGetToken(param, ''); if CompareText(name, 'quality') = 0 then begin o[i] := PChar('quality'); k[i] := PChar(value); inc(i); end; end; o[i] := nil; k[i] := nil; SwapRB(Bitmap.Startline, Bitmap.Width * Bitmap.Height); Result := gdk_pixbuf_savev(pb, PChar(AFileName), PChar(encoderType), @o[0], @k[0], nil); SwapRB(Bitmap.Startline, Bitmap.Width * Bitmap.Height); end else begin SwapRB(Bitmap.Startline, Bitmap.Width * Bitmap.Height); Result := gdk_pixbuf_save(pb, PChar(AFileName), PChar(encoderType), nil); SwapRB(Bitmap.Startline, Bitmap.Width * Bitmap.Height); end; gdk_pixbuf_unref(pb); end; end; { TvgCanvasCairo } var CS: string; var ColorArray: array [0..100] of cardinal; OffsetArray: array [0..100] of single; constructor TvgCanvasCairo.Create(const AWidth, AHeight: integer); begin inherited ; memsr := cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 1, 1); memcr := cairo_create(memsr); memlayout := pango_cairo_create_layout(memcr); end; constructor TvgCanvasCairo.CreateFromBitmap(const ABitmap: TvgBitmap); begin inherited; memsr := cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 1, 1); memcr := cairo_create(memsr); memlayout := pango_cairo_create_layout(memcr); FBitmap := ABitmap; UpdateBitmap(FBitmap); if FBitmap.Handle <> 0 then FHandle := Integer(cairo_create(Pcairo_surface_t(FBitmap.Handle))) end; destructor TvgCanvasCairo.Destroy; begin g_object_unref(memlayout); cairo_destroy(memcr); cairo_surface_destroy(memsr); inherited; end; procedure TvgCanvasCairo.FreeBuffer; begin if (FBitmap <> nil) and (Handle <> 0) then begin cairo_destroy(Pcairo_t(Handle)); end; if FBufferBits <> nil then System.l3System.FreeLocalMem(FBufferBits); if FBuffered then begin cairo_destroy(Pcairo_t(Handle)); cairo_surface_destroy(sr); end; Handle := 0; end; procedure TvgCanvasCairo.ResizeBuffer(const AWidth, AHeight: integer); begin if (AWidth = FWidth) and (AHeight = FHeight) then Exit; FreeBuffer; FWidth := AWidth; FHeight := AHeight; if FWidth <= 0 then FWidth := 1; if FHeight <= 0 then FHeight := 1; FResized := true; if FWidth * FHeight = 0 then Exit; if FBuffered then begin l3System.GetLocalMem(FBufferBits, FWidth * FHeight * 4); sr := cairo_image_surface_create_for_data(FBufferBits, CAIRO_FORMAT_ARGB32, FWidth, FHeight, FWidth * 4); Handle := Integer(cairo_create(sr)); end else begin l3System.GetLocalMem(FBufferBits, 4); end; end; procedure TvgCanvasCairo.FlushBuffer(const X, Y: integer; const DC: Cardinal); begin end; procedure TvgCanvasCairo.FlushBufferRect(const X, Y: integer; const DC: Cardinal; const ARect: TvgRect); begin end; procedure TvgCanvasCairo.Clear(const Color: cardinal); begin if FBufferBits = nil then Exit; if not FBuffered then begin with TvgColorRec(Color) do cairo_set_source_rgba(Pcairo_t(Handle), R / $FF, G / $FF, B / $FF, A / $FF); cairo_paint(Pcairo_t(Handle)); end else vgFillLongword(FBufferBits, FWidth * FHeight, Color); end; procedure TvgCanvasCairo.ClearRect(const ARect: TvgRect; const AColor: TvgColor); var R: TRect; begin if FBufferBits = nil then Exit; R := Rect(Trunc(ARect.Left), Trunc(ARect.Top), Round(ARect.Right), Round(ARect.Bottom)); if R.Left < 0 then R.Left := 0; if R.Top < 0 then R.Top := 0; if R.Top < 0 then R.Top := 0; if R.Right > FWidth then R.Right := FWidth; if R.Bottom > FHeight then R.Bottom := FHeight; if R.Bottom < R.Top then R.Bottom := R.Top; if R.Right < R.Left then R.Right := R.Left; if (R.Right < 0) or (R.Top < 0) or (R.Left > FWidth) or (R.Top > FHeight) then Exit; if not FBuffered then begin with TvgColorRec(AColor) do cairo_set_source_rgba(Pcairo_t(Handle), R / $FF, G / $FF, B / $FF, A / $FF); cairo_rectangle(Pcairo_t(Handle), R.Left, R.Top, R.right - R.left, R.bottom - R.top); cairo_fill(Pcairo_t(Handle)); end else vgFillLongwordRect(FBufferBits, FWidth, FHeight, R.Left, R.Top, R.Right, R.Bottom, AColor); end; class function TvgCanvasCairo.GetBitmapScanline(Bitmap: TvgBitmap; y: integer): PvgColorArray; begin if (y >= 0) and (y < Bitmap.Height) and (Bitmap.StartLine <> nil) then Result := @PvgColorArray(Bitmap.StartLine)[(y) * Bitmap.Width] else Result := nil; end; procedure TvgCanvasCairo.SetMatrix(const M: TvgMatrix); var cm: cairo_matrix_t; begin if Handle = 0 then Exit; FMatrix := M; with FMatrix do begin cm.xx := m11; cm.yx := m12; cm.xy := m21; cm.yy := m22; cm.x0 := m31; cm.y0 := m32; end; cairo_set_matrix(Pcairo_t(Handle), @cm); end; procedure TvgCanvasCairo.MultyMatrix(const M: TvgMatrix); var cm: cairo_matrix_t; begin if Handle = 0 then Exit; inherited; with M do begin cm.xx := m11; cm.yx := m12; cm.xy := m21; cm.yy := m22; cm.x0 := m31; cm.y0 := m32; end; cairo_transform(Pcairo_t(Handle), @cm); end; function TvgCanvasCairo.SaveCanvas: cardinal; var i: integer; begin Result := InvalideCanvasState; if Handle = 0 then Exit; cairo_save(Pcairo_t(Handle)); // find exists if Length(FSaveData) > 0 then for i := 0 to High(FSaveData) do if FSaveData[i].Index = InvalideCanvasState then begin Result := i; Break; end; if Result = InvalideCanvasState then begin SetLength(FSaveData, Length(FSaveData) + 1); Result := High(FSaveData); end; FSaveData[Result].Index := Result; FSaveData[Result].Matrix := FMatrix; FSaveData[Result].Stroke := TvgBrush.Create(vgBrushSolid, InvalideCanvasState); FSaveData[Result].Stroke.Assign(Stroke); FSaveData[Result].Fill := TvgBrush.Create(vgBrushSolid, $FF000000); FSaveData[Result].Fill.Assign(Fill); FSaveData[Result].StrokeThickness := FStrokeThickness; FSaveData[Result].StrokeCap := StrokeCap; FSaveData[Result].StrokeJoin := StrokeJoin; FSaveData[Result].StrokeDash := StrokeDash; if StrokeDash <> vgDashSolid then begin SetLength(FSaveData[Result].Dash, Length(FDash)); Move(FDash[0], FSaveData[Result].Dash[0], SizeOf(FDash[0]) * Length(FDash)); end; FSaveData[Result].DashOffset := FDashOffset; FSaveData[Result].Font := TvgFont.Create; FSaveData[Result].Font.Assign(Font); end; procedure TvgCanvasCairo.RestoreCanvas(const AState: cardinal); begin if Handle = 0 then Exit; if (AState >= 0) and (AState < Length(FSaveData)) then begin cairo_restore(Pcairo_t(Handle)); FSaveData[AState].Index := InvalideCanvasState; FMatrix := FSaveData[AState].Matrix; Stroke.Assign(FSaveData[AState].Stroke); FSaveData[AState].Stroke.Free; Fill.Assign(FSaveData[AState].Fill); FSaveData[AState].Fill.Free; SetMatrix(FMatrix); FStrokeThickness := FSaveData[AState].StrokeThickness; FStrokeCap := FSaveData[AState].StrokeCap; FStrokeJoin := FSaveData[AState].StrokeJoin; FStrokeDash := FSaveData[AState].StrokeDash; if StrokeDash <> vgDashSolid then begin SetLength(FDash, Length(FSaveData[AState].Dash)); Move(FSaveData[AState].Dash[0], FDash[0], SizeOf(FDash[0]) * Length(FDash)); end; FDashOffset := FSaveData[AState].DashOffset; Font.Assign(FSaveData[AState].Font); FSaveData[AState].Font.Free; end end; procedure TvgCanvasCairo.SetClipRects(const ARects: array of TvgRect); var i: integer; begin if Handle = 0 then Exit; cairo_reset_clip(Pcairo_t(Handle)); for i := 0 to High(ARects) do begin cairo_rectangle(Pcairo_t(Handle), ARects[i].Left, ARects[i].Top, vgRectWidth(ARects[i]), vgRectHeight(ARects[i])); end; cairo_clip(Pcairo_t(Handle)); end; procedure TvgCanvasCairo.IntersectClipRect(const ARect: TvgRect); begin if Handle = 0 then Exit; cairo_rectangle(Pcairo_t(Handle), ARect.Left, ARect.Top, vgRectWidth(ARect), vgRectHeight(ARect)); cairo_clip(Pcairo_t(Handle)); end; procedure TvgCanvasCairo.ExcludeClipRect(const ARect: TvgRect); var R: TvgRect; i: integer; RR: array [0..3] of TvgRect; begin if Handle = 0 then Exit; R := ARect; RR[0] := vgRect(0, 0, R.Left, FHeight); RR[1] := vgRect(R.Right, 0, FWidth, FHeight); RR[2] := vgRect(R.Left, 0, R.Right, R.Top); RR[3] := vgRect(R.Left, R.Bottom, R.Right, FHeight); for i := 0 to High(RR) do begin cairo_rectangle(Pcairo_t(Handle), RR[i].Left, RR[i].Top, vgRectWidth(RR[i]), vgRectHeight(RR[i])); end; cairo_clip(Pcairo_t(Handle)); end; procedure TvgCanvasCairo.ResetClipRect; begin if Handle = 0 then Exit; cairo_reset_clip(Pcairo_t(Handle)); end; procedure TvgCanvasCairo.ApplyFill(ARect: TvgRect; const AOpacity: single); var C: TvgColor; i: integer; count: integer; cm: cairo_matrix_t; begin if Handle = 0 then Exit; if (FFill.Style = vgBrushResource) and (FFill.Resource <> nil) and (FFill.Resource.Brush <> nil) then FFill.Assign(FFill.Resource.Brush); with FFill do begin case Style of vgBrushSolid: begin with TvgColorRec(vgOpacity(SolidColor, AOpacity)) do cairo_set_source_rgba(Pcairo_t(Handle), R / $FF, G / $FF, B / $FF, A / $FF); end; vgBrushGradient: begin if Gradient.Points.Count > 1 then begin count := 0; if Gradient.Points[0].Offset > 0 then begin ColorArray[count] := vgOpacity(Gradient.Points[0].IntColor, AOpacity); OffsetArray[count] := 0; count := count + 1; end; for i := 0 to Gradient.Points.Count - 1 do begin ColorArray[i + count] := vgOpacity(Gradient.Points[i].IntColor, AOpacity); OffsetArray[i + count] := Gradient.Points[i].Offset; end; if Gradient.Points[Gradient.Points.Count - 1].Offset < 1 then begin count := count + 1; ColorArray[Gradient.Points.Count + count - 1] := vgOpacity(Gradient.Points[Gradient.Points.Count - 1].IntColor, AOpacity); OffsetArray[Gradient.Points.Count + count - 1] := 1; end; if Gradient.Style = vgLinearGradient then begin { Linear } grad := cairo_pattern_create_linear(ARect.Left + Gradient.StartPosition.X * ARect.Right, ARect.Top + Gradient.StartPosition.Y * ARect.Bottom, ARect.Left + Gradient.StopPosition.X * ARect.Right, ARect.Top + Gradient.StopPosition.Y * ARect.Bottom); for i := 0 to Gradient.Points.Count + count - 1 do with TvgColorRec(ColorArray[i]) do cairo_pattern_add_color_stop_rgba(grad, OffsetArray[i], R / $FF, G / $FF, B / $FF, A / $FF); // TGPLinearGradientBrush(FGPBrush).SetWrapMode(WrapModeTileFlipX); cairo_set_source(Pcairo_t(Handle), grad); end else begin { Radial } grad := cairo_pattern_create_radial((ARect.Left + ARect.Right) / 2, (ARect.Top + ARect.Bottom) / 2, 0, (ARect.Left + ARect.Right) / 2, (ARect.Top + ARect.Bottom) / 2, vgMaxFloat(vgRectWidth(ARect), vgRectWidth(ARect))); for i := 0 to Gradient.Points.Count + count - 1 do with TvgColorRec(ColorArray[i]) do cairo_pattern_add_color_stop_rgba(grad, OffsetArray[i], R / $FF, G / $FF, B / $FF, A / $FF); // TGPLinearGradientBrush(FGPBrush).SetWrapMode(WrapModeTileFlipX); cairo_set_source(Pcairo_t(Handle), grad); end; end else cairo_set_source_rgba(Pcairo_t(Handle), 0, 0, 0, 0); end; vgBrushBitmap: begin if (Bitmap.Bitmap <> nil) and (Bitmap.Bitmap.Width > 0) and (Bitmap.Bitmap.Height > 0) then begin UpdateBitmap(Bitmap.Bitmap); if (Bitmap.Bitmap.Handle <> 0) then begin grad := cairo_pattern_create_for_surface(Pcairo_surface_t(Bitmap.Bitmap.Handle)); if Bitmap.WrapMode = vgWrapTileStretch then begin cairo_matrix_init_scale(@cm, Bitmap.Bitmap.Width / (vgRectWidth(ARect) + (StrokeThickness / 2)), Bitmap.Bitmap.Height / (vgRectHeight(ARect) + (StrokeThickness / 2))); cairo_pattern_set_matrix(grad, @cm); end; if Bitmap.WrapMode = vgWrapTile then cairo_pattern_set_extend (grad, CAIRO_EXTEND_REPEAT); cairo_set_source(Pcairo_t(Handle), grad); end else cairo_set_source_rgba(Pcairo_t(Handle), 0, 0, 0, 0); end else cairo_set_source_rgba(Pcairo_t(Handle), 0, 0, 0, 0); end; else cairo_set_source_rgba(Pcairo_t(Handle), 0, 0, 0, 0); end; end; end; procedure TvgCanvasCairo.DeapplyFill; begin if Handle = 0 then Exit; with FFill do begin case Style of vgBrushSolid: begin end; vgBrushGradient: begin cairo_pattern_destroy(grad); end; vgBrushResource: begin end; vgBrushVisual: begin end; vgBrushBitmap: begin cairo_pattern_destroy(grad); end; end; end; end; procedure TvgCanvasCairo.ApplyStroke(ARect: TvgRect; const AOpacity: single); var i: integer; dash: array of double; begin if Handle = 0 then Exit; if (FStroke.Style = vgBrushResource) and (FStroke.Resource <> nil) and (FStroke.Resource.Brush <> nil) then FStroke.Assign(FStroke.Resource.Brush); with FStroke do begin case Style of vgBrushSolid: begin with TvgColorRec(vgOpacity(SolidColor, AOpacity)) do cairo_set_source_rgba(Pcairo_t(Handle), R / $FF, G / $FF, B / $FF, A / $FF); end; (* vgBrushGradient: begin if Gradient.Points.Count > 1 then begin for i := 0 to Gradient.Points.Count - 1 do begin ColorArray[i] := vgOpacity(Gradient.Points[i].IntColor, AOpacity); OffsetArray[i] := Gradient.Points[i].Offset; end; FGPPenBrush := TGPLinearGradientBrush.Create(MakePoint(ARect.Left + Gradient.StartPosition.X * ARect.Right, ARect.Top + Gradient.StartPosition.Y * ARect.Bottom), MakePoint(ARect.Left + Gradient.StopPosition.X * ARect.Right, ARect.Top + Gradient.StopPosition.Y * ARect.Bottom), SolidColor, SolidColor); TGPLinearGradientBrush(FGPPenBrush).SetInterpolationColors(PGPColor(@ColorArray), PSingle(@OffsetArray), Gradient.Points.Count); if Abs(FStroke.Gradient.StartPosition.X - FStroke.Gradient.StopPosition.X) < Abs(FStroke.Gradient.StartPosition.Y - FStroke.Gradient.StopPosition.Y) then TGPLinearGradientBrush(FGPPenBrush).ScaleTransform(vgRectHeight(ARect), vgRectWidth(ARect)) else TGPLinearGradientBrush(FGPPenBrush).ScaleTransform(vgRectWidth(ARect), vgRectHeight(ARect)); end else FGPPenBrush := TGPSolidBrush.Create(vgOpacity(SolidColor, AOpacity)); end; vgBrushVisual: begin FGPPenBrush := TGPSolidBrush.Create($00000000); end; vgBrushBitmap: begin if (Bitmap.Bitmap <> nil) and (Bitmap.Bitmap.Width > 0) and (Bitmap.Bitmap.Height > 0) then begin UpdateBitmap(Bitmap.Bitmap); if (Bitmap.Bitmap.Handle <> 0) then begin if Bitmap.WrapMode <> vgWrapTileStretch then FGPPenBrush := TGPTextureBrush.Create(TGPBitmap(Bitmap.Bitmap.Handle), TWrapMode(Bitmap.WrapMode)) else begin FGPPenBrush := TGPTextureBrush.Create(TGPBitmap(Bitmap.Bitmap.Handle), WrapModeClamp); TGPTextureBrush(FGPPenBrush).ScaleTransform(vgRectWidth(ARect) / Bitmap.Bitmap.Width, vgRectHeight(ARect) / Bitmap.Bitmap.Height); end; end else FGPPenBrush := TGPSolidBrush.Create($00000000); end else FGPPenBrush := TGPSolidBrush.Create($00000000); end; *) else cairo_set_source_rgba(Pcairo_t(Handle), 0, 0, 0, 0); end; end; case StrokeCap of vgCapFlat: cairo_set_line_cap(Pcairo_t(Handle), CAIRO_LINE_CAP_BUTT); vgCapRound: cairo_set_line_cap(Pcairo_t(Handle), CAIRO_LINE_CAP_ROUND); end; if Length(FDash) > 0 then begin SetLength(dash, Length(FDash)); for i := 0 to High(FDash) do begin dash[i] := FDash[i] * StrokeThickness; if (StrokeCap = vgCapRound) then begin if odd(i) then dash[i] := (FDash[i] + 1) * StrokeThickness else dash[i] := (FDash[i] - 1) * StrokeThickness; end; end; cairo_set_dash(Pcairo_t(Handle), @dash[0], Length(FDash), FDashOffset); end else cairo_set_dash(Pcairo_t(Handle), nil, 0, 0); case StrokeJoin of vgJoinMiter: cairo_set_line_join(Pcairo_t(Handle), CAIRO_LINE_JOIN_MITER); vgJoinRound: cairo_set_line_join(Pcairo_t(Handle), CAIRO_LINE_JOIN_ROUND); vgJoinBevel: cairo_set_line_join(Pcairo_t(Handle), CAIRO_LINE_JOIN_BEVEL); end; cairo_set_line_width(Pcairo_t(Handle), StrokeThickness); end; procedure TvgCanvasCairo.FontChanged(Sender: TObject); begin end; procedure TvgCanvasCairo.DrawLine(const APt1, APt2: TvgPoint; const AOpacity: single); begin if Handle = 0 then Exit; if FStroke.Style <> vgBrushNone then begin ApplyStroke(vgRect(APt1.X, APt1.Y, APt2.X, APt2.Y), AOpacity); cairo_move_to(Pcairo_t(Handle), APt1.X, APt1.Y); cairo_line_to(Pcairo_t(Handle), APt2.X, APt2.Y); cairo_stroke(Pcairo_t(Handle)); end; end; procedure TvgCanvasCairo.DrawRect(const ARect: TvgRect; const xRadius, yRadius: single; const ACorners: TvgCorners; const AOpacity: single; const ACornerType: TvgCornerType = vgCornerRound); var x1, x2, y1, y2: single; R: TvgRect; begin if Handle = 0 then Exit; if FStroke.Style <> vgBrushNone then begin R := ARect; ApplyStroke(ARect, AOpacity); if (xRadius < Epsilon) and (yRadius < Epsilon) then begin cairo_rectangle(Pcairo_t(Handle), R.Left, R.Top, vgRectWidth(R), vgRectHeight(R)); cairo_stroke(Pcairo_t(Handle)); end else begin x1 := xRadius; if vgRectWidth(R) - (x1 * 2) < 0 then x1 := (xRadius * (vgRectWidth(R) / (x1 * 2))); x2 := x1 * CurveKappaInv; y1 := yRadius; if vgRectHeight(R) - (y1 * 2) < 0 then y1 := (yRadius * (vgRectHeight(R) / (y1 * 2))); y2 := y1 * CurveKappaInv; cairo_new_path(Pcairo_t(Handle)); cairo_move_to(Pcairo_t(Handle), R.Left, R.Top + y1); if vgCornerTopLeft in ACorners then begin case ACornerType of // vgCornetRound - default vgCornerBevel: cairo_line_to(Pcairo_t(Handle), R.Left + x1, R.Top); vgCornerInnerRound: cairo_curve_to(Pcairo_t(Handle), R.Left + x2, R.Top + y1, R.Left + x1, R.Top + y2, R.Left + x1, R.Top); vgCornerInnerLine: begin cairo_line_to(Pcairo_t(Handle), R.Left + x2, R.Top + y1); cairo_line_to(Pcairo_t(Handle), R.Left + x1, R.Top + y2); cairo_line_to(Pcairo_t(Handle), R.Left + x1, R.Top); end; else cairo_curve_to(Pcairo_t(Handle), R.Left, R.Top + (y2), R.Left + x2, R.Top, R.Left + x1, R.Top) end; end else begin cairo_line_to(Pcairo_t(Handle), R.Left, R.Top); cairo_line_to(Pcairo_t(Handle), R.Left + x1, R.Top); end; cairo_line_to(Pcairo_t(Handle), R.Right - x1, R.Top); if vgCornerTopRight in ACorners then begin case ACornerType of // vgCornetRound - default vgCornerBevel: cairo_line_to(Pcairo_t(Handle), R.Right, R.Top + y1); vgCornerInnerRound: cairo_curve_to(Pcairo_t(Handle), R.Right - x1, R.Top + y2, R.Right - x2, R.Top + y1, R.Right, R.Top + y1); vgCornerInnerLine: begin cairo_line_to(Pcairo_t(Handle), R.Right - x1, R.Top + y2); cairo_line_to(Pcairo_t(Handle), R.Right - x2, R.Top + y1); cairo_line_to(Pcairo_t(Handle), R.Right, R.Top + y1); end; else cairo_curve_to(Pcairo_t(Handle), R.Right - x2, R.Top, R.Right, R.Top + (y2), R.Right, R.Top + y1) end; end else begin cairo_line_to(Pcairo_t(Handle), R.Right, R.Top); cairo_line_to(Pcairo_t(Handle), R.Right, R.Top + y1); end; cairo_line_to(Pcairo_t(Handle), R.Right, R.Bottom - y1); if vgCornerBottomRight in ACorners then begin case ACornerType of // vgCornetRound - default vgCornerBevel: cairo_line_to(Pcairo_t(Handle), R.Right - x1, R.Bottom); vgCornerInnerRound: cairo_curve_to(Pcairo_t(Handle), R.Right - x2, R.Bottom - y1, R.Right - x1, R.Bottom - y2, R.Right - x1, R.Bottom); vgCornerInnerLine: begin cairo_line_to(Pcairo_t(Handle), R.Right - x2, R.Bottom - y1); cairo_line_to(Pcairo_t(Handle), R.Right - x1, R.Bottom - y2); cairo_line_to(Pcairo_t(Handle), R.Right - x1, R.Bottom); end; else cairo_curve_to(Pcairo_t(Handle), R.Right, R.Bottom - (y2), R.Right - x2, R.Bottom, R.Right - x1, R.Bottom) end; end else begin cairo_line_to(Pcairo_t(Handle), R.Right, R.Bottom); cairo_line_to(Pcairo_t(Handle), R.Right - x1, R.Bottom); end; cairo_line_to(Pcairo_t(Handle), R.Left + x1, R.Bottom); if vgCornerBottomLeft in ACorners then begin case ACornerType of // vgCornetRound - default vgCornerBevel: cairo_line_to(Pcairo_t(Handle), R.Left, R.Bottom - y1); vgCornerInnerRound: cairo_curve_to(Pcairo_t(Handle), R.Left + x1, R.Bottom - y2, R.Left + x2, R.Bottom - y1, R.Left, R.Bottom - y1); vgCornerInnerLine: begin cairo_line_to(Pcairo_t(Handle), R.Left + x1, R.Bottom - y2); cairo_line_to(Pcairo_t(Handle), R.Left + x2, R.Bottom - y1); cairo_line_to(Pcairo_t(Handle), R.Left, R.Bottom - y1); end; else cairo_curve_to(Pcairo_t(Handle), R.Left + x2, R.Bottom, R.Left, R.Bottom - (y2), R.Left, R.Bottom - y1) end; end else begin cairo_line_to(Pcairo_t(Handle), R.Left, R.Bottom); cairo_line_to(Pcairo_t(Handle), R.Left, R.Bottom - y1); end; end; cairo_close_path(Pcairo_t(Handle)); cairo_stroke(Pcairo_t(Handle)); end; end; procedure TvgCanvasCairo.FillRect(const ARect: TvgRect; const xRadius, yRadius: single; const ACorners: TvgCorners; const AOpacity: single; const ACornerType: TvgCornerType = vgCornerRound); var x1, x2, y1, y2: single; R: TvgRect; begin if Handle = 0 then Exit; if FFill.Style <> vgBrushNone then begin R := ARect; ApplyFill(R, AOpacity); if ((xRadius = 0) and (yRadius = 0)) or (ACorners = []) then begin cairo_rectangle(Pcairo_t(Handle), R.Left, R.Top, vgRectWidth(R), vgRectHeight(R)); cairo_fill(Pcairo_t(Handle)); end else begin x1 := xRadius; if vgRectWidth(R) - (x1 * 2) < 0 then x1 := (xRadius * (vgRectWidth(R) / (x1 * 2))); x2 := x1 * CurveKappaInv; y1 := yRadius; if vgRectHeight(R) - (y1 * 2) < 0 then y1 := (yRadius * (vgRectHeight(R) / (y1 * 2))); y2 := y1 * CurveKappaInv; cairo_new_path(Pcairo_t(Handle)); cairo_move_to(Pcairo_t(Handle), R.Left, R.Top + y1); if vgCornerTopLeft in ACorners then begin case ACornerType of // vgCornetRound - default vgCornerBevel: cairo_line_to(Pcairo_t(Handle), R.Left + x1, R.Top); vgCornerInnerRound: cairo_curve_to(Pcairo_t(Handle), R.Left + x2, R.Top + y1, R.Left + x1, R.Top + y2, R.Left + x1, R.Top); vgCornerInnerLine: begin cairo_line_to(Pcairo_t(Handle), R.Left + x2, R.Top + y1); cairo_line_to(Pcairo_t(Handle), R.Left + x1, R.Top + y2); cairo_line_to(Pcairo_t(Handle), R.Left + x1, R.Top); end; else cairo_curve_to(Pcairo_t(Handle), R.Left, R.Top + (y2), R.Left + x2, R.Top, R.Left + x1, R.Top) end; end else begin cairo_line_to(Pcairo_t(Handle), R.Left, R.Top); cairo_line_to(Pcairo_t(Handle), R.Left + x1, R.Top); end; cairo_line_to(Pcairo_t(Handle), R.Right - x1, R.Top); if vgCornerTopRight in ACorners then begin case ACornerType of // vgCornetRound - default vgCornerBevel: cairo_line_to(Pcairo_t(Handle), R.Right, R.Top + y1); vgCornerInnerRound: cairo_curve_to(Pcairo_t(Handle), R.Right - x1, R.Top + y2, R.Right - x2, R.Top + y1, R.Right, R.Top + y1); vgCornerInnerLine: begin cairo_line_to(Pcairo_t(Handle), R.Right - x1, R.Top + y2); cairo_line_to(Pcairo_t(Handle), R.Right - x2, R.Top + y1); cairo_line_to(Pcairo_t(Handle), R.Right, R.Top + y1); end; else cairo_curve_to(Pcairo_t(Handle), R.Right - x2, R.Top, R.Right, R.Top + (y2), R.Right, R.Top + y1) end; end else begin cairo_line_to(Pcairo_t(Handle), R.Right, R.Top); cairo_line_to(Pcairo_t(Handle), R.Right, R.Top + y1); end; cairo_line_to(Pcairo_t(Handle), R.Right, R.Bottom - y1); if vgCornerBottomRight in ACorners then begin case ACornerType of // vgCornetRound - default vgCornerBevel: cairo_line_to(Pcairo_t(Handle), R.Right - x1, R.Bottom); vgCornerInnerRound: cairo_curve_to(Pcairo_t(Handle), R.Right - x2, R.Bottom - y1, R.Right - x1, R.Bottom - y2, R.Right - x1, R.Bottom); vgCornerInnerLine: begin cairo_line_to(Pcairo_t(Handle), R.Right - x2, R.Bottom - y1); cairo_line_to(Pcairo_t(Handle), R.Right - x1, R.Bottom - y2); cairo_line_to(Pcairo_t(Handle), R.Right - x1, R.Bottom); end; else cairo_curve_to(Pcairo_t(Handle), R.Right, R.Bottom - (y2), R.Right - x2, R.Bottom, R.Right - x1, R.Bottom) end; end else begin cairo_line_to(Pcairo_t(Handle), R.Right, R.Bottom); cairo_line_to(Pcairo_t(Handle), R.Right - x1, R.Bottom); end; cairo_line_to(Pcairo_t(Handle), R.Left + x1, R.Bottom); if vgCornerBottomLeft in ACorners then begin case ACornerType of // vgCornetRound - default vgCornerBevel: cairo_line_to(Pcairo_t(Handle), R.Left, R.Bottom - y1); vgCornerInnerRound: cairo_curve_to(Pcairo_t(Handle), R.Left + x1, R.Bottom - y2, R.Left + x2, R.Bottom - y1, R.Left, R.Bottom - y1); vgCornerInnerLine: begin cairo_line_to(Pcairo_t(Handle), R.Left + x1, R.Bottom - y2); cairo_line_to(Pcairo_t(Handle), R.Left + x2, R.Bottom - y1); cairo_line_to(Pcairo_t(Handle), R.Left, R.Bottom - y1); end; else cairo_curve_to(Pcairo_t(Handle), R.Left + x2, R.Bottom, R.Left, R.Bottom - (y2), R.Left, R.Bottom - y1) end; end else begin cairo_line_to(Pcairo_t(Handle), R.Left, R.Bottom); cairo_line_to(Pcairo_t(Handle), R.Left, R.Bottom - y1); end; end; cairo_close_path(Pcairo_t(Handle)); cairo_fill(Pcairo_t(Handle)); DeapplyFill; end; end; procedure TvgCanvasCairo.DrawEllipse(const ARect: TvgRect; const AOpacity: single); begin if Handle = 0 then Exit; if FStroke.Style <> vgBrushNone then begin ApplyStroke(ARect, AOpacity); cairo_save(Pcairo_t(Handle)); cairo_translate(Pcairo_t(Handle), (ARect.Left + ARect.Right) / 2, (ARect.Top + ARect.Bottom) / 2); cairo_scale(Pcairo_t(Handle), vgRectWidth(ARect) / 2, vgRectHeight(ARect) / 2); cairo_arc(Pcairo_t(Handle), 0, 0, 1, 0, Pi * 2); cairo_restore(Pcairo_t(Handle)); cairo_stroke(Pcairo_t(Handle)); end; end; procedure TvgCanvasCairo.FillEllipse(const ARect: TvgRect; const AOpacity: single); begin if Handle = 0 then Exit; if FFill.Style <> vgBrushNone then begin ApplyFill(ARect, AOpacity); cairo_save(Pcairo_t(Handle)); cairo_translate(Pcairo_t(Handle), (ARect.Left + ARect.Right) / 2, (ARect.Top + ARect.Bottom) / 2); cairo_scale(Pcairo_t(Handle), vgRectWidth(ARect) / 2, vgRectHeight(ARect) / 2); cairo_arc(Pcairo_t(Handle), 0, 0, 1, 0, Pi * 2); cairo_restore(Pcairo_t(Handle)); cairo_fill(Pcairo_t(Handle)); DeapplyFill; end; end; procedure TvgCanvasCairo.FillText(const ARect, AClipRect: TvgRect; const AText: WideString; const WordWrap: boolean; const AOpacity: single; const ATextAlign: TvgTextAlign; const AVTextAlign: TvgTextAlign = vgTextAlignCenter); var text: string; pdesc: PPangoFontDescription; playout: PPangoLayout; FullString: String; lineWidth: longint; pr, pr2: TPangoRectangle; begin if Handle = 0 then Exit; ApplyFill(ARect, AOpacity); cairo_save(Pcairo_t(Handle)); cairo_rectangle(Pcairo_t(Handle), ARect.Left, ARect.Top, vgRectWidth(ARect), vgRectHeight(ARect)); cairo_clip(Pcairo_t(Handle)); cairo_translate(Pcairo_t(Handle), ARect.left, ARect.Top); playout := pango_cairo_create_layout(Pcairo_t(Handle)); if playout <> nil then begin FullString := FFont.Family; pdesc := pango_font_description_from_string(Pchar(FullString + ' ' + IntToStr(Round(FFont.Size * 0.75)))); if pdesc = nil then pdesc := pango_font_description_from_string(Pchar('Sans ' + IntToStr(Round(FFont.Size * 0.75)))); if pdesc <> nil then begin if FFont.Style in [vgFontItalic, vgFontBoldItalic] then pango_font_description_set_style(pdesc, PANGO_STYLE_ITALIC); if FFont.Style in [vgFontBold, vgFontBoldItalic] then pango_font_description_set_weight(pdesc, PANGO_WEIGHT_BOLD); pango_layout_set_font_description(playout, pdesc); pango_font_description_free(pdesc); end; pango_layout_set_height(playout, Round(vgRectHeight(ARect) * PANGO_SCALE)); if WordWrap then pango_layout_set_width(playout, Round(vgRectWidth(ARect) * PANGO_SCALE)) else pango_layout_set_width(playout, 5000 * PANGO_SCALE); // formating case ATextAlign of vgTextAlignCenter: begin pango_layout_set_alignment(playout, PANGO_ALIGN_CENTER); if not WordWrap then cairo_translate(Pcairo_t(Handle), -2500 + (vgRectWidth(ARect) / 2), 0); end; vgTextAlignNear: begin pango_layout_set_alignment(playout, PANGO_ALIGN_LEFT); end; vgTextAlignFar: begin pango_layout_set_alignment(playout, PANGO_ALIGN_RIGHT); if not WordWrap then cairo_translate(Pcairo_t(Handle), -5000 + vgRectWidth(ARect), 0); end; end; text := UTF8Encode(AText); pango_layout_set_text(playout, PAnsiChar(text), -1); pango_layout_get_pixel_extents(playout, @pr, @pr2); case AVTextAlign of vgTextAlignCenter: begin cairo_translate(Pcairo_t(Handle), 0, (vgRectHeight(ARect) - pr2.height) / 2); end; vgTextAlignNear: begin end; vgTextAlignFar: begin cairo_translate(Pcairo_t(Handle), 0, (vgRectHeight(ARect) - pr2.height)); end; end; pango_cairo_show_layout(Pcairo_t(Handle), playout); g_object_unref(playout); end; cairo_restore(Pcairo_t(Handle)); DeapplyFill; end; procedure TvgCanvasCairo.MeasureText(var ARect: TvgRect; AClipRect: TvgRect; const AText: WideString; const WordWrap: boolean; const ATextAlign, AVTextAlign: TvgTextAlign); var text: string; pdesc: PPangoFontDescription; FullString: String; lineWidth: longint; pr, pr2: TPangoRectangle; begin if not WordWrap then ARect.Right := ARect.Left; if Length(AText) = 0 then Exit; FullString := FFont.Family; pdesc := pango_font_description_from_string(Pchar(FullString + ' ' + IntToStr(Round(FFont.Size * 0.75)))); if pdesc = nil then pdesc := pango_font_description_from_string(Pchar('Sans ' + IntToStr(Round(FFont.Size * 0.75)))); if pdesc <> nil then begin if FFont.Style in [vgFontItalic, vgFontBoldItalic] then pango_font_description_set_style(pdesc, PANGO_STYLE_ITALIC); if FFont.Style in [vgFontBold, vgFontBoldItalic] then pango_font_description_set_weight(pdesc, PANGO_WEIGHT_BOLD); pango_layout_set_font_description(memlayout, pdesc); pango_font_description_free(pdesc); end; pango_layout_set_height(memlayout, Round(vgRectHeight(ARect) * PANGO_SCALE)); if WordWrap then pango_layout_set_width(memlayout, Round(vgRectWidth(ARect) * PANGO_SCALE)) else pango_layout_set_width(memlayout, 5000 * PANGO_SCALE); // formating case ATextAlign of vgTextAlignCenter: begin pango_layout_set_alignment(memlayout, PANGO_ALIGN_CENTER); end; vgTextAlignNear: begin pango_layout_set_alignment(memlayout, PANGO_ALIGN_LEFT); end; vgTextAlignFar: begin pango_layout_set_alignment(memlayout, PANGO_ALIGN_RIGHT); end; end; text := UTF8Encode(AText); pango_layout_set_text(memlayout, PChar(text), -1); pango_layout_get_pixel_extents(memlayout, @pr, @pr2); ARect.Right := ARect.Left + pr2.width; ARect.Bottom := ARect.Top + pr2.height; end; function TvgCanvasCairo.TextToPath(Path: TvgPathData; const ARect: TvgRect; const AText: WideString; const WordWrap: boolean; const ATextAlign: TvgTextAlign; const AVTextAlign: TvgTextAlign = vgTextAlignCenter): boolean; var text: string; pdesc: PPangoFontDescription; FullString: String; lineWidth: longint; pr, pr2: TPangoRectangle; i: integer; B: TvgRect; W, H, NewW, NewH, VOffset, HOffset: single; cpath: Pcairo_path_t; pathdata: Pcairo_path_data_t; pointtype: cairo_path_data_type_t; CP1, CP2: TvgPoint; begin if AText <> '' then begin Path.Clear; FullString := FFont.Family; pdesc := pango_font_description_from_string(Pchar(FullString + ' ' + IntToStr(Round(FFont.Size * 0.75)))); if pdesc = nil then pdesc := pango_font_description_from_string(Pchar('Sans ' + IntToStr(Round(FFont.Size * 0.75)))); if pdesc <> nil then begin if FFont.Style in [vgFontItalic, vgFontBoldItalic] then pango_font_description_set_style(pdesc, PANGO_STYLE_ITALIC); if FFont.Style in [vgFontBold, vgFontBoldItalic] then pango_font_description_set_weight(pdesc, PANGO_WEIGHT_BOLD); pango_layout_set_font_description(memlayout, pdesc); pango_font_description_free(pdesc); end; pango_layout_set_height(memlayout, Round(vgRectHeight(ARect) * PANGO_SCALE)); if WordWrap then pango_layout_set_width(memlayout, Round(vgRectWidth(ARect) * PANGO_SCALE)) else pango_layout_set_width(memlayout, 5000 * PANGO_SCALE); // formating HOffset := 0; case ATextAlign of vgTextAlignCenter: begin pango_layout_set_alignment(memlayout, PANGO_ALIGN_CENTER); if not WordWrap then HOffset := -2500 + (vgRectWidth(ARect) / 2); end; vgTextAlignNear: begin pango_layout_set_alignment(memlayout, PANGO_ALIGN_LEFT); end; vgTextAlignFar: begin pango_layout_set_alignment(memlayout, PANGO_ALIGN_RIGHT); if not WordWrap then HOffset := -5000 + vgRectWidth(ARect); end; end; text := UTF8Encode(AText); pango_layout_set_text(memlayout, PAnsiChar(text), -1); pango_layout_get_pixel_extents(memlayout, @pr, @pr2); case AVTextAlign of vgTextAlignCenter: begin VOffset := (vgRectHeight(ARect) - pr2.height) / 2; end; vgTextAlignNear: begin VOffset := 0; end; vgTextAlignFar: begin VOffset := vgRectHeight(ARect) - pr2.height; end; end; // create path cairo_new_path(memcr); // draw text pango_cairo_layout_path(memcr, memlayout); // parse path cpath := cairo_copy_path(memcr); if cpath <> nil then begin pathdata := cpath^.data; i := 0; while i < cpath^.num_data do begin // point type pointtype := pathdata.header._type; Inc(PathData); Inc(i); if pointtype = CAIRO_PATH_CLOSE_PATH then begin Path.ClosePath; Continue; end; // point if pointtype = CAIRO_PATH_MOVE_TO then begin Path.MoveTo(vgPoint(pathdata.point.x + HOffset, pathdata.point.y + VOffset)); end; if pointtype = CAIRO_PATH_LINE_TO then begin Path.LineTo(vgPoint(pathdata.point.x + HOffset, pathdata.point.y + VOffset)); end; if pointtype = CAIRO_PATH_CURVE_TO then begin CP1 := vgPoint(pathdata.point.x + HOffset, pathdata.point.y + VOffset); Inc(PathData); Inc(i); CP2 := vgPoint(pathdata.point.x + HOffset, pathdata.point.y + VOffset); Inc(PathData); Inc(i); Path.CurveTo(CP1, CP2, vgPoint(pathdata.point.x + HOffset, pathdata.point.y + VOffset)); end; Inc(PathData); Inc(i); end; end; Result := true; cairo_path_destroy(cpath); end else Result := false; end; { Bitmaps } procedure TvgCanvasCairo.DrawThumbnail(const ABitmap: TvgBitmap; const Width, Height: single); {var scale: single; graphics: TGPGraphics;} begin { UpdateBitmap(ABitmap); if ABitmap.Handle = 0 then Exit; scale := Width / ABitmap.Width; if FBitmap <> nil then begin Fgraphics.ScaleTransform(scale, scale); Fgraphics.DrawImage(TGPBitmap(ABitmap.Handle), 0, 0, ABitmap.Width, ABitmap.Height); end;} end; procedure TvgCanvasCairo.DrawBitmap(const ABitmap: TvgBitmap; const SrcRect, DstRect: TvgRect; const AOpacity: single; const HighSpeed: boolean = false); var pat: Pcairo_pattern_t; pb, subpb: PGdkPixbuf; cm: cairo_matrix_t; sc: single; begin UpdateBitmap(ABitmap); if Handle = 0 then Exit; if ABitmap.Handle = 0 then Exit; if (SrcRect.Left <> 0) or (SrcRect.top <> 0) or (SrcRect.right <> ABitmap.Width) or (SrcRect.bottom <> ABitmap.Height) then begin pb := gdk_pixbuf_new_from_data(Pguchar(ABitmap.StartLine), GDK_COLORSPACE_RGB, true, 8, ABitmap.Width, ABitmap.Height, ABitmap.Width * 4, nil, nil); if pb <> nil then begin subpb := gdk_pixbuf_new_subpixbuf(pb, Trunc(SrcRect.Left), Trunc(SrcRect.top), trunc(vgRectWidth(SrcRect)), trunc(vgRectHeight(SrcRect))); if subpb <> nil then begin cairo_save(Pcairo_t(Handle)); gdk_cairo_set_source_pixbuf(Pcairo_t(Handle), subpb, 0, 0); pat := cairo_get_source(Pcairo_t(Handle)); cairo_matrix_init_translate(@cm, -DstRect.Left * (vgRectWidth(SrcRect) / vgRectWidth(DstRect)), -DstRect.Top * (vgRectHeight(SrcRect) / vgRectHeight(DstRect))); cairo_matrix_scale(@cm, vgRectWidth(SrcRect) / vgRectWidth(DstRect), vgRectHeight(SrcRect) / vgRectHeight(DstRect)); cairo_pattern_set_matrix(pat, @cm); if HighSpeed then cairo_pattern_set_filter(pat, CAIRO_FILTER_FAST) else cairo_pattern_set_filter(pat, CAIRO_FILTER_BEST); cairo_pattern_set_extend(pat, CAIRO_EXTEND_NONE); cairo_set_source(Pcairo_t(Handle), pat); cairo_rectangle(Pcairo_t(Handle), DstRect.Left, DstRect.Top, vgRectWidth(DstRect), vgRectHeight(DstRect)); cairo_clip(Pcairo_t(Handle)); cairo_paint_with_alpha(Pcairo_t(Handle), AOpacity); cairo_restore(Pcairo_t(Handle)); g_object_unref(subpb); end; g_object_unref(pb); end; Exit; end; cairo_save(Pcairo_t(Handle)); pat := cairo_pattern_create_for_surface(Pcairo_surface_t(ABitmap.Handle)); cairo_matrix_init_translate(@cm, -DstRect.Left * (vgRectWidth(SrcRect) / vgRectWidth(DstRect)), -DstRect.Top * (vgRectHeight(SrcRect) / vgRectHeight(DstRect))); cairo_matrix_scale(@cm, vgRectWidth(SrcRect) / vgRectWidth(DstRect), vgRectHeight(SrcRect) / vgRectHeight(DstRect)); cairo_pattern_set_matrix(pat, @cm); if HighSpeed then cairo_pattern_set_filter(pat, CAIRO_FILTER_FAST) else cairo_pattern_set_filter(pat, CAIRO_FILTER_BEST); cairo_pattern_set_extend(pat, CAIRO_EXTEND_NONE); cairo_set_source(Pcairo_t(Handle), pat); cairo_rectangle(Pcairo_t(Handle), DstRect.Left, DstRect.Top, vgRectWidth(DstRect), vgRectHeight(DstRect)); cairo_clip(Pcairo_t(Handle)); cairo_paint_with_alpha(Pcairo_t(Handle), AOpacity); cairo_pattern_destroy(pat); cairo_restore(Pcairo_t(Handle)); end; procedure TvgCanvasCairo.UpdateBitmap(ABitmap: TvgBitmap); begin // update bitmap to GDI+ bitmap if ABitmap = nil then Exit; // create - if need if ABitmap.Handle = 0 then begin ABitmap.Handle := Cardinal(cairo_image_surface_create_for_data(PByte(ABitmap.StartLine), CAIRO_FORMAT_ARGB32, ABitmap.Width, ABitmap.Height, ABitmap.Width * 4)); end; // clear flag ABitmap.NeedUpdate := false; ABitmap.OnDestroyHandle := DoDestroyBitmap; end; procedure TvgCanvasCairo.DoDestroyBitmap(Sender: TObject); begin if (Sender <> nil) then begin if (TvgBitmap(Sender).Handle <> 0) then cairo_surface_destroy(Pcairo_surface_t(TvgBitmap(Sender).Handle)); TvgBitmap(Sender).Handle := 0; end; end; { Path } procedure TvgCanvasCairo.DrawPath(const APath: TvgPathData; const ARect: TvgRect; const AOpacity: single); var i: integer; B: TvgRect; W, H, NewW, NewH: single; CP1, CP2: TvgPoint; begin if Handle = 0 then Exit; if FStroke.Style = vgBrushNone then Exit; ApplyStroke(ARect, AOpacity); B := APath.GetBounds; W := vgRectWidth(B); H := vgRectHeight(B); NewW := vgRectWidth(ARect); NewH := vgRectHeight(ARect); { draw } cairo_save(Pcairo_t(Handle)); cairo_new_path(Pcairo_t(Handle)); i := 0; while i < Length(APath.PathData) do begin case APath.PathData[i].Kind of vgPathPointMoveTo: begin cairo_move_to(Pcairo_t(Handle), ARect.Left + (APath.PathData[i].Point.X - B.Left) / W * NewW, ARect.Top + (APath.PathData[i].Point.Y - B.Top) / H * NewH); end; vgPathPointLineTo: begin cairo_line_to(Pcairo_t(Handle), ARect.Left + (APath.PathData[i].Point.X - B.Left) / W * NewW, ARect.Top + (APath.PathData[i].Point.Y - B.Top) / H * NewH); end; vgPathPointCurveTo: begin CP1 := vgPoint(ARect.Left + (APath.PathData[i].Point.X - B.Left) / W * NewW, ARect.Top + (APath.PathData[i].Point.Y - B.Top) / H * NewH); Inc(i); CP2 := vgPoint(ARect.Left + (APath.PathData[i].Point.X - B.Left) / W * NewW, ARect.Top + (APath.PathData[i].Point.Y - B.Top) / H * NewH); Inc(i); cairo_curve_to(Pcairo_t(Handle), CP1.X, CP1.Y, CP2.X, CP2.Y, ARect.Left + (APath.PathData[i].Point.X - B.Left) / W * NewW, ARect.Top + (APath.PathData[i].Point.Y - B.Top) / H * NewH); end; vgPathPointClose: begin cairo_close_path(Pcairo_t(Handle)); end; end; inc(i); end; cairo_stroke(Pcairo_t(Handle)); cairo_restore(Pcairo_t(Handle)); end; procedure TvgCanvasCairo.FillPath(const APath: TvgPathData; const ARect: TvgRect; const AOpacity: single); var i: integer; B: TvgRect; W, H, NewW, NewH: single; CP1, CP2: TvgPoint; begin if Handle = 0 then Exit; if FFill.Style = vgBrushNone then Exit; ApplyFill(ARect, AOpacity); B := APath.GetBounds; W := vgRectWidth(B); H := vgRectHeight(B); NewW := vgRectWidth(ARect); NewH := vgRectHeight(ARect); cairo_save(Pcairo_t(Handle)); cairo_new_path(Pcairo_t(Handle)); i := 0; while i < Length(APath.PathData) do begin case APath.PathData[i].Kind of vgPathPointMoveTo: begin cairo_move_to(Pcairo_t(Handle), ARect.Left + (APath.PathData[i].Point.X - B.Left) / W * NewW, ARect.Top + (APath.PathData[i].Point.Y - B.Top) / H * NewH); end; vgPathPointLineTo: begin cairo_line_to(Pcairo_t(Handle), ARect.Left + (APath.PathData[i].Point.X - B.Left) / W * NewW, ARect.Top + (APath.PathData[i].Point.Y - B.Top) / H * NewH); end; vgPathPointCurveTo: begin CP1 := vgPoint(ARect.Left + (APath.PathData[i].Point.X - B.Left) / W * NewW, ARect.Top + (APath.PathData[i].Point.Y - B.Top) / H * NewH); Inc(i); CP2 := vgPoint(ARect.Left + (APath.PathData[i].Point.X - B.Left) / W * NewW, ARect.Top + (APath.PathData[i].Point.Y - B.Top) / H * NewH); Inc(i); cairo_curve_to(Pcairo_t(Handle), CP1.X, CP1.Y, CP2.X, CP2.Y, ARect.Left + (APath.PathData[i].Point.X - B.Left) / W * NewW, ARect.Top + (APath.PathData[i].Point.Y - B.Top) / H * NewH); end; vgPathPointClose: begin cairo_close_path(Pcairo_t(Handle)); end; end; inc(i); end; cairo_fill(Pcairo_t(Handle)); DeApplyFill; cairo_restore(Pcairo_t(Handle)); end; function TvgCanvasCairo.PtInPath(const APoint: TvgPoint; const ARect: TvgRect; const APath: TvgPathData): boolean; var i: integer; B: TvgRect; W, H, NewW, NewH: single; CP1, CP2: TvgPoint; begin Result := false; if Handle = 0 then Exit; B := APath.GetBounds; W := vgRectWidth(B); H := vgRectHeight(B); NewW := vgRectWidth(ARect); NewH := vgRectHeight(ARect); cairo_save(Pcairo_t(Handle)); cairo_new_path(Pcairo_t(Handle)); i := 0; while i < Length(APath.PathData) do begin case APath.PathData[i].Kind of vgPathPointMoveTo: begin cairo_move_to(Pcairo_t(Handle), ARect.Left + (APath.PathData[i].Point.X - B.Left) / W * NewW, ARect.Top + (APath.PathData[i].Point.Y - B.Top) / H * NewH); end; vgPathPointLineTo: begin cairo_line_to(Pcairo_t(Handle), ARect.Left + (APath.PathData[i].Point.X - B.Left) / W * NewW, ARect.Top + (APath.PathData[i].Point.Y - B.Top) / H * NewH); end; vgPathPointCurveTo: begin CP1 := vgPoint(ARect.Left + (APath.PathData[i].Point.X - B.Left) / W * NewW, ARect.Top + (APath.PathData[i].Point.Y - B.Top) / H * NewH); Inc(i); CP2 := vgPoint(ARect.Left + (APath.PathData[i].Point.X - B.Left) / W * NewW, ARect.Top + (APath.PathData[i].Point.Y - B.Top) / H * NewH); Inc(i); cairo_curve_to(Pcairo_t(Handle), CP1.X, CP1.Y, CP2.X, CP2.Y, ARect.Left + (APath.PathData[i].Point.X - B.Left) / W * NewW, ARect.Top + (APath.PathData[i].Point.Y - B.Top) / H * NewH); end; vgPathPointClose: begin cairo_close_path(Pcairo_t(Handle)); end; end; inc(i); end; cairo_restore(Pcairo_t(Handle)); Result := cairo_in_fill(Pcairo_t(Handle), APoint.X, APoint.Y) > 0; end; {$ENDIF} initialization {$IFDEF LINUX} DefaultCanvasClass := TvgCanvasCairo; DefaultFilterClass := TvgFilterGtk; {$ENDIF} end.
unit AvoidanceZoneParametersUnit; interface uses REST.Json.Types, HttpQueryMemberAttributeUnit, JSONNullableAttributeUnit, NullableBasicTypesUnit, GenericParametersUnit, TerritoryUnit; type TAvoidanceZoneParameters = class(TGenericParameters) private [JSONMarshalled(False)] [HttpQueryMember('device_id')] [Nullable] FDeviceId: NullableString; [JSONNameAttribute('territory_id')] [Nullable] FTerritoryId: NullableString; [JSONNameAttribute('territory_name')] [Nullable] FTerritoryName: NullableString; [JSONNameAttribute('territory_color')] [Nullable] FTerritoryColor: NullableString; [JSONNameAttribute('member_id')] [Nullable] FMemberId: NullableString; [JSONNameAttribute('territory')] [NullableObject(TTerritory)] FTerritory: NullableObject; public constructor Create; override; destructor Destroy; override; property DeviceId: NullableString read FDeviceId write FDeviceId; property TerritoryId: NullableString read FTerritoryId write FTerritoryId; property TerritoryName: NullableString read FTerritoryName write FTerritoryName; property TerritoryColor: NullableString read FTerritoryColor write FTerritoryColor; property MemberId: NullableString read FMemberId write FMemberId; property Territory: NullableObject read FTerritory write FTerritory; end; implementation { TAvoidanceZoneParameters } constructor TAvoidanceZoneParameters.Create; begin Inherited Create; DeviceId := NullableString.Null; TerritoryId := NullableString.Null; TerritoryName := NullableString.Null; TerritoryColor := NullableString.Null; MemberId := NullableString.Null; Territory := NullableObject.Null; end; destructor TAvoidanceZoneParameters.Destroy; begin FTerritory.Free; inherited; end; end.
unit evTableCellHotSpot; {* Реализация интерфейсов IevHotSpotTester и IevHotSpot для ячейки таблицы. } { Библиотека "Эверест" } { Автор: Люлин А.В. © } { Модуль: evTableCellHotSpot - } { Начат: 02.11.2000 10:18 } { $Id: evTableCellHotSpot.pas,v 1.82 2015/01/19 18:36:36 lulin Exp $ } // $Log: evTableCellHotSpot.pas,v $ // Revision 1.82 2015/01/19 18:36:36 lulin // {RequestLink:580710025} // // Revision 1.81 2015/01/19 16:52:44 lulin // {RequestLink:580710025} // // Revision 1.80 2014/04/30 11:23:52 lulin // - выпрямляем зависимости. // // Revision 1.79 2014/04/29 13:38:51 lulin // - вычищаем ненужные зависимости. // // Revision 1.78 2014/04/21 11:45:00 lulin // - переходим от интерфейсов к объектам. // // Revision 1.77 2014/04/07 17:56:59 lulin // - переходим от интерфейсов к объектам. // // Revision 1.76 2014/03/28 12:15:23 lulin // - переходим от интерфейсов к объектам. // // Revision 1.75 2014/03/18 15:56:59 lulin // - перетряхиваем работу с тегами. // // Revision 1.74 2013/10/21 17:30:59 lulin // - потихоньку избавляемся от использования идентификаторов типов тегов. // // Revision 1.73 2013/10/21 15:42:58 lulin // - потихоньку избавляемся от использования идентификаторов типов тегов. // // Revision 1.72 2013/10/21 10:30:41 lulin // - потихоньку избавляемся от использования идентификаторов типов тегов. // // Revision 1.71 2011/09/13 10:48:06 lulin // {RequestLink:278839709}. // // Revision 1.70 2011/02/22 19:41:04 lulin // {RequestLink:182157315}. // // Revision 1.69 2011/02/15 11:24:49 lulin // {RequestLink:231670346}. // // Revision 1.68 2010/06/24 18:33:33 lulin // {RequestLink:219125149}. // - таки скроллируем окно, если ушли за его пределы. // - обрабатываем любую диагональ в таблице. // // Revision 1.67 2010/06/24 15:16:27 lulin // {RequestLink:219125149}. // - пытаемся скроллировать окно, если ушли за его пределы. // // Revision 1.66 2010/06/24 12:52:54 lulin // {RequestLink:219125149}. // // Revision 1.65 2010/03/02 13:34:35 lulin // {RequestLink:193823544}. // // Revision 1.64 2010/03/01 14:50:06 lulin // {RequestLink:193823544}. // - шаг второй. // // Revision 1.63 2009/07/23 08:14:39 lulin // - вычищаем ненужное использование процессора операций. // // Revision 1.62 2009/07/14 14:56:28 lulin // {RequestLink:141264340}. №25. // // Revision 1.61 2009/07/13 12:31:37 lulin // {RequestLink:141264340}. №23ac. // // Revision 1.60 2009/07/11 17:11:05 lulin // {RequestLink:141264340}. №19. // // Revision 1.59 2009/07/11 15:55:09 lulin // {RequestLink:141264340}. №22. // // Revision 1.58 2009/07/10 16:15:41 lulin // - избавляемся от лишнего дёрганья счётчиков ссылок. // // Revision 1.57 2009/06/25 12:57:30 lulin // - вычищаем ненужный контекст. // // Revision 1.56 2009/05/29 17:18:25 lulin // [$142610853]. // // Revision 1.55 2009/05/22 11:38:03 dinishev // Чиним выделение ячеек. // // Revision 1.54 2009/04/14 18:11:55 lulin // [$143396720]. Подготовительная работа. // // Revision 1.53 2009/04/06 09:45:27 lulin // [$140837386]. Убираем старорежимную примесь для списков параграфов. // // Revision 1.52 2009/03/04 13:32:47 lulin // - <K>: 137470629. Генерируем идентификаторы типов с модели и убираем их из общей помойки. // // Revision 1.51 2008/12/12 19:19:14 lulin // - <K>: 129762414. // // Revision 1.50 2008/12/12 15:34:20 lulin // - <K>: 129762414. // // Revision 1.49 2008/10/02 15:34:22 lulin // - <K>: 119476261. // // Revision 1.48 2008/05/05 12:56:39 lulin // - <K>: 90439843. // // Revision 1.47 2008/04/24 12:26:19 lulin // - изменения в рамках <K>: 89106312. // // Revision 1.46 2008/04/15 08:23:46 lulin // - передаём вью в качестве параметра. // // Revision 1.45 2008/04/14 07:48:09 lulin // - передаём вью в рамках <K>: 89096854. // // Revision 1.44 2008/04/10 14:34:05 lulin // - <K>: 89098970. // // Revision 1.43 2008/04/09 17:57:08 lulin // - передаём вью в рамках <K>: 89096854. // // Revision 1.42 2008/04/08 16:41:20 lulin // - передаём View в AssignPoint. <K>: 89096854. // // Revision 1.41 2008/04/04 16:17:59 lulin // - теперь у базового вью нельзя получить курсор по точке. // // Revision 1.40 2008/02/29 10:52:39 dinishev // Bug fix: AV при расширении выделения ячейки // // Revision 1.39 2008/02/27 17:24:58 lulin // - подгоняем код под модель. // // Revision 1.38 2007/12/04 12:47:05 lulin // - перекладываем ветку в HEAD. // // Revision 1.33.4.45 2007/11/28 15:31:54 dinishev // Избавляемся от Assert'ов при работе с таблицами в Арчи // // Revision 1.33.4.44 2007/09/14 13:26:06 lulin // - объединил с веткой B_Tag_Clean. // // Revision 1.33.4.43.2.1 2007/09/12 15:23:02 lulin // - избавляемся от метода, дублирующего функциональность получения атрибута. // // Revision 1.33.4.43 2007/07/18 15:07:19 lulin // - выпрямляем зависимости. Схема документа, теперь не зависит от Эвереста. // // Revision 1.33.4.42 2007/02/12 17:15:59 lulin // - переводим на строки с кодировкой. // // Revision 1.33.4.41 2007/02/12 16:40:20 lulin // - переводим на строки с кодировкой. // // Revision 1.33.4.40 2007/01/24 10:21:42 oman // - new: Локализация библиотек - ev (cq24078) // // Revision 1.33.4.39 2006/11/03 11:00:07 lulin // - объединил с веткой 6.4. // // Revision 1.33.4.38.2.10 2006/10/31 09:39:37 lulin // - используем карту форматирования переданную сверху, а не привязанную к курсору. // // Revision 1.33.4.38.2.9 2006/10/31 09:21:18 lulin // - при поиске горячей точки подаем уже вычисленную карту форматирования. // // Revision 1.33.4.38.2.8 2006/10/25 14:30:48 lulin // - визуальная точка изничтожена как класс. // // Revision 1.33.4.38.2.7 2006/10/25 10:47:11 lulin // - с видимой точки убрана горизонтальная координата. // // Revision 1.33.4.38.2.6 2006/10/23 08:58:09 lulin // - теперь при определении "горячей точки" передаем базовый курсор. // // Revision 1.33.4.38.2.5 2006/10/19 13:33:18 lulin // - переводим курсоры и подсказки на новые рельсы. // // Revision 1.33.4.38.2.4 2006/10/19 12:05:43 lulin // - добавлен метод для выяснения информации о позиции курсора. // // Revision 1.33.4.38.2.3 2006/10/19 10:56:17 lulin // - параметры курсора переехали в более общую библиотеку. // // Revision 1.33.4.38.2.2 2006/10/18 13:06:34 lulin // - вычищены ненужные данные. // // Revision 1.33.4.38.2.1 2006/10/18 12:33:15 lulin // - типы для обработки мыши переехали в более общую библиотеку. // // Revision 1.33.4.38 2006/10/10 12:06:14 lulin // - cleanup. // // Revision 1.33.4.37 2006/10/06 08:19:42 lulin // - выкидываем ненужный параметр - класс горячей точки. // // Revision 1.33.4.36.2.2 2006/10/04 15:17:08 lulin // - выкидываем ненужный параметр - класс горячей точки. // // Revision 1.33.4.36.2.1 2006/10/04 14:10:20 lulin // - упрощаем механизм получения горячих точек. // // Revision 1.33.4.36 2006/10/04 11:23:02 lulin // - при получении горячей точки передаем "состояние" курсора. // // Revision 1.33.4.35 2006/10/04 08:32:06 lulin // - теперь умолчательное поведение при действиях мышью описывается структурой - чтобы проще было расширять интерфейс. // // Revision 1.33.4.34 2006/10/04 06:23:44 lulin // - точку мыши упаковываем в состояние мыши. // // Revision 1.33.4.33 2006/10/04 04:33:51 lulin // - избавляемся от возвращаемого результа в стиле OLE. // // Revision 1.33.4.32 2006/07/21 11:40:26 lulin // - имя метода убрано из комментариев - чтобы не находилось контекстным поиском. // // Revision 1.33.4.31 2006/07/21 11:35:25 lulin // - имя метода убрано из комментариев - чтобы не находилось контекстным поиском. // // Revision 1.33.4.30 2006/07/20 18:36:56 lulin // - имя метода убрано из комментариев - чтобы не находилось контекстным поиском. // // Revision 1.33.4.29 2006/07/20 12:55:46 lulin // - имя метода убрано из комментариев - чтобы не находилось контекстным поиском. // // Revision 1.33.4.28 2006/07/03 11:58:53 lulin // - передаем не множество клавиш, а "состояние мыши". // // Revision 1.33.4.27 2005/11/21 09:56:54 lulin // - удален ненужный глобальный метод. // // Revision 1.33.4.26 2005/11/08 06:39:37 lulin // - с текстового параграфа и списка параграфов вычищены ненужные методы получения сложной формы параграфа. // // Revision 1.33.4.25 2005/11/07 06:25:22 lulin // - выделяем у якоря и у курсора общую функциональность. // // Revision 1.33.4.24 2005/09/23 16:03:55 lulin // - выделен модуль с общими интерфейсами. // // Revision 1.33.4.23 2005/08/31 12:04:34 lulin // - удален ненужный модуль. // // Revision 1.33.4.22 2005/08/25 14:12:52 lulin // - new behavior: для КЗ не выводим Hint'ы и прочее для строк и ячеек таблицы с контролами. // // Revision 1.33.4.21 2005/07/20 18:21:14 lulin // - убран переходный интерфейс. // // Revision 1.33.4.20 2005/07/18 11:22:37 lulin // - методу, возвращаещему выделение на параграфе дано более подходящее название. // // Revision 1.33.4.19 2005/07/07 16:54:02 lulin // - cleanup. // // Revision 1.33.4.18 2005/07/07 15:38:05 lulin // - InevViewPoint теперь не наследуется от InevAnchor. // // Revision 1.33.4.17 2005/07/07 15:10:38 lulin // - new behavior: теперь HotSpot запоминает точку в которой находился курсор. // // Revision 1.33.4.16 2005/07/07 13:09:28 lulin // - упорядочены названия интерфейсов. // // Revision 1.33.4.15 2005/07/07 11:41:17 lulin // - передаем в _GetAdvancedHotSpot специальный интерфейс InevViewPoint. // // Revision 1.33.4.14 2005/07/05 16:02:44 lulin // - bug fix: восстановлен скроллинг при выделении текста мышью. // // Revision 1.33.4.13 2005/06/20 15:42:10 lulin // - cleanup: избавляемся от абсолютных координат. // // Revision 1.33.4.12 2005/06/16 11:24:12 lulin // - убрана косвенная типизация параграфов (при помощи _QI и QT). // // Revision 1.33.4.11 2005/06/15 17:23:52 lulin // - remove proc: _evMoveCursor. // // Revision 1.33.4.10 2005/06/14 14:51:51 lulin // - new interface: _InevSelection. // - remove interface: IevSelection. // // Revision 1.33.4.9 2005/06/14 12:38:58 lulin // - избавился от передачи безликого интерфейса (теперь передается View). // // Revision 1.33.4.8 2005/06/14 10:01:31 lulin // - избавился от передачи безликого интерфейса (теперь передается View). // // Revision 1.33.4.7 2005/06/11 08:55:38 lulin // - в какой-то мере восстановлена работоспособность HotSpot'ов. // // Revision 1.33.4.6 2005/06/06 15:36:09 lulin // - продолжаем бороться со знанием о природе реализации курсоров. // // Revision 1.33.4.5 2005/06/02 12:33:08 lulin // - вчерне заменил прямое создание блока выделения на его получение от фабрики. // // Revision 1.33.4.4 2005/06/01 16:22:25 lulin // - remove unit: evIntf. // // Revision 1.33.4.3 2005/05/31 17:46:39 lulin // - изживаем остатки объектов в качестве курсоров. // // Revision 1.33.4.2 2005/05/31 14:48:01 lulin // - cleanup: при работе с курсорами используем интерфейсы, а не объекты. // // Revision 1.33.4.1 2005/05/18 12:42:47 lulin // - отвел новую ветку. // // Revision 1.30.2.4 2005/05/18 12:32:10 lulin // - очередной раз объединил ветку с HEAD. // // Revision 1.30.2.3 2005/04/28 09:18:30 lulin // - объединил с веткой B_Tag_Box. // // Revision 1.30.2.2 2005/04/09 12:48:37 lulin // - метод ParaByOffset переименован в _ShapeByPt и перенесен на интерфейс InevComplexShape. // // Revision 1.30.2.1 2005/04/08 13:35:05 lulin // - _Processor стал обязательным параметром. // // Revision 1.32.2.1 2005/04/23 16:07:25 lulin // - удален временный интерфейс Ik2TagBox. // // Revision 1.32 2005/04/21 05:11:38 lulin // - используем _Box (пока из-за постоянных преобразований туда и обратно - по скорости стало только хуже). // // Revision 1.31 2005/04/20 17:40:50 lulin // - избавился от промежуточного интерфейса Ik2TagBoxQT. // // Revision 1.33 2005/04/28 15:03:38 lulin // - переложил ветку B_Tag_Box в HEAD. // // Revision 1.32.2.1 2005/04/23 16:07:25 lulin // - удален временный интерфейс Ik2TagBox. // // Revision 1.32 2005/04/21 05:11:38 lulin // - используем _Box (пока из-за постоянных преобразований туда и обратно - по скорости стало только хуже). // // Revision 1.31 2005/04/20 17:40:50 lulin // - избавился от промежуточного интерфейса Ik2TagBoxQT. // // Revision 1.30 2005/04/07 15:42:05 lulin // - cleanup. // // Revision 1.29 2005/04/07 14:32:49 lulin // - remove proc: evGetTopPara. // // Revision 1.28 2005/03/28 11:32:08 lulin // - интерфейсы переехали в "правильный" модуль. // // Revision 1.27 2005/03/24 13:14:37 lulin // - уделена ненужная функция преобразования Tk2AtomR к _Ik2Tag. // // Revision 1.26 2005/03/21 16:28:16 lulin // - переходим к _Ik2Tag. // // Revision 1.25 2005/03/19 16:39:51 lulin // - спрятаны ненужные методы. // // Revision 1.24 2005/03/16 17:04:21 lulin // - переходим к _Ik2Tag. // // Revision 1.23 2005/03/16 12:16:52 lulin // - переходим к _Ik2Tag. // // Revision 1.22 2005/03/10 16:22:31 lulin // - от Tk2AtomR переходим к _Ik2Tag. // // Revision 1.21 2005/03/10 14:58:38 lulin // - от Tk2AtomR переходим к _Ik2Tag. // // Revision 1.20 2005/03/09 18:40:19 lulin // - remove method: Tk2AtomR.DeleteChild. // - new method: _Ik2Tag.DeleteChild. // // Revision 1.19 2004/11/10 11:06:08 lulin // - new interface: IevTagShape. // - remove interface: IevVisualShapedTag. // // Revision 1.18 2004/06/30 10:48:41 law // - изменен тип параметра Parent у методов IevVisualShapedTag._ParentToClient, _ClientToParent с IUnknown на _Ik2Tag. // // Revision 1.17 2003/10/02 16:33:24 law // - rename unit: evBseCur -> evBaseCursor. // // Revision 1.16 2003/02/14 17:10:06 law // - bug fix: BUG: Если вставить новую таблицу, потом выделить две соседние ячейки (при помощи HotSpot), потом во вторую вставить три-четыре параграфа, а потом опять попытаться выделить те же самые ячейки, то вторая ячейка выделяется не целиком (№122). // // Revision 1.15 2003/01/14 17:26:40 law // - bug fix: улучшено выделение столбца по Ctrl. // - new behavior: возможность выделения нескольких столбцов. // // Revision 1.14 2003/01/14 16:48:40 law // - new behavior: возможность выделения сразу нескольких ячеек из HotSpot. // // Revision 1.13 2003/01/14 15:21:26 law // - bug fix: некорректно обрабатывался DoubleClick - в конце операции оставалась выделенной ячейка, а не строка. // // Revision 1.12 2003/01/13 17:35:49 law // - new behavior: расширена возможность выделения строк при DoubleClick внутри ячейки. // // Revision 1.11 2002/07/09 12:02:21 law // - rename unit: evUnits -> l3Units. // // Revision 1.10 2001/11/26 14:31:04 law // - change type: Keys: Long -> Keys: TShiftState. // // Revision 1.9 2001/04/27 14:11:49 law // - new behavior: убран ненужный вертикальный строб. // // Revision 1.8 2001/04/12 16:35:26 law // - new behavior: сделаны стробы при операциях с мышью. // // Revision 1.7 2001/03/22 15:20:23 law // - добавлена функция evTable_GetMergeHead. // // Revision 1.6 2001/03/19 15:34:56 law // - сделана обработка вертикального объединения ячеек. // // Revision 1.5 2001/03/01 14:13:45 law // - сделано выделение таблицы целиком при Ctrl+Double Click. // // Revision 1.4 2001/01/31 10:37:31 law // - оптимизировано использование QueryInterface. // // Revision 1.3 2000/12/15 15:10:38 law // - вставлены директивы Log. // {$Include evDefine.inc } interface uses Windows, Classes, l3Types, l3Base, l3IID, l3Units, afwInterfaces, k2Interfaces, k2InternalInterfaces, evInternalInterfaces, evEditorInterfaces, evParaListHotSpotTester, evSelectingHotSpot, nevBase, nevTools, nevGUIInterfaces ; type TevTableCellHotSpotTester = class(TevParaListHotSpotTester) {* - реализует интерфейс IevHotSpotTester для ячейки таблицы. } protected // internal methods function NeedCellSpot: Boolean; virtual; {-} public // public methods function DoGetAdvancedHotSpot(const aView : InevControlView; const aState : TevCursorState; const aPt : InevBasePoint; const aMap : InevMap; out theSpot : IevHotSpot): Boolean; override; {* - возвращает HotSpot для точки aPt ячейки таблицы. } end;//TevTableCellHotSpotTester TevTableCellHotSpot = class(TevSelectingHotSpotEx) {* - реализует интерфейс IevAdvancedHotSpot для ячейки таблицы. } private //internal fields f_Cell : IedCell; f_StartCell : InevBasePoint; protected //property methods procedure DoHitTest(const aView : InevControlView; const aState : TafwCursorState; var theInfo : TafwCursorInfo); override; {-} protected //internal methods procedure Cleanup; override; {-} function DoMouseAction(const aView : InevControlView; aButton : TevMouseButton; anAction : TevMouseAction; const Keys : TevMouseState; var Effect : TevMouseEffect): Bool; override; {* - обрабатывает событие мыши. } function SelectionTable : InevParaList; {-} function InitSelection(const aView : InevControlView; const aPt : InevBasePoint; const theStart : InevBasePoint; const theFinish : InevBasePoint): Bool; override; {-} public //public methods function COMQueryInterface(const IID: Tl3GUID; out Obj): Tl3HResult; override; {-} end;//TevTableCellHotSpot implementation uses SysUtils, l3InterfacesMisc, l3String, evdTypes, evConst, k2Tags, evOp, evCursorTools, evParaTools, evTableTools, evTableRowHotSpot, evTableHotSpot, evHotSpotMisc, nevInterfaces, TableRow_Const, TableCell_Const ; // start class TevTableCellHotSpotTester function TevTableCellHotSpotTester.NeedCellSpot: Boolean; //virtual; {-} begin Result := true; end; function TevTableCellHotSpotTester.DoGetAdvancedHotSpot(const aView : InevControlView; const aState : TevCursorState; const aPt : InevBasePoint; const aMap : InevMap; out theSpot : IevHotSpot): Boolean; //override; {-} var l_Map : InevMap; l_Pt : TnevPoint; begin if NeedCellSpot then begin l_Map := aMap; if (l_Map <> nil) then begin l_Pt := Tl3Point(aState.rPoint).Sub(l_Map.Bounds.R.TopLeft); with l_Pt do begin if (X > evEpsilon * 2) AND (X <= evEpsilon * 7) AND (Y >= l_Map.FI.Height - evEpsilon * 7) then begin theSpot := TevHotSpotWrap.Make(TevTableCellHotSpot.Make(GetRedirect, Processor)); Result := True; Exit; end;//X <= evEpsilon * 2.. end;//with aPt end;//l_Map <> nil end;//..IevAdvancedHotSpot.. Result := inherited DoGetAdvancedHotSpot(aView, aState, aPt, aMap, theSpot); end; // start class TevTableCellHotSpot procedure TevTableCellHotSpot.Cleanup; //override; {-} begin f_Cell := nil; f_StartCell := nil; inherited; end; procedure TevTableCellHotSpot.DoHitTest(const aView : InevControlView; const aState : TafwCursorState; var theInfo : TafwCursorInfo); //override; {-} begin inherited; theInfo.rCursor := ev_csSelectCell; theInfo.rHint := str_nevmhhTableCell.AsCStr; end; function TevTableCellHotSpot.COMQueryInterface(const IID: Tl3GUID; out Obj): Tl3HResult; //override; {-} begin if IID.EQ(IedCell) AND (f_Cell <> nil) then begin IedCell(Obj) := f_Cell; Result.SetOk; end//IID.EQ(IedCell) AND (f_Cell <> nil) else Result := inherited COMQueryInterface(IID, Obj); end; function TevTableCellHotSpot.DoMouseAction(const aView : InevControlView; aButton : TevMouseButton; anAction : TevMouseAction; const Keys : TevMouseState; var Effect : TevMouseEffect): Bool; {-} var l_TableHotSpot : TevTableHotSpot; l_Point : InevBasePoint; l_Start : InevPoint; l_Finish : InevPoint; l_Block : InevRange; begin evQueryParaInterface(aView, aView.Control.Processor, ParaX, Tl3GUID_C(IedCell), f_Cell); case aButton of ev_mbLeft : begin case anAction of ev_maDown : if not (ssCtrl in Keys.rKeys) then begin f_StartCell := ParaX.MakePoint; f_StartCell.SetAtStart(aView, True); f_StartCell := f_StartCell.PointToTypedParent(k2_typTableRow); Result := aView.Control.Selection <> nil; if Result then begin l_Start := ParaX.MakePoint; l_Finish := ParaX.MakePoint; l_Start.SetAtStart(aView, True); l_Finish.SetAtEnd(aView, True); if (ParaX.AsObject.ChildrenCount <= 1) AND l_Finish.AtStart then l_Block := ParaX.Range(l_Finish, l_Finish) else l_Block := ParaX.Range(l_Start, l_Finish); aView.Control.Selection.Select(l_Block, false); end; // if Result then end//not (ssCtrl in Keys.rKeys) else begin l_Point := aView.PointByPt(Tl3Point(Keys.rPoint)); while l_Point.HasInner do begin if l_Point.AsObject.IsKindOf(k2_typTableCell) then Break; l_Point := l_Point.Inner; end;//while l_Point.HasInner if l_Point <> nil then l_TableHotSpot := TevTableHotSpot.Create(SelectionTable.AsObject, Processor, l_Point.Obj.PID) else Assert(False); try f_ForeignHotSpot := l_TableHotSpot; Result := f_ForeignHotSpot.MouseAction(aView, aButton, ev_maDown, Keys, Effect); finally l3Free(l_TableHotSpot); end;//try..finally end;//not (ssCtrl in Keys.rKeys) ev_maDouble : begin if not (ssCtrl in Keys.rKeys) then begin f_ForeignHotSpot := TevTableRowHotSpot.Make(GetRedirect.Owner, Processor); Result := f_ForeignHotSpot.MouseAction(aView, aButton, ev_maDown, Keys, Effect); end//not (ssCtrl in Keys.rKeys) else begin Result := evSelectTablePara(aView.Control.Selection, SelectionTable); if Result then Effect.rNeedAsyncLoop := False; end;//not (ssCtrl in Keys.rKeys) end;//ev_maDouble else Result := True; end;//case anAction end;//ev_mbLeft else Result := False; end;//case aButton end; function TevTableCellHotSpot.SelectionTable : InevParaList; //override; {-} begin Result := ParaX.OwnerPara.OwnerPara; end; function TevTableCellHotSpot.InitSelection(const aView : InevControlView; const aPt : InevBasePoint; const theStart : InevBasePoint; const theFinish : InevBasePoint): Bool; //override; {-} var l_Point : InevBasePoint; l_StartCell : InevBasePoint; l_FinishCell : InevBasePoint; begin Result := True; Assert(aView <> nil); l_Point := aPt; while (l_Point <> nil) do begin if l_Point.AsObject.IsKindOf(k2_typTableRow) then Break; l_Point := l_Point.Inner; end;//while (l_Point <> nil) if (l_Point <> nil) then begin if (f_StartCell.Obj.PID > l_Point.Obj.PID) then begin if (l_Point.Inner <> nil) AND (f_StartCell.Inner.Obj.PID < l_Point.Inner.Obj.PID) then begin l_StartCell := f_StartCell.Inner; l_FinishCell := l_Point.Inner; theFinish.AssignPoint(aView, f_StartCell); theFinish.SetEntryPoint(l_FinishCell.Obj.PID + 1); theStart.AssignPoint(aView, l_Point); theStart.SetEntryPoint(l_StartCell.Obj.PID + 1); end//f_StartCell.Inner.Obj.PID < l_Point.Inner.Obj.PID else begin theFinish.AssignPoint(aView, f_StartCell); theStart.AssignPoint(aView, l_Point); end;//f_StartCell.Inner.Obj.PID < l_Point.Inner.Obj.PID end//f_StartCell.Obj.PID > l_Point.Obj.PID else begin if (l_Point.Inner <> nil) AND (f_StartCell.Inner.Obj.PID > l_Point.Inner.Obj.PID) then begin if (f_StartCell.Obj.PID = l_Point.Obj.PID) then begin theFinish.AssignPoint(aView, f_StartCell); theStart.AssignPoint(aView, l_Point); end//f_StartCell.Obj.PID = l_Point.Obj.PID else begin l_StartCell := f_StartCell.Inner; l_FinishCell := l_Point.Inner; theFinish.AssignPoint(aView, l_Point{f_StartCell}); theFinish.SetEntryPoint(l_FinishCell.Obj.PID + 1); theStart.AssignPoint(aView, f_StartCell{l_Point}); theStart.SetEntryPoint(l_StartCell.Obj.PID + 1); end;//f_StartCell.Obj.PID = l_Point.Obj.PID end//f_StartCell.Inner.Obj.PID > l_Point.Inner.Obj.PID else begin theStart.AssignPoint(aView, f_StartCell); theFinish.AssignPoint(aView, l_Point); end;//f_StartCell.Inner.Obj.PID > l_Point.Inner.Obj.PID end;//f_StartCell.Obj.PID > l_Point.Obj.PID if theStart.HasInner then theStart.Inner.SetAtStart(aView, True); if theFinish.HasInner then theFinish.Inner.SetAtEnd(aView, True); end//l_Point <> nil else Result := False; end; end.
namespace Sugar.Test; interface uses Sugar; type XmlTestData = public static class public method RssXml: String; method PIXml: String; method CharXml: String; method DTDXml: String; end; implementation method XmlTestData.RssXml: String; begin exit "<?xml version=""1.0"" encoding=""UTF-8""?> <rss version=""2.0"" xmlns:content=""http://purl.org/rss/1.0/modules/content/"" xmlns:wfw=""http://wellformedweb.org/CommentAPI/"" xmlns:dc=""http://purl.org/dc/elements/1.1/"" xmlns:atom=""http://www.w3.org/2005/Atom"" xmlns:sy=""http://purl.org/rss/1.0/modules/syndication/"" xmlns:slash=""http://purl.org/rss/1.0/modules/slash/""> <channel> <title>RemObjects Blogs</title> <atom:link href=""http://blogs.remobjects.com/feed"" rel=""self"" type=""application/rss+xml"" /> <link>http://blogs.remobjects.com</link> <description>Remobjects Software Blogs</description> <lastBuildDate>Mon, 04 Nov 2013 18:10:49 +0000</lastBuildDate> <!--Rss--> <language>en-US</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.5</generator> <item> <title>Announcing the Oxygene &#8220;October 2013&#8243; Update</title> <link>http://blogs.remobjects.com/blogs/mh/2013/11/04/p6509</link> <comments>http://blogs.remobjects.com/blogs/mh/2013/11/04/p6509#comments</comments> <pubDate>Mon, 04 Nov 2013 18:10:49 +0000</pubDate> <dc:creator>marc</dc:creator> <category><![CDATA[iOS]]></category> <category><![CDATA[Nougat]]></category> <category><![CDATA[Oxygene]]></category> <guid isPermaLink=""false"">http://blogs.remobjects.com/?p=6509</guid> <description><![CDATA[Description]]></description> <content:encoded><![CDATA[Content]]></content:encoded> <wfw:commentRss>http://blogs.remobjects.com/blogs/mh/2013/11/04/p6509/feed</wfw:commentRss> <slash:comments>0</slash:comments> </item> </channel> </rss>"; end; class method XmlTestData.PIXml: String; begin exit "<?xml version=""1.0"" encoding=""UTF-8""?> <?xml-stylesheet type=""text/xsl"" href=""test""?> <?custom?> <Root> <Readers> <User Name=""First"" Id=""1""> <Config xmlns:cfg=""http://example.com/config/""> <cfg:mail cfg:verified=""true"">first@example.com</cfg:mail> <cfg:autologin>true</cfg:autologin> <cfg:savepassword>true</cfg:savepassword> </Config> </User> <User Name=""Second"" Id=""2""/> <User Name=""Third"" Id=""3""/> </Readers> <Admins> <User Name=""Admin"" Id=""0""/> </Admins> </Root> "; end; class method XmlTestData.CharXml: String; begin exit "<?xml version=""1.0"" encoding=""UTF-8""?> <!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Transitional//EN"" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd""> <Book> <Title>Text</Title> <Description><![CDATA[Description]]></Description> <!--Comment--> </Book>"; end; class method XmlTestData.DTDXml: String; begin exit "<?xml version=""1.0""?> <!DOCTYPE note [ <!ELEMENT note (to,from,heading,body)> <!ELEMENT to (#PCDATA)> <!ELEMENT from (#PCDATA)> <!ELEMENT heading (#PCDATA)> <!ELEMENT body (#PCDATA)> ]> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend</body> </note>"; end; end.
unit DEX.Transform; interface uses System.SysUtils, System.DateUtils, System.Math, Charts.Math, Candles.Types, Measures.Types, DEX.Types; const CANDLE_DURATION = 1000; type TCandlesTransform = class private const UNIX_MINUTE = 60; UNIX_5_MINUTE = 5*UNIX_MINUTE; UNIX_15_MINUTE = 15*UNIX_MINUTE; UNIX_30_MINUTE = 30*UNIX_MINUTE; UNIX_HOUR = 60*UNIX_MINUTE; UNIX_2_HOUR = 2*UNIX_HOUR; UNIX_6_HOUR = 6*UNIX_HOUR; UNIX_12_HOUR = 12*UNIX_HOUR; UNIX_DAY = 24*UNIX_HOUR; UNIX_WEEK = 7*UNIX_DAY; DIV_MINUTE_COUNT = 5; DIV_5_MINUTE_COUNT = 6; DIV_15_MINUTE_COUNT = 4; DIV_30_MINUTE_COUNT = 6; DIV_HOUR_COUNT = 6; DIV_2_HOUR_COUNT = 6; DIV_6_HOUR_COUNT = 8; DIV_12_HOUR_COUNT = 6; DIV_DAY_COUNT = 5; DIV_WEEK_COUNT = 6; DIV_MONTH_COUNT = 6; private IntervalCode: Integer; StartDateTime: TDateTime; EndDateTime: TDateTime; FirstTime: Int64; LastDateTime: TDateTime; LastTime: Int64; EndIntervalTime: Int64; LastClose: Extended; MinValue: Extended; MaxValue: Extended; procedure DoExceptionIntervalCode; inline; function UnixTimeToTime(UnixTime: Int64): Int64; function TimeToDateTime(Time: Int64): TDateTime; function DecOneInterval(UnixTime: Int64): Int64; function GetDivFirstTime: Int64; function GetAlignedTime(UnixTime: Int64): Int64; function GetDivDuration: Int64; function FormatTime(DateTime: TDateTime): string; function FormatTitleTime(DateTime: TDateTime): string; public constructor Create; function AddDataCandle(IntervalCode: Integer; const Candles: TDataCandles): TCandles; procedure Clear; function GetLastTime: Int64; function GetLastDateTime: TDateTime; function GetValueMeasure: TMeasures; function GetElapsesMeasure: TElapses; function GetIntervalCode: Integer; procedure InitStartInterval(IntervalCode: Integer); function GetStartDateTime: TDateTime; function GetTime: Int64; end; implementation constructor TCandlesTransform.Create; begin Clear; end; function TCandlesTransform.GetIntervalCode: Integer; begin Result:=IntervalCode; end; function TCandlesTransform.GetLastTime: Int64; begin Result:=LastTime; end; function TCandlesTransform.GetTime: Int64; begin if LastTime=0 then Result:=EndIntervalTime else Result:=LastTime; end; function TCandlesTransform.GetLastDateTime: TDateTime; begin Result:=LastDateTime; end; procedure TCandlesTransform.DoExceptionIntervalCode; begin raise Exception.Create('candles transform: invalid interval code: '+IntervalCode.ToString); end; procedure TCandlesTransform.InitStartInterval(IntervalCode: Integer); begin case IntervalCode of 1: StartDateTime:=IncMinute(Now,-60); 2: StartDateTime:=IncMinute(Now,-80*5); 3: StartDateTime:=IncMinute(Now,-60*15); 4: StartDateTime:=IncMinute(Now,-40*30); 5: StartDateTime:=IncHour(Now,-40); 6: StartDateTime:=IncHour(Now,-40*2); 7: StartDateTime:=IncHour(Now,-40*6); 8: StartDateTime:=IncHour(Now,-40*12); 9: StartDateTime:=IncDay(Now,-40); 10: StartDateTime:=IncWeek(Now,-40); 11: StartDateTime:=IncMonth(Now,-40); else DoExceptionIntervalCode; end; Clear; Self.IntervalCode:=IntervalCode; FirstTime:=GetAlignedTime(DateTimeToUnix(StartDateTime,False)); EndIntervalTime:=UnixTimeToTime(DateTimeToUnix(Now,False)); end; function TCandlesTransform.GetStartDateTime: TDateTime; begin Result:=StartDateTime; end; function TCandlesTransform.GetAlignedTime(UnixTime: Int64): Int64; begin case IntervalCode of 1: Result:=(UnixTime div UNIX_MINUTE)*UNIX_MINUTE; 2: Result:=(UnixTime div UNIX_5_MINUTE)*UNIX_5_MINUTE; 3: Result:=(UnixTime div UNIX_15_MINUTE)*UNIX_15_MINUTE; 4: Result:=(UnixTime div UNIX_30_MINUTE)*UNIX_30_MINUTE; 5: Result:=(UnixTime div UNIX_HOUR)*UNIX_HOUR; 6: Result:=(UnixTime div UNIX_2_HOUR)*UNIX_2_HOUR; 7: Result:=(UnixTime div UNIX_6_HOUR)*UNIX_6_HOUR; 8: Result:=(UnixTime div UNIX_12_HOUR)*UNIX_12_HOUR; 9: Result:=(UnixTime div UNIX_DAY)*UNIX_DAY; 10: Result:=(UnixTime div UNIX_WEEK)*UNIX_WEEK-UNIX_DAY*3; // unix 0 time is thursday 11: Result:=DateTimeToUnix(StartOfTheYear(UnixToDateTime(UnixTime))); else DoExceptionIntervalCode; end; end; function TCandlesTransform.UnixTimeToTime(UnixTime: Int64): Int64; begin case IntervalCode of 1: Result:=((UnixTime-FirstTime) div UNIX_MINUTE)*CANDLE_DURATION; 2: Result:=((UnixTime-FirstTime) div UNIX_5_MINUTE)*CANDLE_DURATION; 3: Result:=((UnixTime-FirstTime) div UNIX_15_MINUTE)*CANDLE_DURATION; 4: Result:=((UnixTime-FirstTime) div UNIX_30_MINUTE)*CANDLE_DURATION; 5: Result:=((UnixTime-FirstTime) div UNIX_HOUR)*CANDLE_DURATION; 6: Result:=((UnixTime-FirstTime) div UNIX_2_HOUR)*CANDLE_DURATION; 7: Result:=((UnixTime-FirstTime) div UNIX_6_HOUR)*CANDLE_DURATION; 8: Result:=((UnixTime-FirstTime) div UNIX_12_HOUR)*CANDLE_DURATION; 9: Result:=((UnixTime-FirstTime) div UNIX_DAY)*CANDLE_DURATION; 10: Result:=((UnixTime-FirstTime) div UNIX_WEEK)*CANDLE_DURATION; 11: Result:=MonthsBetween(UnixToDateTime(FirstTime),StartOfTheMonth(UnixToDateTime(UnixTime)))*CANDLE_DURATION; else DoExceptionIntervalCode; end; end; function TCandlesTransform.TimeToDateTime(Time: Int64): TDateTime; begin case IntervalCode of 1: Time:=(Time div CANDLE_DURATION)*UNIX_MINUTE+FirstTime; 2: Time:=(Time div CANDLE_DURATION)*UNIX_5_MINUTE+FirstTime; 3: Time:=(Time div CANDLE_DURATION)*UNIX_15_MINUTE+FirstTime; 4: Time:=(Time div CANDLE_DURATION)*UNIX_30_MINUTE+FirstTime; 5: Time:=(Time div CANDLE_DURATION)*UNIX_HOUR+FirstTime; 6: Time:=(Time div CANDLE_DURATION)*UNIX_2_HOUR+FirstTime; 7: Time:=(Time div CANDLE_DURATION)*UNIX_6_HOUR+FirstTime; 8: Time:=(Time div CANDLE_DURATION)*UNIX_12_HOUR+FirstTime; 9: Time:=(Time div CANDLE_DURATION)*UNIX_DAY+FirstTime; 10: Time:=(Time div CANDLE_DURATION)*UNIX_WEEK+FirstTime; 11: begin Result:=UnixToDateTime(FirstTime,False); Exit(IncMonth(Result,Time div CANDLE_DURATION)); end else DoExceptionIntervalCode; end; Result:=UnixToDateTime(Time,False); end; function TCandlesTransform.DecOneInterval(UnixTime: Int64): Int64; begin case IntervalCode of 1: Result:=UnixTime-UNIX_MINUTE; 2: Result:=UnixTime-UNIX_5_MINUTE; 3: Result:=UnixTime-UNIX_15_MINUTE; 4: Result:=UnixTime-UNIX_30_MINUTE; 5: Result:=UnixTime-UNIX_HOUR; 6: Result:=UnixTime-UNIX_2_HOUR; 7: Result:=UnixTime-UNIX_6_HOUR; 8: Result:=UnixTime-UNIX_12_HOUR; 9: Result:=UnixTime-UNIX_DAY; 10: Result:=UnixTime-UNIX_WEEK; 11: Result:=DateTimeToUnix(IncMonth(UnixToDateTime(UnixTime),-1)); else DoExceptionIntervalCode; end; end; function TCandlesTransform.GetDivFirstTime: Int64; begin case IntervalCode of 1: Result:=-((FirstTime mod (UNIX_MINUTE*DIV_MINUTE_COUNT)) div UNIX_MINUTE)*CANDLE_DURATION; 2: Result:=-((FirstTime mod (UNIX_5_MINUTE*DIV_5_MINUTE_COUNT)) div UNIX_5_MINUTE)*CANDLE_DURATION; 3: Result:=-((FirstTime mod (UNIX_15_MINUTE*DIV_15_MINUTE_COUNT)) div UNIX_15_MINUTE)*CANDLE_DURATION; 4: Result:=-((FirstTime mod (UNIX_30_MINUTE*DIV_30_MINUTE_COUNT)) div UNIX_30_MINUTE)*CANDLE_DURATION; 5: Result:=-((FirstTime mod (UNIX_HOUR*DIV_HOUR_COUNT)) div UNIX_HOUR)*CANDLE_DURATION; 6: Result:=-((FirstTime mod (UNIX_2_HOUR*DIV_2_HOUR_COUNT)) div UNIX_2_HOUR)*CANDLE_DURATION; 7: Result:=-((FirstTime mod (UNIX_6_HOUR*DIV_6_HOUR_COUNT)) div UNIX_6_HOUR)*CANDLE_DURATION; 8: Result:=-((FirstTime mod (UNIX_12_HOUR*DIV_12_HOUR_COUNT)) div UNIX_12_HOUR)*CANDLE_DURATION; 9: Result:=-((FirstTime mod (UNIX_DAY*DIV_DAY_COUNT)) div UNIX_DAY)*CANDLE_DURATION; 10: Result:=-((FirstTime mod (UNIX_WEEK*DIV_WEEK_COUNT)) div UNIX_WEEK)*CANDLE_DURATION; 11: Result:=0; else DoExceptionIntervalCode; end; end; function TCandlesTransform.GetDivDuration: Int64; begin case IntervalCode of 1: Result:=DIV_MINUTE_COUNT*CANDLE_DURATION; 2: Result:=DIV_5_MINUTE_COUNT*CANDLE_DURATION; 3: Result:=DIV_15_MINUTE_COUNT*CANDLE_DURATION; 4: Result:=DIV_30_MINUTE_COUNT*CANDLE_DURATION; 5: Result:=DIV_HOUR_COUNT*CANDLE_DURATION; 6: Result:=DIV_2_HOUR_COUNT*CANDLE_DURATION; 7: Result:=DIV_6_HOUR_COUNT*CANDLE_DURATION; 8: Result:=DIV_12_HOUR_COUNT*CANDLE_DURATION; 9: Result:=DIV_DAY_COUNT*CANDLE_DURATION; 10: Result:=DIV_WEEK_COUNT*CANDLE_DURATION; 11: Result:=DIV_MONTH_COUNT*CANDLE_DURATION; else DoExceptionIntervalCode; end; end; function TCandlesTransform.FormatTime(DateTime: TDateTime): string; begin case IntervalCode of 1: Result:=FormatDateTime('hh:mm',DateTime); 2: Result:=FormatDateTime('hh:mm',DateTime); 3: Result:=FormatDateTime('hh:mm',DateTime); 4: Result:=FormatDateTime('hh:mm',DateTime); 5: Result:=FormatDateTime('dd.mm hh:mm',DateTime); 6: Result:=FormatDateTime('dd.mm hh:mm',DateTime); 7: Result:=FormatDateTime('dd.mm hh:mm',DateTime); 8: Result:=FormatDateTime('dd.mm hh:mm',DateTime); 9: Result:=FormatDateTime('dd.mm.yyyy',DateTime); 10: Result:=FormatDateTime('dd.mm.yyyy',DateTime); 11: Result:=FormatDateTime('mmm yyyy',DateTime); else DoExceptionIntervalCode; end; end; function TCandlesTransform.FormatTitleTime(DateTime: TDateTime): string; begin case IntervalCode of 1..8: Result:=FormatDateTime('dd.mm.yyyy hh:mm',DateTime); 9,10: Result:=FormatDateTime('dd.mm.yyyy',DateTime); 11: Result:=FormatDateTime('mmmm yyyy',DateTime); else DoExceptionIntervalCode; end; end; procedure TCandlesTransform.Clear; begin FirstTime:=0; LastTime:=0; LastClose:=0; LastDateTime:=0; MinValue:=0; MaxValue:=0; end; function TCandlesTransform.AddDataCandle(IntervalCode: Integer; const Candles: TDataCandles): TCandles; var C: TCandle; Candle: TDataCandle; DateTime: TDateTime; CandleTime: Int64; begin Result:=nil; for Candle in Candles do begin CandleTime:=DecOneInterval(Candle.Time); if LastTime=0 then begin MinValue:=Candle.Min; MaxValue:=Candle.Max; end else begin MinValue:=Min(MinValue,Candle.Min); MaxValue:=Max(MaxValue,Candle.Max); end; DateTime:=UnixToDateTime(CandleTime,False); LastTime:=UnixTimeToTime(CandleTime); C.Title:=FormatTitleTime(DateTime); C.DateTime:=DateTime; C.Min:=Candle.Min; C.Max:=Candle.Max; C.Open:=Candle.Open; C.Close:=Candle.Close; C.Volume:=Candle.Volume; C.Time:=LastTime; C.Duration:=CANDLE_DURATION; LastTime:=LastTime+C.Duration; LastDateTime:=Candle.DateTime; LastClose:=C.Close; Result:=Result+[C]; end; end; function GetValueStep(Interval: Extended; Count: Integer; out Digits: Integer): Extended; var M: Extended; begin Result:=Interval; if Result=0 then Exit(0); M:=1; Digits:=1; while Result/M<1 do begin M:=M/10; Inc(Digits) end; while Result/M>10 do begin M:=M*10; Dec(Digits) end; Result:=FloatDiv(Result/Count,M/10*5); if Result=0 then Result:=M/10*5; end; function TCandlesTransform.GetValueMeasure: TMeasures; var M: TMeasure; Value,Step: Extended; Digits: Integer; S: string; begin Result:=nil; Step:=GetValueStep(Self.MaxValue-Self.MinValue,3,Digits); if Step<=0 then Exit; Value:=FloatDiv(Self.MaxValue,Step)+Step; S:='0.'+string.Create('0',Digits); repeat M.Value:=Value; M.Text:=FormatFloat(S,M.Value); Result:=Result+[M]; Value:=Value-Step; until Value<MinValue-Step; end; function TCandlesTransform.GetElapsesMeasure: TElapses; var C,DivDuration: Int64; E: TElapse; begin Result:=nil; C:=GetDivFirstTime; DivDuration:=GetDivDuration; repeat E.Time:=C; E.DateTime:=TimeToDateTime(E.Time); E.Text:=FormatTime(E.DateTime); C:=C+DivDuration; Result:=Result+[E]; until E.Time>GetTime; end; end.
unit uWinSocket; interface uses SysUtils, Classes,WinSock,Messages,SyncObjs,ExtCtrls, Forms,u_c_byte_buffer; const wm_asynch_select= wm_User; const k_buffer_max= 4096; k_tcp_ip_chunk= 1500; MAXSOCKCOUNT = 100; type TSocketDataEvent = procedure(Sender: TObject;SockNo:integer; Buf:String;DataLen: Integer)of object; TSocketConnectEvent = procedure(Sender: TObject;SockNo:integer)of object; TSocketErrorEvent = procedure(Sender: TObject;SockNo:integer;SocketError: Integer)of object; TServerSocketDataEvent = procedure(Sender: TObject;aWinSocket:tSocket;ClientIP:string; Buf:String;DataLen: Integer)of object; TdmWinsocket = class(TDataModule) procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); private l_wsa_data: twsaData; l_c_reception_buffer: c_byte_buffer; FTCSDeviceSender : TCriticalSection; FHandle : THandle; FOpen: Boolean; FConnectPort: integer; FConnectIP: string; FWinSocket: tSocket; FOnSocketSendComplete: TSocketConnectEvent; FOnSocketDisConnected: TSocketConnectEvent; FOnSocketConnected: TSocketConnectEvent; FOnSocketRead: TSocketDataEvent; FOnSocketSend: TSocketDataEvent; FOnSocketError: TSocketErrorEvent; { Private declarations } function GetHandle: THandle; procedure SetConnectIP(const Value: string); procedure SetConnectPort(const Value: integer); procedure SetOpen(const Value: Boolean); protected procedure WndProc ( var Message : TMessage ); virtual; public { Public declarations } function HandleAllocated : Boolean; procedure HandleNeeded; procedure handle_wm_async_select(var Msg: TMessage); message wm_asynch_select; function PutString(aData:string):Boolean; function PutChar(aChar:char):integer; published property Handle : THandle read GetHandle; property WinSocket : tSocket read FWinSocket write FWinSocket; property ConnectIP : string read FConnectIP write SetConnectIP; property ConnectPort : integer read FConnectPort write SetConnectPort; property Open : Boolean read FOpen write SetOpen; published //소켓 이벤트 property OnSocketConnected : TSocketConnectEvent read FOnSocketConnected write FOnSocketConnected; property OnSocketDisConnected : TSocketConnectEvent read FOnSocketDisConnected write FOnSocketDisConnected; property OnSocketRead : TSocketDataEvent read FOnSocketRead write FOnSocketRead; property OnSocketSend : TSocketDataEvent read FOnSocketSend write FOnSocketSend; property OnSocketSendComplete : TSocketConnectEvent read FOnSocketSendComplete write FOnSocketSendComplete; property OnSocketError : TSocketErrorEvent read FOnSocketError write FOnSocketError; end; var dmWinsocket: TdmWinsocket; implementation uses uUtil; {$R *.dfm} { TdmWinsocket } function TdmWinsocket.GetHandle: THandle; begin HandleNeeded; Result := FHandle; end; procedure TdmWinsocket.handle_wm_async_select(var Msg: TMessage); // -- wParam: hSocket, lo(lParam): notification, hi(lParam): error procedure handle_fd_connect_notification(p_socket: Integer); begin if Assigned(FOnSocketConnected) then begin OnSocketConnected(Self,p_socket); end; end; procedure handle_fd_write_notification(p_socket: Integer); begin if Assigned(FOnSocketSendComplete) then begin OnSocketSendComplete(Self,p_socket); end; end; procedure handle_fd_read_notification(p_socket: tSocket); var l_remaining: Integer; l_pt_start_reception: Pointer; l_packet_bytes: Integer; l_eol_position: Integer; stTemp : String; begin if l_c_reception_buffer = nil then Exit; with l_c_reception_buffer do begin l_remaining:= m_buffer_size- m_write_index; // -- if not at least a tcp-ip chunk, increase the room if l_remaining < k_tcp_ip_chunk then begin // -- reallocate double_the_capacity; l_remaining:= m_buffer_size- m_write_index; end; // -- add the received data to the current buffer l_pt_start_reception:= @ m_oa_byte_buffer[m_write_index]; // -- get the data from the client socket l_packet_bytes:= Recv(WinSocket, l_pt_start_reception^, l_remaining, 0); if l_packet_bytes < 0 then begin if Assigned(FOnSocketError) then begin OnSocketError(Self,p_socket,WSAGetLastError); end; end else begin m_write_index:= m_write_index+ l_packet_bytes; if Assigned(FOnSocketRead) then begin stTemp := ByteCopy(l_pt_start_reception,l_packet_bytes); OnSocketRead(Self,p_socket,stTemp,l_packet_bytes); end; end; end; // with g_c_reception_buffer end; // handle_fd_read_notification procedure handle_fd_close_notification(p_socket: Integer); var l_status: Integer; l_linger: TLinger; l_absolute_linger: array[0..3] of char absolute l_linger; begin if WSAIsBlocking then begin WSACancelBlockingCall; end; ShutDown(p_socket, 2); l_linger.l_onoff:= 1; l_linger.l_linger:= 0; SetSockOpt(p_socket, Sol_Socket, So_Linger, pAnsichar(AnsiString(l_absolute_linger)), sizeof(l_linger)); //l_absolute_linger[0] -> AnsiString(l_absolute_linger) 으로 변경 l_status:= CloseSocket(p_socket); if l_status <> 0 then begin if Assigned(FOnSocketDisConnected) then begin OnSocketDisConnected(Self,p_socket); end; end; end; // handle_fd_close_notification var l_param: Integer; l_error, l_notification: Integer; l_socket_handle: Integer; begin l_param:= Msg.lParam; l_socket_handle:= Msg.wParam; // -- extract the error and the notification code from l_param l_error:= wsaGetSelectError(l_param); l_notification:= wsaGetSelectEvent(l_param); if l_error <= wsaBaseErr then begin case l_notification of FD_CONNECT: handle_fd_connect_notification(l_socket_handle); FD_ACCEPT: {display_bug_stop('no_client_accept')} ; FD_WRITE: handle_fd_write_notification(l_socket_handle); FD_READ: handle_fd_read_notification(l_socket_handle); FD_CLOSE: handle_fd_close_notification(l_socket_handle); end // case end else begin if l_notification= FD_CLOSE then handle_fd_close_notification(l_socket_handle) else begin if Assigned(FOnSocketError) then begin OnSocketError(Self,l_socket_handle,WSAGetLastError); end; end; end; end; function TdmWinsocket.HandleAllocated: Boolean; begin Result := ( FHandle <> 0 ); end; procedure TdmWinsocket.HandleNeeded; begin if not HandleAllocated then FHandle := AllocateHWND ( WndProc ); end; function TdmWinsocket.PutString(aData: string): Boolean; var l_result: Integer; buf: array of Byte; nLen : integer; i : integer; begin Try FTCSDeviceSender.Enter; result := False; if Not Open then Exit; nLen := Length(aData); SetLength(buf, nLen); for i := 1 to nLen do begin buf[i-1] := ord(aData[i]); end; Try l_result:= Send(WinSocket,buf[0], nLen, 0); if l_result < 0 then begin if Assigned(FOnSocketError) then begin OnSocketError(Self,WinSocket,WSAGetLastError); end; Exit; end; Except Exit; End; result := True; Finally FTCSDeviceSender.Leave; End; end; procedure TdmWinsocket.SetConnectIP(const Value: string); begin FConnectIP := Value; end; procedure TdmWinsocket.SetConnectPort(const Value: integer); begin FConnectPort := Value; end; procedure TdmWinsocket.SetOpen(const Value: Boolean); var l_result : Integer; l_error: Integer; l_version : Word; l_socket_address_in: tSockAddrIn; l_ip_z: array[0..255] of char; rset: TFDSet; t: TTimeVal; rslt: integer; stConnectIP : string; begin if FOpen = Value then Exit; stConnectIP := ConnectIP; FOpen := Value; if Value then begin l_version:= $0101; l_result := wsaStartup(l_version, l_wsa_data); if l_result <> 0 then begin Open := False; Exit; //소켓생성 실패 시에 Open False end; WinSocket:= Socket(PF_INET, SOCK_STREAM, IPPROTO_IP); if WinSocket = INVALID_SOCKET then begin Open := False; Exit; //소켓생성 실패 시에 Open False end; l_result:= wsaAsyncSelect(WinSocket, Handle, wm_asynch_select, FD_CONNECT+ FD_READ+ FD_WRITE+ FD_CLOSE); FillChar(l_socket_address_in, sizeof(l_socket_address_in), 0); with l_socket_address_in do begin sin_family:= pf_Inet; // -- the requested service sin_port:= hToNs(ConnectPort); // -- the server IP address if Not IsIPTypeCheck(ConnectIP) then begin stConnectIP := GetIpFromDomain(ConnectIP); end; StrPCopy(l_ip_z, stConnectIP); sin_addr.s_Addr:= inet_addr(PAnsichar(AnsiString(l_ip_z))); end; // with m_socket_address_in l_result:= Connect(WinSocket, l_socket_address_in, sizeof(l_socket_address_in)); if l_result<> 0 then begin l_error:= WSAGetLastError; if l_error <> wsaEWouldBlock then begin Open := False; Exit; //소켓생성 실패 시에 Open False end else begin end; end; end else begin if WinSocket <> INVALID_SOCKET then begin l_result:= CloseSocket(WinSocket); if l_result = 0 then begin if Assigned(FOnSocketDisConnected) then begin OnSocketDisConnected(Self,WinSocket); end; WinSocket:= INVALID_SOCKET; end; end; end; end; procedure TdmWinsocket.WndProc(var Message: TMessage); begin Dispatch ( Message ); end; procedure TdmWinsocket.DataModuleCreate(Sender: TObject); begin FHandle := 0; WinSocket := Invalid_Socket; FTCSDeviceSender := TCriticalSection.Create; l_c_reception_buffer:= c_byte_buffer.create_byte_buffer('reception_buffer', k_buffer_max); end; procedure TdmWinsocket.DataModuleDestroy(Sender: TObject); begin Open := False; l_c_reception_buffer.Free; l_c_reception_buffer:= Nil; if HandleAllocated then DeAllocateHWND ( FHandle ); FTCSDeviceSender.Free; end; function TdmWinsocket.PutChar(aChar: char): integer; begin result:= Send(WinSocket,aChar, 1, 0); end; end.
{ Subroutine SST_CHAR_FROM_INS (CHAR_H) * * Determine whether a character came from the special include file specified * with the -INS command line option. CHAR_H is the handle to the source * stream character. This routine always returns FALSE when not doing a * special include file translation. } module sst_CHAR_FROM_INS; define sst_char_from_ins; %include 'sst2.ins.pas'; function sst_char_from_ins ( {check for char is from special include file} in char_h: syo_char_t) {handle to source character to check} :boolean; {TRUE is character is from the include file} val_param; var file_p: syo_file_p_t; {points to descriptor for one input file} begin sst_char_from_ins := false; {init to char is not from the include file} if not sst_ins then return; {not doing include file translate ?} if char_h.crange_p = nil {no pointer to source line char range ?} then return; if char_h.crange_p^.line_p = nil {no pointer to source line ?} then return; file_p := char_h.crange_p^.line_p^.file_p; {get pointer to file descriptor} while file_p <> nil do begin {loop thru file nesting hierarchy} if {this is the right source file ?} string_equal(file_p^.conn_p^.tnam, sst_ins_tnam) then begin sst_char_from_ins := true; return; end; file_p := file_p^.parent_p; {pop one level in file nesting hierarchy} end; {back and check this parent file name} end;
unit EvalLib; interface uses System.Math, System.SysUtils, System.Rtti, System.TypInfo, System.Generics.Collections, System.Generics.Defaults; {$TYPEINFO ON} type {$REGION 'TRttiContextHelper'} TRttiContextHelper = record helper for TRttiContext public function FindPublishedType(const Name: String): TRttiType; end; {$ENDREGION} {$REGION 'TValueHelper'} TValueHelper = record helper for TValue function HumanReadable: String; end; {$ENDREGION} {$REGION 'TObjectRttiHelper'} TObjectRttiHelper = class helper for TObject private function GetThis: TObject; inline; public class procedure Use; function ReadProperty (const Name: String): TValue; procedure WriteProperty(const Name: String; Value: TValue); function InvokeMethod(const Name: String; Args: TArray<TValue>): TValue; function IsReadable (const Name: String): Boolean; function IsWriteable(const Name: String): Boolean; published property This: TObject read GetThis; end; {$ENDREGION} EReadOnlyProperty = class(Exception); EUnknownProperty = class(Exception); EUnknownMethod = class(Exception); EUnknownClass = class(Exception); {$REGION 'TExpandableObject'} TExpandableObject = class public function ReadExpandedProperty (const Name: String): TValue; virtual; procedure WriteExpandedProperty(const Name: String; Value: TValue); virtual; function InvokeExpandedMethod(const Name: String; Args: TArray<TValue>): TValue; virtual; function IsExpandedReadable (const Name: String): Boolean; virtual; function IsExpandedWriteable(const Name: String): Boolean; virtual; end; {$ENDREGION} {$REGION 'TClassFactory'} TClassFactory = class(TExpandableObject) function ReadExpandedProperty(const Name: String): TValue; override; function IsExpandedReadable (const Name: String): Boolean; override; published function New(const Name: String): TValue; inline; end; {$ENDREGION} {$REGION 'TVariableStore'} TVariableStore = class(TExpandableObject) private fVariables: TDictionary<String, TValue>; fAutoDeclare: Boolean; public constructor Create; destructor Destroy; override; function ReadExpandedProperty (const Name: String): TValue; override; procedure WriteExpandedProperty(const Name: String; Value: TValue); override; function IsExpandedReadable (const Name: String): Boolean; override; function IsExpandedWriteable(const Name: String): Boolean; override; procedure Declare(const Name: String; Value: TValue); overload; published procedure Delete (const Name: String); inline; procedure Declare(const Name: String); overload; property Variables: TDictionary<String, TValue> read fVariables; property AutoDeclare: Boolean read fAutoDeclare write fAutoDeclare; end; {$ENDREGION} {$REGION 'TEvaluator'} TEvaluator = class(TVariableStore) private fNamespace: TArray<TObject>; public constructor Create; published procedure Push(const Namespace: TObject); inline; procedure Pop; inline; function ReadValue (const Name: String; var Value: TValue): Boolean; function WriteValue(const Name: String; const Value: TValue): Boolean; function Eval(const Expression: String): TValue; end; {$ENDREGION} EEvaluator = class(Exception); var RttiContext: TRttiContext; implementation {$REGION 'TRttiContextHelper'} function TRttiContextHelper.FindPublishedType(const Name: String): TRttiType; var i: Integer; f, n: String; begin f := lowercase(Name); for Result in RttiContext.GetTypes do begin n := lowercase(Result.QualifiedName); for i := length(n) downto 1 do if n[i] = '.' then break; n := copy(n, i + 1, length(n)); if n = f then exit; end; Result := nil; end; {$ENDREGION} {$REGION 'TValueHelper'} function TValueHelper.HumanReadable; begin try Exit(AsString); except case Kind of tkInteger: Result := IntToStr(AsInteger); tkEnumeration: Result := BoolToStr(AsBoolean); tkFloat: Result := FloatToStr(AsExtended); tkSet: Result := '<set>'; tkClass: Result := '<class>'; tkMethod: Result := '<method>'; tkVariant: Result := AsVariant; tkArray: Result := '<array>'; tkRecord: Result := '<record>'; tkInterface: Result := '<interface>'; tkInt64: Result := IntToStr(AsInt64); tkDynArray: Result := '<dynamicarray>'; tkClassRef: Result := '<classref>'; tkPointer: Result := '<pointer>'; tkProcedure: Result := '<procedure>'; else Result := '<unknown>'; end; end; end; {$ENDREGION} {$REGION 'TObjectRttiHelper'} function TObjectRttiHelper.GetThis: TObject; begin Result := Self; end; class procedure TObjectRttiHelper.Use; asm nop end; function TObjectRttiHelper.ReadProperty(const Name: String): TValue; var RttiProperty: TRttiProperty; begin TMonitor.Enter(Self); try if Self is TExpandableObject then with Self as TExpandableObject do begin if IsExpandedReadable(Name) then try Result := ReadExpandedProperty(Name); Exit; except end; end; RttiProperty := RttiContext.GetType(Self.ClassType).GetProperty(Name); if (RttiProperty = nil) or (RttiProperty.Visibility in [mvPrivate, mvProtected]) then raise EUnknownProperty.Create(Name); Result := RttiProperty.GetValue(Self); finally TMonitor.Exit(Self); end; end; procedure TObjectRttiHelper.WriteProperty(const Name: String; Value: TValue); var RttiProperty: TRttiProperty; begin TMonitor.Enter(Self); try if Self is TExpandableObject then with Self as TExpandableObject do begin if IsExpandedWriteable(Name) then try WriteExpandedProperty(Name, Value); Exit; except end; end; RttiProperty := RttiContext.GetType(Self.ClassType).GetProperty(Name); if (RttiProperty = nil) or (RttiProperty.Visibility in [mvPrivate, mvProtected]) then raise EUnknownProperty.Create(Name); if not RttiProperty.IsWritable then raise EReadOnlyProperty.Create(Name); RttiProperty.SetValue(Self, Value); finally TMonitor.Exit(Self); end; end; function TObjectRttiHelper.InvokeMethod(const Name: String; Args: TArray<TValue>): TValue; var RttiMethod: TRttiMethod; begin TMonitor.Enter(Self); try if Self is TExpandableObject then with Self as TExpandableObject do begin if IsExpandedReadable(Name) then try Result := InvokeExpandedMethod(Name, Args); Exit; except end; end; RttiMethod := RttiContext.GetType(Self.ClassType).GetMethod(Name); if (RttiMethod = nil) or (RttiMethod.Visibility in [mvPrivate, mvProtected]) then raise EUnknownMethod.Create(Name); Result := RttiMethod.Invoke(Self, Args); finally TMonitor.Exit(Self); end; end; function TObjectRttiHelper.IsReadable(const Name: String): Boolean; var RttiProperty: TRttiProperty; RttiMethod: TRttiMethod; begin if Self is TExpandableObject then begin Result := TExpandableObject(Self).IsExpandedReadable(Name); if Result then Exit; end; RttiProperty := RttiContext.GetType(Self.ClassType).GetProperty(Name); if RttiProperty <> nil then Result := (RttiProperty.Visibility in [mvPublic, mvPublished]) and RttiProperty.IsReadable else begin RttiMethod := RttiContext.GetType(Self.ClassType).GetMethod(Name); Result := (RttiMethod <> nil) and (RttiMethod.Visibility in [mvPublic, mvPublished]); end; end; function TObjectRttiHelper.IsWriteable(const Name: String): Boolean; var RttiProperty: TRttiProperty; begin if Self is TExpandableObject then begin Result := TExpandableObject(Self).IsExpandedWriteable(Name); if Result then Exit; end; RttiProperty := RttiContext.GetType(Self.ClassType).GetProperty(Name); Result := (RttiProperty <> nil) and (RttiProperty.Visibility in [mvPublic, mvPublished]) and RttiProperty.IsWritable; end; {$ENDREGION} {$REGION 'TExpandableObject'} function TExpandableObject.ReadExpandedProperty(const Name: String): TValue; begin raise EUnknownProperty.Create(Name); end; procedure TExpandableObject.WriteExpandedProperty(const Name: String; Value: TValue); begin raise EUnknownProperty.Create(Name); end; function TExpandableObject.InvokeExpandedMethod(const Name: String; Args: TArray<TValue>): TValue; begin raise EUnknownMethod.Create(Name); end; function TExpandableObject.IsExpandedReadable(const Name: String): Boolean; begin Result := False; end; function TExpandableObject.IsExpandedWriteable(const Name: String): Boolean; begin Result := False; end; {$ENDREGION} {$REGION 'TClassFactory'} function TClassFactory.ReadExpandedProperty(const Name: String): TValue; var t: TRttiType; begin TMonitor.Enter(Self); try t := RttiContext.FindPublishedType(Name); if t = nil then Exit(inherited); Result := TValue.From<TObject>(t.GetMethod('NewInstance').Invoke(t.AsInstance.MetaclassType, []).AsObject); finally TMonitor.Exit(Self); end; end; function TClassFactory.IsExpandedReadable(const Name: String): Boolean; begin Result := RttiContext.FindPublishedType(Name) <> nil; end; function TClassFactory.New; begin Result := ReadExpandedProperty(Name); end; {$ENDREGION} {$REGION 'TVariableStore'} constructor TVariableStore.Create; begin inherited; fVariables := TDictionary<String, TValue>.Create; fAutoDeclare := False; end; destructor TVariableStore.Destroy; begin fVariables.Free; inherited; end; function TVariableStore.ReadExpandedProperty(const Name: String): TValue; begin if not fVariables.ContainsKey(LowerCase(Name)) then begin if fAutoDeclare then try Result := inherited; except Result := TValue.Empty; end else Result := inherited; end else Result := fVariables[LowerCase(Name)]; end; procedure TVariableStore.WriteExpandedProperty(const Name: String; Value: TValue); begin if not fVariables.ContainsKey(LowerCase(Name)) then begin if fAutoDeclare then try inherited; except fVariables.Add(LowerCase(Name), Value); end else inherited; end else fVariables[Name] := Value; end; function TVariableStore.IsExpandedReadable(const Name: String): Boolean; begin if fVariables.ContainsKey(LowerCase(Name)) or fAutoDeclare then Result := True else Result := inherited; end; function TVariableStore.IsExpandedWriteable(const Name: String): Boolean; begin if fVariables.ContainsKey(LowerCase(Name)) or fAutoDeclare then Result := True else Result := inherited; end; procedure TVariableStore.Delete(const Name: String); begin fVariables.Remove(LowerCase(Name)); end; procedure TVariableStore.Declare(const Name: String); begin Declare(Name, 0); end; procedure TVariableStore.Declare(const Name: String; Value: TValue); begin if not fVariables.ContainsKey(LowerCase(Name)) then fVariables.Add(LowerCase(Name), Value) else fVariables[LowerCase(Name)] := Value; end; {$ENDREGION} {$REGION 'TEvaluator'} constructor TEvaluator.Create; begin inherited; Push(Self); end; procedure TEvaluator.Push(const Namespace: TObject); begin SetLength(fNamespace, Length(fNamespace) + 1); fNamespace[High(fNamespace)] := Namespace; end; procedure TEvaluator.Pop; begin if Length(fNamespace) = 1 then exit; SetLength(fNamespace, Length(fNamespace) - 1); end; function TEvaluator.ReadValue(const Name: String; var Value: TValue): Boolean; function ReadValueNS(Namespace: TObject): TValue; var i: Integer; p: TArray<TValue>; s: String; c: Char; f: Boolean; procedure Whitespace; begin repeat if not CharInSet(Name[i], [#32, #9]) then Exit; Inc(i); until i > Length(Name); end; procedure OverName; begin Whitespace; s := ''; repeat c := Name[i]; if not CharInSet(c, ['A'..'Z', 'a'..'z', '0'..'9', '_']) then Exit; s := s + c; Inc(i); until i > Length(Name); s := Lowercase(s); end; procedure OverParams; var q: Boolean; n: Integer; v: String; l: TValue; begin q := False; n := 0; v := ''; SetLength(p, 0); Inc(i); repeat if not q then Whitespace; c := Name[i]; case c of '"': q := not q; '(': if not q then Inc(n); ')': if not q then Dec(n); ',': if (not q) and (n = 0) then begin l := Eval(v); SetLength(p, Length(p) + 1); p[High(p)] := l; Inc(i); v := ''; end; end; if i > Length(Name) then Break; v := v + Name[i]; Inc(i); until (n = -1) or (i > Length(Name)); if (n = -1) and (v[Length(v)] = ')') then v := Copy(v, 1, Length(v) - 1); if Length(v) > 0 then begin l := Eval(v); SetLength(p, Length(p) + 1); p[High(p)] := l; end; end; begin Result := TValue.From<TObject>(Namespace); i := 1; repeat OverName; if Result.AsObject.IsReadable(s) then begin f := c = '('; if f then begin OverParams; c := Name[i]; end; if f then Result := Result.AsObject.InvokeMethod(s, p) else Result := Result.AsObject.ReadProperty(s); end else raise EEvaluator.Create('Cannot read value "' + s + '"'); Inc(i); until (c <> '.') or (i > Length(Name)); end; var i: Integer; begin for i := High(fNamespace) downto 0 do try Value := ReadValueNS(fNamespace[i]); Exit(True); except end; Result := False; end; function TEvaluator.WriteValue(const Name: String; const Value: TValue): Boolean; procedure WriteValueNS(Namespace: TObject); var i: Integer; s: String; p: String; v: TValue; begin for i := Length(Name) downto 1 do if not CharInSet(Name[i], ['A'..'Z', 'a'..'z', '0'..'9', '_']) then Break; s := Lowercase(Copy(Name, i + 1, Length(Name))); p := Copy(Name, 1, i - 1); if Length(s) = 0 then raise EEvaluator.Create('Syntax error'); if Length(p) = 0 then v := TValue.From<TObject>(Namespace) else if not ReadValue(p, v) then raise EEvaluator.Create(p); if not v.AsObject.IsWriteable(s) then raise EEvaluator.Create(p); v.AsObject.WriteProperty(s, Value); end; var i: Integer; begin for i := High(fNamespace) downto 0 do try WriteValueNS(fNamespace[i]); Exit(True); except end; Result := False; end; function BinToInt(const S: String): Cardinal; var i, j: Integer; begin Result := 0; if (Length(S) = 0) or (Pos(S[1], '01') = 0) then Exit(0); for i := 1 to Length(S) do begin j := Pos(S[i], '01'); if j = 0 then Exit(0); Result := Result * 2 + (j - 1); end; end; function TEvaluator.Eval(const Expression: String): TValue; var s, v: String; i: Integer; function Compare: TValue; forward; procedure Whitespace; begin repeat if not CharInSet(s[i], [#32, #9]) then Exit; Inc(i); until i > Length(s); end; function CheckSymbol(Symbol: String; Follow: String = ''; State: Boolean = True): Boolean; begin Whitespace; Result := Copy(s, i, Length(Symbol)) = Symbol; if Result and (Length(Follow) > 0) then Result := (Pos(s[i + Length(Symbol)], Follow) = 0) = State; if Result then Inc(i, Length(Symbol)); end; function GetConst(var Value: TValue): Boolean; var c: String; begin Whitespace; Result := True; case s[i] of '0'..'9': begin c := s[i]; Inc(i); while CharInSet(s[i], ['0'..'9', '.']) and (i <= Length(s)) do begin c := c + s[i]; Inc(i); end; if pos('.', c) = 0 then Value := TValue.From<Integer>(StrToInt(c)) else Value := TValue.From<Single>(StrToFloat(c)); end; '$': begin c := s[i]; Inc(i); while CharInSet(s[i], ['0'..'9', 'a'..'f', 'A'..'F']) and (i <= Length(s)) do begin c := c + s[i]; Inc(i); end; Value := TValue.From<Cardinal>(StrToInt(c)); end; '#': begin c := '';//s[i]; Inc(i); while CharInSet(s[i], ['0', '1']) and (i <= Length(s)) do begin c := c + s[i]; Inc(i); end; Value := TValue.From<Cardinal>(BinToInt(c)); end; '"': begin Inc(i); c := ''; while s[i] <> '"' do begin c := c + s[i]; Inc(i); if i > Length(s) then raise EEvaluator.Create('Expected "'); end; Inc(i); Value := TValue.From<String>(c); end; else Result := False; end; if Result then v := ''; end; function GetValue(var Value: TValue): Boolean; var c: Char; procedure OverName; begin Whitespace; repeat c := s[i]; if not CharInSet(c, ['A'..'Z', 'a'..'z', '0'..'9', '_']) then exit; v := v + c; Inc(i); until i > Length(s); end; procedure OverParams; var q: Boolean; n: Integer; begin Whitespace; q := False; n := 0; repeat c := s[i]; case c of '''': q := not q; '(': if not q then Inc(n); ')': if not q then begin Dec(n); if n = 0 then begin v := v + c; Inc(i); Break; end; end; end; v := v + c; Inc(i); until i > Length(s); end; begin Whitespace; Result := False; if not CharInSet(s[i], ['A'..'Z', 'a'..'z', '_']) then exit; v := ''; repeat OverName; if i > Length(s) then Break; if c = '.' then begin v := v + c; Inc(i); Continue; end else begin Whitespace; if c = '(' then begin Whitespace; OverParams; if c = '.' then begin v := v + c; Inc(i); Continue; end; end else Break; end; until i > Length(s); Result := ReadValue(v, Value); end; function IsNot: Boolean; begin Whitespace; Result := s[i] = '!'; if Result then Inc(i); end; function IsNeg: Boolean; begin Whitespace; Result := s[i] = '-'; if Result then Inc(i); end; function Bracket: TValue; var nt: Boolean; ng: Boolean; begin Whitespace; nt := IsNot; ng := IsNeg; v := ''; if CheckSymbol('(') then begin Result := Compare; if not CheckSymbol(')') then raise EEvaluator.Create('Expected )'); end else begin if not GetConst(Result) then if not GetValue(Result) then raise EEvaluator.Create('Expected value'); end; if ng then Result := TValue.FromVariant(-Result.AsVariant); if nt then Result := TValue.From<Boolean>(not Result.AsBoolean); end; function Assign: TValue; var n: String; procedure Check; begin if Length(v) = 0 then raise EEvaluator.Create('Expected variable'); n := v; end; procedure GetValue; begin if not ReadValue(n, Result) then raise EEvaluator.Create('Expected variable'); end; procedure SetValue; begin if not WriteValue(n, Result) then raise EEvaluator.Create('Expected variable'); end; begin Whitespace; Result := Bracket; if CheckSymbol('=', '=') then begin Check; Result := Compare; SetValue; end else if CheckSymbol('*=') then begin Check; GetValue; Result := TValue.FromVariant(Result.AsVariant * Compare.AsVariant); SetValue; end else if CheckSymbol('/=') then begin Check; GetValue; Result := TValue.FromVariant(Result.AsVariant / Compare.AsVariant); SetValue; end else if CheckSymbol('\=') then begin Check; GetValue; Result := TValue.FromVariant(Result.AsVariant div Compare.AsVariant); SetValue; end else if CheckSymbol('%=') then begin Check; GetValue; Result := TValue.FromVariant(Result.AsVariant mod Compare.AsVariant); SetValue; end else if CheckSymbol('&=') then begin Check; GetValue; Result := TValue.FromVariant(Result.AsVariant and Compare.AsVariant); SetValue; end else if CheckSymbol('|=') then begin Check; GetValue; Result := TValue.FromVariant(Result.AsVariant or Compare.AsVariant); SetValue; end else if CheckSymbol('^=') then begin Check; GetValue; Result := TValue.FromVariant(Result.AsVariant xor Compare.AsVariant); SetValue; end else if CheckSymbol('+=') then begin Check; GetValue; Result := TValue.FromVariant(Result.AsVariant + Compare.AsVariant); SetValue; end else if CheckSymbol('-=') then begin Check; GetValue; Result := TValue.FromVariant(Result.AsVariant - Compare.AsVariant); SetValue; end else if CheckSymbol('++') then begin Check; GetValue; Result := TValue.FromVariant(Result.AsVariant + 1); SetValue; s := n + Copy(s, i, Length(s)); i := 1; Result := Compare; end else if CheckSymbol('--') then begin Check; GetValue; Result := TValue.FromVariant(Result.AsVariant - 1); SetValue; s := n + Copy(s, i, Length(s)); i := 1; Result := Compare; end end; function MulDiv: TValue; begin Whitespace; Result := Assign; while True do if CheckSymbol('*', '=') then Result := TValue.FromVariant(Result.AsVariant * Assign.AsVariant) else if CheckSymbol('/', '=') then Result := TValue.FromVariant(Result.AsVariant / Assign.AsVariant) else if CheckSymbol('\', '=') then Result := TValue.FromVariant(Result.AsVariant div Assign.AsVariant) else if CheckSymbol('%', '=') then Result := TValue.FromVariant(Result.AsVariant mod Assign.AsVariant) else if CheckSymbol('^') then Result := TValue.FromVariant(Power(Result.AsVariant, Assign.AsVariant)) else Break; end; function Bitwise: TValue; begin Whitespace; Result := MulDiv; while True do if CheckSymbol('<<') then Result := TValue.From<Cardinal>(Result.AsOrdinal shl MulDiv.AsOrdinal) else if CheckSymbol('>>') then Result := TValue.From<Cardinal>(Result.AsOrdinal shr MulDiv.AsOrdinal) else if CheckSymbol('&', '&=') then Result := TValue.From<Cardinal>(Result.AsOrdinal and MulDiv.AsOrdinal) else if CheckSymbol('|', '|=') then Result := TValue.From<Cardinal>(Result.AsOrdinal or MulDiv.AsOrdinal) else if CheckSymbol('^', '=') then Result := TValue.From<Cardinal>(Result.AsOrdinal xor MulDiv.AsOrdinal) else Break; end; function AddSub: TValue; begin Whitespace; Result := Bitwise; while True do if CheckSymbol('+', '+=') then Result := TValue.FromVariant(Result.AsVariant + Bitwise.AsVariant) else if CheckSymbol('-', '-=') then Result := TValue.FromVariant(Result.AsVariant - Bitwise.AsVariant) else Break; end; function Compare: TValue; begin Whitespace; Result := AddSub; while True do if CheckSymbol('==') then Result := TValue.From<Boolean>(Result.AsVariant = AddSub.AsVariant) else if CheckSymbol('>=') then Result := TValue.From<Boolean>(Result.AsVariant >= AddSub.AsVariant) else if CheckSymbol('<=') then Result := TValue.From<Boolean>(Result.AsVariant <= AddSub.AsVariant) else if CheckSymbol('<>') then Result := TValue.From<Boolean>(Result.AsVariant <> AddSub.AsVariant) else if CheckSymbol('>', '>=') then Result := TValue.From<Boolean>(Result.AsVariant > AddSub.AsVariant) else if CheckSymbol('<', '<=') then Result := TValue.From<Boolean>(Result.AsVariant < AddSub.AsVariant) else if CheckSymbol('!=') then Result := TValue.From<Boolean>(Result.AsVariant <> AddSub.AsVariant) else if CheckSymbol('&&') then Result := TValue.From<Boolean>((Result.AsBoolean) and (AddSub.AsBoolean)) else if CheckSymbol('||') then Result := TValue.From<Boolean>((Result.AsBoolean) or (AddSub.AsBoolean)) else Break; end; begin s := Expression; i := 1; Result := Compare; end; {$ENDREGION} initialization RttiContext := TRttiContext.Create; finalization RttiContext.Free; end.
object fmDateFormat: TfmDateFormat Left = 285 Top = 201 BorderStyle = bsDialog Caption = 'Date/Time Format' ClientHeight = 74 ClientWidth = 337 Color = clBtnFace Font.Charset = ANSI_CHARSET Font.Color = clWindowText Font.Height = -12 Font.Name = 'Tahoma' Font.Style = [] OldCreateOrder = True Position = poScreenCenter Scaled = False PixelsPerInch = 96 TextHeight = 14 object lblFormat: TLabel Left = 17 Top = 13 Width = 95 Height = 14 Alignment = taRightJustify Caption = 'Date/time &format' FocusControl = cbFormat end object cbFormat: TComboBox Left = 120 Top = 9 Width = 209 Height = 22 DropDownCount = 18 ItemHeight = 14 TabOrder = 0 Text = 'cbFormat' Items.Strings = ( 'dddd, mmmm d, yyyy' 'dddd, mmmm d' 'mmmm d' 'mmmm d, yyyy' 'dd/mm/yy' 'mm/dd/yy' 'dd-mm-yy' 'mm-dd-yy' 'dddd, mmmm d, yyyy h:mm am/pm' 'dddd, mmmm d h:mm am/pm' 'mmmm d h:mm am/pm' 'mmmm d, yyyy h:mm am/pm' 'dd/mm/yy h:mm am/pm' 'mm/dd/yy h:mm am/pm' 'dd-mm-yy h:mm am/pm' 'mm-dd-yy h:mm am/pm' 'dddd, mmmm d, yyyy h:mm' 'dddd, mmmm d h:mm' 'mmmm d h:mm' 'mmmm d, yyyy h:mm' 'dd/mm/yy h:mm' 'mm/dd/yy h:mm' 'dd-mm-yy h:mm' 'mm-dd-yy h:mm') end object btnOK: TButton Left = 168 Top = 41 Width = 75 Height = 25 Caption = 'OK' Default = True ModalResult = 1 TabOrder = 1 end object btnCancel: TButton Left = 252 Top = 41 Width = 75 Height = 25 Cancel = True Caption = 'Cancel' ModalResult = 2 TabOrder = 2 end end
unit fFlashOffscreen; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, OleCtrls, ShockwaveFlashObjects_TLB, ExtCtrls; type TfrmFlashOffscreen = class(TForm) ShockwaveFlash1: TShockwaveFlash; procedure FormCreate(Sender: TObject); private FBitmap: TBitmap; FRatio_XY: Double; FFlashWidth : Integer; FFlashHeight: Integer; //FFlashZoom: Double; public destructor Destroy; override; procedure LoadFlash(const aFile: string); procedure PaintToImage(const aImage: TImage); property FlashWidth : Integer read FFlashWidth; property FlashHeight: Integer read FFlashHeight; //property FlashZoom : Integer read FFlashZoom; end; var frmFlashOffscreen: TfrmFlashOffscreen; implementation {$R *.dfm} { TfrmFlashOffscreen } destructor TfrmFlashOffscreen.Destroy; begin FBitmap.Free; inherited; end; procedure TfrmFlashOffscreen.FormCreate(Sender: TObject); begin FBitmap := TBitmap.Create; end; procedure TfrmFlashOffscreen.LoadFlash(const aFile: string); var swidth, sheight: string; // iwidth, iheight: Integer; begin // pnlFlash.Width := Self.Width; // pnlFlash.Height := Self.Height; // pnlFlash.Top := 0; // pnlFlash.Left := 0; ShockwaveFlash1.Align := alClient; ShockwaveFlash1.SAlign := 'TL'; //top left ShockwaveFlash1.BackgroundColor := -1; //default //ShockwaveFlash1.Movie := 'c:\-Andre-\-Projects-\FlashViewer\hoofdstuk1B.swf'; ShockwaveFlash1.Movie := aFile; ShockwaveFlash1.Visible := True; //ShockwaveFlash1.Play; // FFlashData.LoadFromFile(aFlashFile + '.xml'); // FFlashData.PageCount := ShockwaveFlash1.TotalFrames; swidth := ShockwaveFlash1.TGetProperty('/', 8); sheight := ShockwaveFlash1.TGetProperty('/', 9); DecimalSeparator := '.'; ThousandSeparator := ','; FFlashWidth := Round(StrToFloatDef(swidth , Self.Width)); FFlashHeight := Round(StrToFloatDef(sheight, Self.Height)); FRatio_XY := FFlashWidth / FFlashHeight; // iwidth := _FlashWidth; // iheight := _FlashHeight; // if iheight > AdvScrollBox1.Height then // begin // iheight := AdvScrollBox1.Height - 5; // iwidth := AdvScrollBox1.Width - 5; // end; // ShockwaveFlash1.Width := iwidth ; // ShockwaveFlash1.Height := iheight ; Self.BorderStyle := bsNone; Self.Width := 1; Self.Height := 1; Self.Visible := True; Self.Visible := False; Application.ProcessMessages; Self.Width := 100; Self.Height := 100; // edtPage.Text := IntToStr(ShockwaveFlash1.CurrentFrame); // lblPageMax.Caption := IntToStr(ShockwaveFlash1.TotalFrames - 1); // RefreshTextButtons; end; procedure TfrmFlashOffscreen.PaintToImage(const aImage: TImage); begin ShockwaveFlash1.Width := aImage.Width; ShockwaveFlash1.Height := aImage.Height; FBitmap.Pixelformat := pf24bit; // if you want it device independent FBitmap.Width := aImage.Width; FBitmap.Height := aImage.Height; ShockwaveFlash1.PaintTo(FBitmap.Canvas.Handle, 0, 0); //FBitmap.SaveToFile('Test1.bmp'); // * aImage.Picture.Assign(FBitmap); end; end.
unit PyAPI; { Minimum set of Python function declarations for module libraries. Author: Phil (MacPgmr at fastermac.net). To add other Python function declarations, see the Python header files (.h) included with every Python distribution. } {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface {$DEFINE IS32BIT} {$IFDEF CPUX64} {Delphi} {$UNDEF IS32BIT} {$ENDIF} {$IFDEF CPU64} {FPC} {$UNDEF IS32BIT} {$ENDIF} const {$IFDEF MSWINDOWS} {$IFDEF USE_PYTHON23} PythonLib = 'python23.dll'; {$ELSE} PythonLib = 'python27.dll'; {$ENDIF} {$ENDIF} {$IFDEF LINUX} {$IFDEF USE_PYTHON23} PythonLib = 'python23.so'; {$ELSE} PythonLib = 'python27.so'; {$ENDIF} {$ENDIF} {$IFDEF DARWIN} PythonLib = ''; //Link against Python.framework (-k'-framework Python'). // To link against a specific version of Python, pass the // full path to that version's library instead, for example, // -k'/System/Library/Frameworks/Python.framework/Versions/2.6/Python' {$ENDIF} type {$IFDEF IS32BIT} c_long = LongInt; c_ulong = LongWord; c_int = LongInt; {$ELSE} c_long = Int64; c_ulong = UInt64; c_int = Int64; //"int" also appears to be 8 bytes with 64-bit Python {$ENDIF} PyMethodDef = packed record name : PAnsiChar; //Python function name meth : Pointer; //Address of function that implements it flags : c_int; //METH_xxx flags; describe function's arguments doc : PAnsiChar; //Description of funtion end; PyObject = Pointer; const {$IFDEF USE_PYTHON23} PYTHON_API_VERSION = 1012; //Also used with Python 2.4 {$ELSE} PYTHON_API_VERSION = 1013; {$ENDIF} METH_VARARGS = 1; function Py_InitModule( name : PAnsiChar; var methods : PyMethodDef; doc : PAnsiChar = nil; self : PyObject = nil; apiver : c_int = PYTHON_API_VERSION) : PyObject; cdecl; external PythonLib name {$IFDEF IS32BIT}'Py_InitModule4'{$ELSE}'Py_InitModule4_64'{$ENDIF}; function PyArg_ParseTuple(args : PyObject; format : PAnsiChar) : c_int; cdecl; varargs; external PythonLib; //Note varargs allows us to simulate C variable number of arguments (...). function Py_BuildValue(format : PAnsiChar) :PyObject; cdecl; varargs; external PythonLib; function PyInt_FromLong(along : c_long) : PyObject; cdecl; external PythonLib; function PyLong_FromLong(along : c_long) : PyObject; cdecl; external PythonLib; function PyLong_FromUnsignedLong(aulong : c_ulong) : PyObject; cdecl; external PythonLib; function PyString_FromString(astr : PAnsiChar) : PyObject; cdecl; external PythonLib; function PyCallable_Check(call:PyObject):c_int; cdecl; external PythonLib; function Py_IncRef(obj:PyObject) : PyObject; cdecl; external PythonLib; function Py_DecRef(obj:PyObject) : PyObject; cdecl; external PythonLib; function Py_XINCREF(var obj:PyObject) : PyObject; cdecl; external PythonLib; function Py_XDECREF(var obj:PyObject) : PyObject; cdecl; external PythonLib; // function Py_DECREF(var obj:PyObject) : PyObject; cdecl; external PythonLib; function PyCapsule_New( p:pointer; name: PAnsiChar; PyCapsule_Destructor :Pointer) : PyObject; cdecl; external PythonLib; function PyModule_AddObject(module:PyObject ; name: PAnsiChar;value:PyObject ):c_int ; cdecl; external PythonLib; function PyCapsule_Import(name: PAnsiChar; no_block:c_int):Pointer; cdecl; external PythonLib; function PyObject_CallObject(callable_object:PyObject;arg:PyObject):PyObject; cdecl; external PythonLib; function PyObject_GetAttrString(obj:PyObject;name: PAnsiChar):PyObject; cdecl; external PythonLib; function PyObject_SetAttrString(obj:PyObject;name: PAnsiChar;val:PyObject):PyObject; cdecl; external PythonLib; implementation end.
unit TTSCIFTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TTTSCIFRecord = record PLenderNum: String[4]; PCifNumber: String[20]; PModCount: Integer; PBranch: String[8]; PDivision: String[8]; PTapeLoan: Boolean; PName1: String[40]; PName2: String[40]; PAddr1: String[40]; PAddr2: String[40]; PCity: String[25]; PState: String[2]; PZip: String[10]; PPhone: String[40]; PLetterName: String[40]; POfficer: String[6]; PCustCode: String[8]; PActive: String[1]; PHoldNotice: Boolean; PDirectDebt: Currency; PIndirectDebt: Currency; PFirstName1: String[20]; PFirstName2: String[20]; PDept: String[8]; PDataCaddyChgCode: Boolean; PDesc1: String[60]; PDesc2: String[60]; PEMail: String[80]; PAddlField : string[8]; End; TTTSCIFBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TTTSCIFRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEITTSCIF = (TTSCIFPrimaryKey); TTTSCIFTable = class( TDBISAMTableAU ) private FDFLenderNum: TStringField; FDFCifNumber: TStringField; FDFModCount: TIntegerField; FDFBranch: TStringField; FDFDivision: TStringField; FDFTapeLoan: TBooleanField; FDFName1: TStringField; FDFName2: TStringField; FDFAddr1: TStringField; FDFAddr2: TStringField; FDFCity: TStringField; FDFState: TStringField; FDFZip: TStringField; FDFPhone: TStringField; FDFLetterName: TStringField; FDFOfficer: TStringField; FDFCustCode: TStringField; FDFActive: TStringField; FDFHoldNotice: TBooleanField; FDFDirectDebt: TCurrencyField; FDFIndirectDebt: TCurrencyField; FDFFirstName1: TStringField; FDFFirstName2: TStringField; FDFDept: TStringField; FDFNotes: TBlobField; FDFDataCaddyChgCode: TBooleanField; FDFDesc1: TStringField; FDFDesc2: TStringField; FDFEmail: TStringField; FDFAddlField : TStringField; procedure SetPLenderNum(const Value: String); function GetPLenderNum:String; procedure SetPCifNumber(const Value: String); function GetPCifNumber:String; procedure SetPModCount(const Value: Integer); function GetPModCount:Integer; procedure SetPBranch(const Value: String); function GetPBranch:String; procedure SetPDivision(const Value: String); function GetPDivision:String; procedure SetPTapeLoan(const Value: Boolean); function GetPTapeLoan:Boolean; procedure SetPName1(const Value: String); function GetPName1:String; procedure SetPName2(const Value: String); function GetPName2:String; procedure SetPAddr1(const Value: String); function GetPAddr1:String; procedure SetPAddr2(const Value: String); function GetPAddr2:String; procedure SetPCity(const Value: String); function GetPCity:String; procedure SetPState(const Value: String); function GetPState:String; procedure SetPZip(const Value: String); function GetPZip:String; procedure SetPPhone(const Value: String); function GetPPhone:String; procedure SetPLetterName(const Value: String); function GetPLetterName:String; procedure SetPOfficer(const Value: String); function GetPOfficer:String; procedure SetPCustCode(const Value: String); function GetPCustCode:String; procedure SetPActive(const Value: String); function GetPActive:String; procedure SetPHoldNotice(const Value: Boolean); function GetPHoldNotice:Boolean; procedure SetPDirectDebt(const Value: Currency); function GetPDirectDebt:Currency; procedure SetPIndirectDebt(const Value: Currency); function GetPIndirectDebt:Currency; procedure SetPFirstName1(const Value: String); function GetPFirstName1:String; procedure SetPFirstName2(const Value: String); function GetPFirstName2:String; procedure SetPDept(const Value: String); function GetPDept:String; procedure SetPDataCaddyChgCode(const Value: Boolean); function GetPDataCaddyChgCode:Boolean; procedure SetPDesc1(const Value: String); function GetPDesc1:String; procedure SetPDesc2(const Value: String); function GetPDesc2:String; procedure SetPEmail(const Value: String); function GetPEmail:String; procedure SetPAddlField(const Value: String); function GetPAddlField:String; procedure SetEnumIndex(Value: TEITTSCIF); function GetEnumIndex: TEITTSCIF; protected procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TTTSCIFRecord; procedure StoreDataBuffer(ABuffer:TTTSCIFRecord); property DFLenderNum: TStringField read FDFLenderNum; property DFCifNumber: TStringField read FDFCifNumber; property DFModCount: TIntegerField read FDFModCount; property DFBranch: TStringField read FDFBranch; property DFDivision: TStringField read FDFDivision; property DFTapeLoan: TBooleanField read FDFTapeLoan; property DFName1: TStringField read FDFName1; property DFName2: TStringField read FDFName2; property DFAddr1: TStringField read FDFAddr1; property DFAddr2: TStringField read FDFAddr2; property DFCity: TStringField read FDFCity; property DFState: TStringField read FDFState; property DFZip: TStringField read FDFZip; property DFPhone: TStringField read FDFPhone; property DFLetterName: TStringField read FDFLetterName; property DFOfficer: TStringField read FDFOfficer; property DFCustCode: TStringField read FDFCustCode; property DFActive: TStringField read FDFActive; property DFHoldNotice: TBooleanField read FDFHoldNotice; property DFDirectDebt: TCurrencyField read FDFDirectDebt; property DFIndirectDebt: TCurrencyField read FDFIndirectDebt; property DFFirstName1: TStringField read FDFFirstName1; property DFFirstName2: TStringField read FDFFirstName2; property DFDept: TStringField read FDFDept; property DFNotes: TBlobField read FDFNotes; property DFDataCaddyChgCode: TBooleanField read FDFDataCaddyChgCode; property DFDesc1: TStringField read FDFDesc1; property DFDesc2: TStringField read FDFDesc2; property DFEmail:TStringField read FDFEmail; property DFAddlField : TStringField read FDFAddlField; property PLenderNum: String read GetPLenderNum write SetPLenderNum; property PCifNumber: String read GetPCifNumber write SetPCifNumber; property PModCount: Integer read GetPModCount write SetPModCount; property PBranch: String read GetPBranch write SetPBranch; property PDivision: String read GetPDivision write SetPDivision; property PTapeLoan: Boolean read GetPTapeLoan write SetPTapeLoan; property PName1: String read GetPName1 write SetPName1; property PName2: String read GetPName2 write SetPName2; property PAddr1: String read GetPAddr1 write SetPAddr1; property PAddr2: String read GetPAddr2 write SetPAddr2; property PCity: String read GetPCity write SetPCity; property PState: String read GetPState write SetPState; property PZip: String read GetPZip write SetPZip; property PPhone: String read GetPPhone write SetPPhone; property PLetterName: String read GetPLetterName write SetPLetterName; property POfficer: String read GetPOfficer write SetPOfficer; property PCustCode: String read GetPCustCode write SetPCustCode; property PActive: String read GetPActive write SetPActive; property PHoldNotice: Boolean read GetPHoldNotice write SetPHoldNotice; property PDirectDebt: Currency read GetPDirectDebt write SetPDirectDebt; property PIndirectDebt: Currency read GetPIndirectDebt write SetPIndirectDebt; property PFirstName1: String read GetPFirstName1 write SetPFirstName1; property PFirstName2: String read GetPFirstName2 write SetPFirstName2; property PDept: String read GetPDept write SetPDept; property PDataCaddyChgCode: Boolean read GetPDataCaddyChgCode write SetPDataCaddyChgCode; property PDesc1: String read GetPDesc1 write SetPDesc1; property PDesc2: String read GetPDesc2 write SetPDesc2; property PEmail:String read GetPEmail write SetPEmail; property PAddlField:String read GetPAddlField write SetPAddlField; published property Active write SetActive; property EnumIndex: TEITTSCIF read GetEnumIndex write SetEnumIndex; end; { TTTSCIFTable } procedure Register; implementation procedure TTTSCIFTable.CreateFields; begin FDFLenderNum := CreateField( 'LenderNum' ) as TStringField; FDFCifNumber := CreateField( 'CifNumber' ) as TStringField; FDFModCount := CreateField( 'ModCount' ) as TIntegerField; FDFBranch := CreateField( 'Branch' ) as TStringField; FDFDivision := CreateField( 'Division' ) as TStringField; FDFTapeLoan := CreateField( 'TapeLoan' ) as TBooleanField; FDFName1 := CreateField( 'Name1' ) as TStringField; FDFName2 := CreateField( 'Name2' ) as TStringField; FDFAddr1 := CreateField( 'Addr1' ) as TStringField; FDFAddr2 := CreateField( 'Addr2' ) as TStringField; FDFCity := CreateField( 'City' ) as TStringField; FDFState := CreateField( 'State' ) as TStringField; FDFZip := CreateField( 'Zip' ) as TStringField; FDFPhone := CreateField( 'Phone' ) as TStringField; FDFLetterName := CreateField( 'LetterName' ) as TStringField; FDFOfficer := CreateField( 'Officer' ) as TStringField; FDFCustCode := CreateField( 'CustCode' ) as TStringField; FDFActive := CreateField( 'Active' ) as TStringField; FDFHoldNotice := CreateField( 'HoldNotice' ) as TBooleanField; FDFDirectDebt := CreateField( 'DirectDebt' ) as TCurrencyField; FDFIndirectDebt := CreateField( 'IndirectDebt' ) as TCurrencyField; FDFFirstName1 := CreateField( 'FirstName1' ) as TStringField; FDFFirstName2 := CreateField( 'FirstName2' ) as TStringField; FDFDept := CreateField( 'Dept' ) as TStringField; FDFNotes := CreateField( 'Notes' ) as TBlobField; FDFDataCaddyChgCode := CreateField( 'DataCaddyChgCode' ) as TBooleanField; FDFDesc1 := CreateField( 'Desc1' ) as TStringField; FDFDesc2 := CreateField( 'Desc2' ) as TStringField; FDFEmail := CreateField( 'Email' ) as TStringField; FDFAddlField := CreateField ( 'AddlField') as TStringField; end; { TTTSCIFTable.CreateFields } procedure TTTSCIFTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TTTSCIFTable.SetActive } procedure TTTSCIFTable.SetPLenderNum(const Value: String); begin DFLenderNum.Value := Value; end; function TTTSCIFTable.GetPLenderNum:String; begin result := DFLenderNum.Value; end; procedure TTTSCIFTable.SetPCifNumber(const Value: String); begin DFCifNumber.Value := Value; end; function TTTSCIFTable.GetPCifNumber:String; begin result := DFCifNumber.Value; end; procedure TTTSCIFTable.SetPModCount(const Value: Integer); begin DFModCount.Value := Value; end; function TTTSCIFTable.GetPModCount:Integer; begin result := DFModCount.Value; end; procedure TTTSCIFTable.SetPBranch(const Value: String); begin DFBranch.Value := Value; end; function TTTSCIFTable.GetPBranch:String; begin result := DFBranch.Value; end; procedure TTTSCIFTable.SetPDivision(const Value: String); begin DFDivision.Value := Value; end; function TTTSCIFTable.GetPDivision:String; begin result := DFDivision.Value; end; procedure TTTSCIFTable.SetPTapeLoan(const Value: Boolean); begin DFTapeLoan.Value := Value; end; function TTTSCIFTable.GetPTapeLoan:Boolean; begin result := DFTapeLoan.Value; end; procedure TTTSCIFTable.SetPName1(const Value: String); begin DFName1.Value := Value; end; function TTTSCIFTable.GetPName1:String; begin result := DFName1.Value; end; procedure TTTSCIFTable.SetPName2(const Value: String); begin DFName2.Value := Value; end; function TTTSCIFTable.GetPName2:String; begin result := DFName2.Value; end; procedure TTTSCIFTable.SetPAddr1(const Value: String); begin DFAddr1.Value := Value; end; function TTTSCIFTable.GetPAddr1:String; begin result := DFAddr1.Value; end; procedure TTTSCIFTable.SetPAddr2(const Value: String); begin DFAddr2.Value := Value; end; function TTTSCIFTable.GetPAddr2:String; begin result := DFAddr2.Value; end; procedure TTTSCIFTable.SetPCity(const Value: String); begin DFCity.Value := Value; end; function TTTSCIFTable.GetPCity:String; begin result := DFCity.Value; end; procedure TTTSCIFTable.SetPState(const Value: String); begin DFState.Value := Value; end; function TTTSCIFTable.GetPState:String; begin result := DFState.Value; end; procedure TTTSCIFTable.SetPZip(const Value: String); begin DFZip.Value := Value; end; function TTTSCIFTable.GetPZip:String; begin result := DFZip.Value; end; procedure TTTSCIFTable.SetPPhone(const Value: String); begin DFPhone.Value := Value; end; function TTTSCIFTable.GetPPhone:String; begin result := DFPhone.Value; end; procedure TTTSCIFTable.SetPLetterName(const Value: String); begin DFLetterName.Value := Value; end; function TTTSCIFTable.GetPLetterName:String; begin result := DFLetterName.Value; end; procedure TTTSCIFTable.SetPOfficer(const Value: String); begin DFOfficer.Value := Value; end; function TTTSCIFTable.GetPOfficer:String; begin result := DFOfficer.Value; end; procedure TTTSCIFTable.SetPCustCode(const Value: String); begin DFCustCode.Value := Value; end; function TTTSCIFTable.GetPCustCode:String; begin result := DFCustCode.Value; end; procedure TTTSCIFTable.SetPActive(const Value: String); begin DFActive.Value := Value; end; function TTTSCIFTable.GetPActive:String; begin result := DFActive.Value; end; procedure TTTSCIFTable.SetPHoldNotice(const Value: Boolean); begin DFHoldNotice.Value := Value; end; function TTTSCIFTable.GetPHoldNotice:Boolean; begin result := DFHoldNotice.Value; end; procedure TTTSCIFTable.SetPDirectDebt(const Value: Currency); begin DFDirectDebt.Value := Value; end; function TTTSCIFTable.GetPDirectDebt:Currency; begin result := DFDirectDebt.Value; end; procedure TTTSCIFTable.SetPIndirectDebt(const Value: Currency); begin DFIndirectDebt.Value := Value; end; function TTTSCIFTable.GetPIndirectDebt:Currency; begin result := DFIndirectDebt.Value; end; procedure TTTSCIFTable.SetPFirstName1(const Value: String); begin DFFirstName1.Value := Value; end; function TTTSCIFTable.GetPFirstName1:String; begin result := DFFirstName1.Value; end; procedure TTTSCIFTable.SetPFirstName2(const Value: String); begin DFFirstName2.Value := Value; end; function TTTSCIFTable.GetPFirstName2:String; begin result := DFFirstName2.Value; end; procedure TTTSCIFTable.SetPDept(const Value: String); begin DFDept.Value := Value; end; function TTTSCIFTable.GetPDept:String; begin result := DFDept.Value; end; procedure TTTSCIFTable.SetPDataCaddyChgCode(const Value: Boolean); begin DFDataCaddyChgCode.Value := Value; end; function TTTSCIFTable.GetPDataCaddyChgCode:Boolean; begin result := DFDataCaddyChgCode.Value; end; procedure TTTSCIFTable.SetPDesc1(const Value: String); begin DFDesc1.Value := Value; end; function TTTSCIFTable.GetPDesc1:String; begin result := DFDesc1.Value; end; procedure TTTSCIFTable.SetPDesc2(const Value: String); begin DFDesc2.Value := Value; end; function TTTSCIFTable.GetPDesc2:String; begin result := DFDesc2.Value; end; procedure TTTSCIFTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('LenderNum, String, 4, N'); Add('CifNumber, String, 20, N'); Add('ModCount, Integer, 0, N'); Add('Branch, String, 8, N'); Add('Division, String, 8, N'); Add('TapeLoan, Boolean, 0, N'); Add('Name1, String, 40, N'); Add('Name2, String, 40, N'); Add('Addr1, String, 40, N'); Add('Addr2, String, 40, N'); Add('City, String, 25, N'); Add('State, String, 2, N'); Add('Zip, String, 10, N'); Add('Phone, String, 40, N'); Add('LetterName, String, 40, N'); Add('Officer, String, 6, N'); Add('CustCode, String, 8, N'); Add('Active, String, 1, N'); Add('HoldNotice, Boolean, 0, N'); Add('DirectDebt, Currency, 0, N'); Add('IndirectDebt, Currency, 0, N'); Add('FirstName1, String, 20, N'); Add('FirstName2, String, 20, N'); Add('Dept, String, 8, N'); Add('Notes, Memo, 0, N'); Add('DataCaddyChgCode, Boolean, 0, N'); Add('Desc1, String, 60, N'); Add('Desc2, String, 60, N'); Add('Email, String, 80, N'); Add('AddlField,String,8,N'); end; end; procedure TTTSCIFTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, LenderNum;CifNumber, Y, Y, N, N'); end; end; procedure TTTSCIFTable.SetEnumIndex(Value: TEITTSCIF); begin case Value of TTSCIFPrimaryKey : IndexName := ''; end; end; function TTTSCIFTable.GetDataBuffer:TTTSCIFRecord; var buf: TTTSCIFRecord; begin fillchar(buf, sizeof(buf), 0); buf.PLenderNum := DFLenderNum.Value; buf.PCifNumber := DFCifNumber.Value; buf.PModCount := DFModCount.Value; buf.PBranch := DFBranch.Value; buf.PDivision := DFDivision.Value; buf.PTapeLoan := DFTapeLoan.Value; buf.PName1 := DFName1.Value; buf.PName2 := DFName2.Value; buf.PAddr1 := DFAddr1.Value; buf.PAddr2 := DFAddr2.Value; buf.PCity := DFCity.Value; buf.PState := DFState.Value; buf.PZip := DFZip.Value; buf.PPhone := DFPhone.Value; buf.PLetterName := DFLetterName.Value; buf.POfficer := DFOfficer.Value; buf.PCustCode := DFCustCode.Value; buf.PActive := DFActive.Value; buf.PHoldNotice := DFHoldNotice.Value; buf.PDirectDebt := DFDirectDebt.Value; buf.PIndirectDebt := DFIndirectDebt.Value; buf.PFirstName1 := DFFirstName1.Value; buf.PFirstName2 := DFFirstName2.Value; buf.PDept := DFDept.Value; buf.PDataCaddyChgCode := DFDataCaddyChgCode.Value; buf.PDesc1 := DFDesc1.Value; buf.PDesc2 := DFDesc2.Value; buf.PEMail := DFEmail.Value; buf.PAddlField := FDFAddlField.Value; result := buf; end; procedure TTTSCIFTable.StoreDataBuffer(ABuffer:TTTSCIFRecord); begin DFLenderNum.Value := ABuffer.PLenderNum; DFCifNumber.Value := ABuffer.PCifNumber; DFModCount.Value := ABuffer.PModCount; DFBranch.Value := ABuffer.PBranch; DFDivision.Value := ABuffer.PDivision; DFTapeLoan.Value := ABuffer.PTapeLoan; DFName1.Value := ABuffer.PName1; DFName2.Value := ABuffer.PName2; DFAddr1.Value := ABuffer.PAddr1; DFAddr2.Value := ABuffer.PAddr2; DFCity.Value := ABuffer.PCity; DFState.Value := ABuffer.PState; DFZip.Value := ABuffer.PZip; DFPhone.Value := ABuffer.PPhone; DFLetterName.Value := ABuffer.PLetterName; DFOfficer.Value := ABuffer.POfficer; DFCustCode.Value := ABuffer.PCustCode; DFActive.Value := ABuffer.PActive; DFHoldNotice.Value := ABuffer.PHoldNotice; DFDirectDebt.Value := ABuffer.PDirectDebt; DFIndirectDebt.Value := ABuffer.PIndirectDebt; DFFirstName1.Value := ABuffer.PFirstName1; DFFirstName2.Value := ABuffer.PFirstName2; DFDept.Value := ABuffer.PDept; DFDataCaddyChgCode.Value := ABuffer.PDataCaddyChgCode; DFDesc1.Value := ABuffer.PDesc1; DFDesc2.Value := ABuffer.PDesc2; DFEmail.Value := ABuffer.PEMail; DFAddlField.Value := ABuffer.PAddlField; end; function TTTSCIFTable.GetEnumIndex: TEITTSCIF; var iname : string; begin result := TTSCIFPrimaryKey; iname := uppercase(indexname); if iname = '' then result := TTSCIFPrimaryKey; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'TTS Tables', [ TTTSCIFTable, TTTSCIFBuffer ] ); end; { Register } function TTTSCIFBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..29] of string = ('LENDERNUM','CIFNUMBER','MODCOUNT','BRANCH','DIVISION','TAPELOAN' ,'NAME1','NAME2','ADDR1','ADDR2','CITY' ,'STATE','ZIP','PHONE','LETTERNAME','OFFICER' ,'CUSTCODE','ACTIVE','HOLDNOTICE','DIRECTDEBT','INDIRECTDEBT' ,'FIRSTNAME1','FIRSTNAME2','DEPT','DATACADDYCHGCODE' ,'DESC1','DESC2','EMAIL', 'ADDLFIELD' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 29) and (flist[x] <> s) do inc(x); if x <= 29 then result := x else result := 0; end; function TTTSCIFBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftInteger; 4 : result := ftString; 5 : result := ftString; 6 : result := ftBoolean; 7 : result := ftString; 8 : result := ftString; 9 : result := ftString; 10 : result := ftString; 11 : result := ftString; 12 : result := ftString; 13 : result := ftString; 14 : result := ftString; 15 : result := ftString; 16 : result := ftString; 17 : result := ftString; 18 : result := ftString; 19 : result := ftBoolean; 20 : result := ftCurrency; 21 : result := ftCurrency; 22 : result := ftString; 23 : result := ftString; 24 : result := ftString; 25 : result := ftBoolean; 26 : result := ftString; 27 : result := ftString; 28 : Result := ftString; 29 : Result := ftString; end; end; function TTTSCIFBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PLenderNum; 2 : result := @Data.PCifNumber; 3 : result := @Data.PModCount; 4 : result := @Data.PBranch; 5 : result := @Data.PDivision; 6 : result := @Data.PTapeLoan; 7 : result := @Data.PName1; 8 : result := @Data.PName2; 9 : result := @Data.PAddr1; 10 : result := @Data.PAddr2; 11 : result := @Data.PCity; 12 : result := @Data.PState; 13 : result := @Data.PZip; 14 : result := @Data.PPhone; 15 : result := @Data.PLetterName; 16 : result := @Data.POfficer; 17 : result := @Data.PCustCode; 18 : result := @Data.PActive; 19 : result := @Data.PHoldNotice; 20 : result := @Data.PDirectDebt; 21 : result := @Data.PIndirectDebt; 22 : result := @Data.PFirstName1; 23 : result := @Data.PFirstName2; 24 : result := @Data.PDept; 25 : result := @Data.PDataCaddyChgCode; 26 : result := @Data.PDesc1; 27 : result := @Data.PDesc2; 28 : Result := @Data.PEmail; 29 : Result := @Data.PAddlField; end; end; function TTTSCIFTable.GetPEmail: String; begin result := DFEmail.Value; end; procedure TTTSCIFTable.SetPEmail(const Value: String); begin DFEmail.Value := Value; end; function TTTSCIFTable.GetPAddlField: String; begin result := DFAddlField.Value; end; procedure TTTSCIFTable.SetPAddlField(const Value: String); begin DFAddlField.Value := Value; end; end.
unit unitSettings; interface type TSettings = class private FFontSize: Integer; procedure SetFontSize(const Value: Integer); public property FontSize : Integer read FFontSize write SetFontSize; end; TSettingsIniHelper = class helper for TSettings function IniFileName : string; procedure Save; procedure Load; end; implementation uses INIFiles, IOUtils, SysUtils; { TSettings } procedure TSettings.SetFontSize(const Value: Integer); begin FFontSize := Value; end; { TSettingsHelper } function TSettingsIniHelper.IniFileName: string; begin Result := TPath.GetDocumentsPath+PathDelim+'bible.ini'; end; procedure TSettingsIniHelper.Load; var Ini : Tinifile; begin Ini := TIniFile.Create(IniFileName); try FontSize := Ini.ReadInteger('Settings','FontSize',80); finally Ini.Free; end; end; procedure TSettingsIniHelper.Save; var Ini : Tinifile; begin Ini := TIniFile.Create(IniFileName); try Ini.WriteInteger('Settings','FontSize',FontSize); finally Ini.Free; end; end; end.
unit RDOMarshalers; interface uses ActiveX, {$IFDEF AutoServer} RDOClient_TLB, {$ENDIF} RDOInterfaces, RDOQueries; {$IFDEF AutoServer} function MarshalPropertyGet( ObjectId : integer; const PropName : string; RDOConnection : IRDOConnection; TimeOut, Priority : integer; out ErrorCode : integer ) : OleVariant; {$ELSE} function MarshalPropertyGet( ObjectId : integer; const PropName : string; RDOConnection : IRDOConnection; TimeOut, Priority : integer; out ErrorCode : integer ) : variant; {$ENDIF} procedure MarshalPropertySet( ObjectId : integer; const PropName : string; const PropValue : variant; RDOConnection : IRDOConnection; TimeOut, Priority : integer; out ErrorCode : integer ); procedure MarshalMethodCall( ObjectId : integer; const MethodName : string; const Params : PDispParams; var Res : variant; RDOConnection : IRDOConnection; TimeOut, Priority : integer; out ErrorCode : integer ); // procedure MarshalMethodCall( ObjectId : integer; const MethodName : string; var Params : variant; var Res : variant; RDOConnection : IRDOConnection; TimeOut, Priority : integer; out ErrorCode : integer ); function MarshalObjIdGet( ObjectName : string; RDOConnection : IRDOConnection; TimeOut, Priority : integer; out ErrorCode : integer ) : integer; implementation uses Windows, SysUtils, RDOProtocol, RDOUtils, ErrorCodes, RDOVariantUtils; {$IFDEF AutoServer} function MarshalPropertyGet( ObjectId : integer; const PropName : string; RDOConnection : IRDOConnection; TimeOut, Priority : integer; out ErrorCode : integer ) : OleVariant; {$ELSE} function MarshalPropertyGet( ObjectId : integer; const PropName : string; RDOConnection : IRDOConnection; TimeOut, Priority : integer; out ErrorCode : integer ) : variant; {$ENDIF} var Query : TRDOQuery; QueryResult : TRDOQuery; idx : integer; begin result := Unassigned; Query := TRDOQuery.Create(qkGetProp, 0); try if Priority <> THREAD_PRIORITY_NORMAL then Query.Priority := ThreadPriorityToQueryPriority(Priority); Query.ObjId := ObjectId; Query.Name := PropName; QueryResult := RDOConnection.SendReceive(Query, ErrorCode, TimeOut); if ErrorCode = errNoError then begin if QueryResult <> nil then try idx := 0; if QueryResult.QKind = qkError then try ErrorCode := QueryResult.PopParam(idx); except ErrorCode := errMalformedResult; end else try result := QueryResult.PopParam(idx); except ErrorCode := errMalformedResult; end; finally QueryResult.Free; end else ErrorCode := errMalformedResult; end; finally Query.Free; end; end; procedure MarshalPropertySet( ObjectId : integer; const PropName : string; const PropValue : variant; RDOConnection : IRDOConnection; TimeOut, Priority : integer; out ErrorCode : integer ); var Query : TRDOQuery; QueryResult : TRDOQuery; begin Query := TRDOQuery.Create(qkSetProp, 0); try if Priority <> THREAD_PRIORITY_NORMAL then Query.Priority := ThreadPriorityToQueryPriority(Priority); Query.ObjId := ObjectId; Query.Name := PropName; try Query.PushParam(PropValue); ErrorCode := errNoError; except ErrorCode := errIllegalPropValue end; if ErrorCode = errNoError then if TimeOut <> 0 then begin try QueryResult := RDOConnection.SendReceive( Query, ErrorCode, TimeOut ); QueryResult.Free; finally Query.Free; end; end else begin RDOConnection.Send(Query); ErrorCode := errNoError; end; except ErrorCode := errUnknownError; end; end; procedure MarshalMethodCall( ObjectId : integer; const MethodName : string; const Params : PDispParams; var Res : variant; RDOConnection : IRDOConnection; TimeOut, Priority : integer; out ErrorCode : integer ); // procedure MarshalMethodCall( ObjectId : integer; const MethodName : string; var Params : variant; var Res : variant; RDOConnection : IRDOConnection; TimeOut, Priority : integer; out ErrorCode : integer ); const MaxParams = 32; var Query : TRDOQuery; QueryResult : TRDOQuery; ParamIdx : integer; ParamCount : integer; //TmpVariant : variant; idx : integer; ParmsByRef : boolean; Aux : PVariant; PtrRec : TMarshalPtr; ParamInfo : array[1..MaxParams] of boolean; begin ErrorCode := errNoError; // build the query if TVarData( Res ).VType <> varEmpty then Query := TRDOQuery.Create(qkCallRet, 0) else Query := TRDOQuery.Create(qkCallNoRet, 0); Query.ObjId := ObjectId; Query.Name := MethodName; // set priority if Priority <> THREAD_PRIORITY_NORMAL then Query.Priority := ThreadPriorityToQueryPriority(Priority); // get param count { if TVarData( Params ).VType and varArray <> 0 then ParamCount := VarArrayHighBound(Params, 1) else ParamCount := 0; } ParamCount := Params.cArgs; // push in/out params ParmsByRef := false; ParamIdx := pred(ParamCount); while (ParamIdx >= 0) and (ErrorCode = errNoError) do begin if TVarData(Params.rgvarg[ ParamIdx ]).VType and varArray = 0 then begin ParamInfo[ParamIdx] := false; try if TVarData( Params.rgvarg[ ParamIdx ] ).VType and varTypeMask = varVariant then begin Aux := PVariant(TVarData( Params.rgvarg[ ParamIdx ] ).vPointer); if (Aux <> nil) and (TVarData(Aux^).vType = varPointer) then begin PtrRec := GetMarshalPtr(Aux^); Query.PushPtr(PtrRec.ptr, PtrRec.size); end else begin // check for marchaled types... { TVarData( TmpVariant ).VType := varVariant; Params.rgvarg[ ParamIdx ] := TmpVariant; } Query.PushParamRef; ParmsByRef := true; ParamInfo[ParamIdx] := true; end; end else Query.PushParam(variant(Params.rgvarg[ ParamIdx ])); except ErrorCode := errIllegalParamList; end; end else ErrorCode := errIllegalParamList; dec( ParamIdx ); end; if ErrorCode = errNoError then begin if (Query.QKind = qkCallRet) or ParmsByRef then try // invoke method and wait... QueryResult := RDOConnection.SendReceive( Query, ErrorCode, TimeOut ); try if ErrorCode = errNoError then begin idx := 0; ErrorCode := GetQueryErrorCode( QueryResult ); if (ErrorCode = errNoError) and (TVarData( Res ).VType <> varEmpty ) then try if QueryResult.ParamCount > 0 then Res := QueryResult.PopParam(idx) else Res := Unassigned; except Res := Unassigned; ErrorCode := errMalformedResult; end; // Set out params if (ErrorCode = errNoError) and (QueryResult <> nil) and ParmsByRef then begin ParamIdx := pred(ParamCount); while (ParamIdx >= 0) and (ErrorCode = errNoError) do begin if ParamInfo[ParamIdx] then try Params.rgvarg[ ParamIdx ].pvarVal^ := QueryResult.PopParam(idx); except ErrorCode := errMalformedResult; end; dec(ParamIdx); end; end; end; finally // release result QueryResult.Free; end; finally // release query Query.Free; end else RDOConnection.Send( Query ); // invoke method and don't wait... end else Query.Free; end; function MarshalObjIdGet( ObjectName : string; RDOConnection : IRDOConnection; TimeOut, Priority : integer; out ErrorCode : integer ) : integer; var Query : TRDOQuery; QueryResult : TRDOQuery; idx : integer; begin try Query := TRDOQuery.Create(qkGeID, 0); try if Priority <> THREAD_PRIORITY_NORMAL then Query.Priority := ThreadPriorityToQueryPriority(Priority); Query.Name := ObjectName; QueryResult := RDOConnection.SendReceive( Query, ErrorCode, TimeOut ); try if ErrorCode = errNoError then begin ErrorCode := GetQueryErrorCode( QueryResult ); if (ErrorCode = errNoError) and (QueryResult <> nil) then try idx := 0; result := QueryResult.PopParam(idx); except result := 0; ErrorCode := errMalformedQuery; end else result := 0; end else result := 0; finally QueryResult.Free; end; finally Query.Free; end; except result := 0; ErrorCode := errUnknownError; end; end; end.
unit uConsts; interface uses Windows, Classes, SysUtils, Graphics, SyncObjs; const CST_SYSINFOFILE = 'sysinfo.CSV'; CST_CHANNELFILE = 'channels.csv'; CST_DEFJOBINFOFILE = 'defjobinfo.CSV'; CST_JOBINFOFILE = 'jobinfo.CSV'; LARGE_BOX_COUNT = 5; // X_AXIS = 0; Z_AXIS = 0; EMPTY_BOX_Z_AXIS = 1; //2D Scanner ID_LOADING_2D_SCANNER = 1; ID_LOADING_2D_SPECIAL_SCANNER = 2; ID_OUTLET_2D_SCANNER = 3; { Log On Level } LOG_USER = 0; LOG_ADMIN = 1; LOG_SUPER = 2; TCP_AUTO_LABEL = 1; TCP_MANUAL_LABEL = 2; SIMAX_MANUAL_LABEL = 1; SIMAX_AUTO_LABEL = 2; SIMAX_SBOX_MERGE = 1; SIMAX_LBOX_CHECK = 2; { 에러 번호 } //ETC ERR_X0100_MAIN_POWER_OFF_CHECK = 1001; ERR_X0101_EMERGENCY_OFF_CHECK = 1002; ERR_X0102_DC_POWER_OFF_CHECK = 1003; ERR_X0103_MAIN_AIR_CHECK = 1004; Z_CARD_STATUS_SERVO_OFF = 1005; Z_CARD_STATUS_SERVO_ALARM = 1006; ERR_NOT_LARGE_BOX_SAVE = 1007; ERR_NOT_SMALL_BOX_SAVE = 1008; ERR_SIMAX_LABEL_COUNT_SHORTAGE = 1020; ERR_NOT_INITIALIZE_ALL = 1101; WARN_AUTO_RUNNING = 1102; WARN_MANUAL_RUNNING = 1103; ERR_NOT_INLET_SAMSUNG_SCAN = 1104; ERR_NOT_INLET_SPECIAL_SCAN = 1105; ERR_NOT_OUTLET_SAMSUNG_SCAN = 1106; ERR_NOT_OUTLET_SPECIAL_SCAN = 1107; ERR_NOT_Z_CONVEYORRUN_POS = 1108; ERR_NOT_Z_STANDBY_POS = 1109; ERR_X0500_DOOR_FRONT_LEFT_CLOSE = 1201; ERR_X0501_DOOR_FRONT_RIGHT_CLOSE = 1202; ERR_X0502_DOOR_MONITOR_CLOSE = 1203; ERR_X0700_LABEL_PRINTER_CLOSE = 1204; ERR_X1016_DOOR_BYPASS_STACKER_CLOSE = 1205; ERR_X0403_DOOR_FENCE_PLUG_ALL_CLOSE = 1206; ERR_X0504_DOOR_FRONT_FENCE_CLOSE = 1207; ERR_X0506_DOOR_LEFT_FENCE_LEFT_CLOSE = 1208; ERR_X0507_DOOR_LEFT_FENCE_RIGHT_CLOSE = 1209; ERR_X050C_DOOR_REAR_FENCE_LEFT_CLOSE = 1210; ERR_X050D_DOOR_REAR_FENCE_RIGHT_CLOSE = 1211; ERR_X0901_DOOR_FRONT_CLOSE = 1212; ERR_X0505_DOOR_FRONT_FENCE_LOCK = 1301; ERR_X0508_DOOR_LEFT_FENCE_UPPER_LOCK = 1302; ERR_X0509_DOOR_LEFT_FENCE_LOWER_LOCK = 1303; ERR_X050E_DOOR_REAR_FENCE_LEFT_LOCK = 1304; ERR_X050F_DOOR_REAR_FENCE_RIGHT_LOCK = 1305; ERR_X053C_DOOR_FRONT_UPPER_LOCK = 1306; ERR_X053D_DOOR_FRONT_LOWER_LOCK = 1307; ERR_X053E_DOOR_MONITOR_UPPER_LOCK = 1308; ERR_X053F_DOOR_MONITOR_LOWER_LOCK = 1309; ERR_X0701_LABEL_PRINTER_LOCK = 1310; ERR_X0920_BOX_LOADING_DOOR_LOCK = 1311; ERR_X1017_DOOR_BYPASS_STACKER_LOCK = 1312; ERR_PRINT_PAPER_OUT = 1401; ERR_PRINT_RIBON_OUT = 1402; ERR_PRINT_OFF_LINE = 1403; ERR_PRINT_HEAD_UP = 1404; ERR_PRINT_COMM = 1405; ERR_PRINT_PRINTING_FAIL = 1406; ERR_EC_DATA_CHECK = 1501; ERR_EC_DATA_LABEL_CHECK = 1502; ERR_EC_SERVER_COMM_FAIL = 1503; ERR_NOT_SAME_LOADING_LOTID = 1504; ERR_SIMAX_DATA_FAIL = 1601; ERR_SIMAX_LBOX_FAIL_DATA = 1602; ERR_SIMAX_COMM_FAIL = 1603; ERR_SMALL_BOX_LOADING_CONVEYOR_BOX_CHECK = 2001; //자재를 감지해야 하는데 감지를 못한경우 ERR_X0900_SMALL_BOX_LOADING_CONVEYOR_RUN = 2002; ERR_X0900_SMALL_BOX_LOADING_CONVEYOR_STOP = 2003; ERR_X0910_SMALL_BOX_LOADING_STOPPER_UP = 2004; ERR_X0911_SMALL_BOX_LOADING_STOPPER_DOWN = 2005; ERR_X0914_SMALL_BOX_LOADING_SAMSUNG_SCAN_UP = 2006; ERR_X0915_SMALL_BOX_LOADING_SAMSUNG_SCAN_DOWN = 2007; ERR_X0916_SMALL_BOX_LOADING_SEPCIAL_SCAN_UP = 2008; ERR_X0917_SMALL_BOX_LOADING_SEPCIAL_SCAN_DOWN = 2009; ERR_NOT_SMALL_BOX_LOADING_CONVEYOR_BOX_CHECK = 2010; //자재가 없어야 하는데 감지가 된경우 ERR_X0906_SMALL_BOX_LOADING_STOPPERPOS = 2011; ERR_X1835_EMPTY_BOX_LOADING_CONVEYOR_BOX_FEED_GUIDE_UP_DOWN_CYLINDER_DOWN_FAIL = 2020; ERR_X1834_EMPTY_BOX_LOADING_CONVEYOR_BOX_FEED_GUIDE_UP_DOWN_CYLINDER_UP_FAIL = 2021; ERR_NOT_EMPTY_BOX = 2030; ERR_EMPTY_BOX_LODING_CONVEYOR_BOX_OUT_CHECK_ON = 2031; ERR_EMPTY_BOX_UP_DOWN_SERVO_MOVING_FAIL = 2032; ERR_EMPTY_BOX_STACKER_FRONT_STOP_CYLINDER_RETRACT_FAIL = 2033; ERR_EMPTY_BOX_STACKER_REAR_STOP_CYLINDER_RETRACT_FAIL = 2034; ERR_EMPTY_BOX_UP_DOWN_SERVO_POP_POSITION_CHECK_FAIL = 2035; ERR_EMPTY_BOX_UP_DOWN_SERVO_POP_POSTION_MOVNG_FAIL = 2036; ERR_EMPTY_BOX_UP_DOWN_SERVO_DOWN_POSITION_CHECK_FAIL = 2037; ERR_EMPTY_BOX_UP_DOWN_SERVO_DOWN_POSITOIN_MOVNG_FAIL = 2038; ERR_EMPTY_BOX_STACKER_STOP_CYLINDER_EXTEND_FAIL = 2039; ERR_EMPTY_BOX_UP_DOWN_SERVO_STANDBY_POSITION_CHECK_FAIL = 2040; ERR_EMPTY_BOX_UP_DOWN_SERVO_STANDBY_POSITOIN_MOVNG_FAIL = 2041; ERR_EMPTY_BOX_STACKER_FRONT_STOP_CYLINDER_EXTEND_FAIL = 2042; ERR_EMPTY_BOX_STACKER_REAR_STOP_CYLINDER_EXTEND_FAIL = 2043; ERR_EMPTY_BOX_STACKER_STOP_CYLINDER_RETREACT_FAIL = 2044; ERR_EMPTY_BOX_STACKER_FEED_CONVEYOR_CYLINDER_UP_FAIL = 2045; ERR_EMPTY_BOX_CONVEYOR_STOP_POSITION_RUN_FIAL = 2046; ERR_EMPTY_BOX_CONVEYOR_STOP_POSITION_ALIVE_FAIL = 2047; ERR_EMPTY_BOX_FEED_CONVEYOR_DOWN_POSITION_CHECK = 2048; ERR_EMPTY_BOX_CONVEYOR_OUT_POSITION_RUN_FAIL = 2049; ERR_EMPTY_BOX_FEED_CONVEYOR_RUN_FAIL = 2050; ERR_EMPTY_BOX_CONVEYOR_OUT_POSITION_ALIVE_FAIL = 2051; ERR_EMPTY_BOX_FEED_CONVEYOR_ALIVE_POSITION_RUN_FAIL = 2052; ERR_EMPTY_BOX_FEED_CONVEYOR_ALIVE_BOX_OUT_SENSOR_CHECK_FAIL = 2053; ERR_EMPTY_BOX_FEED_CONVEYOR_ALIVE_BOX_IN_SENSOR_CHECK = 2054; ERR_EMPTY_BOX_FEED_UP_DOWN_CONVEYOR_UP_DOWN_POSITION_FAIL = 2055; ERR_EMPTY_BOX_FEED_UP_DOWN_CONVEYOR_UP_POSITION_FAIL = 2056; ERR_EMPTY_BOX_STACKER_FEED_CONVEYOR_CYLINDER_DOWN_FAIL = 2057; ERR_EMPTY_BOX_FEED_CONVEYOR_BOX_PUSHER_CYLINDER_EXTEND_FAIL = 2058; ERR_EMPTY_BOX_FEED_CONVEYOR_BOX_PUSHER_CYLINDER_RETRACT_FAIL = 2059; ERR_LOADING_CONVEYOR_EMPTY_BOX_GUIDE_CYLINDER_UP_FAIL = 2060; ERR_LOADING_CONVEYOR_EMPTY_BOX_GUIDE_CYLINDER_DOWN_FAIL = 2061; ERR_EMPTY_BOX_FEED_UP_DOWN_CONVEYOR_DOWN_POSITION_FAIL = 2062; ERR_EMPTY_BOX_FEED_CONVEYOR_STATUS_CHECK = 2063; ERR_X1807_EMPTY_BOX_LOADING_CONVEYOR_DOOR_FRONT_TOP_DOOR_CLOSE_FAIL = 2064; ERR_X1809_EMPTY_BOX_LOADING_CONVEYOR_DOOR_BOX_INSERT_DOOR_LEFT_DOOR_CLOSE_CHECK_FAIL = 2065; ERR_X180B_EMPTY_BOX_LOADING_CONVEYOR_DOOR_BOX_INSERT_DOOR_RIGHT_DOOR_CLOSE_FAIL = 2066; ERR_X180D_EMPTY_BOX_LOADING_CONVEYOR_DOOR_CONTROL_PANEL_DOOR_CLOSE_FAIL = 2067; ERR_X180E_EMPTY_BOX_LOADING_CONVEYOR_DOOR_UNDER_LEFT_DOOR_CLOSE_FAIL = 2068; ERR_X180F_EMPTY_BOX_LOADING_CONVEYOR_DOOR_UNDER_RIGHT_DOOR_CLOSE_FAIL = 2069; ERR_X1808_EMPTY_BOX_LOADING_CONVEYOR_DOOR_FRONT_TOP_DOOR_LOCK_FAIL = 2070; ERR_X180A_EMPTY_BOX_LOADING_CONVEYOR_DOOR_BOX_INSERT_DOOR_LEFT_DOOR_LOCK_FAIL = 2071; ERR_X180C_EMPTY_BOX_LOADING_CONVEYOR_DOOR_BOX_INSERT_DOOR_RIGHT_DOOR_LOCK_FAIL = 2072; ERR_X0400_SMALL_BOX_INLET_CONVEYOR_RUN = 2101; ERR_X0400_SMALL_BOX_INLET_CONVEYOR_STOP = 2102; ERR_X0510_SMALL_BOX_INLET_IN_CHECK = 2103; //자재를 감지해야 하는데 감지를 못한경우 ERR_NOT_X0510_SMALL_BOX_INLET_IN_CHECK = 2104; //자재가 없어야 하는데 감지가 된경우 ERR_X0511_SMALL_BOX_INLET_STOPPERPOS_CHECK = 2105; ERR_NOT_X0511_SMALL_BOX_INLET_STOPPERPOS_CHECK = 2106; ERR_X0512_SMALL_BOX_INLET_STOPPER_FRONT_UP = 2107; ERR_X0513_SMALL_BOX_INLET_STOPPER_FRONT_DOWN = 2108; ERR_X0514_SMALL_BOX_INLET_STOPPER_REAR_UP = 2109; ERR_X0515_SMALL_BOX_INLET_STOPPER_REAR_DOWN = 2110; ERR_X0516_SMALL_BOX_INLET_ALIGN_FRONT_FWD = 2111; ERR_X0517_SMALL_BOX_INLET_ALIGN_FRONT_BWD = 2112; ERR_X0518_SMALL_BOX_INLET_ALIGN_REAR_FWD = 2113; ERR_X0519_SMALL_BOX_INLET_ALIGN_REAR_BWD = 2114; ERR_X051C_SMALL_BOX_INLET_GUIDE_FWD = 2115; ERR_X051D_SMALL_BOX_INLET_GUIDE_BWD = 2116; ERR_X0520_SMALL_BOX_INLET_PUSHER_FWD = 2117; ERR_X0521_SMALL_BOX_INLET_PUSHER_BWD = 2118; ERR_X0522_SMALL_BOX_INLET_PUSHER_UP = 2119; ERR_X0523_SMALL_BOX_INLET_PUSHER_DOWN = 2120; ERR_X0720_SMALL_BOX_INLET_PICKER_UP = 2121; ERR_X0721_SMALL_BOX_INLET_PICKER_DOWN = 2122; ERR_X0722_SMALL_BOX_INLET_PICKER_TURN = 2123; ERR_X0723_SMALL_BOX_INLET_PICKER_HOME = 2124; ERR_X0806_SMALL_BOX_INLET_PICKER_VACCUM_ON = 2125; ERR_X0806_SMALL_BOX_INLET_PICKER_VACCUM_OFF = 2126; ERR_X051A_SMALL_BOX_INLET_BOX_PUSH_POSITION = 2127; //자재를 감지해야 하는데 감지를 못한경우 ERR_NOT_X051A_SMALL_BOX_INLET_BOX_PUSH_POSITION = 2128; //자재가 없어야 하는데 감지가 된경우 ERR_X0724_SMALL_BOX_INLET_PICKER_CHECK = 2129; ERR_X051B_SMALL_BOX_INLET_ON_PUSHER = 2130; // 박스가 푸셔에 올라 탔다. ERR_X0108_LARGE_BOX_INLET_CONVEYOR_RUN = 2201; ERR_X0108_LARGE_BOX_INLET_CONVEYOR_STOP = 2202; ERR_X0128_LARGE_BOX_INLET_BOX_IN_CHECK = 2203; //자재를 감지해야 하는데 감지를 못한경우 ERR_NOT_X0128_LARGE_BOX_INLET_BOX_IN_CHECK = 2204; //자재가 없어야 하는데 감지가 된경우 ERR_X0129_LARGE_BOX_INLET_PUSHER_BWD = 2205; ERR_X012A_LARGE_BOX_INLET_PUSHER_FWD = 2206; ERR_NOT_X012B_LARGE_BOX_INLET_BOX_MIDDLE_CHECK = 2207; //자재가 없어야 하는데 감지가 된경우 ERR_X0110_BTM_SEALING_EMPTY_BOX = 2208; ERR_X0111_BTM_SEALING_POWER_CHECK = 2209; ERR_X0112_BTM_SEALING_RUN = 2210; ERR_X010F_BTM_SEALING_BOX_EMPTY_CHECK = 2211; ERR_X0116_BTM_SEALING_TAPING_ERROR = 2212; ERR_X0534_BANDING_WIRE_NO_DETECTION = 2213; ERR_X0511_BOX_NOT_MOVE = 2214; ERR_X0702_LABEL_PRINTER_UNLOCK = 2303; ERR_X0704_LABEL_UNIT_SPECIALPOS = 2304; ERR_X0705_LABEL_UNIT_SAMSUNGPOS = 2305; ERR_X0706_LABEL_PICKER_PICKPOS = 2306; ERR_X0707_LABEL_PICKER_DROPPOS = 2307; ERR_X0710_LABEL_PICKER_UP = 2308; ERR_X0711_LABEL_PICKER_DOWN = 2309; ERR_X0714_LABEL_LARGEBOX_SCAN_FWD = 2310; ERR_X0715_LABEL_LARGEBOX_SCAN_BWD = 2311; ERR_X0807_LABEL_PICKER_VACUUM_ON = 2312; ERR_X0807_LABEL_PICKER_VACUUM_OFF = 2313; ERR_X0703_LABEL_PRINTING_CHECK = 2314; //자재를 감지해야 하는데 감지를 못한경우 ERR_NOT_X0703_LABEL_PRINTING_CHECK = 2315; //자재가 없어야 하는데 감지가 된경우 ERR_X0401_OUTLET_LARGE_BOX_CONVEYOR_RUN = 2401; ERR_X0401_OUTLET_LARGE_BOX_CONVEYOR_STOP = 2402; ERR_X0526_OUTLET_LARGE_BOX_IN_CHECK = 2403; //자재를 감지해야 하는데 감지를 못한경우 ERR_X0527_OUTLET_LARGE_BOX_MIDDLE1_CHECK = 2404; ERR_X0528_OUTLET_LARGE_BOX_MIDDLE2_CHECK = 2405; ERR_X0529_OUTLET_LARGE_BOX_STOPPOS_CHECK = 2406; ERR_X052A_OUTLET_LARGE_BOX_OUT_CHECK = 2407; ERR_NOT_X0526_OUTLET_LARGE_BOX_IN_CHECK = 2408; //자재가 없어야 하는데 감지가 된경우 ERR_NOT_X0527_OUTLET_LARGE_BOX_MIDDLE1_CHECK = 2409; ERR_NOT_X0528_OUTLET_LARGE_BOX_MIDDLE2_CHECK = 2410; ERR_NOT_X0529_OUTLET_LARGE_BOX_STOPPOS_CHECK = 2411; ERR_NOT_X052A_OUTLET_LARGE_BOX_OUT_CHECK = 2412; ERR_X052C_OUTLET_LARGE_BOX_STOPPER_UP = 2413; ERR_X052D_OUTLET_LARGE_BOX_STOPPER_DOWN = 2414; ERR_X0530_OUTLET_LARGE_BOX_TIPER_LEFT_UP = 2415; ERR_X0531_OUTLET_LARGE_BOX_TIPER_LEFT_DOWN = 2416; ERR_X0533_OUTLET_LARGE_BOX_TIPER_RIGHT_DOWN = 2417; ERR_X0532_OUTLET_LARGE_BOX_TIPER_RIGHT_UP = 2418; ERR_X052B_OUTLET_LARGE_BOX_LOADINGELEVATORPOS_CHECK = 2419; ERR_X011A_TOP_SELING_MOTOR_UP_LIMIT = 2501; ERR_X011B_TOP_SELING_MOTOR_DOWN_LIMIT = 2502; ERR_X011C_TOP_SELING_TAPE_CHECK = 2503; ERR_X011D_TOP_SELING_BOX_IN_CHECK = 2504; ERR_X011E_TOP_SELING_TAPE_ROTATE_CHECK = 2505; ERR_X0120_TOP_SEALING_SMALLBOX_PUSHER_HOME = 2506; ERR_X0121_TOP_SEALING_SMALLBOX_PUSHER_PUSH = 2507; ERR_X0122_TOP_SEALING_SMALLBOX_PUSHER_BAR_UP = 2508; ERR_X0123_TOP_SEALING_SMALLBOX_PUSHER_BAR_DOWN = 2509; ERR_X0124_TOP_SEALING_BOX_IN_CHECK = 2510; //자재를 감지해야 하는데 감지를 못한경우 ERR_NOT_X0124_TOP_SEALING_BOX_IN_CHECK = 2511; //자재가 없어야 하는데 감지가 된경우 ERR__X011F_TOP_SELING_BOX_MIDDLE_CHECK = 2512; ERR_NOT_X011F_TOP_SELING_BOX_MIDDLE_CHECK = 2513; ERR_X0119_TOP_SELING_BOX_OUT_CHECK = 2514; ERR_NOT_X0119_TOP_SELING_BOX_OUT_CHECK = 2515; ERR_X0118_TOP_SELING_POWER_OFF = 2516; ERR_X011A_TOP_SELING_UNIT_UP = 2517; ERR_X011B_TOP_SELING_UNIT_DOWN = 2518; ERR_X1000_STACKER_UNIT_UP = 2601; ERR_X1001_STACKER_UNIT_DOWN = 2602; ERR_X1002_BYPASS_STACKER_BOX1 = 2603; ERR_X1003_BYPASS_STACKER_BOX2 = 2604; ERR_X1004_BYPASS_STACKER_BOX3 = 2605; ERR_X1005_BYPASS_STACKER_BOX4 = 2606; ERR_X1006_BYPASS_STACKER_BOX5 = 2607; ERR_NOT_X1002_BYPASS_STACKER_BOX1 = 2608; ERR_NOT_X1003_BYPASS_STACKER_BOX2 = 2609; ERR_NOT_X1004_BYPASS_STACKER_BOX3 = 2610; ERR_NOT_X1005_BYPASS_STACKER_BOX4 = 2611; ERR_NOT_X1006_BYPASS_STACKER_BOX5 = 2612; ERR_X1007_STACKER_BOX_GUIDE_FWD = 2613; ERR_X1008_STACKER_BOX_GUIDE_BWD = 2614; ERR_X1009_STACKER_LOWER_STOPPER_LEFT_FRONT_FWD = 2615; ERR_X100A_STACKER_LOWER_STOPPER_LEFT_FRONT_BWD = 2616; ERR_X100B_STACKER_LOWER_STOPPER_LEFT_REAR_FWD = 2617; ERR_X100C_STACKER_LOWER_STOPPER_LEFT_REAR_BWD = 2618; ERR_X100D_STACKER_LOWER_STOPPER_RIGHT_FRONT_FWD = 2619; ERR_X100E_STACKER_LOWER_STOPPER_RIGHT_FRONT_BWD = 2620; ERR_X1010_STACKER_LOWER_STOPPER_RIGHT_REAR_FWD = 2621; ERR_X1011_STACKER_LOWER_STOPPER_RIGHT_REAR_BWD = 2622; ERR_X1012_STACKER_UPPER_STOPPER_FRONT_FWD = 2623; ERR_X1013_STACKER_UPPER_STOPPER_FRONT_BWD = 2624; ERR_X1014_STACKER_UPPER_STOPPER_REAR_FWD = 2625; ERR_X1015_STACKER_UPPER_STOPPER_REAR_BWD = 2626; ERR_X0120_SMALL_BOX_PUSHER_NOT_HOME = 2800; ERR_PRINTER_COUNT_INIT = 3605; //라벨 프린터 수량 카운트 추가 *****LJH ERR_PRINTER_BLACK_PAPER_EMPTY = 3606; //라벨 프린터 수량 카운트 추가 *****LJH ERR_PRINTER_COUNT_INIT_1 = 3616; //라벨 프린터 수량 카운트 추가 1 *****LJH ERR_PRINTER_LABEL_EMPTY = 3617; //라벨 프린터 수량 카운트 추가 1 *****LJH ERR_1ST_LABEL_FORMAT = 3718; //라벨 양식 없음 ERROR *****LJH ERR_2ND_LABEL_FORMAT = 3719; //라벨 양식 없음 ERROR *****LJH ERR_EC_LABEL_FORMAT = 3720; //라벨 양식 없음 ERROR *****LJH ERR_LBOX_VID_RESULT_FAIL = 3721; ERR_LBOX_VID_DATA_FAIL = 3722; ERR_EMPTY_BOX_SCAN_CHECK = 3723; { 메시지 ID } STR_OK = 1; STR_CANCEL = 2; STR_FINISH = 3; STR_CLOSE = 4; STR_READY = 5; STR_PROJECT = 6; STR_SYSTEM_STOP = 7; STR_JOG = 8; STR_UP = 9; STR_DOWN = 10; STR_LEFT = 11; STR_RIGHT = 12; STR_BACKWARD = 13; STR_FORWARD = 14; STR_QUERY_EXIT_PROGRAM = 15; STR_NOT_FOUND_SYSINFOFILE = 16; STR_NOT_FOUND_CHANNELFILE = 17; STR_IO_SERVICE_NOT_INSTALLED = 18; STR_AIO_SERVICE_NOT_INSTALLED = 19; STR_CANNOT_STARTUP_AMC = 20; STR_INIT_AXIS = 21; STR_INVALID_KEY = 22; STR_CURRENT_JOB = 23; STR_INPUT_PASSWORD = 24; STR_INPUT_NEW_PASSWORD = 25; STR_PASSWORD_OK = 26; STR_WRONG_PASSWORD = 27; STR_LOGIN = 28; STR_LOGOUT = 29; STR_MANAUL_IO_RUNNING = 30; STR_SELECT_OPERATOR_ID = 31; STR_NOT_IMAGE_FILE = 32; STR_INITIALIZE = 33; STR_LARGE_BOX_OUTPUT = 34; STR_ENABLE_STACKER_LOADING = 35; STR_ENABLE_QC_MODE = 36; STR_ENABLE_MANUAL_MODE = 37; var { 로깅 레벨 } VerboseMode : Integer; { Demo Mode ? } StartUpWithHW : Boolean; LogOnLevel : Integer; LoggedUser : String; { 시스템 정보 파일 } InfoFile : string; { 시스템 설정 정보 파일 } SysInfoFile : string; { 시스템 설정 정보 파일 } DefSysInfoFile : string; { 채널 임시 설정 정보 파일 } ChannelInfoFile : string; { 현재 프로젝트 } CurProject : string; { 현재 프로젝트 정보가 있는 디렉토리 이름 } CurProjectDir : string; { 마지막 작업일 } LastWorkDate : TDateTime; FSelectedNode : Integer; MotionCardNo : Integer; CS_PRINTER : TCriticalSection; resourcestring SFileNotFound = 'The File %s does not exist'; implementation initialization CS_PRINTER := TCriticalSection.Create; finalization CS_PRINTER.Free; end.
unit UnitApp; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls; type TForm10 = class(TForm) Timer1: TTimer; Memo1: TMemo; procedure Timer1Timer(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormDestroy(Sender: TObject); private FContador: integer; FServico: Boolean; FLock: TObject; { Private declarations } public { Public declarations } procedure Log(texto: string); procedure Execute; procedure Init; end; var Form10: TForm10; implementation {$R *.dfm} procedure TForm10.Execute; begin // procedure a ser executa quando estiver chamando como serviço // nao executa o SHOW do formulário FServico := true; Init; end; procedure TForm10.FormCreate(Sender: TObject); begin FContador := 0; FServico := false; FLock := TObject.create; end; procedure TForm10.FormDestroy(Sender: TObject); begin FLock.Free; end; procedure TForm10.FormShow(Sender: TObject); begin // quando é executa como Aplicativo, usa o show para dar inicio ao funcinamento FServico := false; Init; end; procedure TForm10.Init; begin Timer1.Enabled := true; end; procedure WriteLogText(AArquivo: string; ATexto: string); var Lf: textfile; LS: string; begin AssignFile(Lf, AArquivo); try {$I-} Append(Lf); {$I+} if IOResult <> 0 then Rewrite(Lf); WriteLn(Lf, ATexto); finally CloseFile(Lf); end; end; procedure TForm10.Log(texto: string); procedure LogServico; begin System.TMonitor.Enter(FLock); // controle de acesso ao arquivo de LOG try WriteLogText( ExtractFilePath(ParamStr(0))+ '\AppService.log',DatetimeToStr(now)+'-'+texto); finally System.TMonitor.Exit(FLock); end; end; begin if FServico then LogServico else TThread.Queue(nil, procedure // sincroniza a escrita no memo1 - previne chamada multi-thread begin Memo1.Lines.Add(texto); // mostra o texto em um memo. end); end; procedure TForm10.Timer1Timer(Sender: TObject); begin inc(FContador); Log('Chamada: ' + intToStr(FContador)); end; end.
unit UFormReloc; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, StdCtrls, ExtCtrls, XPMan; type TFormReloc = class(TForm) btnOK: TButton; btnCancel: TButton; GroupBox1: TGroupBox; chkAppData: TRadioButton; chkDefault: TRadioButton; chkCustom: TRadioButton; btnPath: TButton; edPath: TEdit; GroupBox2: TGroupBox; Label2: TLabel; Label3: TLabel; chkAllUsers: TCheckBox; Bevel1: TBevel; Label1: TLabel; XPManifest1: TXPManifest; procedure btnPathClick(Sender: TObject); procedure chkDefaultClick(Sender: TObject); procedure btnOKClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } FFolder: AnsiString; procedure ReadParams; procedure SaveParams; public { Public declarations } end; var FormReloc: TFormReloc; implementation uses ATxSProc, ATxFProc, ATxRegistry, ATxUtils, FileCtrl; {$R *.DFM} const cRegKey = 'Software\UniversalViewer'; cRegValue = 'ConfigurationFolder'; cAppData = '%AppData%\ATViewer'; procedure TFormReloc.ReadParams; begin FFolder:= GetRegKeyStr(HKEY_CURRENT_USER, cRegKey, cRegValue, GetRegKeyStr(HKEY_LOCAL_MACHINE, cRegKey, cRegValue, '')); end; procedure TFormReloc.SaveParams; begin SetRegKeyStr(HKEY_CURRENT_USER, cRegKey, cRegValue, FFolder); if chkAllUsers.Checked then SetRegKeyStr(HKEY_LOCAL_MACHINE, cRegKey, cRegValue, FFolder); end; procedure TFormReloc.btnPathClick(Sender: TObject); var Path: AnsiString; begin Path:= ''; if SelectDirectory('', '', Path) then edPath.Text:= Path; end; procedure TFormReloc.chkDefaultClick(Sender: TObject); begin edPath.Enabled:= chkCustom.Checked; btnPath.Enabled:= chkCustom.Checked; end; procedure TFormReloc.btnOKClick(Sender: TObject); begin if chkDefault.Checked then FFolder:= '' else if chkAppData.Checked then FFolder:= cAppData else if chkCustom.Checked then begin FFolder:= edPath.Text; if not IsDirExist(SExpandVars(FFolder)) then begin Application.MessageBox('Selected folder does not exist', PChar(Caption), MB_OK or MB_ICONERROR); Exit end; end; SaveParams; Close; end; procedure TFormReloc.btnCancelClick(Sender: TObject); begin Close; end; procedure TFormReloc.FormCreate(Sender: TObject); begin ReadParams; chkDefault.Checked:= FFolder=''; chkAppData.Checked:= StrIComp(PChar(FFolder), cAppData)=0; chkCustom.Checked:= (not chkDefault.Checked) and (not chkAppData.Checked); if chkCustom.Checked then edPath.Text:= FFolder; chkDefaultClick(Self); chkAppData.Enabled:= Pos('%', SExpandVars('%AppData%'))=0; end; 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: StGenLog.pas 4.04 *} {*********************************************************} {* SysTools: General Logging *} {*********************************************************} {$I StDefine.inc} unit StGenLog; interface uses Windows, SysUtils, Classes, StBase; const StDefBufferSize = 65536; { Default buffer size } StDefHighLevel = 0; { Default high level point } StMaxLogSize = 16000000; { Max size of general log buffer } // StCRLF = #10#13; {!!.01} StCRLF = #13#10; {!!.01} StLogFileFooter = ''; StLogFileHeader = 'SysTools General Log' + StCRLF + '=============================================================================' + StCRLF + StCRLF; { General log constants } leEnabled = 1; leDisabled = 2; leString = DWORD($80000000); type TStGetLogStringEvent = procedure(Sender : TObject; const D1, D2, D3, D4 : DWORD; var LogString : AnsiString) of object; TStWriteMode = (wmOverwrite, wmAppend); { Record for log entries } PStLogRec = ^TStLogRec; TStLogRec = record lrTime : DWORD; lrData1 : DWORD; lrData2 : DWORD; lrData3 : DWORD; lrData4 : DWORD; end; PStLogBuffer = ^TStLogBuffer; TStLogBuffer = array[0..StMaxLogSize] of Byte; StGenOptions = (goSuppressEnableMsg, goSuppressDisableMsg); {!!.01} StGenOptionSet = set of StGenOptions; {!!.01} TStGeneralLog = class(TStComponent) private { Property variables } FBufferSize : DWORD; FEnabled : Boolean; FFileName : TFileName; FHighLevel : Byte; FLogFileFooter : string; FLogFileHeader : string; FLogOptions : StGenOptionSet; {!!.01} FWriteMode : TStWriteMode; { Event variables } FOnHighLevel : TNotifyEvent; FOnGetLogString : TStGetLogStringEvent; { Private variables } glBuffer : PStLogBuffer; glBufferHead : DWORD; glBufferTail : DWORD; glHighLevelMark : DWORD; glHighLevelTriggered : Boolean; glLogCS : TRTLCriticalSection; glTempBuffer : PByteArray; glTempSize : DWORD; glTimeBase : DWORD; protected { Property access methods } procedure DoGetLogString(const D1, D2, D3, D4 : DWORD; var LogString : AnsiString); virtual; function GetBufferEmpty : Boolean; function GetBufferFree : DWORD; function GetBufferSize : DWORD; function GetEnabled : Boolean; function GetFileName : TFileName; function GetHighLevel : Byte; function GetLogOptions : StGenOptionSet; {!!.01} function GetWriteMode : TStWriteMode; procedure SetBufferSize(const Value : DWORD); procedure SetEnabled(const Value : Boolean); virtual; procedure SetFileName(const Value : TFileName); virtual; procedure SetHighLevel(const Value : Byte); procedure SetLogOptions(const Value : StGenOptionSet); {!!.01} procedure SetWriteMode(const Value : TStWriteMode); { Internal methods } procedure glCalcHighLevel; procedure glCheckTempSize(SizeReq : DWORD); procedure glHighLevelCheck; procedure glLockLog; function glPopLogEntry(var LogRec : TStLogRec) : Boolean; function glTimeStamp(Mark : DWORD) : string; procedure glUnlockLog; public { Public methods } constructor Create(Owner : TComponent); override; destructor Destroy; override; procedure AddLogEntry(const D1, D2, D3, D4 : DWORD); procedure ClearBuffer; procedure DumpLog; virtual; procedure WriteLogString(const LogString : AnsiString); { Public properties } property BufferEmpty : Boolean read GetBufferEmpty; property BufferFree : DWORD read GetBufferFree; published { Published properties } property BufferSize : DWORD read GetBufferSize write SetBufferSize default StDefBufferSize; property Enabled : Boolean read GetEnabled write SetEnabled default True; property FileName : TFileName read GetFileName write SetFileName; property HighLevel : Byte read GetHighLevel write SetHighLevel default StDefHighLevel; property LogFileFooter : string read FLogFileFooter write FLogFileFooter; property LogFileHeader : string read FLogFileHeader write FLogFileHeader; property LogOptions : StGenOptionSet read GetLogOptions {!!.01} write SetLogOptions default []; {!!.01} property WriteMode : TStWriteMode read GetWriteMode write SetWriteMode; { Event properties } property OnHighLevel : TNotifyEvent read FOnHighLevel write FOnHighLevel; property OnGetLogString : TStGetLogStringEvent read FOnGetLogString write FOnGetLogString; end; function HexifyBlock(var Buffer; BufferSize : Integer) : AnsiString; implementation { TStGeneralLog } { Gives text representation of a block of data } function HexifyBlock(var Buffer; BufferSize : Integer) : AnsiString; type TCastCharArray = array[0..Pred(High(Integer))] of AnsiChar; const { Starting string to work with - this is directly written to by index } { below, so any positional changes here will also have to be made below. } StockString = ' %6.6x: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 : 0000000000000000' + StCRLF; HexDigits : array[0..$F] of AnsiChar = '0123456789ABCDEF'; var I, J, K, Lines : Integer; TempStr : AnsiString; Hex1, Hex2 : array[0..23] of AnsiChar; Ascii1, Ascii2 : array[0..7] of AnsiChar; begin K := 0; FillChar(Hex1, SizeOf(Hex1), #32); FillChar(Hex2, SizeOf(Hex2), #32); { Calculate number of lines required } Lines := BufferSize div 16; if (BufferSize mod 16) <> 0 then Inc(Lines); { Process and append lines } for I := 0 to Lines-1 do begin { Load string, add index marker } TempStr := AnsiString(Format(StockString, [I*16])); { Format data for first word } for J := 0 to 7 do begin if J+K >= BufferSize then begin Ascii1[J] := ' '; Hex1[J*3] := ' '; Hex1[J*3+1] := ' '; end else begin Ascii1[J] := TCastCharArray(Buffer)[J+K]; Hex1[J*3] := HexDigits[Byte(Ascii1[J]) shr 4]; Hex1[J*3+1] := HexDigits[Byte(Ascii1[J]) and $F]; { Clamp Ascii to printable range } if (Ascii1[J] < #32) or (Ascii1[J] > #126) then Ascii1[J] := '.'; end; end; Inc(K,8); { Format data for second word } for J := 0 to 7 do begin if J+K >= BufferSize then begin Ascii2[J] := ' '; Hex2[J*3] := ' '; Hex2[J*3+1] := ' '; end else begin Ascii2[J] := TCastCharArray(Buffer)[J+K]; Hex2[J*3] := HexDigits[Byte(Ascii2[J]) shr 4]; Hex2[J*3+1] := HexDigits[Byte(Ascii2[J]) and $F]; { Clamp Ascii to printable range } if (Ascii2[J] < #32) or (Ascii2[J] > #126) then Ascii2[J] := '.'; end; end; Inc(K,8); { Move data to existing temp string } Move(Hex1[0], TempStr[11], SizeOf(Hex1)); Move(Hex2[0], TempStr[36], SizeOf(Hex2)); Move(Ascii1[0], TempStr[62], SizeOf(Ascii1)); Move(Ascii2[0], TempStr[70], SizeOf(Ascii2)); { Append temp string to result } Result := Result + TempStr; end; end; constructor TStGeneralLog.Create(Owner : TComponent); begin inherited Create(Owner); InitializeCriticalSection(glLogCS); BufferSize := StDefBufferSize; FEnabled := True; FFileName := 'debug.log'; FLogFileFooter := StLogFileFooter; FLogFileHeader := StLogFileHeader; HighLevel := StDefHighLevel; glHighLevelTriggered := False; glTimeBase := GetTickCount; end; destructor TStGeneralLog.Destroy; begin FreeMem(glBuffer); FreeMem(glTempBuffer); DeleteCriticalSection(glLogCS); inherited Destroy; end; procedure TStGeneralLog.glLockLog; begin if IsMultiThread then EnterCriticalSection(glLogCS); end; procedure TStGeneralLog.glUnlockLog; begin if IsMultiThread then LeaveCriticalSection(glLogCS); end; { AddLogEntry notes: } { } { D1 = $FFFFFFFF is reserved for internal events } { } { D1, D2, D3, D4 are "info" fields to be used in the OnGetLogString } { handler to identify the logged event and what type of data would be } { appropriate for the corresponding log entry. } { } { While you're free to come up with your own logging scheme, it was } { envisioned that D1 would identify the logged event in the broadest } { terms, and the event classification would be narrowed further and } { further with D2 --> D4. } { } { Special case: If the high bit of D2 is set, D3 becomes a pointer } { to data, and D4 is the size of the data. Make *sure* the high bit } { isn't set unless you are using this special situation. } { } { If you just have a simple case for logging that probably won't get } { used that often, consider adding entries with the WriteDebugString } { method. } procedure TStGeneralLog.AddLogEntry(const D1, D2, D3, D4 : DWORD); var LogEntry : TStLogRec; EntryPtr : PStLogRec; SizeReq, TimeMrk, ChunkSize : DWORD; HasData : Boolean; begin glLockLog; try { Bail if we're not logging } if not Enabled then Exit; TimeMrk := GetTickCount; { Determine size needed } SizeReq := SizeOf(TStLogRec); if (D2 and $80000000) = $80000000 then begin HasData := True; Inc(SizeReq, D4); end else begin HasData := False; end; { Bail if SizeReq is bigger than the whole buffer } if SizeReq > FBufferSize then Exit; { Make more room in buffer if necessary } while (SizeReq > BufferFree) and glPopLogEntry(LogEntry) do ; { Do we need to wrap this entry? } if (glBufferTail + SizeReq) <= FBufferSize then begin { Wrap not required, write directly to glBuffer } EntryPtr := @glBuffer[glBufferTail]; EntryPtr.lrTime := TimeMrk; EntryPtr.lrData1 := D1; EntryPtr.lrData2 := D2; EntryPtr.lrData3 := D3; EntryPtr.lrData4 := D4; { Write add'l data if necessary } if HasData then begin Move(Pointer(D3)^, glBuffer[glBufferTail + SizeOf(TStLogRec)], D4); end; Inc(glBufferTail, SizeReq); { Fix tail if necessary } if glBufferTail = FBufferSize then glBufferTail := 0; end else begin { Wrap required, use temp buffer } glCheckTempSize(SizeReq); EntryPtr := @glTempBuffer[0]; EntryPtr.lrTime := TimeMrk; EntryPtr.lrData1 := D1; EntryPtr.lrData2 := D2; EntryPtr.lrData3 := D3; EntryPtr.lrData4 := D4; { Write add'l data if necessary } if HasData then begin Move(Pointer(D3)^, glTempBuffer[SizeOf(TStLogRec)], D4); end; { Move first half } ChunkSize := FBufferSize - glBufferTail; Move(glTempBuffer[0], glBuffer[glBufferTail], ChunkSize); { Move second half } Move(glTempBuffer[ChunkSize], glBuffer[0], SizeReq - ChunkSize); { Set tail } glBufferTail := SizeReq - ChunkSize; end; glHighLevelCheck; finally glUnlockLog; end; end; { Clears all data from buffer (does not write data to disk) } procedure TStGeneralLog.ClearBuffer; begin glLockLog; try glBufferHead := 0; glBufferTail := 0; finally glUnlockLog; end; end; { Let user fill in the data for the LogString } procedure TStGeneralLog.DoGetLogString(const D1, D2, D3, D4 : DWORD; var LogString : AnsiString); begin if Assigned(FOnGetLogString) then FOnGetLogString(Self, D1, D2, D3, D4, LogString); end; { Calculate the BufferFree level, in bytes, to trip the high level alarm } procedure TStGeneralLog.glCalcHighLevel; begin glLockLog; try glHighLevelMark := FBufferSize - Round(FBufferSize * FHighLevel / 100); glHighLevelCheck; finally glUnlockLog; end; end; { Verifies the size of the temp buffer } procedure TStGeneralLog.glCheckTempSize(SizeReq : DWORD); begin if (SizeReq > glTempSize) then begin ReallocMem(glTempBuffer, SizeReq); glTempSize := SizeReq; end; end; { Test for high level condition, fire event if necessary } procedure TStGeneralLog.glHighLevelCheck; begin glLockLog; try if FHighLevel = 0 then Exit; if BufferFree < glHighLevelMark then begin if Assigned(FOnHighLevel) and not glHighLevelTriggered then begin FOnHighLevel(Self); glHighLevelTriggered := True; end; end else begin glHighLevelTriggered := False; end; finally glUnlockLog; end; end; { Pop log record from log, return False if no record to return } function TStGeneralLog.glPopLogEntry(var LogRec : TStLogRec) : Boolean; type BytesArray = array[0..SizeOf(TStLogRec)-1] of Byte; var Bytes : BytesArray absolute LogRec; ChunkSize : DWORD; begin glLockLog; try { Check for empty buffer } if (glBufferHead = glBufferTail) then begin Result := False; Exit; end else begin Result := True; end; { Check to see if log record wraps } if (glBufferHead + SizeOf(TStLogRec)) <= FBufferSize then begin { No wrap, copy directly over } Move(glBuffer[glBufferHead], LogRec, SizeOf(LogRec)); Inc(glBufferHead, SizeOf(LogRec)); { Fix head if needed } if (glBufferHead = FBufferSize) then glBufferHead := 0; end else begin { Need to deal with wrap -- copy first half } ChunkSize := (FBufferSize - glBufferHead); Move(glBuffer[glBufferHead], Bytes[0], ChunkSize); { Copy second half } Move(glBuffer[0], Bytes[ChunkSize], (SizeOf(LogRec) - ChunkSize)); glBufferHead := SizeOf(LogRec) - ChunkSize; end; { Do we have data? If so, deal with it } if (LogRec.lrData2 and $80000000) = $80000000 then begin { Check to see if log data wraps } if (glBufferHead + LogRec.lrData4) <= FBufferSize then begin { No wrap -- point D2 to buffer } LogRec.lrData3 := DWORD(@glBuffer[glBufferHead]); Inc(glBufferHead, LogRec.lrData4); end else begin { Wrap -- copy first half to temp buffer } glCheckTempSize(LogRec.lrData4); ChunkSize := (FBufferSize - glBufferHead); Move(glBuffer[glBufferHead], glTempBuffer[0], ChunkSize); { Copy second half } Move(glBuffer[0], glTempBuffer[ChunkSize], (LogRec.lrData4 - ChunkSize)); LogRec.lrData3 := DWORD(@glTempBuffer[0]); glBufferHead := LogRec.lrData4 - ChunkSize; end; end finally glUnlockLog; end; end; { Return time stamp string } function TStGeneralLog.glTimeStamp(Mark : DWORD) : string; begin Result := Format('%07.7d : ', [Mark - glTimeBase]); Insert('.', Result, 5); end; { Dumps log file to disk } procedure TStGeneralLog.DumpLog; var LR : TStLogRec; FS : TFileStream; S, T : AnsiString; begin glLockLog; try { Open file stream } if FileExists(FileName) and (WriteMode = wmAppend) then begin FS := TFileStream.Create(FileName, fmOpenReadWrite or fmShareDenyWrite); FS.Seek(0, soFromEnd); end else begin FS := TFileStream.Create(FileName, fmCreate or fmShareDenyWrite); end; try { Do file header if appropriate } if (FS.Size = 0) then begin S := AnsiString(FLogFileHeader); FS.Write(S[1], Length(S)); { Write trailing CRLF } {!!.02} FS.Write(StCRLF[1], Length(StCRLF)); {!!.02} end; { Cycle through all data } while glPopLogEntry(LR) do begin if LR.lrData1 <> $FFFFFFFF then begin { It belongs to somone else, let them process it } DoGetLogString(LR.lrData1, LR.lrData2, LR.lrData3, LR.lrData4, S); end else begin { Something we're supposed to know about, deal with it } case LR.lrData2 of { Logging enabled } leEnabled : S := '**** Logging Enabled' + StCRLF; { Logging disabled } leDisabled : S := '**** Logging Disabled' + StCRLF; { WriteLogString entry } leString : begin if LR.lrData4 > 0 then begin {!!.02} SetLength(S, LR.lrData4); Move(PByteArray(LR.lrData3)[0], S[1], LR.lrData4); end else begin {!!.02} S := ''; { empty string } {!!.02} end; {!!.02} end; else S := AnsiString(Format('!! Unknown log entry : [%8.8x][%8.8x][%8.8x][%8.8x]' + StCRLF, [LR.lrData1, LR.lrData2, LR.lrData3, LR.lrData4])); end; end; { Write time stamp } T := AnsiString(glTimeStamp(LR.lrTime)); FS.Write(T[1], Length(T)); { Write log string } if Length(S) > 0 then {!!.02} FS.Write(S[1], Length(S)); { Write trailing CRLF } FS.Write(StCRLF[1], Length(StCRLF)); end; { Do file header if appropriate } if (FLogFileFooter <> '') then begin S := AnsiString(FLogFileFooter); FS.Write(S[1], Length(S)); { Write trailing CRLF } {!!.02} FS.Write(StCRLF[1], Length(StCRLF)); {!!.02} end; glHighLevelTriggered := False; finally FS.Free; end; finally glUnlockLog; end; end; { Determines whether something is in the buffer } function TStGeneralLog.GetBufferEmpty : Boolean; begin glLockLog; try Result := (glBufferHead = glBufferTail); finally glUnlockLog; end; end; { Calculates free space in the buffer } function TStGeneralLog.GetBufferFree : DWORD; begin glLockLog; try if (glBufferHead <= glBufferTail) then { One less than actual, since we always leave one byte free } Result := Pred(FBufferSize - (glBufferTail - glBufferHead)) else Result := Pred(glBufferHead - glBufferTail); finally glUnlockLog; end; end; { Retrieves buffer size } function TStGeneralLog.GetBufferSize : DWORD; begin glLockLog; try Result := FBufferSize; finally glUnlockLog; end; end; { Get Enabled property } function TStGeneralLog.GetEnabled : Boolean; begin glLockLog; try Result := FEnabled; finally glUnlockLog; end; end; { Get FileName property } function TStGeneralLog.GetFileName : TFileName; begin glLockLog; try Result := FFileName; finally glUnlockLog; end; end; { Retrieves high level setpoint } function TStGeneralLog.GetHighLevel : Byte; begin glLockLog; try Result := FHighLevel; finally glUnlockLog; end; end; {!!.01 - added} { Retrieves log options } function TStGeneralLog.GetLogOptions : StGenOptionSet; begin glLockLog; try Result := FLogOptions; finally glUnlockLog; end; end; { Retrieves write mode } function TStGeneralLog.GetWriteMode : TStWriteMode; begin glLockLog; try Result := FWriteMode; finally glUnlockLog; end; end; { Sets the size of the logging buffer } procedure TStGeneralLog.SetBufferSize(const Value : DWORD); begin glLockLog; try if Value <> FBufferSize then begin FBufferSize := Value; ReallocMem(glBuffer, Value); ClearBuffer; glCalcHighLevel; end; finally glUnlockLog; end; end; { Enables (or disables) logging } procedure TStGeneralLog.SetEnabled(const Value : Boolean); begin glLockLog; try if (Value = True) then begin { Allocate buffer if not already done } if (glBuffer = nil) then begin GetMem(glBuffer, FBufferSize); end; { Init temp buffer if not already done } if (glTempBuffer = nil) then begin glTempSize := 1024; GetMem(glTempBuffer, glTempSize); end; end else if not (goSuppressDisableMsg in LogOptions) then begin {!!.01} AddLogEntry($FFFFFFFF, leDisabled, 0, 0); end; FEnabled := Value; finally glUnlockLog; end; if (Value = True) and not (goSuppressEnableMsg in LogOptions) then {!!.01} AddLogEntry($FFFFFFFF, leEnabled, 0, 0); end; { Set FileName property } procedure TStGeneralLog.SetFileName(const Value : TFileName); begin glLockLog; try FFileName := Value; finally glUnlockLog; end; end; { Set HighLevel property } procedure TStGeneralLog.SetHighLevel(const Value : Byte); begin glLockLog; try if (FHighLevel <> Value) and (Value <= 100) then begin FHighLevel := Value; glCalcHighLevel; end; finally glUnlockLog; end; end; {!!.01 - added} { Set LogOptions property } procedure TStGeneralLog.SetLogOptions(const Value : StGenOptionSet); begin glLockLog; try FLogOptions := Value; finally glUnlockLog; end; end; { Set WriteMode property } procedure TStGeneralLog.SetWriteMode(const Value : TStWriteMode); begin glLockLog; try FWriteMode := Value; finally glUnlockLog; end; end; { Write log string to log buffer } procedure TStGeneralLog.WriteLogString(const LogString : AnsiString); begin AddLogEntry($FFFFFFFF, leString, NativeInt(LogString), Length(LogString)); end; end.
unit LibCalnd; { // // Calendar dialog pop-up demonstration - Use with TwwDBComboDlg // // Copyright (c) 1995 by Woll2Woll Software // // Credit: Thanks to Walter Fordham and International Software Systems // for providing the inspiration and work for this example. // // // I M P O R T A N T E ! ! ! // No Evento OnCustomDlg do Componente TwwDBComboDlg não esquecer de incluir a linha: // "wwCalendarComboDlg(Sender as TwwDBComboDlg)"; // // } interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Grids, Calendar, ExtCtrls, Buttons, Wwdbdlg, wwsystem, wwdotdot; type TMyCalendar = class(TForm) Calendar1: TCalendar; Panel1: TPanel; OkButton: TBitBtn; CancelButton: TBitBtn; MonthCombo: TComboBox; YearCombo: TComboBox; procedure MonthComboChange(Sender: TObject); procedure YearComboChange(Sender: TObject); procedure FormActivate(Sender: TObject); procedure Calendar1Change(Sender: TObject); procedure Calendar1DblClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); public DateVal: TDateTime; end; function Calendario(ComboDlg: TwwDBComboDlg): Boolean; procedure DispCalendario; implementation {$R *.DFM} function Calendario(ComboDlg: TwwDBComboDlg): Boolean; var rectBox : TRect; UpperPoint, LowerPoint : TPoint; myForm : TMyCalendar; begin Screen.cursor := crHourGlass; myForm := TMyCalendar.create(Application); with myForm do begin Screen.cursor := crDefault; if wwStrToDate(combodlg.text) then DateVal := strToDate(comboDlg.text) else DateVal := Date; with comboDlg do begin {Get the relative screen position of TwwDBComboDlg} rectBox := ClientRect; UpperPoint.X := rectBox.Left; UpperPoint.Y := rectBox.Top; UpperPoint := ClientToScreen(UpperPoint); LowerPoint.X := rectBox.Right; LowerPoint.Y := rectBox.Bottom; LowerPoint := ClientToScreen(LowerPoint); { If calendar too far down, popup over wwDBComboDlg } if UpperPoint.X + 1 + MyForm.Width > Screen.Width then MyForm.Left := Screen.Width - Myform.Width - 1 else MyForm.Left := UpperPoint.X + 1; if LowerPoint.Y + 1 + MyForm.Height > Screen.Height then MyForm.Top := UpperPoint.Y - Myform.Height else MyForm.Top := LowerPoint.Y + 1; end; result := ShowModal = mrOK; if result then with combodlg do begin if (datasource <> nil) and (datafield <> '') then datasource.dataset.fieldByName(dataField).text := DateToStr(DateVal) else text := DateToStr(DateVal); end; Free; end end; procedure DispCalendario; var myForm : TMyCalendar; begin MyForm := TMyCalendar.Create(Application); with MyForm do begin DateVal := Date; OkButton.Visible := False; CancelButton.Visible := False; BorderIcons := [biSystemMenu]; Position := poScreenCenter; Show; end; end; procedure TMyCalendar.MonthComboChange(Sender: TObject); begin Calendar1.Month := MonthCombo.ItemIndex + 1; end; procedure TMyCalendar.YearComboChange(Sender: TObject); begin Calendar1.Year := StrToInt(YearCombo.Items[YearCombo.ItemIndex]); end; procedure TMyCalendar.FormActivate(Sender: TObject); begin Calendar1.CalendarDate := DateVal; OkButton.Caption := ''; CancelButton.Caption := ''; MonthCombo.ItemIndex := Calendar1.Month - 1; YearCombo.ItemIndex := YearCombo.Items.IndexOf(IntToStr(Calendar1.Year)); Calendar1.OnChange(Calendar1); end; procedure TMyCalendar.Calendar1Change(Sender: TObject); begin DateVal := Calendar1.CalendarDate; end; procedure TMyCalendar.Calendar1DblClick(Sender: TObject); begin modalResult := mrOK; end; procedure TMyCalendar.FormShow(Sender: TObject); begin {$IFDEF win32} width := width - 5; height := height - 5; {$ENDIF} end; procedure TMyCalendar.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; end.
unit RVStyle; {$mode Delphi} interface {.$R RVStyle} uses {$IFDEF FPC} LCLType, {$ELSE} Windows, Messages, {$ENDIF} SysUtils, Classes, Graphics, Controls, Forms, {LibConst,} IniFiles; const crJump = 101; rvsNormal = 0; rvsHeading = 1; rvsSubheading = 2; rvsKeyword = 3; rvsJump1 = 4; rvsJump2 = 5; LAST_DEFAULT_STYLE_NO = rvsJump2; {$I RV_Defs.inc} type {--------------------------------------------------------------} TFontInfo = class(TCollectionItem) private { Private declarations } FFontName: TFontName; FSize: Integer; FColor: TColor; FStyle: TFontStyles; {$IFDEF RICHVIEWDEF3} FCharSet: TFontCharSet; {$ENDIF} public { Public declarations } constructor Create(Collection: TCollection); override; procedure Assign(Source: TPersistent); override; published { Published declarations } {$IFDEF RICHVIEWDEF3} property CharSet: TFontCharSet read FCharSet write FCharSet; {$ENDIF} property FontName: TFontName read FFontNAme write FFontName; property Size: Integer read FSize write FSize; property Color: TColor read FColor write FColor; property Style: TFontStyles read FStyle write FStyle; end; {--------------------------------------------------------------} TFontInfos = class (TCollection) private function GetItem(Index: Integer): TFontInfo; procedure SetItem(Index: Integer; Value: TFontInfo); public constructor Create; function Add: TFontInfo; procedure Delete(Index: Integer); procedure AddFont(Name: TFontName; Size: Integer; Color: TColor; Style:TFontStyles); {$IFDEF RICHVIEWDEF3} procedure AddFontEx(Name: TFontName; Size: Integer; Color: TColor; Style:TFontStyles; CharSet: TFontCharSet); {$ENDIF} property Items[Index: Integer]: TFontInfo read GetItem write SetItem; default; end; {--------------------------------------------------------------} TRVStyle = class(TComponent) private { Private declarations } FColor, FHoverColor, FSelColor, FSelTextColor: TColor; FCursor: TCursor; FTextStyles: TFontInfos; FFullRedraw: Boolean; function GetTextStyle(Index: Integer): TFontInfo; procedure SetTextStyles(ATextStyles: TFontInfos); protected { Protected declarations } public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; function AddTextStyle: Integer; { returns index of new style } procedure DeleteTextStyle(Index: Integer); { removes NONSTANDARD text style} procedure SaveINI(filename, section: String); {WARNING: before saving all section will be removed} procedure LoadINI(filename, section: String); published { Published declarations } property TextStyles: TFontInfos read FTextStyles write SetTextStyles; property JumpCursor: TCursor read FCursor write FCursor; property Color: TColor read FColor write FColor; property HoverColor: TColor read FHoverColor write FHoverColor; property FullRedraw: Boolean read FFullRedraw write FFullRedraw; property SelColor: TColor read FSelColor write FSelColor; property SelTextColor: TColor read FSelTextColor write FSelTextColor; end; implementation {--------------------------------------------------------------} { TFontInfo } {--------------------------------------------------------------} constructor TFontInfo.Create(Collection: TCollection); begin inherited Create(Collection); FFontName := 'Arial'; FSize := 10; FColor := clWindowText; FStyle := []; {$IFDEF RICHVIEWDEF3} FCharSet := DEFAULT_CHARSET; {$ENDIF} end; {--------------------------------------------------------------} procedure TFontInfo.Assign(Source: TPersistent); begin if Source is TFontInfo then begin FFontName := TFontInfo(Source).FFontName; FSize := TFontInfo(Source).FSize; FColor := TFontInfo(Source).FColor; FStyle := TFontInfo(Source).FStyle; {$IFDEF RICHVIEWDEF3} FCharSet := TFontInfo(Source).FCharSet; {$ENDIF} end else inherited Assign(Source); end; {--------------------------------------------------------------} { TFontInfos } {--------------------------------------------------------------} constructor TFontInfos.Create; begin inherited Create(TFontInfo); end; {-------------------------------------------------------------} function TFontInfos.Add: TFontInfo; begin Result := TFontInfo(inherited Add); end; {-------------------------------------------------------------} procedure TFontInfos.AddFont(Name: TFontName; Size: Integer; Color: TColor; Style:TFontStyles); var v: TFontInfo; begin v := Add; v.FontName := Name; v.Size := Size; v.Color := Color; v.Style := Style; end; {-------------------------------------------------------------} {$IFDEF RICHVIEWDEF3} procedure TFontInfos.AddFontEx(Name: TFontName; Size: Integer; Color: TColor; Style:TFontStyles; CharSet: TFontCharSet); var v: TFontInfo; begin v := Add; v.FontName := Name; v.Size := Size; v.Color := Color; v.Style := Style; v.CharSet := CharSet; end; {$ENDIF} {-------------------------------------------------------------} function TFontInfos.GetItem(Index: Integer): TFontInfo; begin Result := TFontInfo(inherited GetItem(Index)); end; {-------------------------------------------------------------} procedure TFontInfos.SetItem(Index: Integer; Value: TFontInfo); begin inherited SetItem(Index, Value); end; {-------------------------------------------------------------} procedure TFontInfos.Delete(Index: Integer); begin if (Index<=LAST_DEFAULT_STYLE_NO) or (Index>=Count) then exit; Items[Index].Free; { c:=TFontInfos.Create; c.Assign(Self); Clear; for i:=0 to c.Count-1 do if i<>Index then AddFont(c[i].FontName, c[i].Size, c[i].Color, c[i].Style); c.Free; } end; {--------------------------------------------------------------} { TRVStyle } {--------------------------------------------------------------} constructor TRVStyle.Create(AOwner: TComponent); var fi: TFontInfo; i : Integer; begin inherited Create(AOwner); FFullRedraw := False; {$IFDEF FPC} Screen.Cursors[crJump] := LoadCursorFromLazarusREsource('RV_JUMP_CURSOR'); {$ELSE} Screen.Cursors[crJump] := LoadCursor(hInstance,'RV_JUMP_CURSOR'); {$ENDIF} FCursor := crJump; FColor := clWindow; FHoverColor := clNone; FSelColor := clHighlight; FSelTextColor := clHighlightText; FTextStyles := TFontInfos.Create; for i := 0 to LAST_DEFAULT_STYLE_NO do begin fi := FTextStyles.Add; case i of rvsHeading: begin fi.Style := fi.Style + [fsBold]; fi.Color := clBlue; end; rvsSubheading: begin fi.Style := fi.Style + [fsBold]; fi.Color := clNavy; end; rvsKeyword: begin fi.Style := fi.Style + [fsItalic]; fi.Color := clMaroon; end; rvsJump1, rvsJump2: begin fi.Style := fi.Style + [fsUnderline]; fi.Color := clGreen; end; end; end; end; {--------------------------------------------------------------} destructor TRVStyle.Destroy; begin FTextStyles.Free; inherited Destroy; end; {--------------------------------------------------------------} function TRVStyle.GetTextStyle(Index: Integer): TFontInfo; begin GetTextStyle := FTextStyles[Index]; end; {--------------------------------------------------------------} procedure TRVStyle.SetTextStyles(ATextStyles: TFontInfos); begin FTextStyles.Assign(ATextStyles); end; {--------------------------------------------------------------} function TRVStyle.AddTextStyle: Integer; begin FTextStyles.Add; AddTextStyle := FTextStyles.Count-1; end; {--------------------------------------------------------------} procedure TRVStyle.DeleteTextStyle(Index: Integer); begin FTextStyles.Delete(Index); end; {--------------------------------------------------------------} procedure TRVStyle.SaveINI(filename, section: String); var i: Integer; ini: TIniFile; s : String; begin ini := nil; try ini := TIniFile.Create(filename); ini.EraseSection(section); ini.WriteInteger(section,'Color',FColor); ini.WriteInteger(section,'HoverColor',FHoverColor); ini.WriteInteger(section,'SelColor',FSelColor); ini.WriteInteger(section,'SelTextColor',FSelTextColor); ini.WriteInteger(section,'JumpCursor',FCursor); ini.WriteInteger(section,'FontsCount',FTextStyles.Count); for i:=0 to FTextStyles.Count-1 do begin ini.WriteString(section,'FontName'+IntToStr(i),FTextStyles[i].FontName); ini.WriteInteger(section,'FontSize'+IntToStr(i),FTextStyles[i].Size); ini.WriteInteger(section,'FontColor'+IntToStr(i),FTextStyles[i].Color); {$IFDEF RICHVIEWDEF3} ini.WriteInteger(section,'FontCharSet'+IntToStr(i),FTextStyles[i].CharSet); {$ENDIF} if fsBold in FTextStyles[i].Style then s := 'Yes' else s := 'No'; ini.WriteString(section,'FontBold'+IntToStr(i),s); if fsUnderline in FTextStyles[i].Style then s := 'Yes' else s := 'No'; ini.WriteString(section,'FontUnderline'+IntToStr(i),s); if fsStrikeOut in FTextStyles[i].Style then s := 'Yes' else s := 'No'; ini.WriteString(section,'FontStrikeOut'+IntToStr(i),s); if fsItalic in FTextStyles[i].Style then s := 'Yes' else s := 'No'; ini.WriteString(section,'FontItalic'+IntToStr(i),s); end; except on Exception do ; end; ini.Free; end; {--------------------------------------------------------------} procedure TRVStyle.LoadINI(filename, section: String); var i, fontcounts: Integer; ini: TIniFile; begin ini := nil; try ini := TIniFile.Create(filename); FColor := ini.ReadInteger(section, 'Color', clWindow); FHoverColor := ini.ReadInteger(section, 'HoverColor', clNone); FSelColor := ini.ReadInteger(section, 'SelColor', clHighlight); FSelTextColor := ini.ReadInteger(section, 'SelTextColor', clHighlightText); FCursor := ini.ReadInteger(section, 'JumpCursor', crJump); fontcounts := ini.ReadInteger(section, 'FontsCount', LAST_DEFAULT_STYLE_NO+1); if fontcounts<LAST_DEFAULT_STYLE_NO+1 then fontcounts := LAST_DEFAULT_STYLE_NO+1; while FTextStyles.Count > fontcounts do DeleteTextStyle(FTextStyles.Count-1); while FTextStyles.Count < fontcounts do AddTextStyle; for i:=0 to fontcounts-1 do begin FTextStyles[i].FontName := ini.ReadString(section,'FontName'+IntToStr(i), 'Arial'); FTextStyles[i].Size := ini.ReadInteger(section,'FontSize'+IntToStr(i), 10); FTextStyles[i].Color := ini.ReadInteger(section,'FontColor'+IntToStr(i), clWindowText); {$IFDEF RICHVIEWDEF3} FTextStyles[i].CharSet := ini.ReadInteger(section,'FontCharSet'+IntToStr(i), DEFAULT_CHARSET); {$ENDIF} FTextStyles[i].Style := []; if ini.ReadString(section,'FontBold'+IntToStr(i),'No')='Yes' then FTextStyles[i].Style := FTextStyles[i].Style + [fsBold]; if ini.ReadString(section,'FontUnderline'+IntToStr(i),'No')='Yes' then FTextStyles[i].Style := FTextStyles[i].Style + [fsUnderline]; if ini.ReadString(section,'FontStrikeOut'+IntToStr(i),'No')='Yes' then FTextStyles[i].Style := FTextStyles[i].Style + [fsStrikeOut]; if ini.ReadString(section,'FontItalic'+IntToStr(i),'No')='Yes' then FTextStyles[i].Style := FTextStyles[i].Style + [fsItalic]; end; except on Exception do ; end; ini.Free; end; end.
unit Environment; interface const tidEnvironment_Beauty = 'Beauty'; tidEnvironment_Pollution = 'Pollution'; tidEnvironment_Crime = 'Crime'; tidEnvironment_Entertaiment = 'Entertaiment'; tidEnvironment_Restaurants = 'Restaurants'; tidEnvironment_Bars = 'Bars'; tidEnvironment_Commerce = 'Commerce'; implementation end.
unit SoundConversion; {$Message '********************************Compiling SoundConversion'} interface {$IFDEF MSWINDOWS} {$IFNDEF MSWINDOWS} {$ERROR 'only supported on windows'} {$ENDIF} uses numbers, systemx, classes, {$IFDEF MSWINDOWS} msacm, mmsystem, {$ENDIF} soundinterfaces, multibuffermemoryfilestream, typex, sounddevice_mm, sysutils, helpers_stream ; function MP3ToRawMemoryStream(sMP3File: string; out info: TMp3info): TMemoryStream; {$ENDIF} implementation {$IFDEF MSWINDOWS} function MP3ToRawMemoryStream(sMP3File: string; out info: TMp3info): TMemoryStream; const MP3_BLOCK_SIZE = 522 div 1; type TStreamType = TMultiBufferMemoryFileStream; var wf2: TWaveFormatEx; wf1: Tmpeglayer3waveformat_tag; has: HACMStream; ash: TACMSTREAMHEADER; targetsize: cardinal; bufSource, bufTarget: PByte; mmr: cardinal; fsin: TStreamType; iToRead: nativeint; iRead: nativeint; f: dword; iPos: int64; mp3info: TMp3Info; begin result := nil; try mp3info := Getmp3info(smp3File); //mp3info.samplerate := 22050; wf2 := GetStandardWaveFormat(mp3info.samplerate); FillMem(Pbyte(@wf1), sizeof(wf1), 0); wf1.wfx.cbSize := MPEGLAYER3_WFX_EXTRA_BYTES; wf1.wfx.wFormatTag := WAVE_FORMAT_MPEGLAYER3; wf1.wfx.nChannels := 2; wf1.wfx.nAvgBytesPerSec := 128;//128 * (1024 div 8); // not really used but must be one of 64, 96, 112, 128, 160kbps wf1.wfx.wBitsPerSample := 0; // MUST BE ZERO wf1.wfx.nBlockAlign := 1; // MUST BE ONE wf1.wfx.nSamplesPerSec := mp3info.samplerate; // 44.1kHz wf1.fdwFlags := MPEGLAYER3_FLAG_PADDING_OFF; wf1.nBlockSize := MP3_BLOCK_SIZE; // voodoo value #1 wf1.nFramesPerBlock := 1; // MUST BE ONE wf1.nCodecDelay := 0;//1393; // voodoo value #2 wf1.wID := MPEGLAYER3_ID_MPEG; bufSource := GetMemory(wf1.nBlockSize); try mmr := acmStreamOpen(@has, 0, @wf1.wfx, @wf2, nil, nil, nil, 0); try if mmr <> 0 then raise Exception.Create('assert '+inttostr(mmr)); mmr := acmStreamSize(has, MP3_BLOCK_SIZE, targetsize, ACM_STREAMSIZEF_SOURCE); bufTarget := GetMemory(targetsize); try // ACMSTREAMHEADER mp3streamHead; FillMem(Pbyte(@ash), sizeof(ash), 0); // ZeroMemory( &mp3streamHead, sizeof(ACMSTREAMHEADER ) ); ash.cbStruct := sizeof(TACMSTREAMHEADER); // mp3streamHead.cbStruct = sizeof(ACMSTREAMHEADER ); ash.pbSrc := bufSource; // mp3streamHead.pbSrc = mp3buf; ash.pbDst := bufTarget; // mp3streamHead.pbDst = rawbuf; ash.cbSrcLength := wf1.nBlockSize; // mp3streamHead.cbSrcLength = MP3_BLOCK_SIZE; ash.cbDstLength := targetsize; // mp3streamHead.cbDstLength = rawbufsize; mmr := acmStreamPrepareHeader(has, @ash, 0); // mmr = acmStreamPrepareHeader( g_mp3stream, &mp3streamHead, 0 ); try fsIn := TStreamType.Create(sMp3File, fmOpenRead+fmShareDenyWrite); fsIn.BufferSize := 2000000; result := TMemoryStream.Create; result.Seek(0,0); try while fsIn.Position < fsIn.Size do begin iPos := result.Position; iToRead := lesserof(fsIn.Size-fsIn.Position, wf1.nBlockSize); //Debug.Log(inttostr(fsIn.position)+':'+inttostr(fsIn.Size)); iRead := Stream_GuaranteeRead(fsIn, @bufSource[0], iToRead); ash.cbSrcLengthUsed := iRead; f := 0; if fsIn.Position = 0 then f := ACM_STREAMCONVERTF_START; if (iRead < iToRead) or (fsIn.Position = fsIn.Size) then f := f + ACM_STREAMCONVERTF_END; mmr := acmStreamConvert(has, ash,ACM_STREAMCONVERTF_BLOCKALIGN+ f); if ash.cbDstLengthUsed <> 0 then Stream_GuaranteeWrite(result, bufTarget, ash.cbDstLengthUsed); end; finally fsIn.Free; end; finally acmStreamUnprepareHeader(has, @ash, 0); end; finally FreeMemory(bufTarget); end; finally mmr := acmStreamClose(has, 0); end; finally FreeMemory(bufSource); end; info := mp3info; except result.free; result := nil; raise; end; end; {$ENDIF} end.
unit ToolbarHandler; interface uses VoyagerInterfaces, VoyagerServerInterfaces, Controls, ToolbarHandlerViewer{, GMChat}; type TToolbarHandler = class( TInterfacedObject, IMetaURLHandler, IURLHandler ) public constructor Create( aNestedMetaHandler, aAdsHandler : IMetaURLHandler ); destructor Destroy; override; private fControl : TToolbarHandlerView; fNestedHandler : IURLHandler; //fAdsHandler : IURLHandler; fMasterURLHandler : IMasterURLHandler; fClientView : IClientView; fUnreadMsgs : integer; //fGMView : TGMView; fToolbarInitialized : boolean; // IMetaURLHandler private function getName : string; function getOptions : TURLHandlerOptions; function getCanHandleURL( URL : TURL ) : THandlingAbility; function Instantiate : IURLHandler; // IURLHandler private function HandleURL( URL : TURL ) : TURLHandlingResult; function HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult; function getControl : TControl; procedure setMasterURLHandler( URLHandler : IMasterURLHandler ); end; const tidMetaHandlerName_Toolbar = 'ToolbarView'; implementation uses Events, ServerCnxHandler, SysUtils, MathUtils, ServerCnxEvents, Forms, Config; constructor TToolbarHandler.Create( aNestedMetaHandler, aAdsHandler : IMetaURLHandler ); begin inherited Create; fNestedHandler := aNestedMetaHandler.Instantiate; //fAdsHandler := aAdsHandler.Instantiate; fControl := TToolbarHandlerView.Create( nil ); //fToolbarInitialized := true; end; destructor TToolbarHandler.Destroy; begin fControl.Free; inherited; end; function TToolbarHandler.getName : string; begin result := tidMetaHandlerName_Toolbar; end; function TToolbarHandler.getOptions : TURLHandlerOptions; begin result := [hopCacheable]; end; function TToolbarHandler.getCanHandleURL( URL : TURL ) : THandlingAbility; begin result := 0; end; function TToolbarHandler.Instantiate : IURLHandler; begin result := self; end; function TToolbarHandler.HandleURL( URL : TURL ) : TURLHandlingResult; begin result := fNestedHandler.HandleURL( URL ); end; function TToolbarHandler.HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult; var RefreshTycoon : TRefreshTycoonInfo absolute info; RefreshDate : TRefreshDateInfo absolute info; NotifyCompanionship : TNotifyCompanionshipInfo absolute info; SetCompany : TSetCompanyInfo absolute info; NewMailInfo : TNewMailInfo absolute info; Command : word absolute info; ChatMsgInfo : TChatMsgInfo absolute info; Error : TLogonError absolute info; PendMailInfo : TNewMailInfo; auxStr : string; CachePath : string; //ConfigHolder : IConfigHolder; begin result := evnHandled; case EventId of evnRefreshTycoon : if fToolbarInitialized and (fControl.Parent <> nil) then try if (RefreshTycoon.Ranking >= 0) and (fClientView.getCompanyId <> 0) then fControl.UserName.Caption := IntToStr( succ(RefreshTycoon.Ranking) ) + '. ' + fClientView.getUserName else fControl.UserName.Caption := fClientView.getUserName; // fControl.CompanyName.Left := fControl.UserName.Left + fControl.UserName.Width + 10; auxStr := FormatMoney( RefreshTycoon.Money ); if RefreshTycoon.NetProfit > 0 then auxStr := auxStr + ' (+' + FormatMoney( RefreshTycoon.NetProfit ) + ')' else if RefreshTycoon.NetProfit < 0 then auxStr := auxStr + ' (' + FormatMoney( RefreshTycoon.NetProfit ) + ')'; fControl.Money.Caption := auxStr; if fClientView.getCompanyId <> 0 then fControl.Money.Caption := FormatMoney( RefreshTycoon.Money ) else fControl.Money.Caption := ''; if RefreshTycoon.NetProfit >= 0 then begin fControl.Money.Hint := auxStr + ' (+' + FormatMoney( RefreshTycoon.NetProfit ) + ')'; fControl.MsgTrouble1Off.Visible := true; fControl.MsgTrouble1On.Visible := false; end else begin fControl.Money.Hint := auxStr + ' (' + FormatMoney( RefreshTycoon.NetProfit ) + ')'; fControl.MsgTrouble1On.Visible := not fControl.MsgTrouble1On.Visible; fControl.MsgTrouble1Off.Visible := not fControl.MsgTrouble1Off.Visible; end; // fControl.MoneyDelta.Left := fControl.Money.Left + fControl.Money.Width + 10; fControl.MoneyDelta.Caption := '(' + MathUtils.FormatMoney( RefreshTycoon.NetProfit ) + '/h)'; fControl.FacCounter.Left := fControl.UserName.Left + fControl.UserName.Width + 10; fControl.FacCounter.Caption := IntToStr(RefreshTycoon.FacCount); if RefreshTycoon.FacMax < high(RefreshTycoon.FacMax) then fControl.FacCounter.Caption := fControl.FacCounter.Caption + '/' + IntToStr(RefreshTycoon.FacMax); fControl.FacIcon.Left := fControl.FacCounter.Left + fControl.FacCounter.Width + 4; except asm nop end; end; evnNotifyCompanionship : if fToolbarInitialized then begin if NotifyCompanionship.Names <> '' then begin fControl.MsgCompanionshipOn.Visible := true; fControl.MsgCompanionshipOff.Visible := false; fControl.MsgCompanionshipOn.Hint := NotifyCompanionship.Names; end else begin fControl.MsgCompanionshipOff.Visible := true; fControl.MsgCompanionshipOn.Visible := false; end; end; evnSetCompany : begin fControl.Container.Enabled := true; fControl.BlockTicker.Enabled := true; fControl.CompanyName.Caption := SetCompany.Name; fToolbarInitialized := true; end; evnRefreshDate : if fToolbarInitialized then begin fControl.Date.Caption := FormatDateTime( 'mmm d, yyyy', RefreshDate.Date ); end; evnHandlerExposed : begin fNestedHandler.getControl.Align := alClient; fNestedHandler.getControl.Parent := fControl.Container; { fAdsHandler.getControl.Align := alClient; fAdsHandler.getControl.Parent := fControl.AdsContainer; fAdsHandler.HandleURL( fClientView.getWorldURL + 'visual/voyager/advertisement/largebanner.asp?frame_NoScrollBars=True&frame_NoBorder=yes' ); } fMasterURLHandler.HandleEvent( evnAnswerPrivateCache, CachePath ); fControl.BusyClipPath := CachePath + 'OtherImages\busy.gif'; fControl.CompanyName.Caption := fClientView.getCompanyName; fMasterURLHandler.HandleEvent( evnAnswerPendingMail, PendMailInfo ); HandleEvent( evnNewMail, PendMailInfo ); fControl.Date.Caption := FormatDateTime( 'mmm d, yyyy', fClientView.getDate ); fControl.ClientView := fClientView; fControl.MasterURLHandler := fMasterURLHandler; end; evnSystemBusy : begin fControl.Busy; result := evnHandled; end; evnSystemIdle : begin fControl.NotBusy; result := evnHandled; end; evnNewMail : if NewMailInfo.count > 0 then begin inc( fUnreadMsgs, NewMailInfo.count ); fControl.UnreadMsgs := fUnreadMsgs; end; evnKeyCommand : case Command of { keyHidden : //fMasterURLHandler.HandleURL( '?frame_Action=Create&frame_Id=CrimeHandler&frame_Class=CrimeHandler&frame_Align=left&frame_Width=400&frame_Visibility=switch' ); fMasterURLHandler.HandleURL( '?frame_Id=UniverseMap&frame_Class=UniversalMapHandler&frame_Action=SetUserInfo&frame_Align=left&UserName=' + fClientView.getUserName + '&Password=' + fClientView.getUserPassword + '&Logon=yes&frame_Visibility=switch' ); } keyCmdFullScreen : if fControl.Height = 0 then begin fControl.Height := 200; fControl.Height := 100; end else fControl.Height := 0; { keyGMClient : begin fMasterURLHandler.HandleEvent( evnAnswerConfigHolder, ConfigHolder ); if ConfigHolder.ReadBoolean( true, '', 'GMSystem', false ) then begin if fGMView = nil then begin fGMView := TGMView.Create( Application ); fGMView.MasterURLHandler := fMasterURLHandler; fGMView.ClientView := fClientView; fGMView.Show; end else begin fGMView.Hide; fGMView.Free; fGMView := nil; end; end; end; } end; evnLanguageSet : fControl.ReloadHints; evnLogonStarted : begin fControl.StopHints; fControl.MsgCompanionshipOff.Visible := true; fControl.MsgCompanionshipOn.Visible := false; fControl.MsgCompanionshipOn.Hint := ''; fControl.Container.Enabled := false; fControl.BlockTicker.Enabled := false; end; evnLogonCompleted : if Error = errNone then fControl.StartHints; { evnChatMsg : fControl.BlockTicker.Caption := ChatMsgInfo.Msg; } { else if fNestedHandler <> nil then result := fNestedHandler.HandleEvent( EventId, info ) else result := evnError; } end; end; function TToolbarHandler.getControl : TControl; begin result := fControl; end; procedure TToolbarHandler.setMasterURLHandler( URLHandler : IMasterURLHandler ); begin fMasterURLHandler := URLHandler; fNestedHandler.setMasterURLHandler( URLHandler ); //fAdsHandler.setMasterURLHandler( URLHandler ); URLHandler.HandleEvent( evnAnswerClientView, fClientView ); end; end.
unit TPicSizeEditDlgWordsPack; // Модуль: "w:\archi\source\projects\Common\Dialogs\TPicSizeEditDlgWordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "TPicSizeEditDlgWordsPack" MUID: (55C8CDD703B3) {$Include w:\archi\source\projects\Common\arCommon.inc} interface {$If NOT Defined(NoScripts)} uses l3IntfUses ; {$IfEnd} // NOT Defined(NoScripts) implementation {$If NOT Defined(NoScripts)} uses l3ImplUses , D_PicSizeEdit , tfwClassLike , tfwScriptingInterfaces , TypInfo , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes //#UC START# *55C8CDD703B3impl_uses* //#UC END# *55C8CDD703B3impl_uses* ; type TkwPopPicSizeEditDlgFake = {final} class(TtfwClassLike) {* Слово скрипта pop:PicSizeEditDlg:Fake } private procedure Fake(const aCtx: TtfwContext; aPicSizeEditDlg: TPicSizeEditDlg); {* Реализация слова скрипта pop:PicSizeEditDlg:Fake } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopPicSizeEditDlgFake procedure TkwPopPicSizeEditDlgFake.Fake(const aCtx: TtfwContext; aPicSizeEditDlg: TPicSizeEditDlg); {* Реализация слова скрипта pop:PicSizeEditDlg:Fake } //#UC START# *55C8CE2502B9_55C8CE2502B9_4F5760C202E6_Word_var* //#UC END# *55C8CE2502B9_55C8CE2502B9_4F5760C202E6_Word_var* begin //#UC START# *55C8CE2502B9_55C8CE2502B9_4F5760C202E6_Word_impl* RunnerError('fake-метод только для регистрации класса формы', aCtx); //#UC END# *55C8CE2502B9_55C8CE2502B9_4F5760C202E6_Word_impl* end;//TkwPopPicSizeEditDlgFake.Fake class function TkwPopPicSizeEditDlgFake.GetWordNameForRegister: AnsiString; begin Result := 'pop:PicSizeEditDlg:Fake'; end;//TkwPopPicSizeEditDlgFake.GetWordNameForRegister function TkwPopPicSizeEditDlgFake.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := @tfw_tiVoid; end;//TkwPopPicSizeEditDlgFake.GetResultTypeInfo function TkwPopPicSizeEditDlgFake.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopPicSizeEditDlgFake.GetAllParamsCount function TkwPopPicSizeEditDlgFake.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TPicSizeEditDlg)]); end;//TkwPopPicSizeEditDlgFake.ParamsTypes procedure TkwPopPicSizeEditDlgFake.DoDoIt(const aCtx: TtfwContext); var l_aPicSizeEditDlg: TPicSizeEditDlg; begin try l_aPicSizeEditDlg := TPicSizeEditDlg(aCtx.rEngine.PopObjAs(TPicSizeEditDlg)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aPicSizeEditDlg: TPicSizeEditDlg : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except Fake(aCtx, l_aPicSizeEditDlg); end;//TkwPopPicSizeEditDlgFake.DoDoIt initialization TkwPopPicSizeEditDlgFake.RegisterInEngine; {* Регистрация pop_PicSizeEditDlg_Fake } TtfwTypeRegistrator.RegisterType(TypeInfo(TPicSizeEditDlg)); {* Регистрация типа TPicSizeEditDlg } {$IfEnd} // NOT Defined(NoScripts) end.
unit afwApplication; {* "Стандартная" реализация приложения AFW. } // Модуль: "w:\common\components\gui\Garant\AFW\implementation\afwApplication.pas" // Стереотип: "UtilityPack" // Элемент модели: "afwApplication" MUID: (47764DEC01A7) {$Include w:\common\components\gui\Garant\AFW\afwDefine.inc} interface uses l3IntfUses , l3CacheableBase , afwInterfaces , l3Core , afwFacade ; const {* Строковые идентификаторы языков. dl - detailed LanguageId. } afw_dlDefault = 'ru_RU.CP1251'; type TafwApplicationClass = class of TafwApplication; {* Ссылка на TafwApplication. } TafwApplication = class(Tl3CacheableBase, IafwSettingsSource, IafwApplication) {* "Стандартная" реализация приложения AFW. } private f_PrintManager: IafwPrintManager; f_UserQuery: Pointer; f_BaseId: AnsiString; f_Settings: IafwSettings; f_LocaleInfo: IafwLocaleInfo; f_Data: IafwApplicationData; f_PermanentSettings: IafwSettingsPrim; private procedure DefineLocaleInfo; protected function DoGetIsTrialMode: Boolean; virtual; function DoGetTabInterfaceType: TafwTabInterfaceType; virtual; function MakeApplicationData: IafwApplicationData; virtual; function MakeSettings: IafwSettings; virtual; function DoGetIsInternal: Boolean; virtual; function MakeLocaleInfo: IafwLocaleInfo; virtual; procedure DoApplyActiveLanguage(const aTarget: IafwResources); virtual; function MakePermanentSettings: IafwSettingsPrim; virtual; procedure DoLockKeyboard; virtual; procedure DoUnLockKeyboard; virtual; procedure GetAskClearClipboardProc(out aProc: TafwAskClearClipboardProc); virtual; function pm_GetBaseId: AnsiString; procedure pm_SetBaseId(const aValue: AnsiString); procedure ApplyActiveLanguage(const aTarget: IafwResources); function pm_GetCurrentMainForm: IafwMainForm; function pm_GetSettings: IafwSettings; procedure pm_SetSettings(const aValue: IafwSettings); function pm_GetPrintManager: IafwPrintManager; procedure pm_SetPrintManager(const aValue: IafwPrintManager); function pm_GetUserQuery: IafwUserQuery; procedure pm_SetUserQuery(const aValue: IafwUserQuery); function pm_GetIsInternal: Boolean; function pm_GetLocaleInfo: IafwLocaleInfo; function Get_Data: IafwApplicationData; function Get_PermanentSettings: IafwSettingsPrim; procedure LockKeyBoard; procedure UnlockKeyBoard; function AskClearClipboardProc: TafwAskClearClipboardProc; function IsTrialMode: Boolean; function Get_TabInterfaceType: TafwTabInterfaceType; procedure Cleanup; override; {* Функция очистки полей объекта. } procedure ClearFields; override; public {$If NOT Defined(NoVCL)} function MakeLongProcessVisualizer(const aCaption: IafwCString; anAttachWnd: THandle = 0; anInitialTimeout: Cardinal = afwInterfaces.afw_lpwTimeout; anImageList: TafwCustomImageList = nil; anImageIndex: Integer = -1): IafwLongProcessVisualizer; {$IfEnd} // NOT Defined(NoVCL) end;//TafwApplication TafwImplementation = class(Tafw) {* Метакласс, реализующий "стандартным" образом точку входа в интерфейсы библиотеки AFW. } public class function GetApplicationClass: TafwApplicationClass; virtual; {* Класс реализации приложения. } class function Application: IafwApplication; override; {* приложение AFW. } end;//TafwImplementation var g_Application: TafwApplication; implementation uses l3ImplUses , l3LocaleInfo , afwLongProcessVisualizer , SysUtils , l3Base {$If NOT Defined(NoVCL)} , Forms {$IfEnd} // NOT Defined(NoVCL) , afwSettingsImplSing , afwSettingsImplemented , Classes //#UC START# *47764DEC01A7impl_uses* //#UC END# *47764DEC01A7impl_uses* ; procedure FreeApp; //#UC START# *4B72F1360176_47764DEC01A7_var* //#UC END# *4B72F1360176_47764DEC01A7_var* begin //#UC START# *4B72F1360176_47764DEC01A7_impl* FreeAndNil(g_Application); //#UC END# *4B72F1360176_47764DEC01A7_impl* end;//FreeApp function TafwApplication.DoGetIsTrialMode: Boolean; //#UC START# *5232DF6F008F_47764DD601C3_var* //#UC END# *5232DF6F008F_47764DD601C3_var* begin //#UC START# *5232DF6F008F_47764DD601C3_impl* Result := false; //#UC END# *5232DF6F008F_47764DD601C3_impl* end;//TafwApplication.DoGetIsTrialMode function TafwApplication.DoGetTabInterfaceType: TafwTabInterfaceType; //#UC START# *54EFFE25008D_47764DD601C3_var* //#UC END# *54EFFE25008D_47764DD601C3_var* begin //#UC START# *54EFFE25008D_47764DD601C3_impl* Result := afw_titNoTabs; //#UC END# *54EFFE25008D_47764DD601C3_impl* end;//TafwApplication.DoGetTabInterfaceType function TafwApplication.MakeApplicationData: IafwApplicationData; //#UC START# *47765163007D_47764DD601C3_var* //#UC END# *47765163007D_47764DD601C3_var* begin //#UC START# *47765163007D_47764DD601C3_impl* Result := nil; //#UC END# *47765163007D_47764DD601C3_impl* end;//TafwApplication.MakeApplicationData function TafwApplication.MakeSettings: IafwSettings; //#UC START# *4776517E01C2_47764DD601C3_var* //#UC END# *4776517E01C2_47764DD601C3_var* begin //#UC START# *4776517E01C2_47764DD601C3_impl* {$If not Defined(Nemesis) OR Defined(NewGen)} Result := TafwSettingsImplemented.Make; //Result := TafwSettingsImplemented.Make; {$Else} Result := nil; {$IfENd} //#UC END# *4776517E01C2_47764DD601C3_impl* end;//TafwApplication.MakeSettings function TafwApplication.DoGetIsInternal: Boolean; //#UC START# *477651920385_47764DD601C3_var* //#UC END# *477651920385_47764DD601C3_var* begin //#UC START# *477651920385_47764DD601C3_impl* Result := True; //#UC END# *477651920385_47764DD601C3_impl* end;//TafwApplication.DoGetIsInternal function TafwApplication.MakeLocaleInfo: IafwLocaleInfo; //#UC START# *4776519F03A3_47764DD601C3_var* //#UC END# *4776519F03A3_47764DD601C3_var* begin //#UC START# *4776519F03A3_47764DD601C3_impl* Result := Tl3UnixLocaleInfo.Make(afw_dlDefault, afw_dlDefault); //#UC END# *4776519F03A3_47764DD601C3_impl* end;//TafwApplication.MakeLocaleInfo procedure TafwApplication.DefineLocaleInfo; //#UC START# *4787714C0379_47764DD601C3_var* //#UC END# *4787714C0379_47764DD601C3_var* begin //#UC START# *4787714C0379_47764DD601C3_impl* if f_LocaleInfo = nil then f_LocaleInfo := MakeLocaleInfo; //#UC END# *4787714C0379_47764DD601C3_impl* end;//TafwApplication.DefineLocaleInfo procedure TafwApplication.DoApplyActiveLanguage(const aTarget: IafwResources); //#UC START# *478781490206_47764DD601C3_var* //#UC END# *478781490206_47764DD601C3_var* begin //#UC START# *478781490206_47764DD601C3_impl* DefineLocaleInfo; //#UC END# *478781490206_47764DD601C3_impl* end;//TafwApplication.DoApplyActiveLanguage function TafwApplication.MakePermanentSettings: IafwSettingsPrim; //#UC START# *4AB72C3B0094_47764DD601C3_var* //#UC END# *4AB72C3B0094_47764DD601C3_var* begin //#UC START# *4AB72C3B0094_47764DD601C3_impl* {$If not Defined(Nemesis) OR Defined(NewGen)} Result := TafwSettingsImplemented.Make; {$Else} Result := nil; {$IfENd} //#UC END# *4AB72C3B0094_47764DD601C3_impl* end;//TafwApplication.MakePermanentSettings procedure TafwApplication.DoLockKeyboard; //#UC START# *4BFE60CB0000_47764DD601C3_var* //#UC END# *4BFE60CB0000_47764DD601C3_var* begin //#UC START# *4BFE60CB0000_47764DD601C3_impl* // Do nothing //#UC END# *4BFE60CB0000_47764DD601C3_impl* end;//TafwApplication.DoLockKeyboard procedure TafwApplication.DoUnLockKeyboard; //#UC START# *4BFE60DE0020_47764DD601C3_var* //#UC END# *4BFE60DE0020_47764DD601C3_var* begin //#UC START# *4BFE60DE0020_47764DD601C3_impl* // Do nothing //#UC END# *4BFE60DE0020_47764DD601C3_impl* end;//TafwApplication.DoUnLockKeyboard procedure TafwApplication.GetAskClearClipboardProc(out aProc: TafwAskClearClipboardProc); //#UC START# *4C9875080352_47764DD601C3_var* //#UC END# *4C9875080352_47764DD601C3_var* begin //#UC START# *4C9875080352_47764DD601C3_impl* aProc := nil; //#UC END# *4C9875080352_47764DD601C3_impl* end;//TafwApplication.GetAskClearClipboardProc function TafwApplication.pm_GetBaseId: AnsiString; //#UC START# *473DA15800E2_47764DD601C3get_var* //#UC END# *473DA15800E2_47764DD601C3get_var* begin //#UC START# *473DA15800E2_47764DD601C3get_impl* Result := f_BaseId; //#UC END# *473DA15800E2_47764DD601C3get_impl* end;//TafwApplication.pm_GetBaseId procedure TafwApplication.pm_SetBaseId(const aValue: AnsiString); //#UC START# *473DA15800E2_47764DD601C3set_var* //#UC END# *473DA15800E2_47764DD601C3set_var* begin //#UC START# *473DA15800E2_47764DD601C3set_impl* f_BaseId := aValue; //#UC END# *473DA15800E2_47764DD601C3set_impl* end;//TafwApplication.pm_SetBaseId procedure TafwApplication.ApplyActiveLanguage(const aTarget: IafwResources); //#UC START# *473DA1B10131_47764DD601C3_var* //#UC END# *473DA1B10131_47764DD601C3_var* begin //#UC START# *473DA1B10131_47764DD601C3_impl* DoApplyActiveLanguage(aTarget); //#UC END# *473DA1B10131_47764DD601C3_impl* end;//TafwApplication.ApplyActiveLanguage function TafwApplication.pm_GetCurrentMainForm: IafwMainForm; //#UC START# *473DA22A0383_47764DD601C3get_var* function _GetMain(aForm: TCustomForm): IafwMainForm; var l_Form : TCustomForm; l_Container: IafwMainFormContainer; begin//_GetMain Result := nil; l_Form := aForm; if Assigned(l_Form) and not (csDestroying in l_Form.ComponentState) then if Supports(aForm, IafwMainFormContainer, l_Container) then try l_Form := l_Container.CurrentMainForm; finally l_Container := nil; end//try..finally else begin while (l_Form <> nil) AND (Result = nil) do if Supports(l_Form, IafwMainForm, Result) then break else l_Form := afw.GetAnotherParentForm(l_Form); end; if (Result = nil) then begin // l_Form := aForm; while (l_Form <> nil) AND (Result = nil) do if Supports(l_Form, IafwMainForm, Result) then break else l_Form := afw.GetParentForm(l_Form.Owner); end;//Result = nil end;//_GetMain //#UC END# *473DA22A0383_47764DD601C3get_var* begin //#UC START# *473DA22A0383_47764DD601C3get_impl* Result := _GetMain(Screen.ActiveForm); if (Result = nil) then Result := _GetMain(Screen.ActiveCustomForm); if (Result = nil) then Result := _GetMain(Application.MainForm); //#UC END# *473DA22A0383_47764DD601C3get_impl* end;//TafwApplication.pm_GetCurrentMainForm function TafwApplication.pm_GetSettings: IafwSettings; //#UC START# *473DA23B0085_47764DD601C3get_var* //#UC END# *473DA23B0085_47764DD601C3get_var* begin //#UC START# *473DA23B0085_47764DD601C3get_impl* if (f_Settings = nil) then f_Settings := MakeSettings; Result := f_Settings; //#UC END# *473DA23B0085_47764DD601C3get_impl* end;//TafwApplication.pm_GetSettings procedure TafwApplication.pm_SetSettings(const aValue: IafwSettings); //#UC START# *473DA23B0085_47764DD601C3set_var* //#UC END# *473DA23B0085_47764DD601C3set_var* begin //#UC START# *473DA23B0085_47764DD601C3set_impl* f_Settings := aValue; //#UC END# *473DA23B0085_47764DD601C3set_impl* end;//TafwApplication.pm_SetSettings function TafwApplication.pm_GetPrintManager: IafwPrintManager; //#UC START# *473DA24E0353_47764DD601C3get_var* //#UC END# *473DA24E0353_47764DD601C3get_var* begin //#UC START# *473DA24E0353_47764DD601C3get_impl* Result := f_PrintManager; //#UC END# *473DA24E0353_47764DD601C3get_impl* end;//TafwApplication.pm_GetPrintManager procedure TafwApplication.pm_SetPrintManager(const aValue: IafwPrintManager); //#UC START# *473DA24E0353_47764DD601C3set_var* //#UC END# *473DA24E0353_47764DD601C3set_var* begin //#UC START# *473DA24E0353_47764DD601C3set_impl* f_PrintManager := aValue; //#UC END# *473DA24E0353_47764DD601C3set_impl* end;//TafwApplication.pm_SetPrintManager function TafwApplication.pm_GetUserQuery: IafwUserQuery; //#UC START# *473DA53603AD_47764DD601C3get_var* //#UC END# *473DA53603AD_47764DD601C3get_var* begin //#UC START# *473DA53603AD_47764DD601C3get_impl* Result := IafwUserQuery(f_UserQuery) //#UC END# *473DA53603AD_47764DD601C3get_impl* end;//TafwApplication.pm_GetUserQuery procedure TafwApplication.pm_SetUserQuery(const aValue: IafwUserQuery); //#UC START# *473DA53603AD_47764DD601C3set_var* //#UC END# *473DA53603AD_47764DD601C3set_var* begin //#UC START# *473DA53603AD_47764DD601C3set_impl* f_UserQuery := Pointer(aValue); //#UC END# *473DA53603AD_47764DD601C3set_impl* end;//TafwApplication.pm_SetUserQuery function TafwApplication.pm_GetIsInternal: Boolean; //#UC START# *473DA5480182_47764DD601C3get_var* //#UC END# *473DA5480182_47764DD601C3get_var* begin //#UC START# *473DA5480182_47764DD601C3get_impl* Result := DoGetIsInternal; //#UC END# *473DA5480182_47764DD601C3get_impl* end;//TafwApplication.pm_GetIsInternal function TafwApplication.pm_GetLocaleInfo: IafwLocaleInfo; //#UC START# *473DA5AE02FB_47764DD601C3get_var* //#UC END# *473DA5AE02FB_47764DD601C3get_var* begin //#UC START# *473DA5AE02FB_47764DD601C3get_impl* DefineLocaleInfo; Result := f_LocaleInfo; //#UC END# *473DA5AE02FB_47764DD601C3get_impl* end;//TafwApplication.pm_GetLocaleInfo function TafwApplication.Get_Data: IafwApplicationData; //#UC START# *4768DE18030F_47764DD601C3get_var* //#UC END# *4768DE18030F_47764DD601C3get_var* begin //#UC START# *4768DE18030F_47764DD601C3get_impl* if f_Data = nil then f_Data := MakeApplicationData; Result := f_Data; //#UC END# *4768DE18030F_47764DD601C3get_impl* end;//TafwApplication.Get_Data {$If NOT Defined(NoVCL)} function TafwApplication.MakeLongProcessVisualizer(const aCaption: IafwCString; anAttachWnd: THandle = 0; anInitialTimeout: Cardinal = afwInterfaces.afw_lpwTimeout; anImageList: TafwCustomImageList = nil; anImageIndex: Integer = -1): IafwLongProcessVisualizer; //#UC START# *49E85D4A0016_47764DD601C3_var* //#UC END# *49E85D4A0016_47764DD601C3_var* begin //#UC START# *49E85D4A0016_47764DD601C3_impl* Result := TafwLongProcessVisualizer.Make(aCaption, anAttachWnd, anInitialTimeout, anImageList, anImageIndex); //#UC END# *49E85D4A0016_47764DD601C3_impl* end;//TafwApplication.MakeLongProcessVisualizer {$IfEnd} // NOT Defined(NoVCL) function TafwApplication.Get_PermanentSettings: IafwSettingsPrim; //#UC START# *4AB72A090253_47764DD601C3get_var* //#UC END# *4AB72A090253_47764DD601C3get_var* begin //#UC START# *4AB72A090253_47764DD601C3get_impl* if (f_PermanentSettings = nil) then f_PermanentSettings := MakePermanentSettings; Result := f_PermanentSettings; //#UC END# *4AB72A090253_47764DD601C3get_impl* end;//TafwApplication.Get_PermanentSettings procedure TafwApplication.LockKeyBoard; //#UC START# *4BFE5ED5019D_47764DD601C3_var* //#UC END# *4BFE5ED5019D_47764DD601C3_var* begin //#UC START# *4BFE5ED5019D_47764DD601C3_impl* DoLockKeyboard; //#UC END# *4BFE5ED5019D_47764DD601C3_impl* end;//TafwApplication.LockKeyBoard procedure TafwApplication.UnlockKeyBoard; //#UC START# *4BFE5EE60134_47764DD601C3_var* //#UC END# *4BFE5EE60134_47764DD601C3_var* begin //#UC START# *4BFE5EE60134_47764DD601C3_impl* DoUnLockKeyboard; //#UC END# *4BFE5EE60134_47764DD601C3_impl* end;//TafwApplication.UnlockKeyBoard function TafwApplication.AskClearClipboardProc: TafwAskClearClipboardProc; //#UC START# *4C9873450385_47764DD601C3_var* //#UC END# *4C9873450385_47764DD601C3_var* begin //#UC START# *4C9873450385_47764DD601C3_impl* GetAskClearClipboardProc(Result); //#UC END# *4C9873450385_47764DD601C3_impl* end;//TafwApplication.AskClearClipboardProc function TafwApplication.IsTrialMode: Boolean; //#UC START# *5232DF2E0192_47764DD601C3_var* //#UC END# *5232DF2E0192_47764DD601C3_var* begin //#UC START# *5232DF2E0192_47764DD601C3_impl* Result := DoGetIsTrialMode; //#UC END# *5232DF2E0192_47764DD601C3_impl* end;//TafwApplication.IsTrialMode function TafwApplication.Get_TabInterfaceType: TafwTabInterfaceType; //#UC START# *54F0063B0015_47764DD601C3get_var* //#UC END# *54F0063B0015_47764DD601C3get_var* begin //#UC START# *54F0063B0015_47764DD601C3get_impl* Result := DoGetTabInterfaceType; //#UC END# *54F0063B0015_47764DD601C3get_impl* end;//TafwApplication.Get_TabInterfaceType procedure TafwApplication.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_47764DD601C3_var* //#UC END# *479731C50290_47764DD601C3_var* begin //#UC START# *479731C50290_47764DD601C3_impl* f_PermanentSettings := nil; pm_SetUserQuery(nil); pm_SetPrintManager(nil); pm_SetSettings(nil); inherited; //#UC END# *479731C50290_47764DD601C3_impl* end;//TafwApplication.Cleanup procedure TafwApplication.ClearFields; begin f_PrintManager := nil; f_Settings := nil; f_LocaleInfo := nil; f_Data := nil; inherited; end;//TafwApplication.ClearFields class function TafwImplementation.GetApplicationClass: TafwApplicationClass; {* Класс реализации приложения. } //#UC START# *47764F8A02D1_47764F3F0064_var* //#UC END# *47764F8A02D1_47764F3F0064_var* begin //#UC START# *47764F8A02D1_47764F3F0064_impl* Result := TafwApplication; //#UC END# *47764F8A02D1_47764F3F0064_impl* end;//TafwImplementation.GetApplicationClass class function TafwImplementation.Application: IafwApplication; {* приложение AFW. } //#UC START# *4775153A0006_47764F3F0064_var* var l_AC : TafwApplicationClass; //#UC END# *4775153A0006_47764F3F0064_var* begin //#UC START# *4775153A0006_47764F3F0064_impl* {$IfNDef DesignTimeLibrary} l_AC := GetApplicationClass; if (g_Application <> nil) AND not l3SystemDown then begin if not g_Application.InheritsFrom(l_AC) then begin FreeAndNil(g_Application); g_Application := l_AC.Create; end;//not g_Application.InheritsFrom(l_AC) end;//g_Application <> nil if (g_Application = nil) AND not l3SystemDown then begin l3System.AddExitProc(FreeApp); g_Application := l_AC.Create; end;//g_Application = nil Result := g_Application; {$Else} Result := nil; {$EndIf DesignTimeLibrary} //#UC END# *4775153A0006_47764F3F0064_impl* end;//TafwImplementation.Application initialization //#UC START# *4B72FD1102AB* afw := TafwImplementation; //#UC END# *4B72FD1102AB* end.
unit Control.Sistemas; interface uses System.SysUtils, FireDAC.Comp.Client, Forms, Windows, Common.ENum, Model.Sistemas, Control.Sistema; type TSistemasControl = class private FSistemas : TSistemas; public constructor Create(); destructor Destroy(); override; property Sistemas: TSistemas read FSistemas write FSistemas; function ValidaCampos(): Boolean; function Localizar(aParam: array of variant): TFDQuery; function Gravar(): Boolean; end; implementation { TSistemasControl } constructor TSistemasControl.Create; begin FSistemas := TSistemas.Create; end; destructor TSistemasControl.Destroy; begin FSistemas.Free; inherited; end; function TSistemasControl.Gravar: Boolean; begin Result := False; if not ValidaCampos() then Exit; Result := FSistemas.Gravar(); end; function TSistemasControl.Localizar(aParam: array of variant): TFDQuery; begin Result := FSistemas.Localizar(aParam); end; function TSistemasControl.ValidaCampos: Boolean; var FDQuery : TFDQuery; aParam: Array of variant; begin try Result := False; FDQuery := TSistemaControl.GetInstance.Conexao.ReturnQuery; if FSistemas.Codigo = 0 then begin Application.MessageBox('Informe um código para o sistema!', 'Atenção', MB_OK + MB_ICONWARNING); Exit; end; SetLength(aParam,2); aParam[0] := 'CODIGO'; aParam[1] := FSistemas.Codigo; FDQuery := FSistemas.Localizar(aParam); Finalize(aParam); if FDQuery.RecordCount >= 1 then begin if FSistemas.Acao = tacIncluir then begin Application.MessageBox('Código de sistema já cadastrado!', 'Atenção', MB_OK + MB_ICONWARNING); FDQuery.Close; Exit; end; end else begin if (FSistemas.Acao = tacAlterar) or (FSistemas.Acao = tacExcluir) then begin Application.MessageBox('Código de sistema não cadastrado!', 'Atenção', MB_OK + MB_ICONWARNING); FDQuery.Close; Exit; end; end; if FSistemas.Descricao.IsEmpty then begin Application.MessageBox('Informe uma descrição para o sistema!', 'Atenção', MB_OK + MB_ICONWARNING); Exit; end; Result := True; finally FDQuery.Free; end; end; end.
unit Utiles; interface uses Windows, Messages, SysUtils, Classes, Controls, Dialogs, Forms, IniFiles, DateUtils, DbClient, Db, Adodb; // devuelve fechas de consulta de sistema // corresponde a ultima consulta hecha por usuario function GetFechaIni( ds:TAdoDataSet): TDatetime; function GetFechaFin( ds:TAdoDataSet): TDatetime; procedure cerrarDataset( cds: TClientDataset ); {: Returns a string with all occurrences of a given Character removed } function StripChar (const S: string; Ch: Char): string; {: Returns the substring consisting of the first N characters of S. If N > Length (S) then the substring = S. } function LeftStr (const S : string; const N : Integer): string; // establece fechas de consulta procedure SetFechas( ds:TAdoDataSet; fecIni, FecFin: TDateTime ); function getAppVersion: string; var fs: TformatSettings; DecimalSeparator, DateSeparator: char; implementation function GetFechaIni( ds:TAdoDataSet): TDatetime; begin try ds.open; result := Date - ds.fieldByName( 'fecini' ).value; finally ds.Close; end; end; function GetFechaFin( ds:TAdoDataSet): TDatetime; begin try ds.open; result := Date + ds.fieldByName( 'fecfin' ).value; finally ds.Close; end; end; procedure cerrarDataset( cds: TClientDataset ); var i: Integer; Field: TAggregateField; begin cds.IndexFieldNames := ''; cds.AggregatesActive := False; cds.Filtered := False; cds.EmptyDataSet; for I := 0 to cds.AggFields.Count - 1 do begin Field := cds.AggFields[I] as TAggregateField; if Field.Handle <> nil then Field.Handle := nil; end; cds.Active := False; end; procedure SetFechas( ds:TAdoDataSet; FecIni, FecFin: TDateTime ); begin try ds.open; ds.Edit; ds.fieldByName( 'fecini' ).value := DaysBetween(date, fecini); ds.fieldByName( 'fecfin' ).value := DaysBetween(date, fecfin); finally ds.Close; end; end; function StripChar (const S: string; Ch: Char): string; var P: Integer; begin Result := S; repeat P := Pos (Ch, Result); if P > 0 then Result := LeftStr (Result, P - 1) + Copy (Result, P + 1, Length (Result) - P); until P = 0; end; function LeftStr (const S : string; const N : Integer): string; begin Result := Copy (S, 1, N); end; function getAppVersion: string; var Size, Size2: DWord; Pt, Pt2: Pointer; begin Size := GetFileVersionInfoSize(PChar (ParamStr (0)), Size2); if Size > 0 then begin GetMem (Pt, Size); try GetFileVersionInfo (PChar (ParamStr (0)), 0, Size, Pt); VerQueryValue (Pt, '\', Pt2, Size2); with TVSFixedFileInfo (Pt2^) do begin Result:= ' Ver '+ IntToStr (HiWord (dwFileVersionMS)) + '.' + IntToStr (LoWord (dwFileVersionMS)) + '.' + IntToStr (HiWord (dwFileVersionLS)) + '.' + IntToStr (LoWord (dwFileVersionLS)); end; finally FreeMem (Pt); end; end; end; initialization fs := Tformatsettings.Create; DecimalSeparator := fs.DecimalSeparator; DateSeparator := fs.DateSeparator; end.
unit GraphASM; {$G+} (****************************************************************************) INTERFACE (****************************************************************************) type Pbyte= ^byte; { TSprite = pointeur sur le type octet } TPalette= array [0..767] of byte; { type palette de couleur } PtMCGA= record X,Y: integer; end; procedure ClsMCGA(couleur: byte); procedure DetectVESA(var segm,offs: word; var Vesa: boolean); procedure InitMode(mode: byte); procedure InitModeVESA(mode: word); procedure EffaceBuffer(buffer: pointer; couleur: byte); procedure CopieBuffer(buffer: pointer); procedure VSync; procedure Pxl(PxX,PxY:word; clr:byte); procedure PixelMCGA(Pxx,Pxy:word; clr:byte); procedure H_LineMCGA(HP1_X,HP1_Y,HP2_X:word; Clr:byte); procedure V_LineMCGA(HP1_X,HP1_Y,HP2_Y:word; Clr:byte); procedure LineMCGA(P1X,P1Y,P2X,P2Y:integer; Color:byte); procedure PixelVESA(PxX,PxY:word; clr:byte); procedure SetPalette(Colors: TPalette); procedure SetColor(index,r,g,b: byte); procedure ChargePCX(nomfichier: string; var destination: Pbyte; var Palette: TPalette); procedure SetClipZone(x1,y1,x2,y2: integer); procedure PutSprite(Buffer: pointer; x,y,largeur,hauteur: integer; sprite: Pbyte); procedure PutSpriteClip(Buffer: pointer; x,y,largeur,hauteur: integer; sprite: Pbyte); procedure GetSprite(source: Pbyte; x1,y1,largeur,hauteur: integer; sprite: Pbyte); (****************************************************************************) IMPLEMENTATION (****************************************************************************) (***************************************************** ROUTINES DE BASE VGA *) var ClipX1,ClipY1,ClipX2,ClipY2:integer; procedure ClsMCGA(couleur: byte); assembler; asm mov ax, 0a000h mov es, ax xor di, di mov cx, 32000 mov al, couleur mov ah, al rep stosw end; procedure DetectVESA(var segm,offs: word; var Vesa: boolean); var Tseg,Toff: word; Tah: byte; begin asm mov al,00h mov ah,4Fh int 10h mov Tseg,es mov Toff,di mov Tah,ah end; segm:=Tseg; offs:=Toff; Vesa:=(Tah=0); end; procedure InitMode(mode: byte); assembler; asm mov al,mode mov ah,00h int 10h end; procedure InitModeVESA(mode: word); assembler; asm mov bx, mode mov al, 02h mov ah, 4Fh int 10h end; procedure EffaceBuffer(buffer: pointer; couleur: byte); assembler; asm les di, buffer mov cx, 16000 db $66, $33,$DB mov bl, couleur mov bh, bl mov ax, bx db $66, $C1, $E0, $10 db $66, $03, $C3 db $F3, $66, $AB end; procedure CopieBuffer(buffer: pointer); assembler; asm push ds lds si, buffer mov ax, 0A000h mov es, ax xor di, di mov cx, 16000 db $66, $F3, $A5 pop ds end; procedure VSync; assembler; asm @Sync_Boucle1: mov DX, 3dah in AL, DX test AL, 8 jne @Sync_Boucle1 @Sync_Boucle2: in AL, DX test AL, 8 jz @Sync_Boucle2 end; procedure Pxl(PxX,PxY:word; clr:byte); assembler; asm mov ax,0A000h mov es,ax mov ax,PxY shl ax,6 mov bx,ax shl ax,2 add ax,bx add ax,PxX mov di,ax mov al,clr mov es:[DI], al end; procedure PixelMCGA(PxX,PxY:word; clr:byte); begin if ((PxX>=0) and (PxX<319) and (PxY in [0..199])) then asm mov ax,0A000h mov es,ax mov ax,PxY shl ax,6 mov bx,ax shl ax,2 add ax,bx add ax,PxX mov di,ax mov al,clr mov es:[DI], al end; end; procedure H_LineMCGA(HP1_X,HP1_Y,HP2_X:word; Clr:byte); var Long: word; begin if ((HP1_X>=0) and (HP2_X<320) and (HP1_Y in [0..199])) then begin Long:=HP2_X-HP1_X+1; asm mov ax,0A000h mov es,ax mov ax,HP1_Y shl ax,6 mov bx,ax shl ax,2 add ax,bx add ax,HP1_X mov bx,Long mov di,ax @X_Loop: mov al,clr mov es:[DI], al inc di dec bx jnz @X_Loop end; end; end; procedure V_LineMCGA(HP1_X,HP1_Y,HP2_Y:word; Clr:byte); var Long: word; begin if ((HP1_Y>=0) and (HP2_Y<200) and (HP1_X>=0) and (HP1_X<320)) then begin Long:=HP2_Y-HP1_Y+1; asm mov ax,0A000h mov es,ax mov ax,HP1_Y shl ax,6 mov bx,ax shl ax,2 add ax,bx add ax,HP1_X mov bx,Long mov di,ax @Y_Loop: mov al,clr mov es:[DI], al add di,0140h dec bx jnz @Y_Loop end; end; end; procedure LineMCGA(P1X,P1Y,P2X,P2Y:integer; Color:byte); var PtX,PtY: word; Dlt,PtRX,PtRY: real; begin if P1X=P2X then begin if P1Y>P2Y then begin PtX:=P1X; PtY:=P1Y; P1X:=P2X; P1Y:=P2Y; P2X:=PtX; P2Y:=PtY; end; PtY:=P2Y-P1Y+1; asm mov ax,0A000h mov es,ax mov ax,P1Y shl ax,6 mov bx,ax shl ax,2 add ax,bx add ax,P1X mov bx,PtY mov di,ax @Y_Loop: mov al,color mov es:[DI], al add di,0140h dec bx jnz @Y_Loop end; end else if P1X>P2X then begin PtX:=P1X; PtY:=P1Y; P1X:=P2X; P1Y:=P2Y; P2X:=PtX; P2Y:=PtY; end; if P1Y=P2Y then begin PtX:=P2X-P1X+1; asm mov ax,0A000h mov es,ax mov ax,P1Y shl ax,6 mov bx,ax shl ax,2 add ax,bx add ax,P1X mov bx,PtX mov di,ax @X_Loop: mov al,color mov es:[DI], al inc di dec bx jnz @X_Loop end; end else if P1Y<P2Y then Dlt:=((P2Y-P1Y+1)/(P2X-P1X+1)) else Dlt:=((P2Y-P1Y-1)/(P2X-P1X+1)); if ((Dlt>-1) and (Dlt<1)) then begin PtRY:=P1Y; for PtX:=P1X to P2X do begin PixelMCGA(PtX,trunc(PtRY),color); PtRY:=PtRY+Dlt; end; end else if Dlt<-1 then begin Dlt:=1/Dlt; PtRX:=P1X; for PtY:=P1Y downto P2Y do begin PixelMCGA(trunc(PtRX),PtY,color); PtRX:=PtRX+Dlt; end; end else begin Dlt:=1/Dlt; PtRX:=P1X; for PtY:=P1Y to P2Y do begin PixelMCGA(trunc(PtRX),PtY,color); PtRX:=PtRX+Dlt; end; end; end; procedure PixelVESA(PxX,PxY:word; clr:byte); begin if ((PxX>=0) and (PxY<640) and (PxY>=0) and (PxY<480)) then begin asm mov ax, 0A000h mov es, ax mov ax, 640 mul PxY add ax, PxX mov di, ax mov al, clr mov es:[DI], al end; end; end; (********************************************************** ROUTINE PALETTE *) procedure SetPalette(Colors:TPalette); assembler; asm les di,colors mov cx,0 @colorLoop: mov dx,$3c8 mov al,cl out dx,al mov dx,$3c9 mov al,es:[di] out dx,al inc di mov al,es:[di] out dx,al inc di mov al,es:[di] out dx,al inc di inc cx cmp cx,256 jne @ColorLoop end; procedure SetColor(index,r,g,b:byte); assembler; asm mov dx, $3c8 mov al, index out dx, al mov dx, $3c9 mov al, r out dx, al mov al, g out dx, al mov al, b out dx, al end; (************************************************************** ROUTINE PCX *) procedure ChargePCX(nomfichier: string; var destination:Pbyte; var Palette:TPalette); var f: file of byte; octet: byte; count: longint; repetition: byte; ptr: PByte; i: integer; begin Getmem(destination,64000); assign(f,nomfichier); reset(f); seek(f,128); ptr:=destination; count:=0; while(count<320*200) do begin read(f,octet); if(octet>$C0) then begin repetition:=octet-$C0; read(f,octet); for i:=1 to repetition do begin ptr^:=octet; inc(ptr); inc(count); end; end else begin ptr^:=octet; inc(ptr); inc(count); end; end; read(f,octet); for i:=0 to 767 do begin read(f,octet); Palette[i]:=(octet SHR 2); end; close(f); end; (****************************************** ROUTINES DE GESTION DES SPRITES *) procedure SetClipZone(x1,y1,x2,y2 : integer); begin ClipX1:=x1; ClipY1:=y1; ClipX2:=x2; ClipY2:=y2; end; procedure PutSprite(Buffer: pointer; x,y,largeur,hauteur: integer; sprite: Pbyte); assembler; asm push ds lds si,sprite les di,buffer mov ax,320 mul y add ax,x add di,ax mov bx,320 sub bx,largeur mov dx,hauteur @Boucle_PutSpriteY: mov cx,largeur @Boucle_PutSpriteX: mov al,[SI] cmp al,0 jz @Sauter_ce_pixel mov es:[DI],al @Sauter_ce_pixel: inc si inc di dec cx jnz @Boucle_PutSpriteX add di,bx dec dx jnz @Boucle_PutSpriteY pop ds end; procedure PutSpriteClip(Buffer: pointer; x,y,largeur,hauteur: integer; sprite: Pbyte); var deltaX1,deltaX2,deltaY1,deltaY2: integer; ancienne_largeur: integer; begin asm mov bx, largeur mov ancienne_largeur, bx mov ax, x add bx, ax mov cx, y mov dx, cx add dx, hauteur cmp ax, ClipX2 jg @fin cmp bx, ClipX1 jl @fin cmp cx, ClipY2 jg @fin cmp dx, ClipY1 jl @fin xor si,si mov deltaX1, si mov deltaX2, si mov deltaY1, si mov deltaY2, si cmp ax, ClipX1 jge @suite1 mov si, ClipX1 mov x, si sub si, ax mov DeltaX1, si sub largeur, si mov ax, x mov bx, ax add bx, largeur @suite1: cmp bx, ClipX2 jle @suite2 mov si, bx sub si, ClipX2 mov DeltaX2, si sub largeur, si @suite2: cmp cx, ClipY1 jge @suite3 mov si, ClipY1 mov y, si sub si, cx mov DeltaY1, si sub hauteur, si mov cx, y mov dx, cx add dx, hauteur @suite3: cmp dx, ClipY2 jle @suite4 mov si, dx sub si, ClipY2 mov DeltaY2, si sub hauteur, si @suite4: push ds lds si, sprite les di, buffer mov ax, ancienne_largeur mul deltaY1 add si, ax mov ax, 320 mul y add ax, x add di, ax mov bx, 320 sub bx, largeur mov dx, hauteur @Boucle_PutSpriteY: mov cx, largeur add si, deltaX1 @Boucle_PutSpriteX: mov al, [SI] cmp al, 0 jz @Sauter_ce_pixel mov es:[DI], al @Sauter_ce_pixel: inc si inc di dec cx jnz @Boucle_PutSpriteX add di, bx add si, deltaX2 dec dx jnz @Boucle_PutSpriteY pop ds @fin: end; end; procedure GetSprite(source: Pbyte; x1,y1,largeur,hauteur: integer; sprite: Pbyte); assembler; asm push ds lds si,source les di,sprite mov ax,140h mul y1 add ax,x1 add si,ax mov bx,320 sub bx,largeur mov dx,hauteur @BoucleHauteur: mov cx,largeur rep movsb add si,bx dec dx jnz @BoucleHauteur pop ds end; begin end.
unit nsDictListChild; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "Diction" // Автор: Тучнин Д.А. // Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/Diction/nsDictListChild.pas" // Начат: 2004/02/20 08:36:17 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> F1 Встроенные продукты::Diction::Diction::Diction$Unit::TnsDictListChild // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If not defined(Admin) AND not defined(Monitorings)} uses DynamicTreeUnit, l3TreeInterfaces, nsINodeOneLevelWrap, bsTypes, l3Interfaces ; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} type TnsDictListChild = class(TnsINodeOneLevelWrap) private // private fields f_Language : TbsLanguage; protected // overridden protected methods function DoGetText: Tl3WString; override; {* Реализация функции получения текста узла } public // public methods constructor Create(const aNode: INodeBase; aLang: TbsLanguage); reintroduce; class function Make(const aNode: INodeBase; aLang: TbsLanguage): Il3SimpleNode; reintroduce; end;//TnsDictListChild {$IfEnd} //not Admin AND not Monitorings implementation {$If not defined(Admin) AND not defined(Monitorings)} uses BaseTypesUnit, l3Chars ; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // start class TnsDictListChild constructor TnsDictListChild.Create(const aNode: INodeBase; aLang: TbsLanguage); //#UC START# *490825F40070_46836BEC0307_var* //#UC END# *490825F40070_46836BEC0307_var* begin //#UC START# *490825F40070_46836BEC0307_impl* inherited Create(aNode); f_Language := aLang; //#UC END# *490825F40070_46836BEC0307_impl* end;//TnsDictListChild.Create class function TnsDictListChild.Make(const aNode: INodeBase; aLang: TbsLanguage): Il3SimpleNode; var l_Inst : TnsDictListChild; begin l_Inst := Create(aNode, aLang); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end; function TnsDictListChild.DoGetText: Tl3WString; //#UC START# *490825370178_46836BEC0307_var* //#UC END# *490825370178_46836BEC0307_var* begin //#UC START# *490825370178_46836BEC0307_impl* Result := inherited DoGetText; if (f_Language = LG_RUSSIAN) then Result.SCodePage := CP_RussianWin else Result.SCodePage := CP_WesternWin; //#UC END# *490825370178_46836BEC0307_impl* end;//TnsDictListChild.DoGetText {$IfEnd} //not Admin AND not Monitorings end.
program ch7(input, output, out6, data6); { Chapter 7 Assignment Alberto Villalobos March 12, 2014 Description: Reads value pairs (balance, interest) from a file, then produces interest charts across 10 years and 4 more in increments of 100. Input: A file with value pairs, balance and interest rate. Output: A file showing interest charts as described above. Level 0: Initialize variables Read Loop Read two values Print table For every year use the compound function Level 1: Initialize variables Reset Input Rewrite Output Read Input with not EOT loop Each two inputs: Chart procedure Compound function Exponentiate function for compunding use the following formula A = P(1+(r/n))^(nt) A = total amount of money after n years P = initial amount of money r = annual rate of interest t = number of years n = number of times the interest is compounded per year } {main program vars} var out6, data6: text; balance, interest, total: real; {exponentiate function} function exponentiate(number, exponent: Real): Real; var exponentiateTotal: Real; begin exponentiateTotal := exp(exponent*ln( number)); exponentiate := exponentiateTotal; end; {calculate compound interest function} function calculateCompoundInterest(initialAmount, annualRate, yearNumber: real): Real; var compoundTotal: real; begin { for compunding use the following formula A = P(1+(r/n))^(nt) A = total amount of money after n years P = initial amount of money r = annual rate of interest t = number of years n = number of times the interest is compounded per year } compoundTotal:= (1 + (annualRate/100)); compoundTotal:= exponentiate(compoundTotal, yearNumber); compoundTotal:= initialAmount * compoundTotal; calculateCompoundInterest := compoundTotal; end; procedure printChart(balance : real; interest : real); { Print Chart Prints a 5 line interest chart given a balance and interest @param balance interest NOTE: First make this do the whole thing, then refactor to a different procedure. } var i, j, k: integer; newBalance : real; numberToString: string(255); begin for i := 0 to 4 do begin {str(balance:5:0, numberToString);} write(out6,balance:5:0); write(out6,interest:6:0); write(out6,'':2); for j := 1 to 10 do begin {write(j:4);} write(out6,calculateCompoundInterest(balance, interest, j):6:0); end; balance := balance + 100; writeln(out6,''); end; end; {main program} begin reset(data6, 'datafiles/data6.dat'); rewrite(out6, 'outputfiles/out6.dat'); while not eof(data6) do begin writeln(out6,'year':35); writeln(out6,'Balance':7,'Rate%':6,'1':6,'2':6,'3':6,'4':6,'5':6,'6':6,'7':6,'8':6,'9':6,'10':6); read(data6, balance); read(data6, interest); {writeln('Balance: ', balance:5:2,' Interest ', interest:5:2); } printChart(balance, interest); if eoln(data6) then readln(data6); end; end.
{ Version 1.0 - Author jasc2v8 at yahoo dot com This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to <http://unlicense.org> } unit threadunit; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type { TThreadUnit } TThreadUnit = class(TThread) private FStatus: string; FName: string; procedure Update; procedure OnTerminate; protected procedure Execute; override; public property Status: string Read FStatus Write FStatus; property Name: string Read FName Write FName; constructor Create(CreateSuspended: Boolean); end; implementation uses Unit1; { TThreadUnit } procedure TThreadUnit.OnTerminate; begin Form1.Memo1.Append('Terminate : '+Name); end; procedure TThreadUnit.Update; begin Form1.Memo1.Append(Status); end; procedure TThreadUnit.Execute; var i: integer; begin { simulate some work } for i:=1 to 10 do begin if Terminated then break; Sleep(Random(500)+500); Status:=Name+' count: '+i.ToString; Synchronize(@Update); end; Synchronize(@OnTerminate); end; constructor TThreadUnit.Create(CreateSuspended: Boolean); begin inherited Create(CreateSuspended); FreeOnTerminate := False; end; end.
unit Finder; {=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=] Copyright (c) 2014, Jarl K. <Slacky> Holta || http://github.com/WarPie All rights reserved. For more info see: Copyright.txt [=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=} {$mode objfpc}{$H+} {$modeswitch advancedrecords} {$inline on} interface uses SysUtils, Classes, Threading, Header; type TColorInfo = Pointer; PColorInfo = ^TColorInfo; TColorDistFunc = function(Color1:TColorInfo; Color2:TColor; mul: TMultiplier): Single; PColorDistFunc = ^TColorDistFunc; PFinder = ^TFinder; TFinder = packed record private FCompareFunc: TColorDistFunc; FNumThreads: UInt8; FCacheSize: UInt8; FColorInfo: TColorInfo; FFormula: EDistanceFormula; FChMul: TMultiplier; FThreadPool: TThreadPool; function SetupColorInfo(const Color: TColor): Single; procedure FreeColorInfo(); public procedure Init(Formula:EDistanceFormula; NumThreads:UInt8; CacheSize:UInt8); procedure Free; procedure SetFormula(Formula: EDistanceFormula); function GetFormula(): EDistanceFormula; procedure SetNumThreads(NumThreads: UInt8); function GetNumThreads(): Int32; procedure SetMultipliers(Mul: TMultiplier); function GetMultipliers(): TMultiplier; function GetMaxDistance(): Single; function SimilarColors(Color1, Color2: TColor; Tolerance: Single): Boolean; function ColorDistance(Color1, Color2: TColor): Single; procedure MatchColor(src:TIntMatrix; out dest:TSingleMatrix; color:TColor); function FindColor(src:TIntMatrix; out dest:TPointArray; color:TColor; Tolerance:Single): Boolean; end; TMicroCacheItem = record Color:TColor; Diff:Single; end; TMicroCache = record High: SizeInt; Color: TColorInfo; MaxDiff: Single; Mods: TMultiplier; Diff: TColorDistFunc; Cache: array of TMicroCacheItem; procedure Init(ASize:UInt8; AColor:TColorInfo; AMaxDiff:Single; AMods:TMultiplier; ADiff: TColorDistFunc); function Compare(TestColor: TColor): TMicroCacheItem; inline; function DirectCompare(TestColor: TColor): Single; inline; end; //-------------------------------------------------- implementation uses math, colordist, colorconversion; procedure TMicroCache.Init(ASize:UInt8; AColor:TColorInfo; AMaxDiff:Single; AMods:TMultiplier; ADiff: TColorDistFunc); var i:Int32; begin self.Color := AColor; self.MaxDiff := AMaxDiff; self.Mods := AMods; self.Diff := ADiff; self.High := ASize-1; SetLength(self.Cache, ASize); for i:=0 to self.High do begin self.Cache[i].Diff := -1; self.Cache[i].Color := -1; end; end; function TMicroCache.Compare(TestColor: TColor): TMicroCacheItem; var i:Int32 = 1; begin if (TestColor = self.cache[0].Color) then Exit(self.cache[0]); //find the item, move it back to 0 while i <= self.High do if self.cache[i].Color = TestColor then begin Result := self.cache[i]; while i > 0 do begin self.cache[i] := self.cache[i-1]; Dec(i); end; self.cache[0] := Result; Exit(Result); end else Inc(i); //add item, push old item out of the way i := self.High; while i >= 0 do begin self.cache[i] := self.cache[i-1]; Dec(i); end; self.cache[0].Color := TestColor; self.cache[0].Diff := Diff(self.Color, TestColor, self.Mods) / self.MaxDiff * 100; Result := self.cache[0]; end; function TMicroCache.DirectCompare(TestColor: TColor): Single; begin Result := Diff(self.Color, TestColor, self.Mods) / self.MaxDiff * 100 end; //[@src, @dest, @FChMul, @maxDist, @FColorInfo, @FCompareFunc, @FCacheSize] procedure ColorCorrelation(params:PParamArray; iLow, iHigh: Int32); var x,y: Int32; src: PIntMatrix; dest:PSingleMatrix; box: TBox; uCache: TMicroCache; begin src := Params^[0]; dest := Params^[1]; uCache.Init( PUInt8(Params^[6])^, //cache size PColorInfo(Params^[4])^, //input color PSingle(Params^[3])^, //maximum diff using this colorspace and current mult PMultiplier(Params^[2])^, //channelwise multipliers PColorDistFunc(Params^[5])^ //the function needed to compute diff between colors ); if uCache.High >= 0 then begin for y:=iLow to iHigh do for x:=0 to High(src^[y]) do dest^[y,x] := uCache.Compare(src^[y,x]).Diff; end else for y:=iLow to iHigh do for x:=0 to High(src^[y]) do dest^[y,x] := uCache.DirectCompare(src^[y,x]); end; (*----| TFinder |-------------------------------------------------------------*) procedure TFinder.Init(Formula:EDistanceFormula; NumThreads:UInt8; CacheSize:UInt8); begin FNumThreads := Max(1,NumThreads); FColorInfo := nil; FFormula := Formula; FCacheSize := CacheSize; FThreadPool := TThreadPool.Create(128); FChMul[0] := 1; FChMul[1] := 1; FChMul[2] := 1; end; procedure TFinder.Free; begin if FColorInfo <> nil then FreeMem(FColorInfo); FCompareFunc:= nil; FFormula := dfRGB; FNumThreads := 1; FThreadPool.Free(); end; (*----| Setup/Unsetup |-------------------------------------------------------*) function TFinder.SetupColorInfo(const Color: TColor): Single; begin case FFormula of dfRGB: begin FCompareFunc := @DistanceRGB; FColorInfo := AllocMem(SizeOf(ColorRGB)); PColorRGB(FColorInfo)^ := ColorToRGB(Color); Result := DistanceRGB_Max(FChMul); end; dfHSV: begin FCompareFunc := @DistanceHSV; FColorInfo := AllocMem(SizeOf(ColorHSV)); PColorHSV(FColorInfo)^ := ColorToHSV(Color); Result := DistanceHSV_Max(FChMul); end; dfHSL: begin FCompareFunc := @DistanceHSL; FColorInfo := AllocMem(SizeOf(ColorHSL)); PColorHSL(FColorInfo)^ := ColorToHSL(Color); Result := DistanceHSL_Max(FChMul); end; dfXYZ: begin FCompareFunc := @DistanceXYZ; FColorInfo := AllocMem(SizeOf(ColorXYZ)); PColorXYZ(FColorInfo)^ := ColorToXYZ(Color); Result := DistanceXYZ_Max(FChMul); end; dfLAB: begin FCompareFunc := @DistanceLAB; FColorInfo := AllocMem(SizeOf(ColorLAB)); PColorLAB(FColorInfo)^ := ColorToLAB(Color); Result := DistanceLAB_Max(FChMul); end; dfLCH: begin FCompareFunc := @DistanceLCH; FColorInfo := AllocMem(SizeOf(ColorLCH)); PColorLCH(FColorInfo)^ := ColorToLCH(Color); Result := DistanceLCH_Max(FChMul); end; dfDeltaE: begin FCompareFunc := @DistanceDeltaE; FColorInfo := AllocMem(SizeOf(ColorLAB)); PColorLAB(FColorInfo)^ := ColorToLAB(Color); Result := DistanceDeltaE_Max(FChMul); end; end; end; procedure TFinder.FreeColorInfo(); begin if FColorInfo <> nil then FreeMem(FColorInfo); FColorInfo := nil; end; (* Set the compare method used to compute the difference between the given color, and each color on the image using a preset. *) procedure TFinder.SetFormula(Formula:EDistanceFormula); begin self.FFormula := Formula; end; function TFinder.GetFormula(): EDistanceFormula; begin Result := self.FFormula; end; (* Get & Set the number of threads to be used *) procedure TFinder.SetNumThreads(numThreads:UInt8); begin FNumThreads := Min(FThreadPool.FMaxThreads, Max(1, numThreads)); end; function TFinder.GetNumThreads(): Int32; begin Result := FNumThreads; end; (* Get & Set the multipliers *) procedure TFinder.SetMultipliers(Mul: TMultiplier); begin FChMul[0] := Mul[0]; FChMul[1] := Mul[1]; FChMul[2] := Mul[2]; end; function TFinder.GetMultipliers(): TMultiplier; begin //Writeln(Format('%.3f, %.3f, %.3f', [Self.FChMul[0], Self.FChMul[1],Self.FChMul[2]])); Result := Self.FChMul; end; function TFinder.GetMaxDistance(): Single; begin Result := Self.SetupColorInfo(0); Self.FreeColorInfo(); end; // tolerance range: 0..100 function TFinder.SimilarColors(Color1, Color2: TColor; Tolerance: Single): Boolean; var maxDist: Single; begin //Color1 := SwapRGBChannels(Color1); //Color2 := SwapRGBChannels(Color2); maxDist := Self.SetupColorInfo(Color1); Result := Self.FCompareFunc(FColorInfo, Color2, FChMul) / maxDist * 100 < Tolerance; Self.FreeColorInfo(); end; // output range: 0..100 function TFinder.ColorDistance(Color1, Color2: TColor): Single; var maxDist: Single; begin //Color1 := SwapRGBChannels(Color1); //Color2 := SwapRGBChannels(Color2); maxDist := Self.SetupColorInfo(Color1); Result := FCompareFunc(FColorInfo, Color2, FChMul) / maxDist * 100; Self.FreeColorInfo(); end; // Threaded cross-correlate a color with an image // output range - 0..100 where 0 means there is no difference! procedure TFinder.MatchColor(src:TIntMatrix; out dest:TSingleMatrix; color:TColor); var W,H: Int32; maxDist: Single; begin H := Length(src); if (H = 0) then Exit; W := Length(src[0]); //color := SwapRGBChannels(color); maxDist := Self.SetupColorInfo(Color); SetLength(dest, H,W); FThreadPool.DoParallel(@ColorCorrelation, [@src, @dest, @FChMul, @maxDist, @FColorInfo, @FCompareFunc, @FCacheSize], Low(src),High(src), FNumThreads); Self.FreeColorInfo(); end; // Tolerance range 0..100 function TFinder.FindColor(src:TIntMatrix; out dest:TPointArray; color:TColor; Tolerance:Single): Boolean; var x,y,c: Int32; xcorr: TSingleMatrix; begin MatchColor(src, xcorr, color); SetLength(dest, 512); c := 0; for y:=0 to High(xcorr) do for x:=0 to High(xcorr[y]) do if xcorr[y,x] <= Tolerance then begin if c = Length(dest) then SetLength(dest, Length(dest)*2); dest[c].x := x; dest[c].y := y; Inc(c); end; SetLength(dest, c); Result := c > 0; end; end.
unit fEnemyStatistics; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, DanHexEdit,cMegaROM, cConfiguration; type TfrmEnemyStatistics = class(TForm) lblGlobalEnemyHealth: TLabel; lblEnemy: TLabel; cbEnemy: TComboBox; txtGlobalHealth: TDanHexEdit; grpIndividualEnemy: TGroupBox; cmdOK: TButton; cmdCancel: TButton; lblPWeaponDamage: TLabel; lblCWeaponDamage: TLabel; lblIWeaponDamage: TLabel; lblBWeaponDamage: TLabel; lblFWeaponDamage: TLabel; lblEWeaponDamage: TLabel; lblGWeaponDamage: TLabel; lblPlayerDamage: TLabel; lblScore: TLabel; txtPWeaponDamage: TDanHexEdit; txtCWeaponDamage: TDanHexEdit; txtIWeaponDamage: TDanHexEdit; txtBWeaponDamage: TDanHexEdit; txtFWeaponDamage: TDanHexEdit; txtEWeaponDamage: TDanHexEdit; txtGWeaponDamage: TDanHexEdit; txtPlayerDamage: TDanHexEdit; txtScore: TDanHexEdit; procedure FormShow(Sender: TObject); procedure cbEnemyChange(Sender: TObject); procedure cmdCancelClick(Sender: TObject); procedure cmdOKClick(Sender: TObject); private _ROMData : TMegamanROM; _EditorConfig : TRRConfig; _PrevID : Byte; procedure LoadEnemyData(pID : Byte); procedure SaveEnemyData(pID : Byte); procedure PopulateEnemyCombobox; { Private declarations } public property ROMData : TMegamanROM read _ROMData write _ROMData; property EditorConfig : TRRConfig read _EditorConfig write _EditorConfig; { Public declarations } end; var frmEnemyStatistics: TfrmEnemyStatistics; implementation uses uGlobal; {$R *.dfm} procedure TfrmEnemyStatistics.PopulateEnemyCombobox; var i : integer; begin cbEnemy.Items.BeginUpdate; for i := 0 to $3A do cbEnemy.Items.Add( _ROMData.EnemyDescriptions[i]); cbEnemy.ItemIndex := 0; cbEnemy.Items.EndUpdate; end; procedure TfrmEnemyStatistics.FormShow(Sender: TObject); begin PopulateEnemyCombobox; _PrevID := cbEnemy.ItemIndex; LoadEnemyData(cbEnemy.ItemIndex); end; procedure TfrmEnemyStatistics.LoadEnemyData(pID : Byte); begin txtGlobalHealth.Text := IntToHex(_ROMData.Properties['GlobalEnemyHealth'].Value,2); txtPWeaponDamage.Text := IntToHex(_ROMData.EnemyStatistics[pID].PWeaponDamage,2); txtCWeaponDamage.Text := IntToHex(_ROMData.EnemyStatistics[pID].CWeaponDamage,2); txtIWeaponDamage.Text := IntToHex(_ROMData.EnemyStatistics[pID].IWeaponDamage,2); txtBWeaponDamage.Text := IntToHex(_ROMData.EnemyStatistics[pID].BWeaponDamage,2); txtFWeaponDamage.Text := IntToHex(_ROMData.EnemyStatistics[pID].FWeaponDamage,2); txtEWeaponDamage.Text := IntToHex(_ROMData.EnemyStatistics[pID].EWeaponDamage,2); txtGWeaponDamage.Text := IntToHex(_ROMData.EnemyStatistics[pID].GWeaponDamage,2); txtPlayerDamage.Text := IntToHex(_ROMData.EnemyStatistics[pID].PlayerDamage,2); txtScore.Text := IntToHex(_ROMData.EnemyStatistics[pID].Score,2); end; procedure TfrmEnemyStatistics.SaveEnemyData(pID : Byte); begin _ROMData.Properties['GlobalEnemyHealth'].Value := StrToInt('$' + txtGlobalHealth.Text); _ROMData.EnemyStatistics[pID].PWeaponDamage := StrToInt('$' + txtPWeaponDamage.Text); _ROMData.EnemyStatistics[pID].CWeaponDamage := StrToInt('$' + txtCWeaponDamage.Text); _ROMData.EnemyStatistics[pID].IWeaponDamage := StrToInt('$' + txtIWeaponDamage.Text); _ROMData.EnemyStatistics[pID].BWeaponDamage := StrToInt('$' + txtBWeaponDamage.Text); _ROMData.EnemyStatistics[pID].FWeaponDamage := StrToInt('$' + txtFWeaponDamage.Text); _ROMData.EnemyStatistics[pID].EWeaponDamage := StrToInt('$' + txtEWeaponDamage.Text); _ROMData.EnemyStatistics[pID].GWeaponDamage := StrToInt('$' + txtGWeaponDamage.Text); _ROMData.EnemyStatistics[pID].PlayerDamage := StrToInt('$' + txtPlayerDamage.Text); _ROMData.EnemyStatistics[pID].Score := StrToInt('$' + txtScore.Text); end; procedure TfrmEnemyStatistics.cbEnemyChange(Sender: TObject); begin SaveEnemyData(_PrevID); _PrevID := cbEnemy.ItemIndex; LoadEnemyData(_PrevID); end; procedure TfrmEnemyStatistics.cmdCancelClick(Sender: TObject); begin _ROMData.LoadEnemyStatistics; end; procedure TfrmEnemyStatistics.cmdOKClick(Sender: TObject); begin _ROMData.SaveEnemyStatistics; end; end.
unit uFrmEditorText; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.ScrollBox, FMX.Memo, FMX.Controls.Presentation, FMX.StdCtrls, FMX.ListBox, FMX.Edit, FMX.EditBox, FMX.NumberBox, FMX.Colors, FMX.ComboEdit, FMX.Objects , qjson, cxClasses, dxColorDialog; type TFrmEditorText = class(TForm) Label1: TLabel; memText: TMemo; Label2: TLabel; nbFontSize: TNumberBox; Label3: TLabel; cbeFontFamily: TComboEdit; btnCancel: TButton; btnSave: TButton; txtDisplay: TText; raDisplay: TRectangle; Label4: TLabel; chkTransparentBackground: TCheckBox; dxColorDialog1: TdxColorDialog; raFontColor: TRectangle; rabackColor: TRectangle; procedure btnSaveClick(Sender: TObject); procedure memTextChangeTracking(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure cbeFontFamilyChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure chkTransparentBackgroundChange(Sender: TObject); procedure raFontColorClick(Sender: TObject); private { Private declarations } FID: Integer; FCfg: TQJson; procedure UI2D(); procedure D2UI(); procedure UpdateDisplay; public { Public declarations } property ID: Integer read FID write FID; // property Cfg: TQJson read FCfg write FCfg; end; var FrmEditorText: TFrmEditorText; function fnOpenEditorText(AOwner: TComponent; AID: Integer): Boolean; implementation uses FMX.Printer, uCfg; {$R *.fmx} function fnOpenEditorText(AOwner: TComponent; AID: Integer): Boolean; var F: TFrmEditorText; bOK: Boolean; begin Result := False; bOK := False; F := TFrmEditorText.Create(AOwner); try F.ID := AID; // F.ShowModal( // procedure(ModalResult: TModalResult) // begin // if ModalResult = mrOK then // begin // bOK := True; // end; // end // ); Result := F.ShowModal = mrOk; //Result := bOK; finally end; end; procedure TFrmEditorText.btnSaveClick(Sender: TObject); begin UI2D; Self.ModalResult := mrOk; end; procedure TFrmEditorText.cbeFontFamilyChange(Sender: TObject); begin UpdateDisplay; end; procedure TFrmEditorText.chkTransparentBackgroundChange(Sender: TObject); begin if chkTransparentBackground.IsChecked then begin raDisplay.Fill.Kind := TBrushKind.None; raBackColor.Enabled := False; end else begin raDisplay.Fill.Kind := TBrushKind.Solid; raBackColor.Enabled := True; end; end; procedure TFrmEditorText.UI2D(); var vJson, vItem, vItems: TQJson; sCfg: string; begin sCfg := ExtractFilePath(ParamStr(0)) + 'cfg.dat'; vJson := TQJson.Create; try FCfg.ForcePath('Texts.Text').AsString := memText.Text; FCfg.ForcePath('Font.Family').AsString := cbeFontFamily.Items.Strings[cbeFontFamily.ItemIndex]; FCfg.ForcePath('Font.Size').AsFloat := nbFontSize.Value; FCfg.ForcePath('Font.FontColor').AsInt64 := raFontColor.Fill.Color; FCfg.ForcePath('Font.BackColor').AsInt64 := raBackColor.Fill.Color; FCfg.ForcePath('Font.BackTran').AsBoolean := chkTransparentBackground.IsChecked; vJson.LoadFromFile(sCfg); vJson.ForcePath('DescTexts.Font.Family').AsString := FCfg.ForcePath('Font.Family').AsString; vJson.ForcePath('DescTexts.Font.Size').AsFloat := FCfg.ForcePath('Font.Size').AsFloat; vJson.ForcePath('DescTexts.Font.FontColor').AsInt64 := FCfg.ForcePath('Font.FontColor').AsInt64; vJson.ForcePath('DescTexts.Font.BackColor').AsInt64 := FCfg.ForcePath('Font.BackColor').AsInt64; vJson.ForcePath('DescTexts.Font.BackTran').AsBoolean := FCfg.ForcePath('Font.BackTran').AsBoolean; vItems := vJson.ForcePath('DescTexts.Texts'); for vItem in vItems do begin if vItem.IntByName('ID', 0) <> FCfg.ForcePath('Texts.ID').AsInt64 then Continue; vItem.ForcePath('Text').AsString := FCfg.ForcePath('Texts.Text').AsString; Break; end; vJson.SaveToFile(sCfg); finally FreeAndNil(vJson); end; end; procedure TFrmEditorText.D2UI(); begin raFontColor.Fill.Color := FCfg.ForcePath('Font.FontColor').AsInt64; raBackColor.Fill.Color := FCfg.ForcePath('Font.BackColor').AsInt64; chkTransparentBackground.IsChecked := FCfg.ForcePath('Font.BackTran').AsBoolean; memText.Text := FCfg.ForcePath('Texts.Text').AsString; cbeFontFamily.ItemIndex := cbeFontFamily.Items.IndexOf(FCfg.ForcePath('Font.Family').AsString); nbFontSize.Value := FCfg.ForcePath('Font.Size').AsFloat; end; procedure TFrmEditorText.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := TCloseAction.caFree; FreeAndNil(FCfg); end; procedure TFrmEditorText.FormCreate(Sender: TObject); begin cbeFontFamily.Items := Printer.Fonts; //cbeFontFamily.Items. end; procedure TFrmEditorText.FormShow(Sender: TObject); begin if FCfg = nil then FCfg := TQJson.Create; FCfg.Parse(GetCfg(FID)); D2UI; end; procedure TFrmEditorText.memTextChangeTracking(Sender: TObject); begin UpdateDisplay; end; procedure TFrmEditorText.raFontColorClick(Sender: TObject); begin if dxColorDialog1.Execute then begin TRectangle(Sender).Fill.Color := dxColorDialog1.Color; UpdateDisplay; end; end; procedure TFrmEditorText.UpdateDisplay; begin try if cbeFontFamily.Items.IndexOf(cbeFontFamily.Text) >= 0 then begin memText.TextSettings.Font.Family := cbeFontFamily.Items.Strings[cbeFontFamily.ItemIndex]; txtDisplay.TextSettings.Font.Family := memText.TextSettings.Font.Family; end; memText.TextSettings.Font.Size := nbFontSize.Value; txtDisplay.TextSettings.Font.Size := nbFontSize.Value; memText.TextSettings.FontColor := raFontColor.Fill.Color; txtDisplay.TextSettings.FontColor := raFontColor.Fill.Color; raDisplay.Fill.Color := raBackColor.Fill.Color; txtDisplay.Text := memText.Text; txtDisplay.Position.X := 0; txtDisplay.Position.Y := 0; raDisplay.Width := txtDisplay.Width; raDisplay.Height := txtDisplay.Height; raDisplay.Position.X := (Self.Width * 1.0 - raDisplay.Width) / 2; except end; end; end.
{$DEFINE USELogs} unit ModelServer; interface uses Windows, Events, Classes, Collection, Protocol, Kernel, World, Population, RDOServer, ExtCtrls, BackupObjects, SyncObjs, RDOInterfaces, MailServerInterfaces, NewsServerInterfaces, Accounts, ActorTypes, ActorPool, Seasons, ClassStorageInt, CacheAgent; const tidRDOHook_World = 'World'; const tidRegKey_ModelServer = '\SOFTWARE\Oceanus\FIVE\ModelServer'; tidRegKey_ModelExtensions = tidRegKey_ModelServer + '\Extensions'; const tidFileName_WorldIniFile = 'world.ini'; const tidIniSection_General = 'General'; tidIniSection_WorldTowns = 'Towns'; tidIniValue_Name = 'Name'; tidIniValue_xSize = 'Width'; tidIniValue_ySize = 'Height'; tidIniValue_TownCount = 'Count'; tidIniValue_TownName = 'TownName'; tidIniValue_TownCluster = 'TownCluster'; tidIniValue_TownX = 'TownX'; tidIniValue_TownY = 'TownY'; type TBackupMode = (bmdInGame, bmdShutdown); //const //BackupPeriod = 30; // in minutes type TModelServer = class(TObject, IMailServer, INewsServer, IConfigHandler) public constructor Create; destructor Destroy; override; public procedure InitWorld( aName : string; aNotEvent : TBackupReaderNotify; aBaseDir, aCacheHost, aSatellitePath : string; aDAPort, aCSPort, aCCPort : integer; aMailHost : string; aMailPort, aNewsPort : integer ); procedure InitInterfaceServerEvents( ServerName : string; ServerPort : integer ); procedure InitMailServer( ServerName : string; ServerPort : integer; WorldName : string ); procedure InitNewsServer( ServerName : string; ServerPort : integer; WorldName : string ); procedure InitDirServer( AreaName, ServerName : string; ServerPort : integer ); procedure SetPurgeTyccons(count : integer); private procedure StartCacheServer( aCSPort : integer ); procedure StartDirectAccessServer( aDAPort : integer ); private fBaseDir : string; fWorld : TInhabitedWorld; fDAConn : IRDOConnectionsServer; fDAServ : TRDOServer; fDALockConn : IRDOConnectionsServer; fDALockServ : TRDOServer; fISConn : IRDOConnectionInit; fISEvents : OleVariant; fBPS : integer; fCurDt : TTimeDelta; fLocalHost : string; fDAPort : integer; fDALockPort : integer; fForceBackup : boolean; fBackupError : boolean; fSaveCount : integer; fSatCount : integer; fCacheOptions : TCacheOptions; fSatRenderComplete : TEvent; fSatelliteMapPath : string; fTycconsToPurge : integer; fCacheLogVer : integer; private function GetHoursADay : integer; public property TheWorld : TInhabitedWorld read fWorld; property BPS : integer read fBPS; // Blocks per second property CurDt : TTimeDelta read fCurDt; property HoursADay : integer read GetHoursADay; property ForceBackup : boolean read fForceBackup write fForceBackup; property CacheOptions : TCacheOptions read fCacheOptions write fCacheOptions; property SatelliteMapPath : string read fSatelliteMapPath write fSatelliteMapPath; property BackupError : boolean read fBackupError; private fExtensionList : TStrings; public property ExtensionList : TStrings read fExtensionList; private procedure LoadExtensions( Notify : TBackupReaderNotify ); procedure LoadWorldExtensions( World : TWorld; Notify : TBackupReaderNotify; WorldLoaded : boolean ); private fTimer : TTimer; fSimTimer : TTimer; fIntTimer : TTimer; fCargoTimer : TTimer; fSimEv : TEvent; fBackupEv : TEvent; fIntEv : TEvent; fCargoEv : TEvent; fSimThread : TThread; fLastBackup : integer; {$IFNDEF REMOVETRANSPORT} fCargoRenderThread : TThread; {$ENDIF} fIntegrationThread : TThread; fIntegrationLock : TCriticalSection; fISProxyLock : TCriticalSection; fDSProxyLock : TCriticalSection; private procedure SetTimeRes( aVirtTimeRate, aSimRate, anIntRate : integer ); procedure OnTimer( Sender : TObject ); procedure OnSimTimer( Sender : TObject ); procedure OnIntTimer( Sender : TObject ); procedure OnCargoTimer( Sender : TObject ); private procedure OnAreaChanged( x, y, dx, dy : integer ); procedure OnFacilityChanged( Facility : TFacility; FacilityChange : TFacilityChange ); procedure OnTycoonsChanged; procedure OnDateChanged( Date : TDateTime ); procedure OnSeasonChanged( Season : TSeason ); procedure OnEndOfPeriod( PeriodType : TPeriodType; PeriodCount : integer ); procedure OnTycoonRetired( name : string ); //procedure OnPoolActed( PoolId : TActorPoolId; ViewerId : TViewerId; TickCount : cardinal; TickData : TStream ); procedure OnSendNotification( TycoonId : integer; Kind : integer; Title, Body : string; Options : integer ); procedure OnModelStatusChange( status : integer ); procedure OnISDisconnect( const ClientConnection : IRDOConnection ); procedure OnDSDisconnect( const ClientConnection : IRDOConnection ); procedure OnMailDisconnect( const ClientConnection : IRDOConnection ); procedure OnNewsDisconnect( const ClientConnection : IRDOConnection ); private procedure StoreBackup( mode : TBackupMode; ErrorLevel : integer ); procedure CreateSatelliteMaps; private fMailConn : IRDOConnectionInit; fMailServer : OleVariant; fMailId : integer; fNewsConn : IRDOConnectionInit; fNewsServer : OleVariant; fDirConn : IRDOConnectionInit; fDirServer : OleVariant; // IUnknown private function QueryInterface(const IID: TGUID; out Obj): hresult; stdcall; function _AddRef : integer; stdcall; function _Release : integer; stdcall; // IMailServer private function NewMailAccount( Account, Alias, FwdAddr : string; KeepMsg : boolean ) : boolean; function DeleteAccount ( Account : string ) : boolean; function SetForwardRule( Account, FwdAddr : string; KeepMsg : boolean ) : boolean; function SendMessage( From, Dest, Subject : string; Lines : TStringList; html : boolean ) : boolean; function SendHTMLMessage( From, Dest, Subject, URL : string ) : boolean; procedure UpdateDate(NewDate : TDateTime); // INewsServer private procedure CreateNewsCenter ( World : string ); procedure CreateNewspaper ( World, Name, Style, Town : string ); procedure GenerateNewspapers( World : widestring; Date : TDateTime ); function RenewCache(Agent, ObjId : string) : TObjectCache; private // fBackupEvent : TEvent; private fMDXNodes : TCollection; public property MailConn : IRDOConnectionInit read fMailConn; property NewsConn : IRDOConnectionInit read fNewsConn; property DirConn : IRDOConnectionInit read fDirConn; // IConfigHandler private function GetInteger( id : integer ) : integer; function GetFloat( id : integer ) : double; function GetString( id : integer ) : string; function GetMoney( id : integer ) : TMoney; function GetIntegerArray( id : integer; i, j, k, l : integer ) : integer; function GetFloatArray( id : integer; i, j, k, l : integer ) : double; function GetStringArray( id : integer; i, j, k, l : integer ) : string; function GetMoneyArray( id : integer; i, j, k, l : integer ) : TMoney; function GetConfigParm( strId, defVal : string ) : string; private fAccountExpires : integer; fLevelLimit : integer; fConfigInfo : TStringList; fIntegration : boolean; public property Integration : boolean read fIntegration write fIntegration; private fAutoRestart : boolean; fRestartDate : TDateTime; fMaintDue : boolean; fWarnMaint : boolean; fTimeToMaint : TDateTime; fLastDowntime : integer; // in minutes fLastDateUp : TDateTime; fMSReadyEvent : TEvent; private function GetMaxInvestors : integer; procedure SetMaxInvestors(value : integer); public property AutoRestart : boolean read fAutoRestart write fAutoRestart; property RestartDate : TDateTime read fRestartDate write fRestartDate; property MaintDue : boolean read fMaintDue write fMaintDue; property LastDateUp : TDateTime read fLastDateUp write fLastDateUp; property MaxInvestors : integer read GetMaxInvestors write SetMaxInvestors; public procedure CheckMaintenanceSchedule; procedure RegisterLastGoodBackup(name : string); procedure SetMSReadyEvent(signal : boolean); function ReportMaintenance(shortMsg, longMsg : string; eta : TDateTime) : boolean; procedure ReportMaintenanceToIS(eta : TDateTime); procedure CalculateDownTime; end; var BackupRate : integer = 45; WorldDt : integer = 0; const TheModelServer : TModelServer = nil; implementation uses SmartThreads, ClassStorage, SysUtils, Trade, ModelServerCache, ComObj, Logs, Registry, IniFiles, KernelCache, PoliticsCache, WinSockRDOConnectionsServer, HostNames, Construction, WinSockRDOConnection, RDOObjectProxy, Surfaces, Banks, BasicTaxes, Politics, BackupInterfaces, PopulatedBlock, WorkCenterBlock, CollectionBackup, BasicPolitics, PyramidalModifier, PublicFacility, StdFluids, MailProtocol, LargeMatrix, BasicCurriculum, Circuits, ResearchCenter, Headquarters, ConnectedBlock, SpontaneousBuildings, StdTaxes, OfficeBlock, BasicAccounts, Newspapers, Broadcast, StdBroadcast, Transport, StreamToStr, VCLBackup, TownPolitics, WorldPolitics, Ministers, TranscendBlock, EvaluatedBlock, Inventions, Rankings, StdRankings, Forms, ServiceBlock, Land, MetaInstances, CompStringsParser, TycoonLevels, JPEG, Graphics, Profiler, BasicEvents, Languages, SimMLS, Taxes, Plotter, FileCtrl, MathUtils, MatrixCircuits, MediaGates, LoggedUserData, Messages, MediaNameHistory, EconomyRelay, Tasks, Tutorial, TycoonVotes, Favorites, DelphiStreamUtils; const InitialWaitTime = 1*30*1000; function MinutesSince(ticks : cardinal) : integer; begin result := (Windows.GetTickCount - ticks) div (1000*60); end; function IntToThreadPriority(value : integer) : TThreadPriority; begin case value of 0: result := tpIdle; 1: result := tpLowest; 2: result := tpLower; 3: result := tpNormal; 4: result := tpHigher; 5: result := tpHighest; 6: result := tpTimeCritical; else result := tpNormal; end; end; // TBackupThread type TBackupThread = class( TSmartThread ) public constructor Create( aServer : TModelServer; aMode : TBackupMode ); private fServer : TModelServer; fMode : TBackupMode; protected procedure Execute; override; end; constructor TBackupThread.Create( aServer : TModelServer; aMode : TBackupMode ); begin inherited Create( true ); fServer := aServer; fMode := aMode; Priority := tpLowest; FreeOnTerminate := true; Resume; end; procedure TBackupThread.Execute; begin fServer.StoreBackup( fMode, 0 ); end; // TSimTread type TSimThread = class( TSmartThread ) private fServer : TModelServer; protected procedure Execute; override; private fThreadInfo : pointer; public procedure Dispatch(var Message); override; end; procedure TSimThread.Execute; var SimStart : integer; OldPriority : TThreadPriority; lstBkTick : integer; warnTick : integer; begin lstBkTick := Windows.GetTickCount; warnTick := 0; // This allows any secure operation inside the simulation thread. LoggedUserData.LogSystem; fServer.fWorld.ForceDt(2); // Worlds start with DT = 2 while not Terminated do try if (fServer.fSimEv.WaitFor( fServer.fSimTimer.Interval ) <> wrTimeout) and not Terminated then begin fServer.fSimEv.ResetEvent; SimStart := DateTimeToTimeStamp(Time).time; if WorldDt > 0 then fServer.fWorld.ForceDt(WorldDt); fServer.fWorld.Simulate; // Maitenance fServer.CheckMaintenanceSchedule; if fServer.fAutoRestart then begin if fServer.fWarnMaint and (MinutesSince(warnTick) > 5) then begin fServer.ReportMaintenanceToIS(fServer.fTimeToMaint); warnTick := Windows.GetTickCount; end; if fServer.fMaintDue then begin fServer.ReportMaintenance('Server down for maintenance', 'Server down for maintenance..', Now + EncodeTime(0, fServer.fLastDowntime + 5, 0, 0)); fServer.SetMSReadyEvent(false); fServer.ReportMaintenanceToIS(0); // Good bye.. Terminate; end; end; if not Terminated and (fServer.ForceBackup or fServer.TheWorld.ForceBackup or (MinutesSince(lstBkTick) > BackupRate)) //(SimCount mod (BackupRate*40*1000 div integer(fServer.fSimTimer.Interval)) = 0) then begin // Wait for file transfer operation uff!! fServer.fIntegrationLock.Enter; try // Create the thread { TBackupThread.Create( fServer, bmdInGame ); fServer.fBackupEv.WaitFor( INFINITE ); } ModelServerCache.InformBackup(true); fServer.OnModelStatusChange( mstBusy ); fServer.TheWorld.WorldLock.Enter; try OldPriority := Priority; Priority := tpHigher; fServer.StoreBackup( bmdInGame, 0 ); Priority := OldPriority; finally fServer.TheWorld.WorldLock.Leave; ModelServerCache.InformBackup(false); if fServer.fBackupError then fServer.OnModelStatusChange( mstError ) else fServer.OnModelStatusChange( mstNotBusy ); end; finally fServer.fIntegrationLock.Leave; fServer.ForceBackup := false; fServer.TheWorld.ForceBackup := false; lstBkTick := Windows.GetTickCount; end; end; if not Terminated and (DateTimeToTimeStamp(Time).time > SimStart) then begin fServer.fBPS := 1000*fServer.fWorld.Facilities.Count div (DateTimeToTimeStamp(Time).time - SimStart); fServer.fCurDt := ITimer(fServer.fWorld).dt; end; end; except end; end; procedure TSimThread.Dispatch(var Message); var msg : TMessage absolute Message; begin case msg.msg of MSG_GETTHREADDATA : begin msg.Result := integer(fThreadInfo); end; MSG_SETTHREADDATA : begin fThreadInfo := pointer(msg.LParam); end; else inherited Dispatch(Message); end; end; {$IFNDEF REMOVETRANSPORT} // TCargoRenderThread type TCargoRenderThread = class( TSmartThread ) public constructor Create( aServer : TModelServer ); private fServer : TModelServer; protected procedure Execute; override; end; constructor TCargoRenderThread.Create( aServer : TModelServer ); begin inherited Create( true ); fServer := aServer; end; procedure TCargoRenderThread.Execute; begin while not Terminated do if fServer.fCargoEv.WaitFor( fServer.fCargoTimer.Interval ) <> wrTimeout then begin Logs.Log( tidLog_Survival, DateTimeToStr(Now) + ' <TRANSPORT' ); fServer.fCargoEv.ResetEvent; try fServer.fWorld.CargoSystem.Render( rqHigh ); except on E : Exception do Logs.Log( tidLog_Survival, DateTimeToStr(Now) + ' ERROR in Cargo Surface: ' + E.Message ); end; Logs.Log( tidLog_Survival, DateTimeToStr(Now) + ' TRANSPORT>' ); end; end; {$ENDIF} // TIntegrationThread type TIntegrationThread = class( TSmartThread ) public constructor Create( aServer : TModelServer ); private fServer : TModelServer; fIntegrationPool : TIntegratorPool; fSurfacePool : TSurfacePool; protected procedure Execute; override; end; constructor TIntegrationThread.Create( aServer : TModelServer ); procedure SetupSurfaceMaps; var i : integer; begin for i := 0 to pred(fSurfacePool.Surfaces.Count) do TSurface(fSurfacePool.Surfaces[i]).SetSize( fServer.fWorld.xSize, fServer.fWorld.ySize ); end; begin inherited Create( true ); fServer := aServer; fIntegrationPool := TIntegratorPool(TheClassStorage.ClassById[tidClassFamily_SurfacePools, tidSurfacePool_Integrators]); fSurfacePool := TSurfacePool(TheClassStorage.ClassById[tidClassFamily_SurfacePools, tidSurfacePool_Surfaces]); Priority := tpIdle; SetupSurfaceMaps; end; procedure TIntegrationThread.Execute; var waitTime : integer; firstInt : boolean; begin waitTime := fServer.fIntTimer.Interval; firstInt := true; fServer.fIntTimer.Interval := InitialWaitTime; Priority := tpHigher; while not Terminated do try if (fServer.fIntEv.WaitFor( waitTime ) <> wrTimeout) and not Terminated then begin if fServer.Integration then begin Logs.Log( tidLog_Survival, DateTimeToStr(Now) + ' <INTEGRATION' ); fServer.fIntegrationLock.Enter; try fServer.fIntEv.ResetEvent; Profiler.ProcStarted( prfKind_Int, prfId_UpdateModifiers ); fSurfacePool.Update; Profiler.ProcEnded( prfKind_Int, prfId_UpdateModifiers ); Profiler.ProcStarted( prfKind_Int, prfId_Integrate ); fIntegrationPool.IntegrateAll; Profiler.ProcEnded( prfKind_Int, prfId_Integrate ); finally fServer.fIntegrationLock.Leave; end; Logs.Log( tidLog_Survival, DateTimeToStr(Now) + ' INTEGRATION>' ); end; fServer.fIntEv.ResetEvent; if firstInt then begin firstInt := false; Priority := IntToThreadPriority(StrToInt(fServer.GetConfigParm('IntSpeed', '0'))); fServer.SetMSReadyEvent(true); end; end; fServer.fIntTimer.Interval := waitTime; except end; end; // TModelServer constructor TModelServer.Create; procedure InitConfig; var filename : string; begin try filename := ExtractFilePath(paramstr(0)) + 'worldconfig.ini'; fConfigInfo := TStringList.Create; if FileExists( filename ) then fConfigInfo.LoadFromFile( filename ); if fConfigInfo.Values['AccountExpires'] <> '' then fAccountExpires := StrToInt( fConfigInfo.Values['AccountExpires'] ) else fAccountExpires := -1; if fConfigInfo.Values['LevelLimit'] <> '' then fLevelLimit := StrToInt( fConfigInfo.Values['LevelLimit'] ) else fLevelLimit := high(fLevelLimit); except end; SetGlobalConfigHandler( self ); end; begin inherited Create; //InitLogs; fExtensionList := TStringList.Create; // >> fBackupEvent := TEvent.Create(nil, true, true, ''); InitConfig; fIntegration := true; fMSReadyEvent := TEvent.Create(nil, true, false, 'ModelServerReady'); end; destructor TModelServer.Destroy; procedure UpdateModelExtensionList; var Reg : TRegistry; i : integer; begin Reg := TRegistry.Create; try Reg.RootKey := HKEY_LOCAL_MACHINE; Reg.DeleteKey( tidRegKey_ModelExtensions ); if Reg.OpenKey( tidRegKey_ModelExtensions, true ) then for i := 0 to pred(fExtensionList.Count) do Reg.WriteString( ExtractFileName(fExtensionList[i]), fExtensionList[i] ) else raise Exception.Create( 'Cannot open Key ' + tidRegKey_ModelExtensions ); finally Reg.Free; end; end; begin try {$IFNDEF REMOVETRANSPORT} // Stop cargo rendering thread if fCargoRenderThread <> nil then begin fCargoRenderThread.Terminate; fCargoEv.SetEvent; WaitForSingleObject( fCargoRenderThread.Handle, 2*fCargoTimer.Interval ); fCargoRenderThread.Free; end; {$ENDIF} // Stop integration thread if fIntegrationThread <> nil then begin fIntegrationThread.Terminate; fIntEv.SetEvent; WaitForSingleObject( fIntegrationThread.Handle, 60000 ); fIntegrationThread.Free; end; // Stop simulation thread if fSimThread <> nil then begin fSimThread.Terminate; fSimEv.SetEvent; WaitForSingleObject( fSimThread.Handle, 60000 ); end; // Free timers and events fTimer.Free; fSimTimer.Free; fIntTimer.Free; fCargoTimer.Free; fSimEv.Free; fBackupEv.Free; fIntEv.Free; // Free world if (fWorld <> nil) and not fBackupError then begin try ModelServerCache.InformBackup(true); try StoreBackup( bmdShutdown, 0 ); finally ModelServerCache.InformBackup(false); end; except MessageBox( 0, 'Could not save world!', 'Backup Error', MB_ICONWARNING or MB_OK ); end; //UpdateModelExtensionList; //fWorld.Free; end; fIntegrationLock.Free; fISProxyLock.Free; fDSProxyLock.Free; fSatRenderComplete.Free; ClassStorage.DoneTheClassStorage; ModelServerCache.DoneModelServerCache; fExtensionList.Free; Kernel.DoneVisualClasses; //DoneLogs; SetGlobalConfigHandler(nil); inherited; except end; end; procedure TModelServer.InitWorld( aName : string; aNotEvent : TBackupReaderNotify; aBaseDir, aCacheHost, aSatellitePath : string; aDAPort, aCSPort, aCCPort : integer; aMailHost : string; aMailPort, aNewsPort : integer ); procedure CreateWorldFromIniFile; var IniFile : TIniFile; Name : string; xSize : integer; ySize : integer; begin IniFile := TIniFile.Create( fBaseDir + aName + '.ini' ); try Name := IniFile.ReadString( tidIniSection_General, tidIniValue_Name, '' ); xSize := IniFile.ReadInteger( tidIniSection_General, tidIniValue_xSize, 0 ); ySize := IniFile.ReadInteger( tidIniSection_General, tidIniValue_ySize, 0 ); if (Name <> '') and (xSize > 0) and (ySize > 0) then fWorld := TPoliticalWorld.Create( Name, xSize, ySize ) else raise Exception.Create( 'Invalid World INI file!' ); finally IniFile.Free; end; end; procedure InitWorldFromIniFile( NotEvent : TBackupReaderNotify ); var MaxLen : integer; procedure CreateRoads( x, y, Length, cellSize : integer; hor : boolean ); procedure CreateRoadSeg( x, y, Length, cellSize, dx, dy : integer ); var ix, iy : integer; finalX : integer; finalY : integer; roads : TCircuitMap; ErrorCode : TErrorCode; count : integer; begin finalX := x + dx*Length*cellSize; finalY := y + dy*Length*cellSize; while finalX < 0 do inc( finalX, cellSize ); while finalY < 0 do inc( finalY, cellSize ); while finalX >= fWorld.xSize do dec( finalX, cellSize ); while finalY >= fWorld.ySize do dec( finalY, cellSize ); while (Length > 0) and (LandClassOf( fWorld.GetGroundMap( finalX, finalY ) ) = lncZoneD) do begin inc( finalX, -cellSize*dx ); inc( finalY, -cellSize*dy ); dec( Length ); end; if (Length > 0) then begin roads := fWorld.CircuitById[cirRoads]; roads.CreateSegment( x, y, finalX, finalY, 1, ErrorCode ); if ErrorCode = NOERROR then begin ix := x; iy := y; if dy = 0 then count := abs(finalX - x) div cellSize else count := abs(finalY - y) div cellSize; while (count > 0) do begin inc( ix, cellSize*dx ); inc( iy, cellSize*dy ); if dy = 0 then CreateRoads( ix, iy, abs(ix - x) div cellSize, cellSize, false ) else CreateRoads( ix, iy, abs(iy - y) div cellSize, cellSize, true ); dec( count ); end; end; end; end; begin if (Length > 0) and (random(MaxLen - Length) <= (MaxLen - Length) div 2) then begin if hor then begin CreateRoadSeg( x, y, Length div 2, cellSize, -1, 0 ); CreateRoadSeg( x, y, Length div 2, cellSize, 1, 0 ); end else begin CreateRoadSeg( x, y, Length div 2, cellSize, 0, -1 ); CreateRoadSeg( x, y, Length div 2, cellSize, 0, 1 ); end end; fWorld.InvalidateRoads; end; procedure InitTowns( IniFile : TIniFile ); var count : integer; i : integer; x, y : integer; Name : string; Cluster : string; Town : TTown; begin count := IniFile.ReadInteger( tidIniSection_WorldTowns, tidIniValue_TownCount, 0 ); MaxLen := min( 30, max( 15, 30 - 2*count ) ); for i := 0 to pred(count) do begin Name := IniFile.ReadString( tidIniSection_WorldTowns, tidIniValue_TownName + IntToStr(i), '' ); Cluster := IniFile.ReadString( tidIniSection_WorldTowns, tidIniValue_TownCluster + IntToStr(i), '' ); x := IniFile.ReadInteger( tidIniSection_WorldTowns, tidIniValue_TownX + IntToStr(i), -1 ); y := IniFile.ReadInteger( tidIniSection_WorldTowns, tidIniValue_TownY + IntToStr(i), -1 ); if (Name <> '') and (Cluster <> '') and (x >= 0) and (y >= 0) then begin NotEvent( 'Initializing town: ' + Name + '...', 100*(i + 1) div count ); Town := TPoliticalTown.Create( Name, Cluster, Cluster + 'TownHall', Cluster + 'TradeCenter', x, y, fWorld ); fWorld.InsertTown( Town ); CacheObject( Town, noKind, noInfo ); CreateRoads( x - 1, y - 1, MaxLen, 7, true ); CreateRoads( x - 1, y - 1, MaxLen, 7, false ); end else raise Exception.Create( 'Invalid Town INI info (' + IntToStr(i) + ')' ); end; // fWorld.InitTownMap; end; var IniFile : TIniFile; begin NotEvent( 'Opening INI file...', 0 ); IniFile := TIniFile.Create( fBaseDir + aName + '.ini' ); try fWorld.Loaded( NotEvent ); NotEvent( 'Initializing clusters...', 0 ); fWorld.InitClusters; NotEvent( 'Initializing towns...', 0 ); InitTowns( IniFile ); fWorld.TycoonsToPurge := fTycconsToPurge; finally IniFile.Free; end; end; procedure StoreMetaTexts; procedure StoreInvClientInfo( LangId : TLanguageId ); var i, count : integer; Inv : TInvention; Stream : TFileStream; Cats : TStringList; resp : string; idx : integer; j : integer; begin Stream := TFileStream.Create( 's:\temp\language\research.' + LangId + '.dat', fmCreate ); Cats := TStringList.Create; try count := TheClassStorage.ClassCount[tidClassFamily_Inventions]; Stream.Write( count, sizeof(count) ); for i := 0 to pred(count) do begin Inv := TInvention(TheClassStorage.ClassByIdx[tidClassFamily_Inventions, i]); Inv.StoreClientInfo( Stream, LangId ); resp := UpperCase(Inv.Resp_MLS.Values[LangId]); idx := Cats.IndexOf(resp); if (idx = -1) and (Inv.Id <> '') then begin j := 0; while (j < Cats.Count) and (TInvention(Cats.Objects[j]).CatPos < Inv.CatPos) do inc(j); if j < Cats.Count then Cats.InsertObject(j, resp, Inv) else Cats.AddObject(resp, Inv); end; end; DelphiStreamUtils.WriteString(Stream, Cats.Text); finally Stream.Free; end end; var SimDict : TDictionary; i : integer; begin SimDict := Languages.CreateDictionary; try SimDict.Store( 'S:\Temp\Language\sim.lang' ); finally SimDict.Free; end; //MetaInstances.StoreTexts( tidClassFamily_Facilities, 'S:\Temp\Language\metafacilities.lang' ); //MetaInstances.StoreTexts( tidClassFamily_Fluids, 's:\temp\language\metafluids.lang' ); //MetaInstances.StoreTexts( tidClassFamily_Ratings, 's:\temp\language\metaratings.lang' ); //MetaInstances.StoreTexts( tidClassFamily_Projects, 's:\temp\language\metaprojects.lang' ); //MetaInstances.StoreTexts( tidClassFamily_PublicFacilities, 's:\temp\language\metapublic.lang' ); //MetaInstances.StoreTexts( tidClassFamily_Accounts, 's:\temp\language\metaaccounts.lang' ); //MetaInstances.StoreTexts( tidClassFamily_Services, 's:\temp\language\metacommerce.lang' ); //MetaInstances.StoreTexts( tidClassFamily_Ministries, 's:\temp\language\metaministries.lang' ); //MetaInstances.StoreTexts( tidClassFamily_FacilityKinds, 's:\temp\language\metakinds.lang' ); //MetaInstances.StoreTexts( tidClassFamily_TycoonLevels, 's:\temp\language\metalevels.lang' ); //MetaInstances.StoreTexts( tidClassFamily_Inventions, 's:\temp\language\metaresearch.lang' ); for i := 0 to pred(LangList.Count) do begin StoreInvClientInfo(LangList[i]); //MetaInstances.StoreMissingTexts( tidClassFamily_Inventions, 'S:\Temp\Language\metaresearch.missing.' + LangList[i] + '.lang', LangList[i] ); end; end; procedure LoadMetaTexts; procedure LoadLanguage( path : string; LangId : TLanguageId ); var Rec : TSearchRec; found : integer; begin path := path + 'ms\' +LangId + '\'; found := FindFirst( path + '*.lang', faAnyFile, Rec ); try while found = 0 do begin MetaInstances.RetrieveTexts( path + Rec.Name ); found := FindNext( Rec ); end; finally FindClose( Rec ); end; end; var i : integer; begin for i := 0 to pred(LangList.Count) do LoadLanguage( ExtractFilePath(paramstr(0)) + 'Languages\', LangList[i] ); end; function GetBackupFilePath : string; var Reg : TRegistry; str : string; begin if ParamStr(1) <> '' then begin Reg := TRegistry.Create; try Reg.RootKey := HKEY_LOCAL_MACHINE; if Reg.OpenKey(tidRegKey_ModelServer, false) then begin str := Reg.ReadString('LastGoodBackup'); if str <> '' then result := fBaseDir + str else result := fBaseDir + aName + '.world' end else raise Exception.Create( 'Cannot open Key ' + tidRegKey_ModelServer); finally Reg.Free; end; end else result := fBaseDir + aName + '.world' end; var Reader : IBackupReader; WorldURL : string; UseBackup : boolean; LogFile : string; bckFile : string; begin Log( 'Survival', TimeToStr( Now ) + ' WORLD LOADED' ); RandSeed := 100; fDAPort := aDAPort; fDALockPort := aDAPort + 1; fLocalHost := GetLocalAddress; fSatelliteMapPath := aSatellitePath + '\' + aName + '\'; // Create the world if aBaseDir[length(aBaseDir)] <> '\' then fBaseDir := aBaseDir + '\' else fBaseDir := aBaseDir; Log( 'Survival', TimeToStr( Now ) + ' Registering at Cache Server...' ); if not ModelServerCache.RegisterWorld( aName, aCacheHost, aCSPort, aCCPort, WorldURL ) then raise Exception.Create( 'Cannot register world in cache server side' ); Log( 'Survival', TimeToStr( Now ) + ' Registering at Cache Server Sucessfull.' ); ModelServerCache.InitModelServerCache; ClassStorage.InitTheClassStorage; Kernel.InitVisualClasses; aNotEvent( 'Readying multilanguage support...', 0 ); Log( 'Survival', TimeToStr( Now ) + ' Reading language files...' ); SimMLS.LoadMLS; Log( 'Survival', TimeToStr( Now ) + ' Reading language files done.' ); aNotEvent( 'Registering Basic Metainstances...', 0 ); Log( 'Survival', TimeToStr( Now ) + ' Registering Basic Metainstances...' ); BasicAccounts.RegisterAccounts; Kernel.RegisterSurfaces; Population.RegisterSurfaces; StdBroadcast.RegisterSurfaces; KernelCache.RegisterCachers; PoliticsCache.RegisterCachers; Rankings.RegisterCachers; Newspapers.RegisterCachers; Population.RegisterMetaFluids; Population.RegisterMetaInstances; StdFluids.RegisterMetaFluids; TycoonLevels.RegisterLevels; VCLBackup.RegisterBackup; Languages.RegisterBackup; CollectionBackup.RegisterBackup; Kernel.RegisterBackup; Accounts.RegisterBackup; BasicTaxes.RegisterBackup; BasicCurriculum.RegisterBackup; World.RegisterBackup; ConnectedBlock.RegisterBackup; Population.RegisterBackup; Politics.RegisterBackup; BasicPolitics.RegisterBackup; TownPolitics.RegisterBackup; WorldPolitics.RegisterBackup; Ministers.RegisterBackup; OfficeBlock.RegisterBackup; ResearchCenter.RegisterBackup; Headquarters.RegisterBackup; Broadcast.RegisterBackup; Trade.RegisterBackup; Construction.RegisterBackup; PopulatedBlock.RegisterBackup; WorkCenterBlock.RegisterBackup; Surfaces.RegisterBackup; Circuits.RegisterBackup; PyramidalModifier.RegisterBackup; PublicFacility.RegisterBackup; SpontaneousBuildings.RegisterBackup; Banks.RegisterBackup; LargeMatrix.RegisterBackup; Events.RegisterBackup; BasicEvents.RegisterBackup; MatrixCircuits.RegisterBackup; TranscendBlock.RegisterBackup; MediaGates.RegisterBackup; MediaNameHistory.RegisterBackup; EconomyRelay.RegisterBackup; TycoonVotes.RegisterBackup; Favorites.RegisterBackup; // Register Invention Classes EvaluatedBlock.RegisterInventionClass; PopulatedBlock.RegisterInventionClass; Broadcast.RegisterInventionClass; //ServiceBlock.RegisterInventionClass; fDSProxyLock := TCriticalSection.Create; WorldPolitics.RegisterCapitol; Log( 'Survival', TimeToStr( Now ) + ' Loading extensions...' ); LoadExtensions( aNotEvent ); Log( 'Survival', TimeToStr( Now ) + ' Loading extensions complete.' ); Kernel.RegisterTownParameters; Population.RegisterTownParameters; PopulatedBlock.RegisterTownParameters; BasicPolitics.RegisterPolitics; WorldPolitics.RegisterPolitics; Broadcast.RegisterTownParameters; // >> REM Tutorial.RegisterTasks; Tasks.RegisterBackup; Tutorial.RegisterBackup; ModelServerCache.EnabledLogs := false; // Register Taxes Log( 'Survival', TimeToStr( Now ) + ' Registering taxes...' ); StdTaxes.RegisterTaxes; Log( 'Survival', TimeToStr( Now ) + ' Registering taxes complete.' ); Log( 'Survival', TimeToStr( Now ) + ' Loading meta texts...' ); aNotEvent( 'Loading texts...', 0 ); LoadMetaTexts; Log( 'Survival', TimeToStr( Now ) + ' Loading meta texts complete.' ); // Evaluate texts Log( 'Survival', TimeToStr( Now ) + 'Evaluating texts...' ); EvaluateTexts( tidClassFamily_Fluids ); EvaluateTexts( tidClassFamily_FacilityKinds ); EvaluateTexts( tidClassFamily_Blocks ); EvaluateTexts( tidClassFamily_Services ); EvaluateTexts( tidClassFamily_FacilityKinds ); EvaluateTexts( tidClassFamily_Facilities ); EvaluateTexts( tidClassFamily_Taxes ); Log( 'Survival', TimeToStr( Now ) + 'Evaluating texts complete.' ); // Post register politics WorldPolitics.PostRegisterPolitics; // Register Taxes Log( 'Survival', TimeToStr( Now ) + ' Registering taxes...' ); StdTaxes.RegisterTaxesToAccounts; Log( 'Survival', TimeToStr( Now ) + ' Registering taxes complete.' ); EvaluateTexts( tidClassFamily_Accounts ); StdRankings.RegisterRankings; // Cache meta-facilities Log( 'Survival', TimeToStr( Now ) + 'Caching metainstances...' ); CloneFamily( tidClassFamily_FacilityKinds ); CacheFamily( tidClassFamily_FacilityKinds ); CloneFamily( tidClassFamily_Facilities ); CacheFamily( tidClassFamily_Facilities ); CloneFamily( tidClassFamily_Services ); CacheFamily( tidClassFamily_Services ); Log( 'Survival', TimeToStr( Now ) + 'Caching metainstances complete.' ); bckFile := GetBackupFilePath; UseBackup := FileExists(bckFile{fBaseDir + aName + '.world'}); if UseBackup then begin aNotEvent( 'Preparing to read world...', 0 ); Reader := OpenBackup(bckFile{fBaseDir + aName + '.world'}, aNotEvent); Log( 'Survival', TimeToStr( Now ) + 'Reading world...' ); Reader.ReadObject( 'World', fWorld, nil ); fCacheLogVer := Reader.ReadInteger('CacheLogVer', 0); Log( 'Survival', TimeToStr( Now ) + 'Reading world complete.' ); Reader := nil; fWorld.DirProxyLock := fDSProxyLock; end else CreateWorldFromIniFile; if fCacheLogVer <= 0 then fCacheLogVer := MSVersion; LogFile := fBaseDir + aName + '.cache'; try ModelServerCache.SetLogPath(LogFile); ModelServerCache.WarpLog(fCacheLogVer - 1); finally DeleteFile(LogFile); end; ModelServerCache.SetLogVer(fCacheLogVer); Log( 'Survival', TimeToStr( Now ) + ' Loading map info...' ); fWorld.LoadLandInfo( fBaseDir + aName + '.bmp' ); Log( 'Survival', TimeToStr( Now ) + ' Loading map info OK.' ); Log( 'Survival', TimeToStr( Now ) + ' Loading town map...' ); //fWorld.InitTownMap( fBaseDir + aName + '.towns.bmp' ); Log( 'Survival', TimeToStr( Now ) + ' Loading town map OK.' ); // Set Cache options fWorld.CacheOptions := CacheOptions; // Set World base URL fWorld.WorldURL := WorldURL; // Start RDO servers StartDirectAccessServer( aDAPort ); StartCacheServer( aCSPort ); // Start Mail Server InitMailServer( aMailHost, aMailPort, aName ); // Start News Server InitNewsServer( aMailHost, aNewsPort, aName ); // Create new world after Mail and RDO servers are running if not UseBackup then begin InitWorldFromIniFile( aNotEvent ); Log( 'Survival', TimeToStr( Now ) + 'Initializing Town Map...' ); fWorld.InitTownMap( fBaseDir + aName + '.towns.bmp' ); LoadWorldExtensions( fWorld, aNotEvent, false ); end else begin Log( 'Survival', TimeToStr( Now ) + 'Initializing Town Map...' ); fWorld.InitTownMap( fBaseDir + aName + '.towns.bmp' ); Log( 'Survival', TimeToStr( Now ) + 'Initializing model objects...' ); fWorld.Loaded( aNotEvent ); Log( 'Survival', TimeToStr( Now ) + 'Initializing model objects complete.' ); LoadWorldExtensions( fWorld, aNotEvent, true ); end; CacheObject( fWorld, noKind, noInfo ); ModelServerCache.EnabledLogs := true; // Init Simulation clockwork fTimer := TTimer.Create( nil ); fSimTimer := TTimer.Create( nil ); fIntTimer := TTimer.Create( nil ); fCargoTimer := TTimer.Create( nil ); fSimEv := TEvent.Create( nil, true, false, '' ); fBackupEv := TEvent.Create( nil, true, false, '' ); fIntEv := TEvent.Create( nil, true, false, '' ); fCargoEv := TEvent.Create( nil, true, false, '' ); fSatRenderComplete := TEvent.Create( nil, true, false, '' ); fSimThread := TSimThread.Create( true ); //fSimThread.Priority := tpLower; //tpHigher; TSimThread(fSimThread).fServer := self; fTimer.OnTimer := OnTimer; fSimTimer.OnTimer := OnSimTimer; fIntTimer.OnTimer := OnIntTimer; fCargoTimer.OnTimer := OnCargoTimer; fCargoTimer.Interval := 12*180000; SetTimeRes(2*2400, 2*2400, 5*60*1000); // SetTimeRes( 2*2400, 2*2400, 4*120000 ); fSimThread.Priority := IntToThreadPriority(StrToInt(GetConfigParm('SimSpeed','3'))); // SimSpeed; fSimThread.Resume; // Init Integration thread fIntegrationThread := TIntegrationThread.Create( self ); fIntegrationLock := TCriticalSection.Create; fISProxyLock := TCriticalSection.Create; fDSProxyLock := TCriticalSection.Create; fIntegrationThread.Priority := IntToThreadPriority(StrToInt(GetConfigParm('IntSpeed', '0'))); //tpIdle; fIntegrationThread.Resume; {$IFNDEF REMOVETRANSPORT} // Init cargo render thread fCargoRenderThread := TCargoRenderThread.Create( self ); fCargoRenderThread.Priority := IntToThreadPriority(StrToInt(GetConfigParm('TransSpeed', '0'))); //tpLowest fCargoRenderThread.Resume; {$ENDIF} // Update land surfaces Kernel.UpdateLandSurfaces( fWorld ); aNotEvent( 'Done.', 0 ); // Assign RegisterIS fWorld.OnRegisterIS := InitInterfaceServerEvents; // Storing texts //Log( 'Survival', TimeToStr( Now ) + ' Storing texts...' ); //StoreMetaTexts; //Log( 'Survival', TimeToStr( Now ) + ' Storing texts complete.' ); // Satellite Log( 'Survival', TimeToStr( Now ) + ' Creating satellite map...' ); CreateSatelliteMaps; Log( 'Survival', TimeToStr( Now ) + ' Creating satellite map complete.' ); // Servers Start Listening fDAConn.StartListening; fDALockConn.StartListening; // Downtime CalculateDownTime; end; procedure TModelServer.StartCacheServer( aCSPort : integer ); var ServerConn : TWinSockRDOConnectionsServer; CacheSpeed : TThreadPriority; begin CacheSpeed := IntToThreadPriority(StrToInt(GetConfigParm('CacheSpeed','3'))); ServerConn := TWinSockRDOConnectionsServer.Create(aCSPort, CacheSpeed); try ModelServerCache.CreateCacheServer( ServerConn, 3{5}, fWorld.WorldLock ); ModelServerCache.MSCacher.OnRenewCache := RenewCache; except ServerConn.Free; raise; end; end; procedure TModelServer.StartDirectAccessServer( aDAPort : integer ); var DASpeed : TThreadPriority; begin DASpeed := IntToThreadPriority(StrToInt(GetConfigParm('DASpeed','3'))); fDAConn := TWinSockRDOConnectionsServer.Create(aDAPort, DASpeed); // >> 100 fDAServ := TRDOServer.Create(fDAConn as IRDOServerConnection, 8{14}, nil); fDALockConn := TWinSockRDOConnectionsServer.Create(aDAPort + 1, DASpeed); // >> 20 fDALockServ := TRDOServer.Create(fDALockConn as IRDOServerConnection, 1, nil); fDAServ.RegisterObject(tidRDOHook_World, integer(fWorld)); //fDAConn.StartListening; fDALockServ.RegisterObject(tidRDOHook_World, integer(fWorld)); //fDALockConn.StartListening; fDALockServ.SetCriticalSection(fWorld.WorldLock); end; procedure TModelServer.InitInterfaceServerEvents( ServerName : string; ServerPort : integer ); begin fISConn := TWinSockRDOConnection.Create( 'ISCnx' ); fISConn.Server := ServerName; fISConn.Port := ServerPort; if fISConn.Connect( 10000 ) then begin fISEvents := TRDOObjectProxy.Create as IDispatch; fISEvents.SetConnection( fISConn ); if fISEvents.BindTo(tidRDOHook_InterfaceEvents) then begin //fISEvents.WaitForAnswer := false; fWorld.OnAreaChanged := OnAreaChanged; fWorld.OnFacilityChanged := OnFacilityChanged; fWorld.OnDateChanged := OnDateChanged; fWorld.OnSeasonChanged := OnSeasonChanged; fWorld.OnTycoonsChanged := OnTycoonsChanged; fWorld.OnEndOfPeriod := OnEndOfPeriod; fWorld.OnTycoonRetired := OnTycoonRetired; //fWorld.OnPoolActed := OnPoolActed; fWorld.OnSendNotification := OnSendNotification; fWorld.OnModelStatusChange := OnModelStatusChange; (fISConn as IRDOConnection).OnDisconnect := OnISDisconnect; end else raise Exception.Create( '' ); end else raise Exception.Create( '' ); end; procedure TModelServer.InitMailServer( ServerName : string; ServerPort : integer; WorldName : string ); var ClientId : integer; begin fMailConn := TWinSockRDOConnection.Create( 'MailCnx' ); fMailConn.Server := ServerName; fMailConn.Port := ServerPort; fMailServer := TRDOObjectProxy.Create as IDispatch; if fMailConn.Connect(10000) then begin fMailServer.TimeOut := 20000; (fMailConn as IRDOConnection).OnDisconnect := OnMailDisconnect; fMailServer.SetConnection(fMailConn); if fMailServer.BindTo(tidRDOHook_MailServer) then begin fMailId := fMailServer.RegisterWorld(WorldName); if fMailId <> 0 then begin fMailServer.BindTo(fMailId); ClientId := fMailServer.RDOCnntId; if fMailServer.SetDAConnectionById(ClientId) //SetDAConnection((fMailConn as IRDOConnection).LocalAddress, fDALockPort) then begin if fMailServer.BindTo(tidRDOHook_MailServer) then fWorld.MailServer := self else begin fMailConn := nil; fMailServer := Unassigned; end end else begin //raise Exception.Create( '' ); fMailConn := nil; fMailServer := Unassigned; end; end else begin //raise Exception.Create( '' ); fMailConn := nil; fMailServer := Unassigned; end; end else begin fMailConn := nil; fMailServer := Unassigned; end; end else begin fMailConn := nil; //raise Exception.Create( '' ); fMailServer := Unassigned; end; end; procedure TModelServer.InitNewsServer( ServerName : string; ServerPort : integer; WorldName : string ); var i : integer; begin fNewsConn := TWinSockRDOConnection.Create( 'NewsCnx' ); fNewsConn.Server := ServerName; fNewsConn.Port := ServerPort; fNewsServer := TRDOObjectProxy.Create as IDispatch; if fNewsConn.Connect( 10000 ) then begin (fNewsConn as IRDOConnection).OnDisconnect := OnNewsDisconnect; fNewsServer.SetConnection( fNewsConn ); if fNewsServer.BindTo(tidRDOHook_NewsServer) then begin fWorld.NewsServer := self; for i := 0 to pred(LangList.Count) do fNewsServer.RDOCreateNewsCenter( WorldName, fLocalHost, fDALockPort, LangList[i] ); end else begin fNewsConn := nil; fNewsServer := Unassigned; end; end else begin //raise Exception.Create( '' ); fNewsConn := nil; fNewsServer := Unassigned; end; end; procedure TModelServer.InitDirServer( AreaName, ServerName : string; ServerPort : integer ); var session : integer; begin fDSProxyLock.Enter; try fDirConn := TWinSockRDOConnection.Create( 'DSCnx' ); fDirConn.Server := ServerName; fDirConn.Port := ServerPort; fDirServer := TRDOObjectProxy.Create as IDispatch; if fDirConn.Connect( 60000 ) then begin (fDirConn as IRDOConnection).OnDisconnect := OnDSDisconnect; fDirServer.SetConnection( fDirConn ); if fDirServer.BindTo('DirectoryServer') then begin fDirServer.TimeOut := 20000; session := fDirServer.RDOOpenSession; end else session := 0; if session <> 0 then begin fDirServer.BindTo( session ); fDirServer.RDOSetExpires(false); fWorld.DirProxy := fDirServer; fWorld.Area := AreaName; end else begin fDirConn := nil; fDirServer := Unassigned; fWorld.DirProxy := Unassigned; raise Exception.Create( '' ); end; end else begin fDirConn := nil; fDirServer := Unassigned; fWorld.DirProxy := Unassigned; raise Exception.Create( '' ); end; finally fDSProxyLock.Leave; end; end; procedure TModelServer.SetPurgeTyccons(count : integer); begin fTycconsToPurge := count; if fWorld <> nil then fWorld.TycoonsToPurge := count; end; type PMDXNode = ^TMDXNode; TMDXNode = record Id : string; MDX : THandle; Depends : TStringList; SubNodes : TCollection; registered : boolean; postregistered : boolean; worldregistered : boolean; end; function TModelServer.GetHoursADay : integer; begin if TheWorld <> nil then result := round(TheWorld.HoursADay) else result := 0; end; procedure TModelServer.LoadExtensions( Notify : TBackupReaderNotify ); var mdxI : integer; mdxCount : integer; { function GetMDXsFilenames : TStringList; var Reg : TRegistry; Values : TStrings; i : integer; begin result := TStringList.Create; Reg := TRegistry.Create; try Reg.RootKey := HKEY_LOCAL_MACHINE; if Reg.OpenKey( tidRegKey_ModelExtensions, false ) then begin Values := TStringList.Create; Reg.GetValueNames( Values ); for i := 0 to pred(Values.Count) do result.Add( Reg.ReadString( Values[i] )); Values.Free; end; finally Reg.Free; end; end; } function GetMDXsFilenames : TStringList; var path : string; SearchRec : TSearchRec; found : integer; begin result := TStringList.Create; path := ExtractFilePath( paramstr(0) ); found := FindFirst( path + '*.mdx', faArchive, SearchRec ); try while found = 0 do begin result.Add( path + SearchRec.Name ); found := FindNext( SearchRec ); end; finally FindClose( SearchRec ); end; end; function LoadMDXs( filenames : TStringList ) : TCollection; var i : integer; Node : PMDXNode; begin mdxI := 0; mdxCount := 3*filenames.Count; result := TCollection.Create( 0, rkUse ); for i := 0 to pred(filenames.Count) do try Notify( 'Loading Model extensions...', 100*succ(mdxI) div mdxCount ); inc( mdxI ); new( Node ); Node.MDX := LoadLibrary( pchar(filenames[i] )); Node.Id := GetMDXId( Node.MDX ); Node.Depends := GetMDXDependances( Node.MDX ); Node.SubNodes := TCollection.Create( 0, rkUse ); Node.registered := false; Node.postregistered := false; Node.worldregistered := false; result.Insert( TObject(Node) ); except raise Exception.Create( 'Could not load MDX: ' + filenames[i] ) end; end; function FindMDXNode( MDXNodes : TCollection; MDXId : string ) : PMDXNode; var i : integer; begin i := 0; while (i < MDXNodes.Count) and (PMDXNode(MDXNodes[i]).Id <> MDXId) do inc( i ); if i < MDXNodes.Count then result := PMDXNode(MDXNodes[i]) else result := nil; end; procedure BuildMDXTree( MDXNodes : TCollection ); var i, j : integer; MDXNode : PMDXNode; SuperMDXNode : PMDXNode; begin for i := 0 to pred(MDXNodes.Count) do begin MDXNode := PMDXNode(MDXNodes[i]); for j := 0 to pred(MDXNode.Depends.Count) do begin SuperMDXNode := FindMDXNode( MDXNodes, MDXNode.Depends[j] ); if SuperMDXNode <> nil then SuperMDXNode.SubNodes.Insert( TObject(MDXNode) ); end; end; end; procedure RegisterMDXTree( MDXRootNode : PMDXNode ); var i : integer; begin if not MDXRootNode.registered then begin Notify( 'Registering extension: ' + MDXRootNode.Id + '...', 100*succ(mdxI) div mdxCount ); inc( mdxI ); RegisterMDX( MDXRootNode.MDX ); MDXRootNode.registered := true; for i := 0 to pred(MDXRootNode.SubNodes.Count) do RegisterMDXTree( PMDXNode(MDXRootNode.SubNodes[i]) ); end; end; procedure RegisterMDXNodes( MDXNodes : TCollection ); var i : integer; begin for i := 0 to pred(MDXNodes.Count) do begin if PMDXNode(MDXNodes[i]).Depends.Count = 0 then RegisterMDXTree( PMDXNode(MDXNodes[i]) ) end; end; procedure PostRegisterMDXTree( MDXRootNode : PMDXNode ); var i : integer; begin if not MDXRootNode.postregistered then begin Notify( 'Post-registering extension: ' + MDXRootNode.Id + '...', 100*succ(mdxI) div mdxCount ); inc( mdxI ); PostRegisterMDX( MDXRootNode.MDX ); MDXRootNode.postregistered := true; for i := 0 to pred(MDXRootNode.SubNodes.Count) do PostRegisterMDXTree( PMDXNode(MDXRootNode.SubNodes[i]) ); end; end; procedure PostRegisterMDXNodes( MDXNodes : TCollection ); var i : integer; begin for i := 0 to pred(MDXNodes.Count) do begin if PMDXNode(MDXNodes[i]).Depends.Count = 0 then PostRegisterMDXTree( PMDXNode(MDXNodes[i]) ) end; end; procedure DisposeMDXNodes( MDXNodes : TCollection ); var i : integer; MDXNode : PMDXNode; begin for i := 0 to pred(MDXNodes.Count) do begin MDXNode := PMDXNode(MDXNodes[i]); MDXNode.Depends.Free; MDXNode.SubNodes.Free; dispose( MDXNode ); end; end; begin fMDXNodes := LoadMDXs( GetMDXsFilenames ); BuildMDXTree( fMDXNodes ); RegisterMDXNodes( fMDXNodes ); Inventions.CreateInventions(ExtractFilePath(ParamStr(0)) + 'Inventions\'); PostRegisterMDXNodes( fMDXNodes ); end; procedure TModelServer.LoadWorldExtensions( World : TWorld; Notify : TBackupReaderNotify; WorldLoaded : boolean ); procedure RegisterWorldMDXTree( MDXRootNode : PMDXNode ); var i : integer; begin if not MDXRootNode.worldregistered then begin Notify( 'Including World extensions from: ' + MDXRootNode.Id + '...', 0 ); RegisterWorldMDX( MDXRootNode.MDX, World, WorldLoaded ); MDXRootNode.worldregistered := true; for i := 0 to pred(MDXRootNode.SubNodes.Count) do RegisterWorldMDXTree( PMDXNode(MDXRootNode.SubNodes[i]) ); end; end; procedure RegisterWorldMDXNodes( MDXNodes : TCollection ); var i : integer; begin for i := 0 to pred(MDXNodes.Count) do begin if PMDXNode(MDXNodes[i]).Depends.Count = 0 then RegisterWorldMDXTree( PMDXNode(MDXNodes[i]) ) end; end; procedure RegisterExtensionsInRDO; var i : integer; id : string; begin for i := 0 to pred(World.WorldExtensions.Count) do begin id := TWorldExtension(World.WorldExtensions[i]).GetId; fDAServ.RegisterObject( id, integer(World.WorldExtensions[i]) ); fDALockServ.RegisterObject( id, integer(World.WorldExtensions[i]) ); end; end; begin RegisterWorldMDXNodes( fMDXNodes ); RegisterExtensionsInRDO; end; procedure TModelServer.SetTimeRes( aVirtTimeRate, aSimRate, anIntRate : integer ); begin fTimer.Interval := aVirtTimeRate; fSimTimer.Interval := aSimRate; fIntTimer.Interval := anIntRate; end; procedure TModelServer.OnTimer( Sender : TObject ); begin fWorld.VirtualTimeTick( 1 ); end; procedure TModelServer.OnSimTimer( Sender : TObject ); begin fSimEv.SetEvent; end; procedure TModelServer.OnIntTimer( Sender : TObject ); begin fIntEv.SetEvent; end; procedure TModelServer.OnCargoTimer( Sender : TObject ); begin fCargoEv.SetEvent; end; procedure TModelServer.OnAreaChanged( x, y, dx, dy : integer ); begin try fISProxyLock.Enter; try if not VarIsEmpty(fISEvents) then fISEvents.RefreshArea( x, y, dx, dy ); finally fISProxyLock.Leave; end; except end; end; procedure TModelServer.OnFacilityChanged( Facility : TFacility; FacilityChange : TFacilityChange ); begin try fISProxyLock.Enter; try if not VarIsEmpty(fISEvents) then fISEvents.RefreshObject( integer(Facility), integer(FacilityChange) ); finally fISProxyLock.Leave; end; except end; end; procedure TModelServer.OnTycoonsChanged; begin try fISProxyLock.Enter; try if not VarIsEmpty(fISEvents) then fISEvents.RefreshTycoons( 0 ); finally fISProxyLock.Leave; end; except end; end; procedure TModelServer.OnDateChanged( Date : TDateTime ); begin try fISProxyLock.Enter; try if not VarIsEmpty(fISEvents) then fISEvents.RefreshDate( Date ); finally fISProxyLock.Leave; end; except end; end; procedure TModelServer.OnSeasonChanged( Season : TSeason ); begin try fISProxyLock.Enter; try if not VarIsEmpty(fISEvents) then fISEvents.RefreshSeason( integer(Season) ); finally fISProxyLock.Leave; end; except end; end; procedure TModelServer.OnEndOfPeriod( PeriodType : TPeriodType; PeriodCount : integer ); begin try if TheWorld.ForceReconnect then begin InitNewsServer( fNewsConn.Server, fNewsConn.Port, TheWorld.Name ); InitDirServer( fWorld.Area, fDirConn.Server, fDirConn.Port ); TheWorld.ForceReconnect := false; end; fISProxyLock.Enter; try if (PeriodType = perYear) and not VarIsEmpty(fISEvents) then fISEvents.EndOfPeriod( 0 ); finally fISProxyLock.Leave; end; except end; end; procedure TModelServer.OnTycoonRetired( name : string ); begin try fISProxyLock.Enter; try if not VarIsEmpty(fISEvents) then fISEvents.TycoonRetired( name ); finally fISProxyLock.Leave; end; except end; end; { procedure TModelServer.OnPoolActed( PoolId : TActorPoolId; ViewerId : TViewerId; TickCount : cardinal; TickData : TStream ); var TickDataStr : string; begin try fISProxyLock.Enter; try if not VarIsEmpty(fISEvents) then begin TickDataStr := StreamToString( TickData ); fISEvents.SendTickData( integer(PoolId), integer(ViewerId), integer(TickCount), widestring(TickDataStr) ); end; finally fISProxyLock.Leave; end; except end; end; } procedure TModelServer.OnSendNotification( TycoonId : integer; Kind : integer; Title, Body : string; Options : integer ); begin try fISProxyLock.Enter; try if not VarIsEmpty(fISEvents) then fISEvents.SendNotification( TycoonId, Kind, widestring(Title), widestring(Body), Options ); finally fISProxyLock.Leave; end; except end; end; procedure TModelServer.OnModelStatusChange( status : integer ); begin try fISProxyLock.Enter; try if not VarIsEmpty(fISEvents) then begin fISEvents.WaitForAnswer := true; try fISEvents.ModelStatusChanged( status ); finally fISEvents.WaitForAnswer := false; end; end; finally fISProxyLock.Leave; end; except end; end; procedure TModelServer.OnISDisconnect( const ClientConnection : IRDOConnection ); begin try fISProxyLock.Enter; try fISEvents := Unassigned; finally fISProxyLock.Leave; end; except end; end; procedure TModelServer.OnDSDisconnect( const ClientConnection : IRDOConnection ); begin try fDSProxyLock.Enter; try fDirConn := nil; fDirServer := Unassigned; fWorld.DirProxy := Unassigned; finally fDSProxyLock.Leave; end; except end; end; procedure TModelServer.OnMailDisconnect( const ClientConnection : IRDOConnection ); begin try fMailConn := nil; fMailServer := Unassigned; except end; end; procedure TModelServer.OnNewsDisconnect( const ClientConnection : IRDOConnection ); begin try fNewsConn := nil; fNewsServer := Unassigned; except end; end; procedure TModelServer.StoreBackup( mode : TBackupMode; ErrorLevel : integer ); const MaxBackupRetries = 2; var Writer : IBackupWriter; filename : string; begin try fWorld.StopVirtualTime; try case mode of bmdShutdown : begin fWorld.SplitBackup := false; try filename := fWorld.Name + '.world'; Writer := CreateBackup( fBaseDir + filename, false, nil ); try Writer.WriteObject( 'World', fWorld ); Writer.WriteInteger('CacheLogVer', fCacheLogVer); inc(fCacheLogVer); ModelServerCache.SetLogVer(fCacheLogVer); finally Writer := nil; end; RegisterLastGoodBackup(filename); except end; try filename := fWorld.Name + '.verb'; Writer := CreateBackup( fBaseDir + filename, true, nil ); try Writer.WriteObject( 'World', fWorld ); Writer.WriteInteger('CacheLogVer', fCacheLogVer); inc(fCacheLogVer); ModelServerCache.SetLogVer(fCacheLogVer); finally Writer := nil; end; except end; end; else begin //OnModelStatusChange( mstBusy ); Application.ProcessMessages; try if fLastBackup < 20 // 100 then inc( fLastBackup ) else fLastBackup := 1; if not fBackupError then filename := fWorld.Name + '.' + IntToStr( fLastBackup ) + '.back' else filename := fWorld.Name + '.ERROR.' + IntToStr( fLastBackup ) + '.back'; inc( fSaveCount ); try if {(fSaveCount mod 20 <> 0) and} not fBackupError then begin Log( tidLog_Survival, TimeToStr( Now ) + ' - Starting binary backup.' ); try Writer := CreateBackup( fBaseDir + filename, false, nil ); try Writer.WriteObject( 'World', fWorld ); Writer.WriteInteger('CacheLogVer', fCacheLogVer); inc(fCacheLogVer); ModelServerCache.SetLogVer(fCacheLogVer); finally Writer := nil; end; RegisterLastGoodBackup(filename); except Log( tidLog_Survival, 'Error backing up world.' ); raise; end; Log( tidLog_Survival, TimeToStr( Now ) + ' - End binary backup.' ); end else begin Log( tidLog_Survival, TimeToStr( Now ) + ' - Starting verbose backup.' ); try Writer := CreateBackup( fBaseDir + filename, true, nil ); try Writer.WriteObject( 'World', fWorld ); Writer.WriteInteger('CacheLogVer', fCacheLogVer); inc(fCacheLogVer); ModelServerCache.SetLogVer(fCacheLogVer); finally Writer := nil; end; //RegisterLastGoodBackup(filename); except Log( tidLog_Survival, 'Error backing up verbose world.' ); raise; end; Log( tidLog_Survival, TimeToStr( Now ) + ' - End verbose backup.' ); end; if fSatCount mod 10 = 0 then begin CallSync( CreateSatelliteMaps ); fSatRenderComplete.WaitFor( INFINITE ); fSatRenderComplete.ResetEvent; end; inc( fSatCount ); finally //OnModelStatusChange( mstNotBusy ); end; fBackupError := false; except if ErrorLevel < MaxBackupRetries then StoreBackup( mode, ErrorLevel + 1 ) else begin fBackupError := true; //OnModelStatusChange( mstError ); end; end; end; end; finally fWorld.ResumeVirtualTime; end; except end; end; procedure TModelServer.CreateSatelliteMaps; type TRGB = packed record r, g, b, x : byte; end; procedure AddClouds( Map : TBitmap ); const MapWeight = 200; MapShadowWeight = 350; var Clouds : TBitmap; x, y : integer; color : TColor; alpha : integer; function cU( x : integer ) : integer; begin if x >= 0 then result := x mod Clouds.Width else result := Clouds.Width + (x mod Clouds.Width); end; function cV( y : integer ) : integer; begin if y >= 0 then result := y mod Clouds.Height else result := Clouds.Height + (y mod Clouds.Height); end; begin Clouds := TBitmap.Create; try Clouds.LoadFromFile( ExtractFilePath(Application.ExeName) + 'Maps\clouds' + IntToStr(random(2)) + '.bmp' ); for y := 0 to pred(Map.Height) do for x := 0 to pred(Map.Width) do begin color := Map.Canvas.Pixels[x, y]; // draw shadow alpha := TRGB(Clouds.Canvas.Pixels[cU(x - 40), cV(y - 40)]).g; TRGB(color).r := (MapShadowWeight*TRGB(color).r) div (alpha + MapShadowWeight); TRGB(color).g := (MapShadowWeight*TRGB(color).g) div (alpha + MapShadowWeight); TRGB(color).b := (MapShadowWeight*TRGB(color).b) div (alpha + MapShadowWeight); // draw cloud alpha := TRGB(Clouds.Canvas.Pixels[cU(x), cV(y)]).g; TRGB(color).r := (MapWeight*TRGB(color).r + alpha*$FF) div (alpha + MapWeight); TRGB(color).g := (MapWeight*TRGB(color).g + alpha*$FF) div (alpha + MapWeight); TRGB(color).b := (MapWeight*TRGB(color).b + alpha*$FF) div (alpha + MapWeight); Map.Canvas.Pixels[x, y] := color; end; finally Clouds.Free; end; end; const Scale = 2; var Map : TBitmap; SmallMap : TBitmap; x, y : integer; xi, yi : integer; rSum, gSum, bSum, xSum : integer; col : TRGB; jpgImage : TJPEGImage; begin try try Map := fWorld.GenerateSatelliteMap( 0 ); try SmallMap := TBitmap.Create; try Logs.Log( tidLog_Survival, TimeToStr(Now) + ' Creating destination bitmap...' ); SmallMap.PixelFormat := pf32bit; SmallMap.Width := Map.Width div Scale; SmallMap.Height := Map.Height div Scale; Logs.Log( tidLog_Survival, TimeToStr(Now) + ' Scaling bitmap...' ); for y := 0 to pred(SmallMap.Width) do for x := 0 to pred(SmallMap.Height) do begin rSum := 0; gSum := 0; bSum := 0; xSum := 0; for yi := 0 to pred(Scale) do for xi := 0 to pred(Scale) do with TRGB(Map.Canvas.Pixels[Scale*x + xi, Scale*y + yi]) do begin rSum := rSum + r; gSum := gSum + g; bSum := bSum + b; xSum := xSum + x; end; col.r := rSum div sqr(Scale); col.g := gSum div sqr(Scale); col.b := bSum div sqr(Scale); col.x := xSum div sqr(Scale); SmallMap.Canvas.Pixels[x, y] := TColor(col); end; Logs.Log( tidLog_Survival, TimeToStr(Now) + ' Adding clouds...' ); AddClouds( SmallMap ); jpgImage := TJPEGImage.Create; try jpgImage.Assign( SmallMap ); ForceDirectories(fSatelliteMapPath); jpgImage.SaveToFile( fSatelliteMapPath + '\general.jpg' ); finally jpgImage.Free; end; finally SmallMap.Free; end; finally Map.Free; end; except end; finally fSatRenderComplete.SetEvent; end; end; function TModelServer.QueryInterface(const IID: TGUID; out Obj): hresult; stdcall; begin pointer(Obj) := nil; result := E_FAIL; end; function TModelServer._AddRef : integer; stdcall; begin result := 1; end; function TModelServer._Release : integer; stdcall; begin result := 1; end; function TModelServer.NewMailAccount(Account, Alias, FwdAddr : string; KeepMsg : boolean) : boolean; begin try if not VarIsEmpty(fMailServer) then result := fMailServer.NewMailAccount(fMailId, Account, Alias, Fwdaddr, KeepMsg) else result := false; except result := false; end; end; function TModelServer.DeleteAccount(Account : string) : boolean; begin try if not VarIsEmpty(fMailServer) then result := fMailServer.DeleteAccount(fMailId, Account) else result := false; except result := false; end; end; function TModelServer.SetForwardRule(Account, FwdAddr : string; KeepMsg : boolean) : boolean; begin try if not VarIsEmpty(fMailServer) then result := fMailServer.SetForwardRule(fMailId, Account, FwdAddr, KeepMsg) else result := false; except result := false; end; end; function TModelServer.SendMessage(From, Dest, Subject : string; Lines : TStringList; html : boolean) : boolean; var Id : integer; i : integer; begin try if not VarIsEmpty(fMailServer) then begin Id := fMailServer.NewMail(From, Dest, Subject); if Id <> 0 then begin fMailServer.BindTo(Id); if html then fMailServer.AddHeaders('ContentType=text/html'); for i := 0 to pred(Lines.Count) do fMailServer.AddLine(Lines[i]); if fMailServer.BindTo(tidRDOHook_MailServer) then begin result := fMailServer.Post(fWorld.Name, Id); fMailServer.CloseMessage(Id); end else result := false; end else result := false; end else result := false; except result := false; end; end; function TModelServer.SendHTMLMessage(From, Dest, Subject, URL : string) : boolean; var List : TStringList; begin try List := TStringList.Create; try List.Add('<HEAD>'); List.Add('<META HTTP-EQUIV="REFRESH" CONTENT="0; URL=' + URL + '">'); List.Add('</HEAD>'); result := SendMessage(From, Dest, Subject, List, true); finally List.Free; end; except result := false; end; end; procedure TModelServer.UpdateDate(NewDate : TDateTime); var RemoteId : integer; begin if not VarIsEmpty(fMailServer) then begin RemoteId := fMailServer.RemoteObjectID; fMailServer.BindTo(fMailId); fMailServer.SetDate(NewDate); fMailServer.BindTo(RemoteId); end; end; procedure TModelServer.CreateNewsCenter( World : string ); var i : integer; begin if not VarIsEmpty(fNewsServer) then try for i := 0 to pred(LangList.Count) do if not VarIsEmpty(fNewsServer) then fNewsServer.RDOCreateNewsCenter( World, fLocalHost, fDALockPort, LangList[i] ); except end; end; procedure TModelServer.CreateNewspaper( World, Name, Style, Town : string ); var i : integer; begin if not VarIsEmpty(fNewsServer) then try for i := 0 to pred(LangList.Count) do if not VarIsEmpty(fNewsServer) then fNewsServer.RDOCreateNewspaper( World, Name, Style, Town, fLocalHost, fDALockPort, LangList[i] ); except end; end; procedure TModelServer.GenerateNewspapers( World : widestring; Date : TDateTime ); var i : integer; begin if not VarIsEmpty(fNewsServer) then try fNewsServer.WaitForAnswer := false; for i := 0 to pred(LangList.Count) do if not VarIsEmpty(fNewsServer) then fNewsServer.RDOGenerateNewspapers( World, Date, fLocalHost, fDALockPort, LangList[i] ); except end; end; function TModelServer.RenewCache(Agent, ObjId : string) : TObjectCache; const Agents : array[0..5] of string = ( 'Facility', 'Input', 'Output', 'Tycoon', 'Company', 'Town' ); var idx : integer; Facility : TFacility; MetaGate : string; Input : TInput; Output : TOutput; Tycoon : TTycoon; Company : TCompany; Town : TTown; p : integer; x, y : integer; procedure GetXY; var aux : string; begin aux := CompStringsParser.GetNextStringUpTo(ObjId, p, ','); x := StrToInt(aux); inc(p); aux := CompStringsParser.GetNextStringUpTo(ObjId, p, ','); y := StrToInt(aux); end; function GetFacilityAt(x, y : integer) : TFacility; begin if (x >= 0) and (y >= 0) and (x < fWorld.xSize) and (y < fWorld.ySize) then result := fWorld.FacilityAt(x, y) else result := nil; end; begin idx := 0; while (idx < 6) and (Agent <> Agents[idx]) do inc(idx); p := 1; case idx of 0 : // Facility begin GetXY; Facility := GetFacilityAt(x, y); if Facility <> nil then result := ModelServerCache.UpdateObjectCacheEx(Facility, noKind, noInfo, true) else result := nil; end; 1 : // Input begin GetXY; Facility := GetFacilityAt(x, y); if Facility <> nil then begin inc(p); MetaGate := CompStringsParser.GetNextStringUpTo(ObjId, p, #0); Input := Facility.CurrBlock.InputsByName[MetaGate]; if Input <> nil then result := ModelServerCache.UpdateObjectCacheEx(Input, noKind, noInfo, true) else result := nil; end else result := nil; end; 2 : // Output begin GetXY; Facility := GetFacilityAt(x, y); if Facility <> nil then begin inc(p); MetaGate := CompStringsParser.GetNextStringUpTo(ObjId, p, #0); Output := Facility.CurrBlock.OutputsByName[MetaGate]; if Output <> nil then result := ModelServerCache.UpdateObjectCacheEx(Output, noKind, noInfo, true) else result := nil; end else result := nil; end; 3 : // Tycoon begin Tycoon := fWorld.TycoonByName[ObjId]; if Tycoon <> nil then result := ModelServerCache.UpdateObjectCacheEx(Tycoon, noKind, noInfo, true) else result := nil; end; 4 : // Company begin Company := fWorld.CompanyByName[ObjId]; if Company <> nil then result := ModelServerCache.UpdateObjectCacheEx(Company, noKind, noInfo, true) else result := nil; end; 5 : // Town begin Town := fWorld.TownByName[ObjId]; if Town <> nil then result := ModelServerCache.UpdateObjectCacheEx(Town, noKind, noInfo, true) else result := nil; end; else result := nil; end; // >> Logs.Log('survival', 'Renew cache: Agent=' + Agent + ', Object=' + ObjId); // >> end; function TModelServer.GetInteger( id : integer ) : integer; begin case id of CFGID_AccountExpires : result := fAccountExpires; CFGID_LevelLimit : result := fLevelLimit; else result := 0; end; end; function TModelServer.GetFloat( id : integer ) : double; begin result := 0; end; function TModelServer.GetString( id : integer ) : string; begin result := ''; end; function TModelServer.GetMoney( id : integer ) : TMoney; begin result := 0; end; function TModelServer.GetIntegerArray( id : integer; i, j, k, l : integer ) : integer; begin result := 0; end; function TModelServer.GetFloatArray( id : integer; i, j, k, l : integer ) : double; begin result := 0; end; function TModelServer.GetStringArray( id : integer; i, j, k, l : integer ) : string; begin result := ''; end; function TModelServer.GetMoneyArray( id : integer; i, j, k, l : integer ) : TMoney; begin result := 0; end; function TModelServer.GetConfigParm( strId, defVal : string ) : string; var value : string; begin value := fConfigInfo.Values[strId]; if value <> '' then result := value else result := defVal; end; function TModelServer.GetMaxInvestors : integer; begin if fWorld <> nil then result := fWorld.MaxInvestors else result := 0; end; procedure TModelServer.SetMaxInvestors(value : integer); begin if fWorld <> nil then fWorld.MaxInvestors := value; end; procedure TModelServer.CheckMaintenanceSchedule; begin if fAutoRestart and not fMaintDue then begin fTimeToMaint := realmax(0, fRestartDate - Now); fWarnMaint := fTimeToMaint < 1/24; // >> less than an hour.. fMaintDue := Now >= fRestartDate; end; end; procedure TModelServer.RegisterLastGoodBackup(name : string); var Reg : TRegistry; begin Reg := TRegistry.Create; try Reg.RootKey := HKEY_LOCAL_MACHINE; if Reg.OpenKey(tidRegKey_ModelServer, true) then Reg.WriteString('LastGoodBackup', name); finally Reg.Free; end; end; procedure TModelServer.SetMSReadyEvent(signal : boolean); begin if signal then fMSReadyEvent.SetEvent else fMSReadyEvent.ResetEvent; end; function TModelServer.ReportMaintenance(shortMsg, longMsg : string; eta : TDateTime) : boolean; begin result := fWorld.ReportMaintenance(shortMsg, longMsg, eta); end; procedure TModelServer.ReportMaintenanceToIS(eta : TDateTime); begin try fISProxyLock.Enter; try if not VarIsEmpty(fISEvents) then fISEvents.ReportMaintenance(eta, fLastDowntime); finally fISProxyLock.Leave; end; except end; end; procedure TModelServer.CalculateDownTime; var delta : TDateTime; hh, mm, ss, ms : word; begin if fLastDateUp <> 0 then delta := Now - fLastDateUp else delta := 0; if delta > 1 then fLastDowntime := 45 else begin DecodeTime(delta, hh, mm, ss, ms); if hh > 1 then fLastDowntime := 45 else fLastDowntime := max(5, min(45, mm)); end; end; end.
unit ChatWindowKeywordsPack; {* Набор слов словаря для доступа к экземплярам контролов формы ChatWindow } // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\Chat\Forms\ChatWindowKeywordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "ChatWindowKeywordsPack" MUID: (4A6971E802F5_Pack) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3IntfUses ; {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL) implementation {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3ImplUses , ChatWindow_Form , tfwPropertyLike , vtProportionalPanel , tfwScriptingInterfaces , TypInfo , tfwTypeInfo , vtSizeablePanel {$If Defined(Nemesis)} , nscChatMemo {$IfEnd} // Defined(Nemesis) , vtPanel , tfwControlString , kwBynameControlPush , TtfwClassRef_Proxy , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes //#UC START# *4A6971E802F5_Packimpl_uses* //#UC END# *4A6971E802F5_Packimpl_uses* ; type TkwChatWindowFormBackgroundPanel = {final} class(TtfwPropertyLike) {* Слово скрипта .TChatWindowForm.BackgroundPanel } private function BackgroundPanel(const aCtx: TtfwContext; aChatWindowForm: TChatWindowForm): TvtProportionalPanel; {* Реализация слова скрипта .TChatWindowForm.BackgroundPanel } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwChatWindowFormBackgroundPanel TkwChatWindowFormBottomPanel = {final} class(TtfwPropertyLike) {* Слово скрипта .TChatWindowForm.BottomPanel } private function BottomPanel(const aCtx: TtfwContext; aChatWindowForm: TChatWindowForm): TvtSizeablePanel; {* Реализация слова скрипта .TChatWindowForm.BottomPanel } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwChatWindowFormBottomPanel TkwChatWindowFormBottomEditor = {final} class(TtfwPropertyLike) {* Слово скрипта .TChatWindowForm.BottomEditor } private function BottomEditor(const aCtx: TtfwContext; aChatWindowForm: TChatWindowForm): TnscChatMemo; {* Реализация слова скрипта .TChatWindowForm.BottomEditor } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwChatWindowFormBottomEditor TkwChatWindowFormTopPanel = {final} class(TtfwPropertyLike) {* Слово скрипта .TChatWindowForm.TopPanel } private function TopPanel(const aCtx: TtfwContext; aChatWindowForm: TChatWindowForm): TvtPanel; {* Реализация слова скрипта .TChatWindowForm.TopPanel } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwChatWindowFormTopPanel TkwChatWindowFormHistoryEditor = {final} class(TtfwPropertyLike) {* Слово скрипта .TChatWindowForm.HistoryEditor } private function HistoryEditor(const aCtx: TtfwContext; aChatWindowForm: TChatWindowForm): TnscChatMemo; {* Реализация слова скрипта .TChatWindowForm.HistoryEditor } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwChatWindowFormHistoryEditor Tkw_Form_ChatWindow = {final} class(TtfwControlString) {* Слово словаря для идентификатора формы ChatWindow ---- *Пример использования*: [code]форма::ChatWindow TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Form_ChatWindow Tkw_ChatWindow_Control_BackgroundPanel = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола BackgroundPanel ---- *Пример использования*: [code]контрол::BackgroundPanel TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ChatWindow_Control_BackgroundPanel Tkw_ChatWindow_Control_BackgroundPanel_Push = {final} class(TkwBynameControlPush) {* Слово словаря для контрола BackgroundPanel ---- *Пример использования*: [code]контрол::BackgroundPanel:push pop:control:SetFocus ASSERT[code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ChatWindow_Control_BackgroundPanel_Push Tkw_ChatWindow_Control_BottomPanel = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола BottomPanel ---- *Пример использования*: [code]контрол::BottomPanel TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ChatWindow_Control_BottomPanel Tkw_ChatWindow_Control_BottomPanel_Push = {final} class(TkwBynameControlPush) {* Слово словаря для контрола BottomPanel ---- *Пример использования*: [code]контрол::BottomPanel:push pop:control:SetFocus ASSERT[code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ChatWindow_Control_BottomPanel_Push Tkw_ChatWindow_Control_BottomEditor = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола BottomEditor ---- *Пример использования*: [code]контрол::BottomEditor TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ChatWindow_Control_BottomEditor Tkw_ChatWindow_Control_BottomEditor_Push = {final} class(TkwBynameControlPush) {* Слово словаря для контрола BottomEditor ---- *Пример использования*: [code]контрол::BottomEditor:push pop:control:SetFocus ASSERT[code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ChatWindow_Control_BottomEditor_Push Tkw_ChatWindow_Control_TopPanel = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола TopPanel ---- *Пример использования*: [code]контрол::TopPanel TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ChatWindow_Control_TopPanel Tkw_ChatWindow_Control_TopPanel_Push = {final} class(TkwBynameControlPush) {* Слово словаря для контрола TopPanel ---- *Пример использования*: [code]контрол::TopPanel:push pop:control:SetFocus ASSERT[code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ChatWindow_Control_TopPanel_Push Tkw_ChatWindow_Control_HistoryEditor = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола HistoryEditor ---- *Пример использования*: [code]контрол::HistoryEditor TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ChatWindow_Control_HistoryEditor Tkw_ChatWindow_Control_HistoryEditor_Push = {final} class(TkwBynameControlPush) {* Слово словаря для контрола HistoryEditor ---- *Пример использования*: [code]контрол::HistoryEditor:push pop:control:SetFocus ASSERT[code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ChatWindow_Control_HistoryEditor_Push function TkwChatWindowFormBackgroundPanel.BackgroundPanel(const aCtx: TtfwContext; aChatWindowForm: TChatWindowForm): TvtProportionalPanel; {* Реализация слова скрипта .TChatWindowForm.BackgroundPanel } begin Result := aChatWindowForm.BackgroundPanel; end;//TkwChatWindowFormBackgroundPanel.BackgroundPanel class function TkwChatWindowFormBackgroundPanel.GetWordNameForRegister: AnsiString; begin Result := '.TChatWindowForm.BackgroundPanel'; end;//TkwChatWindowFormBackgroundPanel.GetWordNameForRegister function TkwChatWindowFormBackgroundPanel.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtProportionalPanel); end;//TkwChatWindowFormBackgroundPanel.GetResultTypeInfo function TkwChatWindowFormBackgroundPanel.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwChatWindowFormBackgroundPanel.GetAllParamsCount function TkwChatWindowFormBackgroundPanel.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TChatWindowForm)]); end;//TkwChatWindowFormBackgroundPanel.ParamsTypes procedure TkwChatWindowFormBackgroundPanel.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству BackgroundPanel', aCtx); end;//TkwChatWindowFormBackgroundPanel.SetValuePrim procedure TkwChatWindowFormBackgroundPanel.DoDoIt(const aCtx: TtfwContext); var l_aChatWindowForm: TChatWindowForm; begin try l_aChatWindowForm := TChatWindowForm(aCtx.rEngine.PopObjAs(TChatWindowForm)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aChatWindowForm: TChatWindowForm : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(BackgroundPanel(aCtx, l_aChatWindowForm)); end;//TkwChatWindowFormBackgroundPanel.DoDoIt function TkwChatWindowFormBottomPanel.BottomPanel(const aCtx: TtfwContext; aChatWindowForm: TChatWindowForm): TvtSizeablePanel; {* Реализация слова скрипта .TChatWindowForm.BottomPanel } begin Result := aChatWindowForm.BottomPanel; end;//TkwChatWindowFormBottomPanel.BottomPanel class function TkwChatWindowFormBottomPanel.GetWordNameForRegister: AnsiString; begin Result := '.TChatWindowForm.BottomPanel'; end;//TkwChatWindowFormBottomPanel.GetWordNameForRegister function TkwChatWindowFormBottomPanel.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtSizeablePanel); end;//TkwChatWindowFormBottomPanel.GetResultTypeInfo function TkwChatWindowFormBottomPanel.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwChatWindowFormBottomPanel.GetAllParamsCount function TkwChatWindowFormBottomPanel.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TChatWindowForm)]); end;//TkwChatWindowFormBottomPanel.ParamsTypes procedure TkwChatWindowFormBottomPanel.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству BottomPanel', aCtx); end;//TkwChatWindowFormBottomPanel.SetValuePrim procedure TkwChatWindowFormBottomPanel.DoDoIt(const aCtx: TtfwContext); var l_aChatWindowForm: TChatWindowForm; begin try l_aChatWindowForm := TChatWindowForm(aCtx.rEngine.PopObjAs(TChatWindowForm)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aChatWindowForm: TChatWindowForm : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(BottomPanel(aCtx, l_aChatWindowForm)); end;//TkwChatWindowFormBottomPanel.DoDoIt function TkwChatWindowFormBottomEditor.BottomEditor(const aCtx: TtfwContext; aChatWindowForm: TChatWindowForm): TnscChatMemo; {* Реализация слова скрипта .TChatWindowForm.BottomEditor } begin Result := aChatWindowForm.BottomEditor; end;//TkwChatWindowFormBottomEditor.BottomEditor class function TkwChatWindowFormBottomEditor.GetWordNameForRegister: AnsiString; begin Result := '.TChatWindowForm.BottomEditor'; end;//TkwChatWindowFormBottomEditor.GetWordNameForRegister function TkwChatWindowFormBottomEditor.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TnscChatMemo); end;//TkwChatWindowFormBottomEditor.GetResultTypeInfo function TkwChatWindowFormBottomEditor.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwChatWindowFormBottomEditor.GetAllParamsCount function TkwChatWindowFormBottomEditor.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TChatWindowForm)]); end;//TkwChatWindowFormBottomEditor.ParamsTypes procedure TkwChatWindowFormBottomEditor.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству BottomEditor', aCtx); end;//TkwChatWindowFormBottomEditor.SetValuePrim procedure TkwChatWindowFormBottomEditor.DoDoIt(const aCtx: TtfwContext); var l_aChatWindowForm: TChatWindowForm; begin try l_aChatWindowForm := TChatWindowForm(aCtx.rEngine.PopObjAs(TChatWindowForm)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aChatWindowForm: TChatWindowForm : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(BottomEditor(aCtx, l_aChatWindowForm)); end;//TkwChatWindowFormBottomEditor.DoDoIt function TkwChatWindowFormTopPanel.TopPanel(const aCtx: TtfwContext; aChatWindowForm: TChatWindowForm): TvtPanel; {* Реализация слова скрипта .TChatWindowForm.TopPanel } begin Result := aChatWindowForm.TopPanel; end;//TkwChatWindowFormTopPanel.TopPanel class function TkwChatWindowFormTopPanel.GetWordNameForRegister: AnsiString; begin Result := '.TChatWindowForm.TopPanel'; end;//TkwChatWindowFormTopPanel.GetWordNameForRegister function TkwChatWindowFormTopPanel.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtPanel); end;//TkwChatWindowFormTopPanel.GetResultTypeInfo function TkwChatWindowFormTopPanel.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwChatWindowFormTopPanel.GetAllParamsCount function TkwChatWindowFormTopPanel.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TChatWindowForm)]); end;//TkwChatWindowFormTopPanel.ParamsTypes procedure TkwChatWindowFormTopPanel.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству TopPanel', aCtx); end;//TkwChatWindowFormTopPanel.SetValuePrim procedure TkwChatWindowFormTopPanel.DoDoIt(const aCtx: TtfwContext); var l_aChatWindowForm: TChatWindowForm; begin try l_aChatWindowForm := TChatWindowForm(aCtx.rEngine.PopObjAs(TChatWindowForm)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aChatWindowForm: TChatWindowForm : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(TopPanel(aCtx, l_aChatWindowForm)); end;//TkwChatWindowFormTopPanel.DoDoIt function TkwChatWindowFormHistoryEditor.HistoryEditor(const aCtx: TtfwContext; aChatWindowForm: TChatWindowForm): TnscChatMemo; {* Реализация слова скрипта .TChatWindowForm.HistoryEditor } begin Result := aChatWindowForm.HistoryEditor; end;//TkwChatWindowFormHistoryEditor.HistoryEditor class function TkwChatWindowFormHistoryEditor.GetWordNameForRegister: AnsiString; begin Result := '.TChatWindowForm.HistoryEditor'; end;//TkwChatWindowFormHistoryEditor.GetWordNameForRegister function TkwChatWindowFormHistoryEditor.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TnscChatMemo); end;//TkwChatWindowFormHistoryEditor.GetResultTypeInfo function TkwChatWindowFormHistoryEditor.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwChatWindowFormHistoryEditor.GetAllParamsCount function TkwChatWindowFormHistoryEditor.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TChatWindowForm)]); end;//TkwChatWindowFormHistoryEditor.ParamsTypes procedure TkwChatWindowFormHistoryEditor.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству HistoryEditor', aCtx); end;//TkwChatWindowFormHistoryEditor.SetValuePrim procedure TkwChatWindowFormHistoryEditor.DoDoIt(const aCtx: TtfwContext); var l_aChatWindowForm: TChatWindowForm; begin try l_aChatWindowForm := TChatWindowForm(aCtx.rEngine.PopObjAs(TChatWindowForm)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aChatWindowForm: TChatWindowForm : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(HistoryEditor(aCtx, l_aChatWindowForm)); end;//TkwChatWindowFormHistoryEditor.DoDoIt function Tkw_Form_ChatWindow.GetString: AnsiString; begin Result := 'ChatWindowForm'; end;//Tkw_Form_ChatWindow.GetString class procedure Tkw_Form_ChatWindow.RegisterInEngine; begin inherited; TtfwClassRef.Register(TChatWindowForm); end;//Tkw_Form_ChatWindow.RegisterInEngine class function Tkw_Form_ChatWindow.GetWordNameForRegister: AnsiString; begin Result := 'форма::ChatWindow'; end;//Tkw_Form_ChatWindow.GetWordNameForRegister function Tkw_ChatWindow_Control_BackgroundPanel.GetString: AnsiString; begin Result := 'BackgroundPanel'; end;//Tkw_ChatWindow_Control_BackgroundPanel.GetString class procedure Tkw_ChatWindow_Control_BackgroundPanel.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtProportionalPanel); end;//Tkw_ChatWindow_Control_BackgroundPanel.RegisterInEngine class function Tkw_ChatWindow_Control_BackgroundPanel.GetWordNameForRegister: AnsiString; begin Result := 'контрол::BackgroundPanel'; end;//Tkw_ChatWindow_Control_BackgroundPanel.GetWordNameForRegister procedure Tkw_ChatWindow_Control_BackgroundPanel_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('BackgroundPanel'); inherited; end;//Tkw_ChatWindow_Control_BackgroundPanel_Push.DoDoIt class function Tkw_ChatWindow_Control_BackgroundPanel_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::BackgroundPanel:push'; end;//Tkw_ChatWindow_Control_BackgroundPanel_Push.GetWordNameForRegister function Tkw_ChatWindow_Control_BottomPanel.GetString: AnsiString; begin Result := 'BottomPanel'; end;//Tkw_ChatWindow_Control_BottomPanel.GetString class procedure Tkw_ChatWindow_Control_BottomPanel.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtSizeablePanel); end;//Tkw_ChatWindow_Control_BottomPanel.RegisterInEngine class function Tkw_ChatWindow_Control_BottomPanel.GetWordNameForRegister: AnsiString; begin Result := 'контрол::BottomPanel'; end;//Tkw_ChatWindow_Control_BottomPanel.GetWordNameForRegister procedure Tkw_ChatWindow_Control_BottomPanel_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('BottomPanel'); inherited; end;//Tkw_ChatWindow_Control_BottomPanel_Push.DoDoIt class function Tkw_ChatWindow_Control_BottomPanel_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::BottomPanel:push'; end;//Tkw_ChatWindow_Control_BottomPanel_Push.GetWordNameForRegister function Tkw_ChatWindow_Control_BottomEditor.GetString: AnsiString; begin Result := 'BottomEditor'; end;//Tkw_ChatWindow_Control_BottomEditor.GetString class procedure Tkw_ChatWindow_Control_BottomEditor.RegisterInEngine; begin inherited; TtfwClassRef.Register(TnscChatMemo); end;//Tkw_ChatWindow_Control_BottomEditor.RegisterInEngine class function Tkw_ChatWindow_Control_BottomEditor.GetWordNameForRegister: AnsiString; begin Result := 'контрол::BottomEditor'; end;//Tkw_ChatWindow_Control_BottomEditor.GetWordNameForRegister procedure Tkw_ChatWindow_Control_BottomEditor_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('BottomEditor'); inherited; end;//Tkw_ChatWindow_Control_BottomEditor_Push.DoDoIt class function Tkw_ChatWindow_Control_BottomEditor_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::BottomEditor:push'; end;//Tkw_ChatWindow_Control_BottomEditor_Push.GetWordNameForRegister function Tkw_ChatWindow_Control_TopPanel.GetString: AnsiString; begin Result := 'TopPanel'; end;//Tkw_ChatWindow_Control_TopPanel.GetString class procedure Tkw_ChatWindow_Control_TopPanel.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtPanel); end;//Tkw_ChatWindow_Control_TopPanel.RegisterInEngine class function Tkw_ChatWindow_Control_TopPanel.GetWordNameForRegister: AnsiString; begin Result := 'контрол::TopPanel'; end;//Tkw_ChatWindow_Control_TopPanel.GetWordNameForRegister procedure Tkw_ChatWindow_Control_TopPanel_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('TopPanel'); inherited; end;//Tkw_ChatWindow_Control_TopPanel_Push.DoDoIt class function Tkw_ChatWindow_Control_TopPanel_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::TopPanel:push'; end;//Tkw_ChatWindow_Control_TopPanel_Push.GetWordNameForRegister function Tkw_ChatWindow_Control_HistoryEditor.GetString: AnsiString; begin Result := 'HistoryEditor'; end;//Tkw_ChatWindow_Control_HistoryEditor.GetString class procedure Tkw_ChatWindow_Control_HistoryEditor.RegisterInEngine; begin inherited; TtfwClassRef.Register(TnscChatMemo); end;//Tkw_ChatWindow_Control_HistoryEditor.RegisterInEngine class function Tkw_ChatWindow_Control_HistoryEditor.GetWordNameForRegister: AnsiString; begin Result := 'контрол::HistoryEditor'; end;//Tkw_ChatWindow_Control_HistoryEditor.GetWordNameForRegister procedure Tkw_ChatWindow_Control_HistoryEditor_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('HistoryEditor'); inherited; end;//Tkw_ChatWindow_Control_HistoryEditor_Push.DoDoIt class function Tkw_ChatWindow_Control_HistoryEditor_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::HistoryEditor:push'; end;//Tkw_ChatWindow_Control_HistoryEditor_Push.GetWordNameForRegister initialization TkwChatWindowFormBackgroundPanel.RegisterInEngine; {* Регистрация ChatWindowForm_BackgroundPanel } TkwChatWindowFormBottomPanel.RegisterInEngine; {* Регистрация ChatWindowForm_BottomPanel } TkwChatWindowFormBottomEditor.RegisterInEngine; {* Регистрация ChatWindowForm_BottomEditor } TkwChatWindowFormTopPanel.RegisterInEngine; {* Регистрация ChatWindowForm_TopPanel } TkwChatWindowFormHistoryEditor.RegisterInEngine; {* Регистрация ChatWindowForm_HistoryEditor } Tkw_Form_ChatWindow.RegisterInEngine; {* Регистрация Tkw_Form_ChatWindow } Tkw_ChatWindow_Control_BackgroundPanel.RegisterInEngine; {* Регистрация Tkw_ChatWindow_Control_BackgroundPanel } Tkw_ChatWindow_Control_BackgroundPanel_Push.RegisterInEngine; {* Регистрация Tkw_ChatWindow_Control_BackgroundPanel_Push } Tkw_ChatWindow_Control_BottomPanel.RegisterInEngine; {* Регистрация Tkw_ChatWindow_Control_BottomPanel } Tkw_ChatWindow_Control_BottomPanel_Push.RegisterInEngine; {* Регистрация Tkw_ChatWindow_Control_BottomPanel_Push } Tkw_ChatWindow_Control_BottomEditor.RegisterInEngine; {* Регистрация Tkw_ChatWindow_Control_BottomEditor } Tkw_ChatWindow_Control_BottomEditor_Push.RegisterInEngine; {* Регистрация Tkw_ChatWindow_Control_BottomEditor_Push } Tkw_ChatWindow_Control_TopPanel.RegisterInEngine; {* Регистрация Tkw_ChatWindow_Control_TopPanel } Tkw_ChatWindow_Control_TopPanel_Push.RegisterInEngine; {* Регистрация Tkw_ChatWindow_Control_TopPanel_Push } Tkw_ChatWindow_Control_HistoryEditor.RegisterInEngine; {* Регистрация Tkw_ChatWindow_Control_HistoryEditor } Tkw_ChatWindow_Control_HistoryEditor_Push.RegisterInEngine; {* Регистрация Tkw_ChatWindow_Control_HistoryEditor_Push } TtfwTypeRegistrator.RegisterType(TypeInfo(TChatWindowForm)); {* Регистрация типа TChatWindowForm } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtProportionalPanel)); {* Регистрация типа TvtProportionalPanel } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtSizeablePanel)); {* Регистрация типа TvtSizeablePanel } {$If Defined(Nemesis)} TtfwTypeRegistrator.RegisterType(TypeInfo(TnscChatMemo)); {* Регистрация типа TnscChatMemo } {$IfEnd} // Defined(Nemesis) TtfwTypeRegistrator.RegisterType(TypeInfo(TvtPanel)); {* Регистрация типа TvtPanel } {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL) end.
{*******************************************************} { } { This unit describe all custom types and event declaration } { } { Copyright (C) 2014 } { } {*******************************************************} unit FmxJabberTools; interface uses Classes, system.SysUtils, IdHashMessageDigest; Type TMechanism = (mecDIGEST_MD5, mecPLAIN, mecNONE); //Encryption mechanisms for jabber protocole TUserStatus = (usOnline, usAway, usDNotDistrub, usFreeForChat,usInVisible, usExtendedAway); // user status TContact = record // Record defining a contact Jid : String; // his jaber ID Name : String; // his name Group : string; // his group Subscription : Boolean; ADisplayMessage : string; // Displayed message AStatus : TUserStatus; // Connection status end; PContact = ^TContact; TOnResponseWithStrData = procedure(AData : string) of Object; //event defining a response with a string paramter TonResponseWithBoolData = procedure(AStatus : Boolean) of object; //event defining a response with a boolean paramter TOnInitConnection = procedure(AId : string; ACompression : String; AUseSASL : Boolean; AMechanism : TMechanism) of Object; TOnResponseWithNoData = procedure of Object; //event defining a response with no paramter TOnUpdateRoster = procedure (AName, JID, ASubscription, AGroup : string) of object; TOnMessageReceived = procedure (AFrom, AMessage : string) of object; // On receive a message TOnPresenceCallBack = procedure (AFrom, ATo, AStatus: String; APresence: TUserStatus) of Object; // On presence status for a contact change TOnContactAskToAdd = procedure (AJid : String; var AAccept : Boolean) of Object; // When someone add you as a contact TOnAddRequestStatus = procedure (AFrom : String; AAccepted : Boolean) of object; //Own request to add a contact Const // not all consts used (TODO : replace all direct string in the code by const name XMLNS_ROSTER = 'jabber:iq:roster'; XMLNS_REGISTER = 'jabber:iq:register'; XMLNS_LAST = 'jabber:iq:last'; XMLNS_TIME = 'jabber:iq:time'; XMLNS_VERSION = 'jabber:iq:version'; XMLNS_IQOOB = 'jabber:iq:oob'; XMLNS_BROWSE = 'jabber:iq:browse'; XMLNS_AGENTS = 'jabber:iq:agents'; XMLNS_SEARCH = 'jabber:iq:search'; XMLNS_PRIVATE = 'jabber:iq:private'; XMLNS_CONFERENCE = 'jabber:iq:conference'; XMLNS_BM = 'storage:bookmarks'; XMLNS_PREFS = 'storage:imprefs'; XMLNS_XEVENT = 'jabber:x:event'; XMLNS_DELAY = 'jabber:x:delay'; XMLNS_XROSTER = 'jabber:x:roster'; XMLNS_XCONFERENCE= 'jabber:x:conference'; XMLNS_XDATA = 'jabber:x:data'; XMLNS_XOOB = 'jabber:x:oob'; XMLNS_MUC = 'http://jabber.org/protocol/muc'; XMLNS_MUCOWNER = 'http://jabber.org/protocol/muc#owner'; XMLNS_MUCADMIN = 'http://jabber.org/protocol/muc#admin'; XMLNS_MUCUSER = 'http://jabber.org/protocol/muc#user'; XMLNS_DISCO = 'http://jabber.org/protocol/disco'; XMLNS_DISCOITEMS = 'http://jabber.org/protocol/disco#items'; XMLNS_DISCOINFO = 'http://jabber.org/protocol/disco#info'; XMLNS_SI = 'http://jabber.org/protocol/si'; XMLNS_FTPROFILE = 'http://jabber.org/protocol/si/profile/file-transfer'; XMLNS_BYTESTREAMS= 'http://jabber.org/protocol/bytestreams'; XMLNS_FEATNEG = 'http://jabber.org/protocol/feature-neg'; XMLNS_CLIENTCAPS = 'http://jabber.org/protocol/caps'; XMLNS_STREAMERR = 'urn:ietf:params:xml:ns:xmpp-stanzas'; XMLNS_XMPP_SASL = 'urn:ietf:params:xml:ns:xmpp-sasl'; XMLNS_XMPP_BIND = 'urn:ietf:params:xml:ns:xmpp-bind'; XMLNS_XMPP_SESSION = 'urn:ietf:params:xml:ns:xmpp-session'; XMLNS_COMMANDS = 'http://jabber.org/protocol/commands'; XMLNS_CAPS = 'http://jabber.org/protocol/caps'; XMLNS_ADDRESS = 'http://jabber.org/protocol/address'; XMLNS_XHTMLIM = 'http://jabber.org/protocol/xhtml-im'; XMLNS_XHTML = 'http://www.w3.org/1999/xhtml'; XMLNS_SHIM = 'http://jabber.org/protocol/shim'; function GetUniqueID: String; // Get a unique ID string function ShaHASH(Fkey: String): String; // HASH function using indy implementation {------------------------------------------------------------------------------- Procedure: GetUniqueID Arguments: None Result: String -------------------------------------------------------------------------------} function GetUniqueID: String; var IntTime: Double; StrHex: String; begin IntTime := Double(Now) + Random(1000);; StrHex := (FloatToStr(IntTime)); StrHex := ShaHASH(StrHex); StrHex := copy(strhex, 1, 10); Result := StrHex; end; {------------------------------------------------------------------------------- Procedure: ShaHASH Arguments: Fkey: String Result: String -------------------------------------------------------------------------------} function ShaHASH(Fkey: String): String; var fdig, fdigest: string; _hasher: TIdHashMessageDigest5; begin fkey := Trim(fkey); _hasher := TIdHashMessageDigest5.Create; fdigest := _hasher.HashStringAsHex(Fkey); FreeAndNil(_hasher); fdig := Lowercase(fdigest); Result := fdig; end; end.
unit DW.ThreadedTimer; { ******************************************************* } { } { Kastri Free } { } { DelphiWorlds Cross-Platform Library } { } { ******************************************************* } // {$I DW.GlobalDefines.inc} interface uses // RTL System.Classes, // FMX FMX.Types; type TThreadedTimer = class(TTimer) private FThread: TThread; procedure DoInterval; protected procedure CheckInterval; procedure KillTimer; override; procedure UpdateTimer; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; TTimerThread = class(TThread) private FTimer: TThreadedTimer; protected procedure Execute; override; public constructor Create(const ATimer: TThreadedTimer); end; implementation { TThreadedTimer } constructor TThreadedTimer.Create(AOwner: TComponent); begin inherited; Enabled := False; FThread := TTimerThread.Create(Self); end; destructor TThreadedTimer.Destroy; begin Enabled := False; FThread.Free; inherited; end; procedure TThreadedTimer.CheckInterval; begin if Enabled then DoInterval; end; procedure TThreadedTimer.DoInterval; begin TThread.Synchronize(nil, procedure begin DoOnTimer; end); end; procedure TThreadedTimer.KillTimer; begin // No implementation of this method, as this timer does not use the platform timer service end; procedure TThreadedTimer.UpdateTimer; begin // No implementation of this method, as this timer does not use the platform timer service end; { TTimerThread } constructor TTimerThread.Create(const ATimer: TThreadedTimer); begin inherited Create; FTimer := ATimer; end; procedure TTimerThread.Execute; begin while not Terminated do begin Sleep(FTimer.Interval); FTimer.CheckInterval; end; end; end.
{$DEFINE UseDiff} {.$DEFINE UseCorrelation} unit UWaveFormComputer; interface uses Windows, Misc; type TWaveFormComputer=object protected tf1,Int1:Double; tf2,Int2:Double; D1,A2,D2:PSingle; Data1,Appr2,Data2:TArrayOfSingle; Size:Integer; function CalcP2(const t,P1:Double):Double; public Alpha1,Alpha2:Double; procedure Init( const MaxTimeDelta, TimeDelta: Double; Src1,Src2:PSingle; ASize:Integer); function CalcCorrelation:Double; procedure GetDrawData(var dA2,dD2:TArrayOfSingle); public property pA2:PSingle read A2; property pD2:PSingle read D2; end; implementation { Based on sample program for the book NUMERICAL RECIPES IN PASCAL: THE ART OF SCIENTIFIC COMPUTING by William H. Press, Saul A. Teukolsky, Brian P. Flannery, and William T. Vetterling Cambridge University Press, New York, 1989. } FUNCTION BesselI1(x: Double): Double; CONST KA01=1/2.; KA03=1/16.; KA05=1/384.; KA07=1/18432.; KA09=1/1474560.; KA11=1/176947200.; KA13=1/29727129600.; KA15=1/6658877030400.; VAR ax: double; y: double; BEGIN IF (abs(x) < 3.75) THEN BEGIN y:=x*x; Result:=x*(KA01+y*(KA03+y*(KA05+y*(KA07+y*(KA09+y*(KA11+y*(KA13+y*KA15))))))); END ELSE BEGIN ax := abs(x); y := 3.75/ax; Result := exp(ax)/sqrt(ax) * ( 0.39894228 + y*(-0.3988024e-1 + y*(-0.362018e-2 + y*( 0.163801e-2 + y*(-0.1031555e-1 + y*(0.2282967e-1 + y*( -0.2895312e-1 + y*(0.1787654e-1 - y*0.420059e-2) ))))))); IF (x<0.0) THEN Result:=-Result END; END; procedure compensate(D:PSingle; n:Integer; Delta:Single); begin while n>0 do begin D^:=D^+Delta; Inc(D); Dec(n); end; end; function Distance(D1,D2:PSingle; n:Integer):Double; var i:Integer; begin Result:=0; i:=n; while i>0 do begin // Result:=Result+D1^*D2^; Result:=Result+Sqr(D1^-D2^); // Result:=Result+Sqr(Sqr(D1^-D2^)); dec(i); Inc(D1); Inc(D2); end; if Result>1e-16 // then Result:=n/Sqrt(Sqrt(Result)) then Result:=n/Sqrt(Result) else Result:=1e+4; { if Result>0 then Result:=n/Result else Result:=0; } end; {$IFDEF UseDiff} procedure CalcWaveData(Src,Dst:PSingle; n:Integer); var S:PSingle; V0,DV,dDV:Double; begin assert(n>1,'CalcWaveData: n<=1'); S:=Src; Inc(S,n-1); V0:=Src^; dDV:=(S^-V0)/(n-1); DV:=0; while n>0 do begin Dst^:=Src^-(V0+DV); DV:=DV+dDV; Inc(Src); Inc(Dst); Dec(n); end; end; {$ELSE} procedure CalcWaveData(Src,Dst:PSingle; n:Integer); var P0:Single; begin P0:=Src^; while n>0 do begin Dst^:=Src^-P0; Inc(Src); Inc(Dst); Dec(n); end; end; {$ENDIF} function TWaveFormComputer.CalcP2(const t,P1:Double):Double; var st,step,P0:Double; begin if t=0 then begin Int1:=0; Int2:=0; // Result:=P1/exp(-Alpha2*tf1)*exp(-Alpha1*tf2)); Result:=P1*exp(Alpha2*tf1 - Alpha1*tf2); end else begin st:=sqrt(2.*tf1*t+t*t); step:=Alpha2*tf1 * exp(-Alpha2*(tf1+t)) * BesselI1(Alpha2*st) / st; P0:=(P1-Int1)/(exp(-Alpha2*tf1)+step); Int1:=Int1+step*P0; // st:=sqrt(2.*tf2*t+t*t); step:=Alpha1*tf2 * exp(-Alpha1*(tf2+t)) * BesselI1(Alpha1*st) / st; Int2:=Int2+step*P0; Result:=P0*exp(-Alpha1*tf2) + Int2; end; end; function TWaveFormComputer.CalcCorrelation; var t:Double; PU,PV:PSingle; n:Integer; Mu1,Sigma1:Double; Mu2,Sigma2:Double; begin // Calculate A2 waveform PU:=D1; PV:=A2; n:=Size; t:=0; while n>0 do begin PV^:=CalcP2(t,PU^); t:=t+1.0; inc(PV); inc(PU); dec(n); end; // Compute similarity :-) {$IFDEF UseCorrelation} CalcMuSigma(A2,Size,Mu1,Sigma1); CalcMuSigma(D2,Size,Mu2,Sigma2); if (Sigma1>0) and (Sigma2>0) then Result:=Cov(A2,D2,Mu1,Mu2,Size)/(Sigma1*Sigma2) else Result:=0; {$ELSE} CalcMuSigma(A2,Size,Mu1,Sigma1); compensate(A2,Size,-Mu1); CalcMuSigma(D2,Size,Mu2,Sigma2); compensate(D2,Size,-Mu2); Result:=Distance(A2,D2,Size); {$ENDIF} end; procedure TWaveFormComputer.Init( const MaxTimeDelta, TimeDelta: Double; Src1,Src2:PSingle; ASize:Integer); begin tf2:=(TimeDelta + MaxTimeDelta)*0.5; if tf2<0 then tf2:=0; tf1:=MaxTimeDelta - tf2; if tf1<0 then tf1:=0; Size:=ASize; //Inc(ASize); SetLength(Data1,ASize); D1:=@(Data1[0]); SetLength(Data2,ASize); D2:=@(Data2[0]); SetLength(Appr2,ASize); A2:=@(Appr2[0]); CalcWaveData(Src1,D1,ASize); CalcWaveData(Src2,D2,ASize); // Inc(D1); Inc(A2); Inc(D2); end; procedure TWaveFormComputer.GetDrawData(var dA2, dD2: TArrayOfSingle); var i:Integer; p1,p2:PSingle; begin SetLength(dA2,Size); SetLength(dD2,Size); p1:=A2; p2:=D2; for i:=0 to Size-1 do begin dA2[i]:=p1^; dD2[i]:=p2^; Inc(p1); Inc(p2); end; end; end.
unit Frame3u; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TFrame3 = class(TFrame) ListBox1: TListBox; btnAdd: TButton; btnDelete: TButton; LabelFile: TLabel; Label1: TLabel; btnSave: TButton; procedure btnAddClick(Sender: TObject); procedure btnDeleteClick(Sender: TObject); procedure btnSaveClick(Sender: TObject); private { Private declarations } public procedure CreateWnd; override; end; implementation {$R *.DFM} procedure TFrame3.btnAddClick(Sender: TObject); var strNew: string; begin if InputQuery ('Enter new item', 'Text', strNew) then ListBox1.Items.Add (strNew); end; procedure TFrame3.btnDeleteClick(Sender: TObject); begin if ListBox1.ItemIndex >= 0 then ListBox1.Items.Delete (ListBox1.ItemIndex); end; procedure TFrame3.CreateWnd; begin inherited; // load data ListBox1.Items.LoadFromFile (LabelFile.Caption); end; procedure TFrame3.btnSaveClick(Sender: TObject); begin ListBox1.Items.SaveToFile (LabelFile.Caption); end; initialization RegisterClass (TFrame3); end.
unit MainUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Grids; type TMainForm = class(TForm) LeftListElement: TButton; RightListElement: TButton; TopStackElement: TButton; BotStackElement: TButton; EditAddingElement: TEdit; ButtonAddToList: TButton; Convert: TButton; LabelList: TLabel; LabelStack: TLabel; LabelAddedElement: TLabel; procedure ButtonAddToListClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ConvertClick(Sender: TObject); procedure LeftListElementClick(Sender: TObject); procedure RightListElementClick(Sender: TObject); procedure BotStackElementClick(Sender: TObject); procedure TopStackElementClick(Sender: TObject); private { Private declarations } public { Public declarations } end; TStackElement = ^TStack; TStack = Record Info: String; BotElement: TStackElement; TopElement: TStackElement; end; TListElement = ^TList; TList = Record Info: String; NextElement: TListElement; PrevEement: TListElement; end; var MainForm: TMainForm; FirstElement, List, ViewListElement: TListElement; FirstStackElement, ViewStackElement: TStackElement; implementation {$R *.dfm} procedure DrawButtons; begin if ViewListElement <> nil then begin MainForm.LeftListElement.Caption := ViewListElement.Info; MainForm.RightListElement.Caption := ViewListElement^.NextElement.Info; end; end; procedure SetActiveButtons; begin // top button if ViewStackElement^.TopElement^.TopElement = nil then MainForm.TopStackElement.Enabled := False else MainForm.TopStackElement.Enabled := True; // bot button if ViewStackElement^.BotElement^.Info = '' then MainForm.BotStackElement.Enabled := False else MainForm.BotStackElement.Enabled := True; end; procedure DrawStackButtons; begin MainForm.TopStackElement.Caption := ViewStackElement^.TopElement^.Info; MainForm.BotStackElement.Caption := ViewStackElement^.Info; SetActiveButtons; end; procedure AddToList(var ListElement: TListElement; AddElement: String); var NextELement: TListElement; begin if ListELement^.NextElement <> nil then begin New(NextElement); ListElement^.NextElement := NextElement; ListElement^.NextElement^.PrevEement := ListElement; ListElement := ListElement^.NextElement; end; ListElement^.Info := AddElement; ListElement^.NextElement := FirstElement; FirstElement^.PrevEement := ListElement; DrawButtons; end; procedure DelFromList(var DelElement: TListElement); begin if DelElement^.NextElement = DelElement then DelElement := nil else begin DelElement^.PrevEement^.NextElement := DelElement^.NextElement; DelElement^.NextElement^.PrevEement := DelElement^.PrevEement; end; end; procedure PushElement(PushElement: String); var NextElement: TStackElement; begin if FirstStackElement <> nil then begin New(NextElement); NextElement^.BotElement := FirstStackElement; NextElement^.TopElement := nil; FirstStackElement^.TopElement := NextElement; FirstStackElement := FirstStackElement^.TopElement end; FirstStackElement^.Info := PushElement; end; procedure TransportListToStack; var pushedList: TListElement; begin if FirstStackElement <> nil then begin Dispose(FirstStackElement); New(FirstStackElement); end; pushedList := FirstElement ; repeat PushElement(pushedList^.Info); pushedList := pushedList^.NextElement; until pushedList = FirstElement; end; procedure TMainForm.ButtonAddToListClick(Sender: TObject); begin AddToList(List, EditAddingElement.Text); LeftListElement.Enabled := True; RightListElement.Enabled := True; end; procedure InitFirstElement; begin New(List); List^.NextElement := nil; FirstElement := List; ViewListElement := List; end; procedure InitEmptyStack; begin New(FirstStackElement); ViewStackElement := FirstStackElement; FirstStackElement^.BotElement := nil; FirstStackElement^.TopElement := nil; end; procedure TMainForm.FormCreate(Sender: TObject); begin InitFirstElement; end; procedure TMainForm.ConvertClick(Sender: TObject); begin if FirstStackElement <> nil then Dispose(FirstStackElement); InitEmptyStack; TransportListToStack; ViewStackElement := ViewStackElement^.TopElement; DrawStackButtons; end; procedure TMainForm.LeftListElementClick(Sender: TObject); begin ViewListElement := ViewListElement^.PrevEement ; DrawButtons; end; procedure TMainForm.RightListElementClick(Sender: TObject); begin ViewListElement := ViewListElement^.NextElement ; DrawButtons; end; procedure TMainForm.BotStackElementClick(Sender: TObject); begin if ViewStackElement^.BotElement <> nil then ViewStackElement := ViewStackElement^.BotElement; DrawStackButtons; end; procedure TMainForm.TopStackElementClick(Sender: TObject); begin if ViewStackElement^.TopElement <> nil then ViewStackElement := ViewStackElement^.TopElement; DrawStackButtons; end; end.
unit ContactForma; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, DB, FIBDataSet, pFIBDataSet, DBGridEh, StdCtrls, DBCtrls, Mask, DBCtrlsEh, DBLookupEh, CnErrorProvider, FIBQuery, PrjConst, System.UITypes, Vcl.Buttons; type TContact = Record cID: Integer; cType: String; Contact: String; Notice: String; Notify: Integer; End; TMaskEdit = class(Mask.TMaskEdit) protected procedure ValidateError; override; end; TContactForm = class(TForm) srcContactType: TDataSource; dsContactType: TpFIBDataSet; cbbContactType: TDBLookupComboboxEh; memNotice: TDBMemoEh; lblAttribute: TLabel; Label2: TLabel; CnErrors: TCnErrorProvider; chkNotify: TDBCheckBoxEh; btnOk: TBitBtn; btnCancel: TBitBtn; dbValue: TMaskEdit; procedure cbbContactTypeChange(Sender: TObject); procedure btnOkClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure dbValueExit(Sender: TObject); end; function EditContact(var Contact: TContact): Boolean; implementation uses DM, CF, RegularExpressions, pFIBQuery, Vcl.Consts, System.MaskUtils; {$R *.dfm} // перехватим вызов исключения при проверки maskedit и просто покажем сообщение procedure TMaskEdit.ValidateError; begin ShowMessage(SMaskEditErr); end; function EditContact(var Contact: TContact): Boolean; begin with TContactForm.Create(Application) do try dsContactType.Open; chkNotify.Checked := False; if (Contact.cID > -1) then begin cbbContactType.Value := Contact.cID; dbValue.Text := Contact.Contact; chkNotify.Checked := (Contact.Notify = 1); memNotice.Lines.Text := Contact.Notice; end else begin cbbContactType.Value := 1; chkNotify.Checked := True; end; if ShowModal = mrOk then begin Contact.cID := cbbContactType.Value; Contact.cType := cbbContactType.Text; Contact.Contact := dbValue.Text; if chkNotify.Checked then Contact.Notify := 1 else Contact.Notify := 0; Contact.Notice := memNotice.Lines.Text; result := true; end else begin result := False; end; finally free end; end; procedure TContactForm.btnOkClick(Sender: TObject); var errors, ce: Boolean; s: string; reg: string; c: Char; begin errors := False; if (cbbContactType.Text = '') then begin errors := true; CnErrors.SetError(cbbContactType, rsEmptyFieldError, iaMiddleLeft, bsNeverBlink); end else CnErrors.Dispose(cbbContactType); ce := False; if ((dbValue.Text <> '')) then begin if dsContactType['REGEXP'] <> '' then begin s := dbValue.Text; reg := '^' + dsContactType['REGEXP'] + '$'; ce := not TRegEx.IsMatch(s, reg); end else begin if (dbValue.EditMask <> '') then begin // проверим есть ли пустой символ шаблона в тексте c := MaskGetMaskBlank(dbValue.EditMask); ce := (Pos(c, dbValue.Text) > 0); end else ce := False; end; end; if ce then begin errors := true; CnErrors.SetError(dbValue, rsInputIncorrect, iaMiddleLeft, bsNeverBlink) end else CnErrors.Dispose(dbValue); if not errors then ModalResult := mrOk else ModalResult := mrNone; end; procedure TContactForm.cbbContactTypeChange(Sender: TObject); var s: string; begin CnErrors.Dispose(dbValue); if dbValue.EditMask <> '' then dbValue.EditMask := ''; if dsContactType['REGEXP'] = '' then begin s := ''; if (cbbContactType.Value = 0) then s := dmMain.GetSettingsValue('PHONE_FMT') else if (cbbContactType.Value = 1) then s := dmMain.GetSettingsValue('MOBILE_FMT'); if s <> '' then dbValue.EditMask := s + ';1;_'; end; end; procedure TContactForm.dbValueExit(Sender: TObject); begin // end; procedure TContactForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Shift = [ssCtrl]) and (Ord(Key) = VK_RETURN) then btnOkClick(Sender); end; procedure TContactForm.FormKeyPress(Sender: TObject; var Key: Char); var go: Boolean; begin if (Key = #13) then begin go := true; if (ActiveControl is TDBLookupComboboxEh) then go := not(ActiveControl as TDBLookupComboboxEh).ListVisible else if (ActiveControl is TDBMemoEh) then go := (ActiveControl as TDBMemoEh).Lines.Text.IsEmpty; if go then begin Key := #0; // eat enter key PostMessage(self.Handle, WM_NEXTDLGCTL, 0, 0); end; end; end; end.
// This unit published all UI elements so makes them accessible from scripts // // Copyright (C) 2020 Ivan Polyacov, Apus Software (ivan@apus-software.com) // This file is licensed under the terms of BSD-3 license (see license.txt) // This file is a part of the Apus Game Engine (http://apus-software.com/engine/) unit UIScript; interface implementation uses MyServis,SysUtils,EventMan,Publics,CmdProc,EngineAPI,UIClasses,Geom2d; type TDefaults=record parentObj:TUICOntrol; // parent element used for creating new elements x,y,width,height,hintDelay,hintDuration:integer; color,backgnd:cardinal; font,style,cursor:integer; caption:string; align:TTextAlignment; end; // TVarType=(vtNone,vtInt,vtByte,vtStr,vtBool,vtSendSignals,vtAlignment,vtBtnStyle,vtTranspMode); TVarTypeUIControl=class(TVarTypeStruct) class function GetField(variable:pointer;fieldName:string;out varClass:TVarClass):pointer; override; class function ListFields:String; override; end; TVarTypeStyleinfo=class(TVarType) class procedure SetValue(variable:pointer;v:string); override; class function GetValue(variable:pointer):string; override; end; TVarTypeTranspMode=class(TVarTypeEnum) class procedure SetValue(variable:pointer;v:string); override; class function GetValue(variable:pointer):string; override; end; TVarTypeSendSignals=class(TVarTypeEnum) class procedure SetValue(variable:pointer;v:string); override; class function GetValue(variable:pointer):string; override; end; TVarTypeBtnStyle=class(TVarTypeEnum) class procedure SetValue(variable:pointer;v:string); override; class function GetValue(variable:pointer):string; override; end; TVarTypePivot=class(TVarTypeEnum) class procedure SetValue(variable:pointer;v:string); override; class function GetValue(variable:pointer):string; override; end; var defaults:TDefaults; // default values used when new element is created curobjname:string; // current element name in upper case procedure onItemCreated(event:eventstr;tag:TTag); var c:TUIControl; begin c:=TUIControl(tag); if c.name<>'' then PublishVar(c,c.name,TVarTypeUIControl); end; procedure onItemRenamed(event:eventstr;tag:TTag); var c:TUIControl; begin c:=TUIControl(tag); UnpublishVar(c); if c.name<>'' then PublishVar(c,c.name,TVarTypeUIControl); end; procedure UseParentCmd(cmd:string); var c:TUIControl; begin EnterCriticalSection(UICritSect); try delete(cmd,1,10); cmd:=UpperCase(cmd); if (defaults.parentObj<>nil) and (UpperCase(defaults.parentObj.name)=cmd) then exit; c:=FindControl(cmd,false); if c=nil then raise EWarning.Create('Object not found - '+cmd); defaults.parentObj:=c; finally LeaveCriticalSection(UICritSect); end; end; procedure SetFocusCmd(cmd:string); var c:TUIControl; begin EnterCriticalSection(UICritSect); try if length(cmd)=8 then c:=curobj else begin if cmd[length(cmd)-8]<>'.' then raise EError.Create('Syntax error, object not specified!'); setLength(cmd,length(cmd)-9); c:=FindControl(cmd,false); end; if c=nil then raise EError.Create('No object!'); if not c.canHaveFocus then raise EError.Create('This object can''t have focus!'); c.SetFocus; finally LeaveCriticalSection(UICritSect); end; end; procedure CreateCmd(cmd:string); var sa:StringArr; c:TUIControl; begin EnterCriticalSection(UICritSect); try if defaults.parentObj=nil then raise EError.Create('No object selected, use "UseParent" to select parent object first!'); delete(cmd,1,7); sa:=Split(' ',cmd,'"'); if length(sa)<>2 then raise EError.Create('Must have 2 parameters'); sa[0]:=uppercase(chop(sa[0])); c:=FindControl(sa[1],false); if c<>nil then begin curObj:=c; curObjClass:=TVarTypeUIControl; curObjName:=UpperCase(c.name); exit; end; with defaults do begin if sa[0]='UIBUTTON' then c:=TUIButton.Create(width,height,sa[1],caption,font,parentobj) else if sa[0]='UIIMAGE' then c:=TUIImage.Create(width,height,sa[1],parentobj) else if sa[0]='UIEDITBOX' then c:=TUIEditBox.Create(width,height,sa[1],font,color,parentobj) else if sa[0]='UILABEL' then begin c:=TUILabel.Create(width,height,sa[1],caption,color,font,parentobj); (c as TUILabel).align:=align; c.transpmode:=tmTransparent; end else if sa[0]='UICONTROL' then begin c:=TUIControl.Create(width,height,parentobj,sa[1]); end else if sa[0]='UILISTBOX' then c:=TUIListBox.Create(width,height,20,sa[1],font,parentobj) else if sa[0]='UICOMBOBOX' then c:=TUIComboBox.Create(width,height,font,nil,parentobj,sa[1]); if c=nil then raise EError.Create('Unknown class - '+sa[0]); // Доп. св-ва if style<>0 then c.style:=style; if cursor<>0 then c.cursor:=cursor; if HintDelay<>0 then c.hintDelay:=hintDelay; if HintDuration<>0 then c.hintDuration:=hintDuration; end; curobj:=c; curObjClass:=TVarTypeUIControl; curobjname:=c.name; finally LeaveCriticalSection(UICritSect); end; end; function StrToAlign(s:string):TTextAlignment; begin s:=uppercase(s); result:=taLeft; if s='RIGHT' then result:=taRight; if s='CENTER' then result:=taCenter; if s='JUSTIFY' then result:=taJustify; end; function EvalInt(st:string):int64; begin result:=round(EvalFloat(st,nil,curObj,curObjClass)); end; {$IFDEF FPC}{$PUSH}{$R-}{$ENDIF} procedure DefaultCmd(cmd:string); var sa:StringArr; begin delete(cmd,1,7); sa:=Split(' ',cmd,'"'); sa[0]:=UpperCase(sa[0]); if sa[0]='X' then defaults.X:=EvalInt(sa[1]) else if sa[0]='Y' then defaults.Y:=EvalInt(sa[1]) else if sa[0]='WIDTH' then defaults.Width:=EvalInt(sa[1]) else if sa[0]='HEIGHT' then defaults.Height:=EvalInt(sa[1]) else if sa[0]='HINTDELAY' then defaults.hintDelay:=EvalInt(sa[1]) else if sa[0]='HINTDURATION' then defaults.hintDuration:=EvalInt(sa[1]) else if sa[0]='COLOR' then defaults.Color:=EvalInt(sa[1]) else if sa[0]='BACKGND' then defaults.Backgnd:=EvalInt(sa[1]) else if sa[0]='FONT' then defaults.Font:=EvalInt(sa[1]) else if sa[0]='CURSOR' then defaults.Cursor:=EvalInt(sa[1]) else if sa[0]='STYLE' then defaults.Style:=EvalInt(sa[1]) else if sa[0]='CAPTION' then defaults.caption:=sa[1] else if sa[0]='ALIGN' then defaults.align:=StrToAlign(sa[1]) else raise EWarning.Create('Incorrect command - '+cmd); end; {$IFDEF FPC}{$POP}{$ENDIF} procedure SetHotKeyCmd(cmd:string); var key,shift:byte; v,i,d:integer; sa:stringArr; obj:TUIControl; begin EnterCriticalSection(UICritSect); try delete(cmd,1,10); cmd:=UpperCase(cmd); obj:=curobj; if (obj=nil) or not (obj is TUIControl) then raise EWarning.Create('No UI object selected'); sa:=Split('+',cmd,#0); v:=0; for i:=0 to length(sa)-1 do begin if sa[i]='ENTER' then d:=13 else if sa[i]='SPACE' then d:=32 else if sa[i]='ESC' then d:=27 else if sa[i]='SHIFT' then d:=$100 else if sa[i]='CTRL' then d:=$200 else if sa[i]='ALT' then d:=$400 else d:=StrToInt(sa[i]); v:=v+d; end; if v=0 then obj.ReleaseHotKey(0,0) else begin key:=v and 255; shift:=v shr 8; obj.SetHotKey(key,shift); end; finally LeaveCriticalSection(UICritSect); end; end; { TVarTypeUIControl } class function TVarTypeUIControl.GetField(variable: pointer; fieldName: string; out varClass: TVarClass): pointer; var obj:TUIControl; begin obj:=variable; ASSERT(fieldName<>''); result:=nil; varClass:=nil; case fieldname[1] of 'a':if (fieldname='align') and (obj is TUILabel) then begin result:=@TUILabel(obj).align; varClass:=TVarTypeAlignment; end else if (fieldname='anchors') then begin result:=@obj.anchorLeft; varClass:=TVarTypeRect2s; end else if (fieldname='autopendingtime') and (obj is TUIButton) then begin result:=@TUIButton(obj).autopendingtime; varClass:=TVarTypeInteger; end; 'b':if (fieldname='btnstyle') and (obj is TUIButton) then begin result:=@TUIButton(obj).btnstyle; varClass:=TVarTypeBtnStyle; end; 'c':if fieldname='canhavefocus' then begin result:=@obj.canHaveFocus; varClass:=TVarTypeBool; end else if fieldname='color' then begin if obj is TUILabel then result:=@TUILabel(obj).color else if obj is TUIEditBox then result:=@TUIEditBox(obj).color else if obj is TUIImage then result:=@TUIImage(obj).color else if obj is TUIScrollBar then result:=@TUIScrollBar(obj).color else exit; varClass:=TVarTypeARGB; end else if fieldname='caption' then begin if obj is TUILabel then result:=@TUILabel(obj).caption else if obj is TUIButton then result:=@TUIButton(obj).caption else if obj is TUIWindow then result:=@TUIWindow(obj).caption else exit; varClass:=TVarTypeString; end else if fieldname='cursor' then begin result:=@obj.cursor; varClass:=TVarTypeInteger; end else if fieldname='clipchildren' then begin result:=@obj.clipchildren; varClass:=TVarTypeBool; end else if fieldname='customdraw' then begin result:=@obj.customdraw; varClass:=TVarTypeBool; end; 'd':if (fieldname='default') and (obj is TUIButton) then begin result:=@TUIButton(obj).default; varClass:=TVarTypeBool; end; 'e':if fieldname='enabled' then begin result:=@obj.enabled; varClass:=TVarTypeBool; end; 'f':if fieldname='font' then begin if obj is TUIButton then result:=@TUIButton(obj).font else if obj is TUILabel then result:=@TUILabel(obj).font else if obj is TUIEditBox then result:=@TUIEditBox(obj).font else if obj is TUIListBox then result:=@TUIListBox(obj).font else if obj is TUIComboBox then result:=@TUIComboBox(obj).font else if obj is TUIWindow then result:=@TUIWindow(obj).font else exit; varClass:=TVarTypeCardinal; end; 'g':if (fieldname='group') and (obj is TUIButton) then begin result:=@TUIButton(obj).group; varClass:=TVarTypeInteger; end; 'h':if fieldname='height' then begin result:=@obj.size.y; varClass:=TVarTypeSingle; end else if fieldname='hint' then begin result:=@obj.hint; varClass:=TVarTypeString; end else if fieldname='hintifdisabled' then begin result:=@obj.hintifdisabled; varClass:=TVarTypeString; end else if fieldname='hintdelay' then begin result:=@obj.hintdelay; varClass:=TVarTypeInteger; end else if fieldname='hintduration' then begin result:=@obj.hintduration; varClass:=TVarTypeInteger; end; 'l':if (fieldname='lineheight') and (obj is TUIListBox) then begin varClass:=TVarTypeInteger; result:=@TUIListBox(obj).lineHeight; end; 'm':if (fieldname='maxlength') and (obj is TUIEditBox) then begin varClass:=TVarTypeInteger; result:=@TUIEditBox(obj).maxlength; end else if (fieldname='min') and (obj is TUIScrollBar) then begin varClass:=TVarTypeInteger; result:=@TUIScrollBar(obj).min; end else if (fieldname='max') and (obj is TUIScrollBar) then begin varClass:=TVarTypeInteger; result:=@TUIScrollBar(obj).max; end; 'n':if fieldname='name' then begin result:=@obj.name; varClass:=TVarTypeString8; end else if (fieldname='noborder') and (obj is TUIEditBox) then begin result:=@TUIEditBox(obj).noborder; varClass:=TVarTypeBool; end; 'o':if fieldname='order' then begin result:=@obj.order; varClass:=TVarTypeInteger; end; 'p':if fieldname='parentclip' then begin result:=@obj.parentClip; varClass:=TVarTypeBool; end else if fieldname='parent' then begin result:=obj.parent; varClass:=TVarTypeUIControl; end else if fieldname='pivot' then begin result:=@obj.pivot; varClass:=TVarTypePivot; end else if (fieldname='pressed') and (obj is TUIButton) then begin result:=@TUIButton(obj).pressed; varClass:=TVarTypeBool; end else if (fieldname='pending') and (obj is TUIButton) then begin result:=@TUIButton(obj).pending; varClass:=TVarTypeBool; end else if (fieldname='password') and (obj is TUIEditBox) then begin result:=@TUIEditBox(obj).password; varClass:=TVarTypeBool; end else if fieldname='paddingleft' then begin result:=@obj.paddingLeft; varClass:=TVarTypeSingle; end else if fieldname='paddingright' then begin result:=@obj.paddingright; varClass:=TVarTypeSingle; end else if fieldname='paddingtop' then begin result:=@obj.paddingtop; varClass:=TVarTypeSingle; end else if fieldname='paddingbottom' then begin result:=@obj.paddingbottom; varClass:=TVarTypeSingle; end else if (fieldname='pagesize') and (obj is TUIScrollBar) then begin varClass:=TVarTypeInteger; result:=@TUIScrollBar(obj).pagesize; end; 's':if fieldname='style' then begin result:=@obj.style; varClass:=TVarTypeInteger; end else if fieldname='styleinfo' then begin result:=obj; varClass:=TVarTypeStyleinfo; end else if fieldname='scalex' then begin result:=@obj.scale.x; varClass:=TVarTypeSingle; end else if fieldname='scaley' then begin result:=@obj.scale.y; varClass:=TVarTypeSingle; end else if fieldname='signals' then begin result:=@obj.sendsignals; varClass:=TVarTypeSendSignals; end else if (fieldname='src') and (obj is TUIImage) then begin result:=@TUIImage(obj).src; varClass:=TVarTypeString; end; 't':if fieldname='transpmode' then begin result:=@obj.transpmode; varClass:=TVarTypeTranspMode; end else if (fieldname='text') and (obj is TUIEditBox) then begin varClass:=TVarTypeWideString; result:=@TUIEditBox(obj).realtext; end else if (fieldname='topofs') and (obj is TUILabel) then begin varClass:=TVarTypeInteger; result:=@TUILabel(obj).topoffset; end; 'v':if fieldname='visible' then begin result:=@obj.visible; varClass:=TVarTypeBool; { end else if (fieldname='value') and (obj is TUIScrollBar) then begin varClass:=TVarTypeInteger; result:=@TUIScrollBar(obj).value;} end; 'w':if fieldname='width' then begin result:=@obj.size.x; varClass:=TVarTypeSingle; end; 'x':if fieldname='x' then begin result:=@obj.position.x; varClass:=TVarTypeSingle; end; 'y':if fieldname='y' then begin result:=@obj.position.y; varClass:=TVarTypeSingle; end; end; end; class function TVarTypeUIControl.ListFields: String; begin result:='name,x,y,width,height,scaleX,scaleY,visible,enabled'; end; class procedure TVarTypeTranspMode.SetValue(variable:pointer;v:string); begin v:=lowercase(v); if v='transparent' then TTranspMode(variable^):=tmTransparent else if v='custom' then TTranspMode(variable^):=tmCustom else if v='opaque' then TTranspMode(variable^):=tmOpaque else raise EWarning.Create('Unknown transparency mode: '+v); end; class function TVarTypeTranspMode.GetValue(variable:pointer):string; begin case TTranspMode(variable^) of tmTransparent:result:='transparent'; tmOpaque:result:='opaque'; tmCustom:result:='custom'; end; end; class procedure TVarTypeSendSignals.SetValue(variable:pointer;v:string); begin v:=lowercase(v); if v='major' then TSendSignals(variable^):=ssMajor else if v='all' then TSendSignals(variable^):=ssAll else if v='none' then TSendSignals(variable^):=ssNone else raise EWarning.Create('Unknown SendSignals mode: '+v); end; class function TVarTypeSendSignals.GetValue(variable:pointer):string; begin case TSendSignals(variable^) of ssMajor:result:='major'; ssAll:result:='all'; ssNone:result:='none'; end; end; class procedure TVarTypeBtnStyle.SetValue(variable:pointer;v:string); begin v:=lowercase(v); if v='normal' then TButtonStyle(variable^):=bsNormal else if v='switch' then TButtonStyle(variable^):=bsSwitch else if (v='item') or (v='checkbox') then TButtonStyle(variable^):=bsCheckbox else raise EWarning.Create('Unknown BtnStyle: '+v); end; class function TVarTypeBtnStyle.GetValue(variable:pointer):string; begin case TButtonStyle(variable^) of bsNormal:result:='normal'; bsSwitch:result:='switch'; bsCheckbox:result:='checkbox'; end; end; { TVarTypePivot } class function TVarTypePivot.GetValue(variable: pointer): string; var p:TPoint2s; begin p:=TPoint2s(variable^); result:=Format('(%.2f,%.2f)',[p.x,p.y]); end; class procedure TVarTypePivot.SetValue(variable: pointer; v: string); begin if SameText(v,'Center') then TPoint2s(variable^):=pivotCenter else if SameText(v,'TopLeft') then TPoint2s(variable^):=pivotTopLeft else if SameText(v,'TopRight') then TPoint2s(variable^):=pivotTopRight else if SameText(v,'BottomLeft') then TPoint2s(variable^):=pivotBottomLeft else if SameText(v,'BottomRight') then TPoint2s(variable^):=pivotBottomRight else raise EWarning.Create('Invalid pivot value: '+v); end; { TVarTypeStyleinfo } class function TVarTypeStyleinfo.GetValue(variable: pointer): string; begin result:=TUIControl(variable).styleInfo; end; class procedure TVarTypeStyleinfo.SetValue(variable: pointer; v: string); begin TUIControl(variable).styleInfo:=v; end; initialization SetEventHandler('UI\ItemCreated',onItemCreated,emInstant); SetEventHandler('UI\ItemRenamed',onItemRenamed,emInstant); SetCmdFunc('USEPARENT ',opFirst,UseParentCmd); SetCmdFunc('CREATE ',opFirst,CreateCmd); SetCmdFunc('DEFAULT',opFirst,DefaultCmd); SetCmdFunc('SETFOCUS',opLast,SetFocusCmd); SetCmdFunc('SETHOTKEY',opFirst,setHotKeyCmd); with defaults do begin x:=0; y:=0; width:=100; height:=20; color:=$FFFFFFFF; backgnd:=$80000000; style:=0; cursor:=crDefault; font:=1; caption:=''; hintDelay:=0; hintDuration:=0; end; finalization end.
unit WaitMessage; interface uses Windows, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, vtGradientWaitbar; type TWaitMessageForm = class(TForm) f_GradientWaitBar: TvtGradientWaitbar; f_GradientWaitBarPanel: TPanel; f_WaitMessageMemo: TMemo; // procedure FormCreate(a_Sender: TObject); procedure FormCloseQuery(a_Sender: TObject; var a_CanClose: Boolean); private procedure pm_SetText(const a_Value: string); public property Text: string write pm_SetText; end; var WaitMessageForm: TWaitMessageForm; implementation {$R *.DFM} uses SysUtils , LocaleMessages ; procedure TWaitMessageForm.FormCreate(a_Sender: TObject); begin Caption := Application.Title; end; procedure TWaitMessageForm.FormCloseQuery(a_Sender: TObject; var a_CanClose: Boolean); begin a_CanClose := False; end; procedure TWaitMessageForm.pm_SetText(const a_Value: string); begin with f_WaitMessageMemo.Lines do begin Clear; // Add(Format(GetCurrentLocaleMessage(c_GarantWaitMessageFormOperationInProgress), [a_Value])); end; end; end.
{***************************************************************************} { } { ICollections - Copyright (C) 2013 - Víctor de Souza Faria } { } { victor@victorfaria.com } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit ICollections.List; interface uses System.SysUtils, System.Generics.Defaults, ICollections.Default; type IList<T> = interface(IEnumerable<T>) ['{5A627266-1B07-4348-8E3B-547D8F8EDE6D}'] function GetItem(Index: Integer): T; procedure SetItem(Index: Integer; const Value: T); function Add(const Value: T): Integer; procedure AddRange(const Value: IEnumerable<T>); procedure Append(const Value: IList<T>); function Contains(const Value: T): Boolean; function First: T; function Last: T; function IsEmpty: Boolean; function Remove(const Value: T): Integer; function IndexOf(const Value: T): Integer; function FindAll(const Expr: TFunc<T, Boolean>): IList<T>; procedure Clear; function GetCapacity: Integer; procedure SetCapacity(Value: Integer); function GetCount: Integer; property Capacity: Integer read GetCapacity write SetCapacity; property Count: Integer read GetCount; property Items[Index: Integer]: T read GetItem write SetItem; default; end; TIntList<T> = class(TInterfacedObject, IList<T>) strict private FITems: array of T; FCount: Integer; FCapacity: Integer; FComparer: IComparer<T>; procedure Resize(NewSize: Integer); function GetCapacity: Integer; procedure SetCapacity(Value: Integer); function GetCount: Integer; function GetItem(Index: Integer): T; procedure SetItem(Index: Integer; const Value: T); public constructor Create; overload; constructor Create(Capacity: Integer); overload; constructor Create(Capacity: Integer; Comparer: IComparer<T>); overload; property Capacity: Integer read GetCapacity write SetCapacity; property Count: Integer read GetCount; property Items[Index: Integer]: T read GetItem write SetItem; default; function IndexOf(const Value: T): Integer; function FindAll(const Expr: TFunc<T, Boolean>): IList<T>; function IsEmpty: Boolean; function Add(const Value: T): Integer; procedure AddRange(const Value: IEnumerable<T>); procedure Append(const Value: IList<T>); function Contains(const Value: T): Boolean; procedure Clear; function First: T; function Last: T; function Remove(const Value: T): Integer; function GetEnumerator: IEnumerator<T>; type TEnumerator = class(TInterfacedObject, IEnumerator<T>) private FList: IList<T>; FIndex: Integer; function GetCurrent: T; public constructor Create(List: IList<T>); property Current: T read GetCurrent; function MoveNext: Boolean; end; end; implementation uses System.RTLConsts; function TIntList<T>.Add(const Value: T): Integer; begin Resize(FCount + 1); FITems[FCount] := Value; Result := FCount; Inc(FCount); end; procedure TIntList<T>.AddRange(const Value: IEnumerable<T>); var Item: T; begin for Item in Value do begin Add(Item); end; end; procedure TIntList<T>.Append(const Value: IList<T>); var i: Integer; begin Resize(FCount + Value.Count); for i := 0 to Value.Count - 1 do begin FITems[FCount] := Value[i]; Inc(FCount); end; end; procedure TIntList<T>.Clear; begin FillChar(FItems[Count], SizeOf(T), 0); FCount := 0; end; function TIntList<T>.Contains(const Value: T): Boolean; begin Result := IndexOf(Value) >= 0; end; constructor TIntList<T>.Create(Capacity: Integer; Comparer: IComparer<T>); begin inherited Create; FCount := 0; Self.Capacity := Capacity; FComparer := Comparer; end; constructor TIntList<T>.Create(Capacity: Integer); begin Create(Capacity, TComparer<T>.Default); end; function TIntList<T>.FindAll(const Expr: TFunc<T, Boolean>): IList<T>; var i: Integer; begin Result := TIntList<T>.Create; for i := 0 to FCount - 1 do begin if Expr(FItems[i]) then begin Result.Add(FItems[i]); end; end; end; function TIntList<T>.First: T; begin if Count > 0 then begin Result := FItems[0]; end; end; constructor TIntList<T>.Create; begin Create(0, TComparer<T>.Default); end; function TIntList<T>.GetCapacity: Integer; begin Result := FCapacity; end; function TIntList<T>.GetCount: Integer; begin Result := FCount; end; function TIntList<T>.GetEnumerator: IEnumerator<T>; begin Result := TIntList<T>.TEnumerator.Create(Self); end; function TIntList<T>.GetItem(Index: Integer): T; begin if (Index >= FCount) or (Index < 0) then begin raise EArgumentOutOfRangeException.CreateRes(@SArgumentOutOfRange); end; Result := FITems[Index]; end; function TIntList<T>.IndexOf(const Value: T): Integer; var i: Integer; found: Boolean; begin i := -1; found := False; while (i < FCount) and not found do begin Inc(i); found := FComparer.Compare(FITems[i], Value) = 0; end; if found then begin Result := i; end else begin Result := -1; end; end; function TIntList<T>.IsEmpty: Boolean; begin Result := FCount = 0; end; function TIntList<T>.Last: T; begin Result := FITems[Count - 1]; end; function TIntList<T>.Remove(const Value: T): Integer; var index: Integer; begin index := IndexOf(Value); if (index > -1) then begin //Force lose of reference to desalocate memory FItems[index] := Default(T); System.Move(FItems[index + 1], FItems[index], (Count - index) * SizeOf(T)); FillChar(FItems[Count], SizeOf(T), 0); Dec(FCount); end; end; procedure TIntList<T>.Resize(NewSize: Integer); var newAllocation: Integer; begin // Based on Python Implementation if (FCapacity >= NewSize) then begin exit; end; newAllocation := (newsize Shr 3); if newsize < 9 then newAllocation := newAllocation + 3 else newAllocation := newAllocation + 6; FCapacity := NewSize + newAllocation; SetLength(FITems, FCapacity); end; procedure TIntList<T>.SetCapacity(Value: Integer); begin Resize(Value); end; procedure TIntList<T>.SetItem(Index: Integer; const Value: T); begin if Index >= FCount then begin raise EArgumentOutOfRangeException.CreateRes(@SArgumentOutOfRange); end; FITems[Index] := Value; end; { TIntList<T>.TEnumerator<T> } constructor TIntList<T>.TEnumerator.Create(List: IList<T>); begin FList := List; FIndex := -1; end; function TIntList<T>.TEnumerator.GetCurrent: T; begin Result := FList[FIndex]; end; function TIntList<T>.TEnumerator.MoveNext: Boolean; begin if (FIndex < FList.Count - 1) then begin Inc(FIndex); Result := True; end else begin Result := False; end; end; end.
unit MdiChilds.PriceSRC; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, MDIChilds.CustomDialog, JvComponentBase, JvDragDrop, Vcl.StdCtrls, Vcl.ExtCtrls, MdiChilds.ProgressForm, Parsers.SRC, ActionHandler; type TFmPriceSRCReader = class(TFmProcess) lbFiles: TListBox; DragDrop: TJvDragDrop; procedure DragDropDrop(Sender: TObject; Pos: TPoint; Value: TStrings); private { Private declarations } protected procedure DoOk(Sender: TObject; ProgressForm: TFmProgress; var ShowMessage: Boolean); override; public { Public declarations } end; TSRCActionHandler = class (TAbstractActionHandler) public procedure ExecuteAction(UserData: Pointer = nil); override; end; var FmPriceSRCReader: TFmPriceSRCReader; implementation {$R *.dfm} procedure TFmPriceSRCReader.DoOk(Sender: TObject; ProgressForm: TFmProgress; var ShowMessage: Boolean); var Parser: TPriceSRCParser; I: Integer; begin ProgressForm.InitPB(lbFiles.Count); ProgressForm.Show; ShowMessage := True; for I := 0 to lbFiles.Count - 1 do begin ProgressForm.StepIt(lbFiles.Items[I]); if ProgressForm.InProcess then begin Parser := TPriceSRCParser.Create; try Parser.LoadFromFile(lbFiles.Items[I]); try Parser.Parse(ChangeFileExt(lbFiles.Items[I], '.xml')); except on E: Exception do Self.MessageBoxError(E.Message); end; finally Parser.Free; end; end else Break; end; end; procedure TFmPriceSRCReader.DragDropDrop(Sender: TObject; Pos: TPoint; Value: TStrings); begin lbFiles.Items.Assign(Value); end; { TSRCActionHandler } procedure TSRCActionHandler.ExecuteAction(UserData: Pointer); begin TFmPriceSRCReader.Create(Application).Show; end; begin ActionHandlerManager.RegisterActionHandler('Импорт ценника SRC', hkDefault, TSRCActionHandler); end.
unit UBSExplorer.RegistrySettings; interface uses System.Win.Registry, Winapi.Windows, Vcl.Themes, Vcl.Styles; type TSettings = class public const RegistryPath = 'Software\UBS-Explorer'; private FChanged: Boolean; FTheme: string; procedure Load; procedure Save; procedure Change; procedure SetTheme(const Value: string); public constructor Create; destructor Destroy; override; procedure InitDefaults; property Changed: Boolean read FChanged; property Theme: string read FTheme write SetTheme; end; var Settings: TSettings; implementation { TSettings } procedure TSettings.Change; begin FChanged := True; end; constructor TSettings.Create; begin InitDefaults; Load; end; destructor TSettings.Destroy; begin if Changed then Save; inherited; end; procedure TSettings.InitDefaults; begin Theme := 'Carbon'; end; procedure TSettings.Load; var Reg: TRegistry; begin Reg := TRegistry.Create; try Reg.RootKey := HKEY_CURRENT_USER; if not Reg.OpenKey(RegistryPath, False) then Exit; Theme := Reg.ReadString('Theme'); finally Reg.Free; end; end; procedure TSettings.Save; var Reg: TRegistry; begin Reg := TRegistry.Create; try Reg.RootKey := HKEY_CURRENT_USER; if not Reg.Openkey(RegistryPath, True) then Exit; Reg.WriteString('Theme', Theme); finally Reg.Free; end; end; procedure TSettings.SetTheme(const Value: string); begin if Theme = Value then Exit; FTheme := Value; TStyleManager.TrySetStyle(Theme); Change; end; initialization Settings := TSettings.Create; finalization Settings.Free; end.
unit Iniciar; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Web.Win.Sockets, Vcl.ExtCtrls, Hashes, Math, StrUtils, Vcl.StdCtrls, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, Soap.EncdDecd, uTPLb_BaseNonVisualComponent, uTPLb_CryptographicLibrary, uTPLb_Codec, ActiveX, Vcl.Imaging.GIFImg, Vcl.ComCtrls; type TfrmIniciar = class(TForm) Pedir: TTimer; Cliente: TIdTCPClient; CryptographicLibrary1: TCryptographicLibrary; Codec: TCodec; Panel1: TPanel; Udp: TUdpSocket; Bar1: TProgressBar; procedure FormShow(Sender: TObject); procedure PedirTimer(Sender: TObject); procedure ClienteConnected(Sender: TObject); procedure FormCreate(Sender: TObject); procedure tito1Timer(Sender: TObject); private { Private declarations } Host: String; Validado: Boolean; function newHash(Str: String; index: Integer): String; function GetValida:String; function GetInfoBiosSerials:String; procedure ConfigInitDb(Sender: TObject; text: String); procedure ExecNewProcess(ProgramName : String); procedure VerificaVersion; public { Public declarations } end; var frmIniciar: TfrmIniciar; const PBS_MARQUEE = $08; PBM_SETMARQUEE = WM_USER+10; implementation {$R *.dfm} uses Data, uSMBIOS, CodigoCon, Clave; function bintoAscii(const bin: array of byte): AnsiString; var i: integer; begin SetLength(Result, Length(bin)); for i := 0 to Length(bin)-1 do Result[1+i] := AnsiChar(bin[i]); end; function GetSerial:string; var G,S:string; VolumeNameBuffer : array [0..MAX_PATH] of Char; VolumeSerialNumber : DWord; MaximumComponentLength : DWord; FileSystemFlags : DWord; begin S:=''; G:=GetCurrentDir; G:=Copy(G,1,3); GetVolumeInformation( PChar(G) ,VolumeNameBuffer ,DWORD(sizeof(VolumeNameBuffer)) ,@VolumeSerialNumber ,MaximumComponentLength ,FileSystemFlags ,nil ,0); S :=S+IntToHex(VolumeSerialNumber,8); Result:=CalcHash2(S,haMD5); end; procedure TfrmIniciar.ExecNewProcess(ProgramName : String); var StartInfo : TStartupInfo; ProcInfo : TProcessInformation; CreateOK : Boolean; begin FillChar(StartInfo,SizeOf(TStartupInfo),#0); FillChar(ProcInfo,SizeOf(TProcessInformation),#0); StartInfo.cb := SizeOf(TStartupInfo); CreateOK := CreateProcess(PChar(ProgramName),nil, nil, nil,False, CREATE_NEW_PROCESS_GROUP+NORMAL_PRIORITY_CLASS, nil, nil, StartInfo, ProcInfo); Application.Terminate; end; function TfrmIniciar.newHash(Str: String; index: Integer): String; var p1,p2,p3,p4: String; OutPutList: TStringList; car: char; i: Integer; begin Result := EmptyStr; OutPutList := TStringList.Create; try OutPutList.Clear; OutPutList.LineBreak := ';'; OutPutList.Text := Str; p1 := OutPutList.Strings[0]; p2 := OutPutList.Strings[1]; p3 := OutPutList.Strings[2]; p4 := OutPutList.Strings[3]; finally OutPutList.Free; end; p1 := CalcHash2(p1,haSHA1); p2 := CalcHash2(p2,haSHA1); p3 := CalcHash2(p3,haSHA1); p4 := CalcHash2(p4,haSHA1); if index < 97 then index := (index - 87) mod 4 else index := (index - 95) mod 4; i:=1; SetLength(Result, 40); while i < 40 do begin case index of 0: begin Result[i]:=p1[i];Result[i+1]:=p2[i+1];Result[i+2]:=p3[i+2];Result[i+3]:=p4[i+3];end; 1: begin Result[i]:=p2[i];Result[i+1]:=p3[i+1];Result[i+2]:=p4[i+2];Result[i+3]:=p1[i+3];end; 2: begin Result[i]:=p3[i];Result[i+1]:=p4[i+1];Result[i+2]:=p1[i+2];Result[i+3]:=p2[i+3];end; 3: begin Result[i]:=p4[i];Result[i+1]:=p1[i+1];Result[i+2]:=p2[i+2];Result[i+3]:=p3[i+3];end; end; i:= i + 4; end; end; procedure TfrmIniciar.VerificaVersion; var G,F,H,NB: String; begin Try frmData.SQL.SQL.Clear; frmData.SQL.SQL.Add('SELECT banca,current_time as hora,current_date as fecha,banca_config,nom_banca from version;'); frmData.SQL.Open; frmData.SQL.First; G:=frmData.SQL.FieldValues['banca']; H:=frmData.SQL.FieldValues['hora']; frmdata.BDFECHA:=frmData.SQL.FieldValues['fecha']; frmdata.PAIS:=copy(frmData.SQL.FieldValues['banca_config'],3,1); frmdata.decimal:=StrToInt(copy(frmData.SQL.FieldValues['banca_config'],4,1)); frmdata.ani:=StrToInt(copy(frmData.SQL.FieldValues['banca_config'],5,1)); NB:=frmData.SQL.FieldValues['nom_banca']; frmData.SQL.Close; ///// 14-05-2019 ///// if NB<>'' then if NB<>Application.Title then begin ShowMessage('Diferencias en Nombre de la Banca'); Application.Terminate; exit; end; /// if G<>'8.0.0' then begin ShowMessage('Versiones Deiferente...B.D.= '+G+' Sistema:= 8.0.0'); //ExecNewProcess('actconter.exe'); Application.Terminate; exit; end; if frmdata.PAIS<>'1' then begin showMessage('Esta aplicacion es para Moneda Extranjera...'); Application.Terminate; exit; end; Except ShowMessage('Error estableciendo conexion 1'); Application.Terminate; End; end; procedure TfrmIniciar.ClienteConnected(Sender: TObject); var s: AnsiString; nh: AnsiString; nh2: String; pase: String; md5:String; res : String; index, i: Integer; Serial, IP, HostName, Valida: String; begin Try Try Cliente.IOHandler.MaxLineLength:= 65535; s:=Cliente.IOHandler.ReadLn; i := Length(s) - 1; if ( i mod 3 <> 0) or (Length(s) = 0) then begin Application.Terminate; exit; end; s:=bintoAscii(DecodeBase64(s)); index := RandomRange(87, 102); nh := newHash(s, index); nh2 := AnsiReverseString(nh); md5 := CalcHash2(nh,haMD5); md5 := md5 + Copy(nh, 32,8); if index < 97 then md5[40] := Char((index - 87) + 48) else md5[40] := Char(index); Cliente.IOHandler.Writeln(md5); nh2 := CalcHash2(nh2, haSHA1); pase := Copy( nh2, 5, 32); s:=Cliente.IOHandler.ReadLn; nh2 := CalcHash2(md5 + 'Es Valido', haSHA1); if s = nh2 then begin Serial := GetSerial() + GetInfoBiosSerials(); Valida := GetValida(); Serial := CalcHash2(Serial, haSHA1); IP := Udp.LocalHostAddr; HostName := Udp.LocalHostName; nh2 := EncodeString(Serial) + ';'+EncodeString(IP)+';'+EncodeString(HostName)+';'+EncodeString(Valida)+';'+EncodeString(DateToStr(Date()))+';'+EncodeString(TimeToStr(Time())); nh2:= EncodeString(nh2); Cliente.IOHandler.Writeln(nh2); s:=Cliente.IOHandler.ReadLn; md5:= EmptyStr; res:= s; for i := 1 to 16 do begin res := bintoAscii(DecodeBase64(res)); md5 := Copy(res, 1, 2) + md5; res := Copy(res, 3, Length(res)-2); end; s := res; if CalcHash2(s, haMD5) = md5 then begin Codec.UTF8Password := pase; Codec.DecryptAnsiString(nh, s); end; ConfigInitDb(Sender, nh); end else begin ShowMessage('Error en verificacion'); Application.Terminate; exit; end; Except Application.Terminate; exit; End; Finally Cliente.IOHandler.Close; End; if Validado then begin Try Try frmData.AbrirConexion; VerificaVersion; Hide; frmClave.ShowModal; Close; Except On E : Exception do begin ShowMessage('Error estableciendo conexion 2'); Application.Terminate; exit; end; End; Finally frmData.Loteria.Close; End; end; end; procedure TfrmIniciar.ConfigInitDb(Sender: TObject; text: String); var i: Integer; OutPutList: TStringList; begin Try text := Trim(Text); OutPutList := TStringList.Create; try OutPutList.Clear; OutPutList.LineBreak := ':::'; OutPutList.Text := text; if OutPutList.Strings[3] <> 'VALIDO' then begin frmCodigoCon.Edit1.Text := OutPutList.Strings[3]; frmCodigoCon.ShowModal; Application.Terminate; exit; end; frmData.Loteria.Server := Host; frmData.Loteria.Username := OutPutList.Strings[0]; frmData.Loteria.Password := OutPutList.Strings[1]; frmData.Loteria.Database := OutPutList.Strings[2]; frmData.Loteria.SpecificOptions.Values['Protocol'] := 'mpSSL'; frmData.BDBANCA := OutPutList.Strings[4]; frmData.BDBASEDATO := OutPutList.Strings[2]; frmData.BDID:= OutPutList.Strings[5]; Validado := True; finally OutPutList.Free; end; Except On E : Exception do begin ShowMessage('Error durante la conexion 3'); raise E; end; End; end; procedure TfrmIniciar.FormCreate(Sender: TObject); var CS: Cardinal; begin { CS := GetWindowLong(Self.ProgressBar1.Handle, GWL_STYLE); CS := CS or PBS_MARQUEE; SetWindowLong(Self.ProgressBar1.Handle, GWL_STYLE, CS); SendMessage(Self.ProgressBar1.Handle, PBM_SETMARQUEE, Integer(True), 0);} end; procedure TfrmIniciar.FormShow(Sender: TObject); var CS: Cardinal; begin Validado := False; frmData.Directorio:=GetCurrentDir; frmData.Loteria.Close; Udp.Open; frmData.HOST:=Udp.LocalHostName; frmData.IP:=Udp.LocalHostAddr; Udp.Close; Pedir.Enabled:=True; // { CS := GetWindowLong(Self.ProgressBar1.Handle, GWL_STYLE); CS := CS or PBS_MARQUEE; SetWindowLong(Self.ProgressBar1.Handle, GWL_STYLE, CS); SendMessage(Self.ProgressBar1.Handle, PBM_SETMARQUEE, Integer(True), 0); } end; function TfrmIniciar.GetValida:String; var i : Integer; LStrings: TStringList; s,str : String; begin LStrings := TStringList.Create; try if FileExists(GetCurrentDir+'\security.dat') then begin LStrings.Loadfromfile(GetCurrentDir+'\security.dat'); s := LStrings.Text; for i := 1 to 15 do s := DecodeString(s); Result := s; end else begin Randomize; str := 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/+'; s := ''; for i := 1 to 32 do s := s + str[Random(Length(str)) + 1]; s := s + '='; Result := s; for i := 1 to 15 do s := EncodeString(s); LStrings.Clear; LStrings.Text := s; LStrings.SaveToFile(GetCurrentDir+'\security.dat'); end; finally FreeAndNil(LStrings); end; end; procedure TfrmIniciar.PedirTimer(Sender: TObject); var u,p: String; F: TextFile; s: String; begin bar1.StepIt; Pedir.Enabled:=False; if FileExists(GetCurrentDir+'\config.dat') then begin AssignFile(F, GetCurrentDir+'\config.dat'); { File selected in dialog } Reset(F); Readln(F,s); { Read first line of file } Host:=copy(s,1,16); Closefile(F); Cliente.Host:=Host; Try //tito1.Enabled:=false; Cliente.Connect; except ShowMessage('No es posible contactar al servidor'); //tito1.Enabled:=false; Application.Terminate; end; end else begin ShowMessage('Error de configuracion'); //tito1.Enabled:=false; Application.Terminate; end; end; procedure TfrmIniciar.tito1Timer(Sender: TObject); var i:integer; begin for I := 0 to 100 do bar1.StepIt; end; function TfrmIniciar.GetInfoBiosSerials:String; Var SMBios : TSMBios; UUID : Array[0..31] of Char; Salida : String; LBIOS : TBiosInformation; LSystem: TSystemInformation; LBaseBoard : TBaseBoardInformation; LProcessorInfo : TProcessorInformation; i : Integer; begin SMBios:= TSMBios.Create; Salida:= ''; try With SMBios do begin LBIOS:=BiosInfo; Salida := Salida + 'Vdr:'+LBIOS.VendorStr; Salida := Salida + 'Vrs:'+LBIOS.VersionStr; Salida := Salida + 'Rls:'+LBIOS.ReleaseDateStr; LSystem:=SMBios.SysInfo; Salida := Salida + 'Sr1:'+LSystem.SerialNumberStr; BinToHex(@LSystem.RAWSystemInformation.UUID,UUID,SizeOf(LSystem.RAWSystemInformation.UUID)); Salida := Salida + 'UID:'+UUID; if HasBaseBoardInfo then begin for LBaseBoard in SMBios.BaseBoardInfo do begin Salida := Salida + 'Sr2:'+LBaseBoard.SerialNumberStr; end end; if HasProcessorInfo then begin for i:=Low(SMBios.ProcessorInfo) to High(SMBios.ProcessorInfo) do begin LProcessorInfo:=SMBios.ProcessorInfo[i]; Salida := Salida + 'PTS:'+LProcessorInfo.ProcessorTypeStr; Salida := Salida + 'PFS:'+LProcessorInfo.ProcessorFamilyStr; Salida := Salida + 'PVS:'+LProcessorInfo.ProcessorVersionStr; Salida := Salida + Format('PID %x',[LProcessorInfo.RAWProcessorInformation^.ProcessorID]); if SMBios.SmbiosVersion>='2.3' then begin Salida := Salida + 'Sr3:'+LProcessorInfo.SerialNumberStr; end; end; end; end; finally SMBios.Free; end; Result:=Salida; end; end.
unit ATxUtilExec; interface function FExecShell(const cmd, params, dir: WideString; ShowCmd: integer; fWait: boolean): boolean; implementation uses Windows, SysUtils, ShellApi; //------------------------ function FExecShellA(const cmd, params, dir: AnsiString; ShowCmd: integer; fWait: boolean): boolean; var si: TShellExecuteInfoA; begin FillChar(si, SizeOf(si), 0); si.cbSize := SizeOf(si); si.fMask := SEE_MASK_FLAG_NO_UI or SEE_MASK_NOCLOSEPROCESS; si.lpFile := PAnsiChar(cmd); si.lpParameters := PAnsiChar(params); si.lpDirectory := PAnsiChar(dir); si.nShow := ShowCmd; Result := ShellExecuteExA(@si); if Result then if fWait then WaitForSingleObject(si.hProcess, INFINITE); end; function FExecShellW(const cmd, params, dir: WideString; ShowCmd: integer; fWait: boolean): boolean; var si: TShellExecuteInfoW; begin FillChar(si, SizeOf(si), 0); si.cbSize := SizeOf(si); si.fMask := SEE_MASK_FLAG_NO_UI or SEE_MASK_NOCLOSEPROCESS; si.lpFile := PWChar(cmd); si.lpParameters := PWChar(params); si.lpDirectory := PWChar(dir); si.nShow := ShowCmd; Result := ShellExecuteExW(@si); if Result then if fWait then WaitForSingleObject(si.hProcess, INFINITE); end; function FExecShell(const cmd, params, dir: WideString; ShowCmd: integer; fWait: boolean): boolean; begin if Win32Platform = VER_PLATFORM_WIN32_NT then Result := FExecShellW(cmd, params, dir, ShowCmd, fWait) else Result := FExecShellA(cmd, params, dir, ShowCmd, fWait); end; end.
unit kwPopEditorGetShowDocumentParts; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "ScriptEngine" // Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwPopEditorGetShowDocumentParts.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<ScriptKeyword::Class>> Shared Delphi Scripting::ScriptEngine::EditorFromStackKeyWords::pop_editor_GetShowDocumentParts // // *Формат:* anEditorControl pop:editor:GetShowDocumentParts // *Описание:* Помещает значение свойства редактора ShowDocumentParts (отображать структуру // документа) в стек. // *Пример:* // {code} // focused:control:push pop:editor:GetShowDocumentParts // . // {code} // *Результат:* В засимости от значения поля в будет напечатано значение "true" или "false" // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$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} TkwPopEditorGetShowDocumentParts = {final} class(_kwEditorFromStackWord_) {* *Формат:* anEditorControl pop:editor:GetShowDocumentParts *Описание:* Помещает значение свойства редактора ShowDocumentParts (отображать структуру документа) в стек. *Пример:* [code] focused:control:push pop:editor:GetShowDocumentParts . [code] *Результат:* В засимости от значения поля в будет напечатано значение "true" или "false" } protected // realized methods procedure DoWithEditor(const aCtx: TtfwContext; anEditor: TevCustomEditorWindow); override; public // overridden public methods class function GetWordNameForRegister: AnsiString; override; end;//TkwPopEditorGetShowDocumentParts {$IfEnd} //not NoScripts implementation {$If not defined(NoScripts)} uses tfwAutoregisteredDiction, tfwScriptEngine, Windows, afwFacade, Forms ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type _Instance_R_ = TkwPopEditorGetShowDocumentParts; {$Include ..\ScriptEngine\kwEditorFromStackWord.imp.pas} // start class TkwPopEditorGetShowDocumentParts procedure TkwPopEditorGetShowDocumentParts.DoWithEditor(const aCtx: TtfwContext; anEditor: TevCustomEditorWindow); //#UC START# *4F4CB81200CA_4F4CB5C50249_var* //#UC END# *4F4CB81200CA_4F4CB5C50249_var* begin //#UC START# *4F4CB81200CA_4F4CB5C50249_impl* aCtx.rEngine.PushBool(anEditor.ShowDocumentParts); //#UC END# *4F4CB81200CA_4F4CB5C50249_impl* end;//TkwPopEditorGetShowDocumentParts.DoWithEditor class function TkwPopEditorGetShowDocumentParts.GetWordNameForRegister: AnsiString; {-} begin Result := 'pop:editor:GetShowDocumentParts'; end;//TkwPopEditorGetShowDocumentParts.GetWordNameForRegister {$IfEnd} //not NoScripts initialization {$If not defined(NoScripts)} {$Include ..\ScriptEngine\kwEditorFromStackWord.imp.pas} {$IfEnd} //not NoScripts end.
unit tmsUXlsHyperLink; {$INCLUDE ..\FLXCOMPILER.INC} {$INCLUDE ..\FLXCONFIG.INC} interface uses Classes, SysUtils, tmsUXlsBaseRecords, tmsXlsMessages, tmsUFlxMessages, tmsUXlsBaseList, tmsUOle2Impl; type TScreenTipRecord=class; THLinkRecord = class(TBaseRecord) private Hint: TScreenTipRecord; function ReadString(var Pos: Integer; const OptMask: Integer; const ByteSize: Integer): UTF16String; function ReadLocalFile(var Pos: Integer): UTF16String; procedure SetString(var Pos: Integer; const OptMask: Integer; const value: UTF16String); procedure SetString2(var Pos: Integer; const GUID: PArrayOfByte; const value: UTF16String; const ByteCount: Integer); procedure SetLocalFile(var Pos: Integer; const value: UTF16String); function IsUrl(pos: Integer): Boolean; function IsFile(pos: Integer): Boolean; function IsUNC(pos: Integer): Boolean; function GetText(var pos: Integer; var HType: THyperLinkType): UTF16String; procedure SetText(var pos: Integer; Text: UTF16String; HType: THyperLinkType); procedure ClearData; function GetFirstRow: Integer; function GetLastRow: Integer; function GetFirstCol: Integer; function GetLastCol: Integer; function GetOptionFlags: Integer; procedure SetFirstRow(Value: Integer); procedure SetLastRow(Value: Integer); procedure SetFirstCol(Value: Integer); procedure SetLastCol(Value: Integer); procedure SetOptionFlags(Value: Integer); protected function DoCopyTo: TBaseRecord; override; public procedure AddHint(const aHint: TScreenTipRecord); constructor Create(const aId: word; const aData: PArrayOfByte; const aDataSize: integer);override; constructor CreateNew(const CellRange: TXlsCellRange; const HLink: THyperLink); destructor Destroy;override; property FirstRow: Integer read GetFirstRow write SetFirstRow; property LastRow: Integer read GetLastRow write SetLastRow; property FirstCol: Integer read GetFirstCol write SetFirstCol; property LastCol: Integer read GetLastCol write SetLastCol; property OptionFlags: Integer read GetOptionFlags write SetOptionFlags; procedure SaveToStream(const Workbook: TOle2File);override; procedure SaveRangeToStream(const Workbook: TOle2File; const CellRange: TXlsCellRange); function TotalRangeSize(const CellRange: TXlsCellRange): Integer; function TotalSize: Integer;override; function TotalSizeNoHeaders: Integer;override; function GetProperties: THyperLink; procedure SetProperties(value: THyperLink); function GetCellRange: TXlsCellRange; procedure SetCellRange(CellRange: TXlsCellRange); procedure ArrangeInsertRange(CellRange: TXlsCellRange; aRowCount: Integer; aColCount: Integer; SheetInfo: TSheetInfo); function Offset(DeltaRow: Integer; DeltaCol: Integer): THLinkRecord; end; TScreenTipRecord = class(TBaseRecord) protected function GetFirstRow: Integer; function GetLastRow: Integer; function GetFirstCol: Integer; function GetLastCol: Integer; function GetText: UTF16String; procedure SetFirstRow(Value: Integer); procedure SetLastRow(Value: Integer); procedure SetFirstCol(Value: Integer); procedure SetLastCol(Value: Integer); procedure SetText(Value: UTF16String); public constructor Create(const aId: word; const aData: PArrayOfByte; const aDataSize: integer); override; constructor CreateNew(aDescription: UTF16String); property FirstRow: Integer read GetFirstRow write SetFirstRow; property LastRow: Integer read GetLastRow write SetLastRow; property FirstCol: Integer read GetFirstCol write SetFirstCol; property LastCol: Integer read GetLastCol write SetLastCol; property Text: UTF16String read GetText write SetText; end; THLinkList = class(TBaseList) {$INCLUDE THLinkListHdr.inc} public procedure CopyFrom(aHLinkList: THLinkList); procedure CopyObjectsFrom(aHLinkList: THLinkList; CopyRange: TXlsCellRange; RowOfs: Integer; ColOfs: Integer); procedure SaveToStream(DataStream: TOle2File); procedure SaveRangeToStream(DataStream: TOle2File; CellRange: TXlsCellRange); function TotalSize: Int64; function TotalRangeSize(CellRange: TXlsCellRange): Int64; procedure InsertAndCopyRange(SourceRange: TXlsCellRange; DestRow: Integer; DestCol: Integer; aRowCount: Integer; aColCount: Integer; SheetInfo: TSheetInfo); procedure DeleteRange(CellRange: TXlsCellRange; aRowCount: Integer; aColCount: Integer; SheetInfo: TSheetInfo); end; implementation {$INCLUDE THLinkListImp.inc} const FILEGUID: array [0..15] of byte=($03, $03, $00, $00, $00, $00, $00, $00, $C0, $00, $00, $00, $00, $00, $00, $46); URLGUID: array [0..15] of byte=($E0, $C9, $EA, $79, $F9, $BA, $CE, $11, $8C, $82, $00, $AA, $00, $4B, $A9, $0B); constructor THLinkRecord.Create(const aId: word; const aData: PArrayOfByte; const aDataSize: integer); begin inherited Create(aId, aData, aDataSize); Hint := nil; end; function THLinkRecord.GetFirstRow: Integer; begin Result := GetWord(Data, 0); end; function THLinkRecord.GetLastRow: Integer; begin Result := GetWord(Data, 2); end; function THLinkRecord.GetFirstCol: Integer; begin Result := GetWord(Data, 4); end; function THLinkRecord.GetLastCol: Integer; begin Result := GetWord(Data, 6); end; function THLinkRecord.GetOptionFlags: Integer; begin Result := GetWord(Data, 28); end; procedure THLinkRecord.SetFirstRow(Value: Integer); begin SetWord(Data, 0, value); end; procedure THLinkRecord.SetLastRow(Value: Integer); begin SetWord(Data, 2, value); end; procedure THLinkRecord.SetFirstCol(Value: Integer); begin SetWord(Data, 4, value); end; procedure THLinkRecord.SetLastCol(Value: Integer); begin SetWord(Data, 6, value); end; procedure THLinkRecord.SetOptionFlags(Value: Integer); begin SetWord(Data, 28, value); end; constructor THLinkRecord.CreateNew(const CellRange: TXlsCellRange; const HLink: THyperLink); var TmpData: PArrayOfByte; begin GetMem(TmpData, 32); FillChar(TmpData[0], 32, 0); try inherited Create(xlr_HLINK, TmpData, 32); TmpData:=nil; FirstRow := CellRange.Top; FirstCol := CellRange.Left; LastRow := CellRange.Bottom; LastCol := CellRange.Right; SetLongWord(Data, 8, $79EAC9D0); SetLongWord(Data, 12, $11CEBAF9); SetLongWord(Data, 16, $AA00828C); SetLongWord(Data, 20, $0BA94B00); SetWord(Data, 24, 2); FillChar(Data[26],6,0); SetProperties(HLink); finally FreeAndNil(TmpData); end; //finally end; procedure THLinkRecord.SaveToStream(const Workbook: TOle2File); begin inherited SaveToStream(Workbook); if (Hint <> nil) then begin Hint.FirstRow := FirstRow; Hint.FirstCol := FirstCol; Hint.LastRow := LastRow; Hint.LastCol := LastCol; Hint.SaveToStream(Workbook); end; end; procedure THLinkRecord.SaveRangeToStream(const Workbook: TOle2File; const CellRange: TXlsCellRange); begin if ((((Self.FirstRow > CellRange.Bottom) or (Self.LastRow < CellRange.Top)) or (Self.FirstCol > CellRange.Right)) or (Self.LastCol < CellRange.Left)) then exit; SaveToStream(Workbook); end; function THLinkRecord.TotalRangeSize(const CellRange: TXlsCellRange): Integer; begin if ((((Self.FirstRow > CellRange.Bottom) or (Self.LastRow < CellRange.Top)) or (Self.FirstCol > CellRange.Right)) or (Self.LastCol < CellRange.Left)) then begin Result := 0; exit; end; Result := TotalSize; end; function THLinkRecord.DoCopyTo: TBaseRecord; begin Result := inherited DoCopyTo; if (Hint <> nil) then (Result as THLinkRecord).Hint := Hint.CopyTo as TScreenTipRecord; end; function THLinkRecord.TotalSize: Integer; begin Result := inherited TotalSize; if (Hint <> nil) then inc(Result, Hint.TotalSize); end; function THLinkRecord.TotalSizeNoHeaders: Integer; begin Result := inherited TotalSizeNoHeaders; if (Hint <> nil) then inc(Result, Hint.TotalSizeNoHeaders); end; function THLinkRecord.ReadString(var Pos: Integer; const OptMask: Integer; const ByteSize: Integer): UTF16String; var OldPos: Integer; p: integer; begin if ((OptionFlags and OptMask) <> OptMask) then begin Result := ''; end else begin OldPos := Pos; inc(Pos, 4+Integer(GetLongWord(Data, Pos))*ByteSize); SetLength(Result, (Pos-(OldPos+4)-2) div 2); //00 Terminated move(Data[OldPos+4], Result[1], Length(Result)*2); p := System.Pos(#0, Result); if (p > 0) then Delete(Result, p, Length(Result)); //string might have a 0 inside. In this case we need to cut it. end; end; function THLinkRecord.ReadLocalFile(var Pos: Integer): UTF16String; var XLen: Integer; RLen: Integer; s8: AnsiString; s16: UTF16String; StrLen: Integer; i: Integer; DirUp: Integer; begin Result := ''; DirUp := GetWord(Data, Pos); for i:=0 to DirUp-1 do Result:=Result+ IncludeTrailingPathDelimiter('..'); inc(Pos,2); StrLen := GetLongWord(Data, Pos); if (StrLen > 1) then Dec(StrLen); SetLength(s8, StrLen); move(Data[Pos+4], s8[1], StrLen); inc(Pos, 4+StrLen+1+24); RLen := GetLongWord(Data, Pos); inc(Pos,4); if (RLen = 0) then begin Result:=Result+ StringToWideStringNoCodePage(s8); Exit; end; XLen := GetLongWord(Data, Pos); inc(Pos, 4+2); SetLength(s16, XLen div 2); move(Data[Pos], s16[1], XLen); inc(Pos, XLen); Result := Result+s16; end; procedure THLinkRecord.SetString(var Pos: Integer; const OptMask: Integer; const value: UTF16String); var Len: Integer; begin if (value= '') then begin if ((OptionFlags and OptMask) <> OptMask) then Exit; //Already empty OptionFlags:=OptionFlags and not OptMask; DataSize:=DataSize-4-Integer(GetLongWord(Data, Pos))*2; ReallocMem(Data, DataSize); end else begin Len := 0; if ((Self.OptionFlags and OptMask) = OptMask) then Len := 4 + GetLongWord(Data, Pos) * 2; DataSize:=DataSize-Len+4+Length(Value)*2+2; ReallocMem(Data, DataSize); if (Pos+1<DataSize) then FillChar(Data[Pos+1], DataSize-Pos-1, 0); SetLongWord(Data, Pos, Length(Value) + 1); move(value[1], Data[Pos+4] , Length(Value)* 2); inc(Pos, 4+Length(Value)*2+2); SetWord(Data, Pos-2, 0); OptionFlags := OptionFlags or OptMask; end; end; procedure THLinkRecord.SetString2(var Pos: Integer; const GUID: PArrayOfByte; const value: UTF16String; const ByteCount: Integer); var GuidSize: integer; begin if GUID=nil then GuidSize:=0 else GuidSize:=16; DataSize:=DataSize +GuidSize+ 4+ Length(Value)*2 + 2; ReallocMem(Data, DataSize); if (Pos+1<DataSize) then FillChar(Data[Pos+1], DataSize-Pos-1, 0); if (GUID<>nil) then begin move(GUID[0], Data[Pos], 16); inc(Pos, 16); end; SetLongWord(Data, Pos, ((Length(value)*2 + 2) div ByteCount)); move(value[1], Data[Pos+4] , Length(Value)* 2); inc(Pos, 4+ Length(Value)*2+2); SetWord(Data, Pos-2 ,0); end; procedure THLinkRecord.SetLocalFile(var Pos: Integer; const value: UTF16String); var WideDataLen: Integer; IsCompressed: Boolean; i: Integer; NewValue: UTF16String; begin i := 0; while copy(value,i+1, 3) = IncludeTrailingPathDelimiter('..') do inc(i,3); NewValue := copy(value, i+1, Length(Value)); IsCompressed := not IsWide(NewValue); WideDataLen := 0; if (not IsCompressed) then begin WideDataLen := 4+4+2+Length(NewValue)*2; end; DataSize:=DataSize+16+2+4+Length(NewValue)+1+24+4+WideDataLen; ReallocMem(Data, DataSize); if (Pos+1<DataSize) then FillChar(Data[Pos+1], DataSize-Pos-1, 0); move(FILEGUID[0], Data[Pos], 16); inc(Pos,16); SetWord(Data, Pos, (i div 3)); inc (Pos, 2); SetLongWord(Data, Pos, Length(NewValue) + 1); inc(Pos,4); CompressBestUnicode(NewValue, Data, Pos); inc(Pos, Length(NewValue) + 1); Data[Pos-1]:=0; FillChar(Data[Pos], 24, 0); SetLongWord(Data, Pos, $DEADFFFF); inc(Pos,24); if IsCompressed then begin Exit; end; SetLongWord(Data, Pos, ((4 + 2) + Length(NewValue)*2)); inc(Pos,4); SetLongWord(Data, Pos, Length(NewValue)*2); inc(Pos,4); SetWord(Data, Pos, 3); inc(Pos,2); move(NewValue[1], Data[Pos] , Length(NewValue)* 2); inc(Pos, Length(NewValue)* 2); end; function THLinkRecord.IsUrl(pos: Integer): Boolean; begin if ((((OptionFlags and 3) = $03) and ((OptionFlags and $60) = 0)) and ((Self.OptionFlags and $100) = 0)) then begin Result := CompareMem(@URLGUID, PAddress(Data)+ pos,16); Exit; end; Result := False; end; function THLinkRecord.IsFile(pos: Integer): Boolean; begin if ((((Self.OptionFlags and 1) = $01) and ((Self.OptionFlags and $60) = 0)) and ((Self.OptionFlags and $100) = 0)) then begin Result := CompareMem(@FILEGUID, PAddress(Data)+ pos,16); Exit; end; Result := False; end; function THLinkRecord.IsUNC(pos: Integer): Boolean; begin Result := ((((Self.OptionFlags and $03) = $03) and ((Self.OptionFlags and $60) =0)) and ((Self.OptionFlags and $100) <> 0)); end; function THLinkRecord.GetText(var pos: Integer; var HType: THyperLinkType): UTF16String; begin if IsUrl(pos) then begin HType := hl_URL; inc(Pos,16); Result := ReadString(pos, 0, 1); Exit; end; if IsFile(pos) then begin HType := hl_LocalFile; inc(Pos,16); Result := ReadLocalFile(pos); Exit; end; if IsUNC(pos) then begin HType := hl_UNC; Result := ReadString(pos, 0, 2); Exit; end; HType := hl_CurrentWorkbook; Result := ''; end; procedure THLinkRecord.SetText(var pos: Integer; Text: UTF16String; HType: THyperLinkType); begin case (HType) of hl_URL: begin OptionFlags:=(OptionFlags or $03) and not $160; SetString2(pos, @URLGUID, Text,1); end; hl_LocalFile: begin OptionFlags:=(OptionFlags or $01) and not $160; SetLocalFile(pos, Text); end; hl_UNC: begin OptionFlags:=(OptionFlags or $103) and not $60; SetString2(pos, nil, Text,2); end; hl_CurrentWorkbook: begin OptionFlags:=(OptionFlags) and not $163; //No SetString2(pos, nil, '', 1); end; end; //case end; function THLinkRecord.GetProperties: THyperLink; var TmpLinkType: THyperLinkType; pos: Integer; begin pos := 32; Result.Description := ReadString(pos, $14, 2); Result.TargetFrame := ReadString(pos, $80, 2); TmpLinkType := hl_CurrentWorkbook; Result.Text := GetText(pos, TmpLinkType); Result.LinkType := TmpLinkType; Result.TextMark := ReadString(pos, $8, 2); if (Hint = nil) then Result.Hint := '' else Result.Hint := Hint.Text; end; procedure THLinkRecord.ClearData; begin DataSize:=32; ReallocMem(Data,DataSize); FillChar(Data[28],4,0); end; procedure THLinkRecord.SetProperties(value: THyperLink); var pos: Integer; begin ClearData; pos := 32; SetString(pos, $14, value.Description); SetString(pos, $80, value.TargetFrame); SetText(pos, value.Text, value.LinkType); SetString(pos, $8, value.TextMark); if (value.Hint = '') then FreeAndNil(Hint) else if (Hint = nil) then Hint := TScreenTipRecord.CreateNew(value.Hint) else Hint.Text := value.Hint; end; function THLinkRecord.GetCellRange: TXlsCellRange; begin Result.Top:=FirstRow; Result.Left:=FirstCol; Result.Bottom:=LastRow; Result.Right:=LastCol; end; procedure THLinkRecord.SetCellRange(CellRange: TXlsCellRange); begin FirstRow := CellRange.Top; FirstCol := CellRange.Left; LastRow := CellRange.Bottom; LastCol := CellRange.Right; end; procedure THLinkRecord.ArrangeInsertRange(CellRange: TXlsCellRange; aRowCount: Integer; aColCount: Integer; SheetInfo: TSheetInfo); begin //Hyperlink data doesn't move when you insert/copy cells or sheets. It is a static text. if ((SheetInfo.InsSheet < 0) or (SheetInfo.FormulaSheet <> SheetInfo.InsSheet)) then Exit; if (((aRowCount <> 0) and (FirstCol >= CellRange.Left)) and (LastCol <= CellRange.Right)) then begin if (FirstRow >= CellRange.Top) then IncWord(Data, 0, (aRowCount * (CellRange.Bottom-CellRange.Top+1)), Max_Rows); if (LastRow >= CellRange.Top) then IncWord(Data, 2, (aRowCount * (CellRange.Bottom-CellRange.Top+1)), Max_Rows); end; if (((aColCount <> 0) and (FirstRow >= CellRange.Top)) and (LastRow <= CellRange.Bottom)) then begin if (FirstCol >= CellRange.Left) then IncWord(Data, 4, (aColCount * (CellRange.Right-CellRange.Left+1)), Max_Columns); if (Self.LastCol >= CellRange.Left) then IncWord(Data, 6, (aColCount * (CellRange.Right-CellRange.Left+1)), Max_Columns); end; end; function THLinkRecord.Offset(DeltaRow: Integer; DeltaCol: Integer): THLinkRecord; begin FirstRow:= FirstRow + DeltaRow; LastRow:= LastRow + DeltaRow; FirstCol:= FirstCol + DeltaCol; LastCol:= LastCol + DeltaCol; Result := Self; end; { TScreenTipRecord } constructor TScreenTipRecord.Create(const aId: word; const aData: PArrayOfByte; const aDataSize: integer); begin inherited Create(aId, aData, aDataSize); end; constructor TScreenTipRecord.CreateNew(aDescription: UTF16String); begin Create(xlr_SCREENTIP, nil, 0); Text := aDescription; end; function TScreenTipRecord.GetFirstRow: Integer; begin Result := GetWord(Data, 2); end; function TScreenTipRecord.GetLastRow: Integer; begin Result := GetWord(Data, 4); end; function TScreenTipRecord.GetFirstCol: Integer; begin Result := GetWord(Data, 6); end; function TScreenTipRecord.GetLastCol: Integer; begin Result := GetWord(Data, 8); end; function TScreenTipRecord.GetText: UTF16String; begin SetLength(Result, (DataSize-10-2)div 2); move(Data[10], Result[1], Length(Result)*2); end; procedure TScreenTipRecord.SetFirstRow(Value: Integer); begin SetWord(Data, 2, value); end; procedure TScreenTipRecord.SetLastRow(Value: Integer); begin SetWord(Data, 4, value); end; procedure TScreenTipRecord.SetFirstCol(Value: Integer); begin SetWord(Data, 6, value); end; procedure TScreenTipRecord.SetLastCol(Value: Integer); begin SetWord(Data, 8, value); end; procedure TScreenTipRecord.SetText(Value: UTF16String); begin FreeAndNil(Data); DataSize:=12+Length(Value)*2; GetMem(Data, DataSize); FillChar(Data[0],DataSize,0); move(Value[1], Data[10], Length(Value)*2); SetWord(Data, 0, 2048); end; { THLinkList } procedure THLinkList.CopyFrom(aHLinkList: THLinkList); var i: Integer; begin for i := 0 to aHLinkList.Count-1 do begin Add(aHLinkList[i].CopyTo as THLinkRecord); end; end; procedure THLinkList.CopyObjectsFrom(aHLinkList: THLinkList; CopyRange: TXlsCellRange; RowOfs: Integer; ColOfs: Integer); var r: THLinkRecord; i: Integer; begin if (aHLinkList = nil) then exit; for i := 0 to aHLinkList.Count-1 do begin r := aHLinkList[i]; if ((((r.FirstCol >= CopyRange.Left) and (r.LastCol <= CopyRange.Right)) and (r.FirstRow >= CopyRange.Top)) and (r.LastRow <= CopyRange.Bottom)) then Add((THLinkRecord(r.CopyTo)).Offset(RowOfs, ColOfs)); end; end; procedure THLinkList.SaveToStream(DataStream: TOle2File); var i: Integer; begin Sort; for i := 0 to Count-1 do begin Items[i].SaveToStream(DataStream); end; end; procedure THLinkList.SaveRangeToStream(DataStream: TOle2File; CellRange: TXlsCellRange); var i: Integer; begin Sort; for i := 0 to Count-1 do begin Items[i].SaveRangeToStream(DataStream, CellRange); end; end; function THLinkList.TotalSize: Int64; var i: Integer; begin Result := 0; for i := 0 to Count-1 do inc(Result, Items[i].TotalSize); end; function THLinkList.TotalRangeSize(CellRange: TXlsCellRange): Int64; var i: Integer; begin Result := 0; for i := 0 to Count-1 do inc(Result, Items[i].TotalRangeSize(CellRange)); end; procedure THLinkList.InsertAndCopyRange(SourceRange: TXlsCellRange; DestRow: Integer; DestCol: Integer; aRowCount: Integer; aColCount: Integer; SheetInfo: TSheetInfo); var cc: Integer; rc: Integer; r: THLinkRecord; i: Integer; RBottom: Integer; RRight: Integer; RLeft: Integer; RTop: Integer; SourceRangeRowCount: integer; SourceRangeColCount: integer; begin SourceRangeRowCount:=SourceRange.Bottom-SourceRange.Top+1; SourceRangeColCount:=SourceRange.Right-SourceRange.Left+1; for i:=0 to Count-1 do begin Items[i].ArrangeInsertRange(OffsetRange(SourceRange, DestRow, DestCol), aRowCount, aColCount, SheetInfo); end; //Pending: if (CopyMode = TRangeCopyMode.None) then exit; RTop := SourceRange.Top; RLeft := SourceRange.Left; if (DestRow <= SourceRange.Top) then inc(RTop, aRowCount* SourceRangeRowCount); if (DestCol <= SourceRange.Left) then inc(RLeft, aColCount* SourceRangeColCount); RRight := ((RLeft + SourceRangeColCount) - 1); RBottom := ((RTop + SourceRangeRowCount) - 1); if ((aRowCount > 0) or (aColCount > 0)) then begin for i:=0 to Count-1 do begin r := Items[i]; if (r.FirstCol >= RLeft) and (r.LastCol <= RRight) and (r.FirstRow>= RTop) and (r.LastRow <= RBottom) then begin for rc:=0 to aRowCount-1 do begin Add(THLinkRecord(r.CopyTo).Offset(DestRow - RTop + rc * SourceRangeRowCount, DestCol - RLeft)); end; for cc:=0 to aColCount-1 do begin Add(THLinkRecord(r.CopyTo).Offset(DestRow - RTop,DestCol - RLeft + cc * SourceRangeColCount)); end; end; end; end; end; procedure THLinkList.DeleteRange(CellRange: TXlsCellRange; aRowCount: Integer; aColCount: Integer; SheetInfo: TSheetInfo); var bColCount: Integer; bRowCount: Integer; r: THLinkRecord; i: Integer; CellRangeRowCount: integer; CellRangeColCount: integer; begin CellRangeRowCount:=CellRange.Bottom-CellRange.Top+1; CellRangeColCount:=CellRange.Right-CellRange.Left+1; for i:= Count-1 downto 0 do begin r := Items[i]; bRowCount := (aRowCount - 1);if (bRowCount < 0) then bRowCount := 0; bColCount := (aColCount - 1);if (bColCount < 0) then bColCount := 0; if (r.FirstRow >= CellRange.Top) and (r.LastRow <= CellRange.Bottom + CellRangeRowCount * bRowCount) and (r.FirstCol >= CellRange.Left) and (r.LastCol <= CellRange.Right + CellRangeColCount * bColCount) then Delete(i) else begin r.ArrangeInsertRange(CellRange, -aRowCount, -aColCount, SheetInfo); if (r.LastRow < r.FirstRow) then Delete(i); end; end; end; procedure THLinkRecord.AddHint(const aHint: TScreenTipRecord); begin FreeAndNil(Hint); Hint:=aHint; end; destructor THLinkRecord.Destroy; begin FreeAndNil(Hint); inherited; end; end.
unit uExterns; interface type {定义一个类} TAnimal = class private {定义字段} FHeight: Integer; function GetHeight: Integer; procedure SetHeight(const Value: Integer); public {定义构造方法} constructor Create(FHeight: Integer); {定义属性} property _FHeight: Integer read GetHeight write SetHeight; {定义虚方法} procedure GetName(); virtual; end; {定义一个派生类,TDog继承于TAnimal} TDog = class(TAnimal) public constructor Create(); procedure GetName(); override; end; implementation { TAnimal } {定义一个构造方法} { TDog } constructor TDog.Create; begin inherited Create(1001); // 指定了方法名称,表示调用指定的方法,有重载的时候就需要这样 end; constructor TAnimal.Create(FHeight: Integer); begin Self._FHeight := FHeight; end; function TAnimal.GetHeight: Integer; begin Result := Self.FHeight; end; procedure TAnimal.GetName; begin Writeln('动物类的虚方法'); end; procedure TAnimal.SetHeight(const Value: Integer); begin Self.FHeight := Value; end; procedure TDog.GetName; begin inherited; // 没有指定具体方法名称,表示调用同名的父类方法 Writeln('狗类的GetName'); end; end.
{*************************************************************** * Unit Name: MemoryManager * Purpose : * Author : Roberto Alonso Gomez * History : Viernes, Febrero 18 2000 ****************************************************************} unit MemoryManager; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; type TMemoryShow = (msMemCount, msFreeMemCount, msReallocMemCount, msAllocMemCount, msAllocMemSize, msPendingCall); TMemoryManagerClass = class(TCustomLabel) public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Reset; private fActive : boolean; fMemoryShow : TMemoryShow; function GetTime: integer; procedure SetTime(const Value: integer); private function GetMemCount : integer; function GetFreeMemCount: integer; function GetReallocMemCount: integer; function GetAllocMemCount: integer; function GetAllocMemSize: integer; procedure SetActive(const value : boolean); procedure SetMemoryShow(const value: TMemoryShow); public property MemCount : integer read GetMemCount; property FreeMemCount : integer read GetFreeMemCount; property ReallocMemCount : integer read GetReallocMemCount; property AllocMemCount : integer read GetAllocMemCount; property AllocMemSize : integer read GetAllocMemSize; published property Active: boolean read fActive write SetActive; property MemoryShow: TMemoryShow read fMemoryShow write SetMemoryShow; property Interval : integer read GetTime write SetTime; property Align; property Alignment; property Anchors; property AutoSize; property Color; property Constraints; property Enabled; property FocusControl; property Font; property ParentColor; property ParentFont; property ParentShowHint; property ShowAccelChar; property ShowHint; property Transparent; property Layout; property Visible; property WordWrap; private fChain : procedure of object; flMemCount : integer; flFreeMemCount : integer; flReallocMemCount: integer; flAllocMemCount : integer; flAllocMemSize : integer; fTimer : TTimer; private procedure Change; procedure UpDateShow; procedure LocalTimer(Sender: TObject); end; procedure Register; implementation var fGetMemCount : Integer = 0; fFreeMemCount : Integer = 0; fReallocMemCount: Integer = 0; fOldMemMgr : TMemoryManager; fReference : integer = 0; fNotify : procedure of object = nil; fFlag : boolean = true; function NewGetMem(Size: integer): pointer; begin inc(fGetMemCount); result := fOldMemMgr.GetMem(Size); if assigned(fNotify) and fFlag then begin fFlag := false; fNotify; fFlag := true; end; end; function NewFreeMem(P: pointer): integer; begin inc(fFreeMemCount); result := fOldMemMgr.FreeMem(P); if assigned(fNotify) and fFlag then begin fFlag := false; fNotify; fFlag := true; end; end; function NewReallocMem(P: pointer; Size: integer): pointer; begin inc(fReallocMemCount); result := fOldMemMgr.ReallocMem(P, Size); if assigned(fNotify) and fFlag then begin fFlag := false; fNotify; fFlag := true; end; end; const NewMemMgr: TMemoryManager = ( GetMem: NewGetMem; FreeMem: NewFreeMem; ReallocMem: NewReallocMem); procedure Register; begin RegisterComponents('rag', [TMemoryManagerClass]); end; { TMemoryManager } procedure TMemoryManagerClass.Change; begin if not fTimer.Enabled then UpDateShow; if assigned(fChain) then fChain; end; constructor TMemoryManagerClass.Create(AOwner: TComponent); begin inherited; fActive := false; fTimer := TTimer.Create(self); fTimer.OnTimer := LocalTimer; UpDateShow; end; destructor TMemoryManagerClass.Destroy; begin Active := false; inherited; end; function TMemoryManagerClass.GetAllocMemCount: integer; begin result := system.AllocMemCount; end; function TMemoryManagerClass.GetAllocMemSize: integer; begin result := system.AllocMemSize; end; function TMemoryManagerClass.GetFreeMemCount: integer; begin result := fFreeMemCount; end; function TMemoryManagerClass.GetMemCount: integer; begin result := fGetMemCount; end; function TMemoryManagerClass.GetReallocMemCount: integer; begin result := fReallocMemCount; end; function TMemoryManagerClass.GetTime: integer; begin result := fTimer.Interval; end; procedure TMemoryManagerClass.LocalTimer(Sender: TObject); begin UpDateShow; end; procedure TMemoryManagerClass.Reset; begin fGetMemCount := 0; fFreeMemCount := 0; fReallocMemCount:= 0; end; procedure TMemoryManagerClass.SetActive(const value: boolean); begin if value<>fActive then begin if value then begin if (not (csDesigning in ComponentState)) and (fReference=0) then begin GetMemoryManager(fOldMemMgr); SetMemoryManager(NewMemMgr); end; inc(fReference); fChain := fNotify; fNotify := Change; if fTimer.Interval >0 then fTimer.Enabled := true; end else begin fNotify := fChain; if (not (csDesigning in ComponentState)) and (fReference=1) then SetMemoryManager(fOldMemMgr); dec(fReference); fTimer.Enabled := false; end; fActive := value; end; end; procedure TMemoryManagerClass.SetMemoryShow(const value: TMemoryShow); begin if fMemoryShow<>value then fMemoryShow := value; end; procedure TMemoryManagerClass.SetTime(const Value: integer); begin if Value = 0 then fTimer.Enabled := false else begin fTimer.Interval := Value; if fActive then fTimer.Enabled := true; end; end; procedure TMemoryManagerClass.UpDateShow; const ActionStr:array[TMemoryShow] of string = ('MemCount', 'FreeMemCount', 'ReallocMemCount', 'AllocMemCount', 'AllocMemSize', 'PendingCall'); begin if (csDesigning in ComponentState) then SetTextBuf(pchar(ActionStr[fMemoryShow])) else if fActive then begin case fMemoryShow of msMemCount: if fGetMemCount <> flMemCount then begin SetTextBuf(pchar(inttostr(fGetMemCount))); flMemCount := fGetMemCount; end; msFreeMemCount: if fFreeMemCount<>flFreeMemCount then begin SetTextBuf(pchar(inttostr(fFreeMemCount))); flFreeMemCount := fFreeMemCount; end; msReallocMemCount: if flReallocMemCount<>fReallocMemCount then begin SetTextBuf(pchar(inttostr(fReallocMemCount))); flReallocMemCount := fReallocMemCount; end; msAllocMemCount: if flAllocMemCount<>system.AllocMemCount then begin SetTextBuf(pchar(inttostr(system.AllocMemCount))); flAllocMemCount:= system.AllocMemCount; end; msAllocMemSize: if flAllocMemSize<>System.AllocMemSize then begin SetTextBuf(pchar(inttostr(System.AllocMemSize))); flAllocMemSize := System.AllocMemSize end; msPendingCall: begin if flAllocMemSize<>System.AllocMemSize then begin SetTextBuf(pchar(inttostr(fGetMemCount-fFreeMemCount))); flAllocMemSize := System.AllocMemSize end; end; end; end else SetTextBuf('UnActive'); end; end.
unit m_spinedit; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, Spin; type { TMariaeSpinEdit } TMariaeSpinEdit = class(TSpinEdit) private FChanged: Boolean; procedure SetChanged(AValue: Boolean); protected public constructor Create(MOwner: TComponent); override; procedure OnChange; procedure ResetChanged; published property Changed: Boolean read FChanged write SetChanged; end; procedure Register; implementation procedure Register; begin {$I m_spinedit_icon.lrs} RegisterComponents('Mariae Controls',[TMariaeSpinEdit]); end; { TMariaeSpinEdit } procedure TMariaeSpinEdit.SetChanged(AValue: Boolean); begin if FChanged = AValue then Exit; FChanged := AValue; end; constructor TMariaeSpinEdit.Create(MOwner: TComponent); begin inherited Create(MOwner); end; procedure TMariaeSpinEdit.OnChange; begin Self.SetChanged(True); end; procedure TMariaeSpinEdit.ResetChanged; begin Self.SetChanged(False); end; end.
/// <summary> /// </summary> unit uTask.Images; interface uses { Rect tpNormal } System.Classes, { IViewControl } uIViews; type /// <summary> /// </summary> TaskImages = class /// <summary> /// </summary> class var FNextLeft, FNextTop: Integer; /// <summary> /// </summary> class var RMain: IViewControl; /// <summary> /// </summary> class procedure InitImages; /// <summary> /// </summary> class procedure FreeImages; /// <summary> /// </summary> class procedure StopTasks; /// <summary> /// </summary> class function LoadAndDisplayImages(APath: String; AExtension: array of String): Integer; /// <summary> /// </summary> class procedure LoadAndDisplayImageAsync(AFileName: String); /// <summary> /// </summary> {$WARNINGS OFF} class procedure RunImageViewThread(AFileName: String; APriority: TThreadPriority); {$WARNINGS ON} end; implementation uses { EnterCriticalSection } Winapi.Windows, { CriticalSection } uCore.CriticalSection, { FreeAndNil } System.SysUtils, uConsts, { TTaskImage } uTask.Image, Vcl.Imaging.jpeg, { clRed } Vcl.Graphics, { TImage } Vcl.ExtCtrls, { FormHelper } uFunctions.Form; class procedure TaskImages.FreeImages; begin EnterCriticalSection(CriticalSection.Section); try FreeAndNil(CriticalSection.FImages); finally LeaveCriticalSection(CriticalSection.Section); end; end; class procedure TaskImages.StopTasks; var I: Integer; begin EnterCriticalSection(CriticalSection.Section); try CriticalSection.FPendingFiles.Clear; for I := 0 to CriticalSection.FImagesThreadPool.LockList.Count - 1 do CriticalSection.FImagesThreadPool.LockList.Items[I].Terminate; finally LeaveCriticalSection(CriticalSection.Section); end; end; class procedure TaskImages.InitImages; begin EnterCriticalSection(CriticalSection.Section); try with CriticalSection do begin FImages := TImages.Create; FDisplayIndex := 0; end; finally LeaveCriticalSection(CriticalSection.Section); end; end; {$WARNINGS OFF} class procedure TaskImages.RunImageViewThread(AFileName: String; APriority: TThreadPriority); {$WARNINGS ON} var LImageViewThread: TTaskImage; begin try { Run new thread } LImageViewThread := TTaskImage.Create(AFileName); with LImageViewThread do begin FreeOnTerminate := True; Priority := tpNormal; Start; end; except FreeAndNil(LImageViewThread); raise; end; { Add new thread into pool list } CriticalSection.FImagesThreadPool.LockList; try CriticalSection.FImagesThreadPool.Add(LImageViewThread); finally CriticalSection.FImagesThreadPool.UnlockList; end; end; class function TaskImages.LoadAndDisplayImages(APath: String; AExtension: array of String): Integer; var LFileType: String; LImages: Integer; LSearchRec: TSearchRec; begin { Just to be sure } APath := IncludeTrailingPathDelimiter(APath); // Not perfect for reload TaskImages.StopTasks; TaskImages.FreeImages; TaskImages.InitImages; FNextLeft := CONST_MARGIN_LEFT; FNextTop := CONST_MARGIN_TOP; EnterCriticalSection(CriticalSection.Section); try CriticalSection.FPostponedCloseOnceAllTaskCompleted := False; CriticalSection.FThreadsCompleted := 0; finally LeaveCriticalSection(CriticalSection.Section); end; LImages := 0; for LFileType in AExtension do try if FindFirst(APath + '*.' + LFileType, faAnyFile, LSearchRec) = 0 then repeat Inc(LImages); if LImages mod 5 = 0 then if RMain <> nil then RMain.UpdateLoadProgress(LImages); LoadAndDisplayImageAsync(APath + LSearchRec.Name); until FindNext(LSearchRec) <> 0; if RMain <> nil then RMain.UpdateLoadProgress(LImages); finally FindClose(LSearchRec); end; Result := LImages; end; class procedure TaskImages.LoadAndDisplayImageAsync(AFileName: String); var LImage: TImage; LMaxParentWidth, LMaxParentHeight: Integer; LPartialVisible: Boolean; begin FormHelper.GetFirstForm(IViewControl, RMain); if RMain <> nil then begin LMaxParentWidth := RMain.GetImageViewsControl.ClientWidth; LMaxParentHeight := RMain.GetImageViewsControl.ClientHeight; end else begin LMaxParentWidth := (CONST_IMAGE_WIDTH + CONST_MARGIN_LEFT) * 3; LMaxParentHeight := (CONST_IMAGE_HEIGHT + CONST_MARGIN_TOP) * 3; end; if FNextLeft + CONST_IMAGE_WIDTH + CONST_MARGIN_LEFT >= LMaxParentWidth then begin FNextLeft := CONST_MARGIN_LEFT; FNextTop := FNextTop + CONST_IMAGE_HEIGHT + CONST_MARGIN_TOP; end; if FNextTop >= LMaxParentHeight then LPartialVisible := False else LPartialVisible := True; try { Create image } LImage := TImage.Create(nil); with LImage do begin Width := CONST_IMAGE_WIDTH; Height := CONST_IMAGE_HEIGHT; Center := True; Stretch := True; Proportional := True; Left := FNextLeft; Top := FNextTop; with Canvas do begin Brush.Color := clRed; Pen.Color := clBlack; FillRect(Rect(0, 0, CONST_IMAGE_WIDTH, CONST_IMAGE_HEIGHT)); end; end; FNextLeft := FNextLeft + CONST_IMAGE_WIDTH + CONST_MARGIN_LEFT; if RMain <> nil then LImage.Parent := RMain.GetImageViewsControl; except FreeAndNil(LImage); end; { Thread count control } EnterCriticalSection(CriticalSection.Section); try CriticalSection.FImages.Add(LImage); if (CriticalSection.FImagesThreadPool.LockList.Count > CONST_MAX_THREADS) or (not LPartialVisible) then begin if CriticalSection.FPendingFiles.IndexOf(AFileName) = -1 then CriticalSection.FPendingFiles.Add(AFileName); Exit; end; finally LeaveCriticalSection(CriticalSection.Section); end; if LPartialVisible then RunImageViewThread(AFileName, tpHigher); end; end.
unit BanksForma; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, GridForma, ActnList, DB, ComCtrls, ToolWin, Grids, DBGridEh, FIBDataSet, pFIBDataSet, GridsEh, Menus, ToolCtrlsEh, DBGridEhToolCtrls, DBAxisGridsEh, System.Actions, Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtCtrls, CnErrorProvider, PrjConst, EhLibVCL, System.UITypes, DBGridEhGrouping, DynVarsEh, DBCtrlsEh, Vcl.Mask; type TBanksForm = class(TGridForm) dsBanks: TpFIBDataSet; lbl2: TLabel; edtName: TDBEditEh; lbl1: TLabel; edtBIK: TDBEditEh; lbl6: TLabel; mmoAddress: TDBMemoEh; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure actNewExecute(Sender: TObject); procedure actDeleteExecute(Sender: TObject); procedure actEditExecute(Sender: TObject); procedure srcDataSourceStateChange(Sender: TObject); procedure srcDataSourceDataChange(Sender: TObject; Field: TField); procedure btnSaveLinkClick(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } public { Public declarations } end; var BanksForm: TBanksForm; implementation uses DM; {$R *.dfm} procedure TBanksForm.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; dsBanks.Close; BanksForm := nil; end; procedure TBanksForm.actNewExecute(Sender: TObject); begin inherited; if (not (dmMain.AllowedAction(rght_Dictionary_full) or dmMain.AllowedAction(rght_Dictionary_Banks))) then exit; StartEdit(True); end; procedure TBanksForm.btnSaveLinkClick(Sender: TObject); var errors : Boolean; begin errors := False; if (edtName.Text = '') then begin errors := True; CnErrors.SetError(edtName, rsEmptyFieldError, iaMiddleLeft, bsNeverBlink); end else CnErrors.Dispose(edtName); if (edtBIK.Text = '') then begin errors := True; CnErrors.SetError(edtBIK, rsEmptyFieldError, iaMiddleLeft, bsNeverBlink); end else CnErrors.Dispose(edtBIK); if not errors then inherited; end; procedure TBanksForm.actDeleteExecute(Sender: TObject); begin inherited; if (not (dmMain.AllowedAction(rght_Dictionary_full) or dmMain.AllowedAction(rght_Dictionary_Banks))) then exit; if (MessageDlg(format(rsDeleteWithName, [srcDataSource.DataSet['O_NAME']]), mtConfirmation, [mbYes, mbNo], 0) = mrYes) then srcDataSource.DataSet.Delete; end; procedure TBanksForm.actEditExecute(Sender: TObject); begin inherited; if (not (dmMain.AllowedAction(rght_Dictionary_full) or dmMain.AllowedAction(rght_Dictionary_Banks))) then exit; StartEdit(); end; procedure TBanksForm.srcDataSourceStateChange(Sender: TObject); begin inherited; tbOk.Enabled := not ((sender as TDataSource).DataSet.State = dsBrowse); tbCancel.Enabled := tbOk.Enabled; btnNew.Enabled := not tbOk.Enabled; btnEdit.Enabled := not tbOk.Enabled; btnDelete.Enabled := not tbOk.Enabled; end; procedure TBanksForm.FormShow(Sender: TObject); begin inherited; dsBanks.Open; // права пользователей FCanEdit := ((dmMain.AllowedAction(rght_Dictionary_full) or dmMain.AllowedAction(rght_Dictionary_Banks))); actNew.Visible := FCanEdit; actDelete.Visible := FCanEdit; actEdit.Visible := FCanEdit; end; procedure TBanksForm.srcDataSourceDataChange(Sender: TObject; Field: TField); begin inherited; actEdit.Enabled := ((sender as TDataSource).DataSet.RecordCount>0) and FCanEdit; actDelete.Enabled := ((sender as TDataSource).DataSet.RecordCount>0) and FCanEdit; end; end.
{ 2020/07/07 0.01 Basic tests for TStrObjMap and TIntObjMap. } {$INCLUDE ../../flcInclude.inc} {$INCLUDE flcTestInclude.inc} unit flcTestDataStructMaps; interface procedure Test; implementation uses SysUtils, flcStdTypes, flcDataStructMaps {$IFDEF Profile}, flcTimers {$ENDIF}; procedure Test_1_StrObjMap; const TestN = 500000; type KeyRefArr = array[0..TestN - 1] of String; KeyRefArrP = ^KeyRefArr; var A : TStrObjMap; I, J : Integer; It : TStrObjMapIterator; KeyRef : KeyRefArrP; ValObj : TObject; {$IFDEF Profile} T1 : Word64; {$ENDIF} begin A := TStrObjMap.Create(False, True, True); try Assert(A.Count = 0); A.Add('a', A); Assert(A.Count = 1); Assert(A.RequireValue('a') = A); New(KeyRef); for I := 0 to TestN - 1 do KeyRef^[I] := IntToStr(I + 1); {$IFDEF Profile} T1 := GetMilliTick; {$ENDIF} for I := 0 to TestN - 1 do A.Add(KeyRef^[I], A); {$IFDEF Profile} T1 := Word64(GetMilliTick - T1); Writeln('StrObjMap.Add:', T1 / 1000000 / (TestN / 100000):0:6, 's/100k'); {$ENDIF} {$IFDEF Profile} T1 := GetMilliTick; {$ENDIF} for J := 1 to 4 do for I := 0 to TestN - 1 do Assert(A.KeyExists(KeyRef^[I])); {$IFDEF Profile} T1 := Word64(GetMilliTick - T1); Writeln('StrObjMap.Exists:', T1 / 1000000 / (TestN / (100000 / 4)):0:6, 's/100k'); {$ENDIF} {$IFDEF Profile} T1 := GetMilliTick; {$ENDIF} for I := 0 to TestN - 1 do Assert(A.GetValue(KeyRef^[I], ValObj)); {$IFDEF Profile} T1 := Word64(GetMilliTick - T1); Writeln('StrObjMap.GetValue:', T1 / 1000000 / (TestN / 100000):0:6, 's/100k'); {$ENDIF} Dispose(KeyRef); Assert(A.Count = TestN + 1); Assert(A.KeyExists('1')); A.Delete('1'); Assert(A.Count = TestN); Assert(not A.KeyExists('1')); Assert(Assigned(A.Iterate(It))); for I := 1 to TestN - 1 do Assert(Assigned(A.IteratorNext(It))); Assert(not Assigned(A.IteratorNext(It))); A.Clear; Assert(A.Count = 0); finally A.Free; end; end; procedure Test_1_IntObjMap; const TestN = 500000; var A : TIntObjMap; I, J : Integer; It : TIntObjMapIterator; ValObj : TObject; {$IFDEF Profile} T1 : Word64; {$ENDIF} begin A := TIntObjMap.Create(False, True); try Assert(A.Count = 0); A.Add(-1, A); Assert(A.Count = 1); Assert(A.RequireValue(-1) = A); {$IFDEF Profile} T1 := GetMilliTick; {$ENDIF} for I := 0 to TestN - 1 do A.Add(I + 1, A); {$IFDEF Profile} T1 := Word64(GetMilliTick - T1); Writeln('IntObjMap.Add:', T1 / 1000000 / (TestN / 100000):0:6, 's/100k'); {$ENDIF} {$IFDEF Profile} T1 := GetMilliTick; {$ENDIF} for J := 1 to 4 do for I := 0 to TestN - 1 do Assert(A.KeyExists(I + 1)); {$IFDEF Profile} T1 := Word64(GetMilliTick - T1); Writeln('IntObjMap.Exists:', T1 / 1000000 / (TestN / (100000 / 4)):0:6, 's/100k'); {$ENDIF} {$IFDEF Profile} T1 := GetMilliTick; {$ENDIF} for I := 0 to TestN - 1 do Assert(A.GetValue(I + 1, ValObj)); {$IFDEF Profile} T1 := Word64(GetMilliTick - T1); Writeln('IntObjMap.GetValue:', T1 / 1000000 / (TestN / 100000):0:6, 's/100k'); {$ENDIF} Assert(A.Count = TestN + 1); Assert(A.KeyExists(1)); A.Delete(1); Assert(A.Count = TestN); Assert(not A.KeyExists(1)); Assert(Assigned(A.Iterate(It))); for I := 1 to TestN - 1 do Assert(Assigned(A.IteratorNext(It))); Assert(not Assigned(A.IteratorNext(It))); A.Clear; Assert(A.Count = 0); finally A.Free; end; end; procedure Test; begin Test_1_StrObjMap; Test_1_IntObjMap; end; end.
program ejercicio6; type str40 = String[40]; microprocesador = record marca : str40; linea : str40; cantCore : Integer; vReloj : Real; tamTransistores: Integer; end; procedure leerProcesador(var m:microprocesador); begin with m do begin write('Ingrese la MARACA: '); readln(marca); write('Ingrese la LINEA: '); readln(linea); write('Ingrese CANTIDAD DE CORE: '); readln(cantCore); write('Ingrese la VELICIDAD DEL RELOJ: '); readln(vReloj); write('Ingrese el TAMANO DEL TRANSISTOR: '); readln(tamTransistores); writeln('---------------------------------'); end; end; procedure mayorCantProcesasores14(marcaActual:str40; var max1,max2: Integer; var marcaMax1, marcaMax2: str40); var m: microprocesador; begin if (m.cantCore >= max1) then begin max2:= max1; marcaMax2:= marcaMax1; max1:= m.cantCore; marcaMax1:= m.marca; end else if (m.cantCore >= max2) then begin max2:= m.cantCore; marcaMax2:=m.marca; end; end; procedure cantProcesadoresMulticore(m:microprocesador; var cantProMulticore:Integer); begin if (m.cantCore > 1) and ((m.marca = 'intel') or (m.marca = 'AMD')) and (m.vReloj >= 2) then begin cantProMulticore:= cantProMulticore + 1; end; end; var m: microprocesador; max1, max2, cantProMulticore, cant14: Integer; marcaMax1, marcaMax2, marcaActual: str40; begin max1:=-1; max2:=-1; cantProMulticore:=0; marcaActual:=''; marcaMax1:=''; marcaMax2:=''; leerProcesador(m); while (m.cantCore <> 0) do begin marcaActual:= m.marca; cant14:=0; while (m.marca = marcaActual) and (m.cantCore <> 0) do begin //inciso 1 if (m.cantCore > 2) and (m.tamTransistores <= 22) then begin writeln('La Marca: ', m.marca); writeln('La Linea: ', m.linea); end; //inciso 2 if (m.tamTransistores = 14) then begin cant14:= cant14 + 1; end; //inciso 3 cantProcesadoresMulticore(m,cantProMulticore); leerProcesador(m); end; mayorCantProcesasores14(marcaActual,cant14,max1,max2,marcaMax1, marcaMax2); //inciso 2 end; writeln('Las dos marcas con mayor cantidad de procesadores con transistores de 14nm son: ', marcaMax1, ' y ', marcaMax2); writeln('La cantidad de procesadores multicore de Intel o AMD, cuyo relojes alcanza velocidad de al menos 2GZ es: ', cantProMulticore); end.
unit Main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, ExtCtrls, Generics.Collections, Generics.Defaults, Math, StopWatch, TimeSpan, SizeRecord, PositionRecord, TileMap, AnimationArchive, Animation, Frame, ZombieController, ZombieCharacter, ZombieDirection, Menus, ActnList, StdCtrls, MPlayer; type TTopDownMainFrm = class(TForm) ZombieActionLst: TListBox; procedure FormPaint(Sender: TObject); procedure FormCreate(Sender: TObject); procedure AppIdle(Sender: Tobject; var Done: Boolean); procedure FormShow(Sender: TObject); procedure ZombieActionLstClick(Sender: TObject); procedure ZombieActionLstMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); protected fTileMap : TTileMap; //The tilemap used for draw the graphics to the screen fZombieController : TZombieController; fTileMapOffsetPosition : TPositionRecord; //Position of the tilemaps upper left corner in the screen (can be used for scrolling the graphics) fMousePosition : TPositionRecord; fMousePositionDestination : TPositionRecord; fMousePositionStartDrag : TPositionRecord; fZombieList : TObjectList<TZombieCharacter>; fLeftMousePressed : Boolean; fLeftMouseReleased : Boolean; fStopwatchLogic: TStopWatch; //Keeps the time between the updates of input fStopwatchGraphics: TStopWatch; //Keeps the time between updates of graphics //Can be called many times between frames, elapsedTime is how long time that has passed from last call procedure UpdateLogic(elapsedSeconds : double); //Called one time every frame, elapsedTime is how long time that has passed from last call procedure UpdateGraphics(elapsedSeconds : double); procedure GoHereSelected(aStateAtDestination : TZombieState); end; var TopDownMainFrm: TTopDownMainFrm; const TILE_SIZE = 128; TILE_MAP_WIDTH = 20; TILE_MAP_HEIGHT = 12; SECONDS_BETWEEN_FRAMES = 0.0055; implementation {$R *.dfm} procedure TTopDownMainFrm.FormCreate(Sender: TObject); function MakeRandomMapPosition() : TPositionRecord; begin Result := TPositionRecord.Create(RandomRange(100,(TILE_SIZE * TILE_MAP_WIDTH) - 100),RandomRange(100,(TILE_SIZE * TILE_MAP_HEIGHT) - 100)) end; function MakeRandomZombieDirection() : TZombieDirection; begin Result := TZombieDirection(RandomRange(0,8)) end; function MakeRandomZombieState() : TZombieState; begin Result := TZombieState(RandomRange(0,3)) end; var i : integer; begin fTileMapOffsetPosition.X := 0; fTileMapOffsetPosition.Y := 0; fTileMap := TTileMap.Create(TILE_SIZE,TILE_MAP_WIDTH,TILE_MAP_HEIGHT); Randomize(); fTileMap.RandomizeMap(); fLeftMousePressed := false; fLeftMouseReleased := False; fStopwatchLogic := TStopwatch.Create(); fStopwatchGraphics := TStopwatch.Create(); Application.OnIdle := AppIdle; fZombieController := TZombieController.Create(TAnimationArchive.Create('.\Characters\Zombie\zombie_0.png',36,9)); //Snett uppifrån med skugga //fZombieController := TZombieController.Create(TAnimationArchive.Create('.\Characters\Zombie\zombie_topdown.png',36,9)); //Rakt uppifrån (större) fZombieList := TObjectList<TZombieCharacter>.Create(True); for i := 0 to 99 do fZombieList.Add(TZombieCharacter.Create(MakeRandomMapPosition(),MakeRandomZombieDirection(),MakeRandomZombieState())); end; procedure TTopDownMainFrm.FormPaint(Sender: TObject); var elapsedTimeGraphics : double; begin elapsedTimeGraphics := fStopwatchGraphics.GetElapsedSecondsWhenRunning(); if(elapsedTimeGraphics > SECONDS_BETWEEN_FRAMES) then begin UpdateGraphics(elapsedTimeGraphics); fStopwatchGraphics.Stop(); fStopwatchGraphics.Start(); end; end; procedure TTopDownMainFrm.FormShow(Sender: TObject); begin fStopwatchLogic.Start(); fStopwatchGraphics.Start(); end; procedure TTopDownMainFrm.GoHereSelected(aStateAtDestination : TZombieState); var zombie : TZombieCharacter; mousePosition : TPositionRecord; begin mousePosition.X := fMousePositionDestination.X - CHARACTER_WIDTH div 2 + fTileMapOffsetPosition.X; mousePosition.Y := fMousePositionDestination.Y - CHARACTER_HEIGHT + 33 + fTileMapOffsetPosition.Y; for zombie in fZombieList do begin if(zombie.GetSelected()) then begin zombie.SetDestination(mousePosition); zombie.SetStateAtDestination(aStateAtDestination); zombie.SetState(TZombieState.Ordered); end; end; end; procedure TTopDownMainFrm.AppIdle(Sender: Tobject; var Done: Boolean); begin UpdateLogic(fStopwatchLogic.GetElapsedSecondsWhenRunning()); fStopwatchLogic.Stop(); fStopwatchLogic.Start(); if(fStopwatchGraphics.GetElapsedSecondsWhenRunning() > SECONDS_BETWEEN_FRAMES) then Self.Invalidate(); Done := False; end; procedure TTopDownMainFrm.UpdateGraphics(elapsedSeconds : double); var clientSize : TSizeRecord; zombie : TZombieCharacter; begin clientSize.Width := Self.ClientWidth; clientSize.Height := Self.ClientHeight; Canvas.Lock(); fTileMap.Draw(Canvas,fTileMapOffsetPosition,clientSize); if(fLeftMousePressed) then begin Canvas.Brush.Color := clDkGray; Canvas.FrameRect(Rect(fMousePositionStartDrag.X, fMousePositionStartDrag.Y, fMousePosition.X, fMousePosition.Y)); end; //Sortera med lägsta y-värde först för att rita de bakomliggande längst bak //(för isometriskt perspektiv, annars spelar det ingen roll) fZombieList.Sort(TComparer<TZombieCharacter>.Construct( function (const L, R: TZombieCharacter): integer begin Result := CompareValue(L.GetPosition().Y,R.GetPosition().Y); end )); for zombie in fZombieList do fZombieController.DrawCharacter(zombie,Canvas,fTileMapOffsetPosition); Canvas.UnLock(); end; procedure TTopDownMainFrm.UpdateLogic(elapsedSeconds : double); var zombie : TZombieCharacter; pt : tPoint; mousePosition : TPositionRecord; someClicked : Boolean; someSelected : Boolean; begin if(GetKeyState(VK_RIGHT) < 0) then fTileMapOffsetPosition.X := fTileMapOffsetPosition.X + Trunc(500.0 * elapsedSeconds); if(GetKeyState(VK_LEFT) < 0) then fTileMapOffsetPosition.X := fTileMapOffsetPosition.X - Trunc(500.0 * elapsedSeconds); if(GetKeyState(VK_DOWN) < 0) then fTileMapOffsetPosition.Y := fTileMapOffsetPosition.Y + Trunc(500.0 * elapsedSeconds); if(GetKeyState(VK_UP) < 0) then fTileMapOffsetPosition.Y := fTileMapOffsetPosition.Y - Trunc(500.0 * elapsedSeconds); if( fTileMapOffsetPosition.X < 0) then fTileMapOffsetPosition.X := 0; if( fTileMapOffsetPosition.Y < 0) then fTileMapOffsetPosition.Y := 0; if( fTileMapOffsetPosition.X > (TILE_MAP_WIDTH * TILE_SIZE) - Self.ClientWidth) then fTileMapOffsetPosition.X := (TILE_MAP_WIDTH * TILE_SIZE) - Self.ClientWidth; if( fTileMapOffsetPosition.Y > (TILE_MAP_HEIGHT * TILE_SIZE) - Self.ClientHeight) then fTileMapOffsetPosition.Y := (TILE_MAP_HEIGHT * TILE_SIZE) - Self.ClientHeight; //Add time for animation and state and sense check (AI routines) for zombie in fZombieList do zombie.AddElapsedSeconds(elapsedSeconds); pt := Mouse.CursorPos; //Mouse position in screen pt := ScreenToClient(pt); //Form position fMousePosition := TPositionRecord.Create(pt.X,pt.Y); //Change to different type of position //Some logic to toggle the mousebutton down or up (you have to release the button before you can select again) if(GetAsyncKeyState(VK_LBUTTON) < 0) then begin if not fLeftMousePressed then begin fMousePositionStartDrag := fMousePosition; end; fLeftMousePressed := True; end else begin if(fLeftMousePressed) then fLeftMouseReleased := True else fLeftMouseReleased := False; fLeftMousePressed := False; end; if fLeftMouseReleased then begin //Check if this was the end of a mouse-drag if(fMousePositionStartDrag.X <> fMousePosition.X) and (fMousePositionStartDrag.Y <> fMousePosition.Y) then begin for zombie in fZombieList do begin //Select or deselects when click if fZombieController.RectangleCollisionWithCharacter(zombie,fTileMapOffsetPosition,fMousePositionStartDrag,fMousePosition) then begin zombie.SetSelected( true ); end; end; end else begin someClicked := False; someSelected := False; for zombie in fZombieList do begin //Select or deselects when click if fZombieController.PositionCollisionWithCharacter(zombie,fTileMapOffsetPosition,fMousePosition) then begin zombie.SetSelected( not zombie.GetSelected() ); someClicked := True; end; if( zombie.GetSelected() ) then someSelected := True; end; if(not someClicked) then begin //Shows or hides action-menu if(not ZombieActionLst.Visible) and (someSelected) then begin fMousePositionDestination := fMousePosition; ZombieActionLst.Left := fMousePosition.X - ZombieActionLst.Width div 2; ZombieActionLst.Top := fMousePosition.Y; ZombieActionLst.Visible := True; ZombieActionLst.ItemIndex := 0; ZombieActionLst.SetFocus(); end else begin ZombieActionLst.Visible := False; end; end; end; end; //Right mousebutton deselects everyone if(GetAsyncKeyState(VK_RBUTTON) < 0) then begin ZombieActionLst.Visible := False; for zombie in fZombieList do begin zombie.SetSelected(false); end; end; end; procedure TTopDownMainFrm.ZombieActionLstClick(Sender: TObject); begin if (ZombieActionLst.ItemIndex = 0) then GoHereSelected(TZombieState.Calm) else if (ZombieActionLst.ItemIndex = 1) then GoHereSelected(TZombieState.Angry); ZombieActionLst.Visible := False; fLeftMouseReleased := False; fLeftMousePressed := False; end; procedure TTopDownMainFrm.ZombieActionLstMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var p:TPoint; begin p.x:=x; p.y:=y; ZombieActionLst.ItemIndex := ZombieActionLst.ItemAtPos(P,True); end; end. // //Check if not inside the action-menu when clicking (or the action-menu is not visible) // if (not PtInRect(ZombieActionLst.ClientRect, pt) or not ZombieActionLst.Visible) then
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpIBerGenerator; {$I ..\Include\CryptoLib.inc} interface uses Classes, ClpIProxiedInterface, ClpIAsn1Generator; type IBerGenerator = interface(IAsn1Generator) ['{9ED01B6B-EF67-46B2-8EF6-023CA3967345}'] procedure WriteHdr(tag: Int32); procedure WriteBerHeader(tag: Int32); procedure WriteBerBody(contentStream: TStream); procedure WriteBerEnd(); procedure AddObject(const obj: IAsn1Encodable); function GetRawOutputStream(): TStream; procedure Close(); end; implementation end.
{====================================================} { } { EldoS Visual Components } { } { Copyright (c) 1998-2003, EldoS Corporation } { } {====================================================} {$I ..\ElPack.inc} unit frmSideBarEdit; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, {$ifdef VCL_6_USED} DesignIntf, DesignEditors, DesignWindows, DsnConst, {$else} DsgnIntf, {$endif} Dialogs, ElSideBar, ExtCtrls, ElPanel, StdCtrls, ElSpin, ElBtnCtl, ElCheckCtl, ElACtrls, ElPopBtn, ElXPThemedControl, ElEdits; type TSideBarEditForm = class(TForm) SideBar: TElSideBar; SectionsGB: TGroupBox; Label1: TLabel; Label2: TLabel; SectionImageSpin: TElSpinEdit; GroupBox1: TGroupBox; Label3: TLabel; Label4: TLabel; ItemImageSpin: TElSpinEdit; Label5: TLabel; SectionTagSpin: TElSpinEdit; Label6: TLabel; ItemTagSpin: TElSpinEdit; Label7: TLabel; Label8: TLabel; SectionCaptionEdit: TElAdvancedEdit; SectionHintEdit: TElAdvancedEdit; ItemCaptionEdit: TElAdvancedEdit; ItemHintEdit: TElAdvancedEdit; VisibleSectionCB: TElCheckBox; EnabledSectionCB: TElCheckBox; VisibleItemCB: TElCheckBox; EnabledItemCB: TElCheckBox; ContainsControlsCB: TElCheckBox; AddSectionBtn: TElPopupButton; MoveUpSectionBtn: TElPopupButton; DeleteSectionBtn: TElPopupButton; MoveDownSectionBtn: TElPopupButton; AddItemBtn: TElPopupButton; MoveUpItemBtn: TElPopupButton; DeleteItemBtn: TElPopupButton; MoveDownItemBtn: TElPopupButton; OkBtn: TElPopupButton; CancelBtn: TElPopupButton; InactiveSectionCB: TElCheckBox; procedure SideBarSectionChange(Sender: TObject); procedure SideBarItemChange(Sender: TObject); procedure SectionCaptionEditChange(Sender: TObject); procedure SectionImageSpinChange(Sender: TObject); procedure EnabledSectionCBClick(Sender: TObject); procedure VisibleSectionCBClick(Sender: TObject); procedure VisibleItemCBClick(Sender: TObject); procedure EnabledItemCBClick(Sender: TObject); procedure ItemCaptionEditChange(Sender: TObject); procedure ItemImageSpinChange(Sender: TObject); procedure MoveUpItemBtnClick(Sender: TObject); procedure MoveDownItemBtnClick(Sender: TObject); procedure MoveUpSectionBtnClick(Sender: TObject); procedure MoveDownSectionBtnClick(Sender: TObject); procedure AddSectionBtnClick(Sender: TObject); procedure AddItemBtnClick(Sender: TObject); procedure DeleteItemBtnClick(Sender: TObject); procedure DeleteSectionBtnClick(Sender: TObject); procedure SectionTagSpinChange(Sender: TObject); procedure ItemTagSpinChange(Sender: TObject); procedure SectionHintEditChange(Sender: TObject); procedure ItemHintEditChange(Sender: TObject); procedure ContainsControlsCBClick(Sender: TObject); procedure InactiveSectionCBClick(Sender: TObject); private FCurItem : TElSideBarItem; FCurSection : TElSideBarSection; public OrigSideBar : TElSideBar; procedure GetData; procedure SetData; end; var SideBarEditForm: TSideBarEditForm; type TSideBarSectionsProperty = class(TPropertyEditor) procedure Edit; override; function GetAttributes : TPropertyAttributes; override; function GetValue : string; override; end; type TSideBarEditor = class(TComponentEditor) procedure ExecuteVerb(Index : Integer); override; function GetVerb(Index : Integer) : string; override; function GetVerbCount : Integer; override; end; implementation {$R *.DFM} procedure TSideBarEditor.ExecuteVerb(Index : Integer); var Form : TCustomForm; begin if Index = 0 then begin with TSideBarEditForm.Create(Application) do begin try { Set dialog's caption. } Caption := TElSideBar(Component).Owner.Name + '.' + TElSideBar(Component).Name + ' - ' + Caption; OrigSideBar := TElSideBar(Component); SetData; if (ShowModal = mrOk) then begin Form := GetParentForm(OrigSideBar); if (Form <> nil) and (Form.Designer <> nil) then Form.Designer.Modified; GetData; end; finally Free; { Free dialog. } end; { try/finally } end; { with } end; end; function TSideBarEditor.GetVerb(Index : Integer) : string; begin if Index = 0 then Result := 'Items Editor'; end; function TSideBarEditor.GetVerbCount : Integer; begin Result := 1; end; procedure TSideBarSectionsProperty.Edit; var Form : TCustomForm; begin with TSideBarEditForm.Create(Application) do begin try { Set dialog's caption. } Caption := TComponent(GetComponent(0)).Owner.Name + '.' + TComponent(GetComponent(0)).Name + ' - ' + Caption; OrigSideBar := GetComponent(0) as TElSideBar; SetData; if (ShowModal = mrOk) then begin Form := GetParentForm(OrigSideBar); if (Form <> nil) and (Form.Designer <> nil) then Form.Designer.Modified; GetData; end; finally Free; { Free dialog. } end; { try/finally } end; { with } end; { Edit } function TSideBarSectionsProperty.GetValue : string; begin result := 'SideBar Sections'; end; function TSideBarSectionsProperty.GetAttributes : TPropertyAttributes; { Returns information used by the Object Inspector to show the approprate adornments (e.g., "..." button, drop-down button). } begin GetAttributes := [paDialog]; end; { GetAttributes } procedure TSideBarEditForm.SetData; var i : integer; j : integer; Item : TElSideBarItem; Section : TElSideBarSection; begin SideBar.SectionImages := OrigSideBar.SectionImages; SideBar.SectionHotImages := OrigSideBar.SectionHotImages; SideBar.SectionDisabledImages := OrigSideBar.SectionDisabledImages; SideBar.ItemImages := OrigSideBar.ItemImages; SideBar.ItemHotImages := OrigSideBar.ItemHotImages; SideBar.ItemDisabledImages := OrigSideBar.ItemDisabledImages; if SideBar.SectionImages <> nil then SectionImageSpin.MaxValue := SideBar.SectionImages.Count - 1; if SideBar.ItemImages <> nil then ItemImageSpin.MaxValue := SideBar.ItemImages.Count - 1; SideBar.ItemSize := OrigSideBar.ItemSize; SideBar.TopSpacing := OrigSideBar.TopSpacing; SideBar.Spacing := OrigSideBar.Spacing; SideBar.WordWrap := OrigSideBar.WordWrap; SideBar.BeginUpdate; SideBar.Sections.Assign(OrigSideBar.Sections); for i := 0 to SideBar.Sections.Count - 1 do // Iterate begin Section := SideBar.Sections[i]; Section.Disabled := not Section.Enabled; Section.Enabled := true; Section.Hidden := not Section.Visible; Section.Visible := true; Section.Active := not Section.Inactive; Section.Inactive := false; Section.Data := OrigSideBar.Sections[i]; for j := 0 to Section.Items.Count - 1 do // Iterate begin Item := Section.Items[j]; Item.Disabled := not Item.Enabled; Item.Enabled := true; Item.Hidden := not Item.Visible; Item.Visible := true; end; // for end; // for SideBar.SectionIndex := OrigSideBar.SectionIndex; SideBar.ItemIndex := OrigSideBar.ItemIndex; SideBar.EndUpdate; SideBarSectionChange(SideBar); end; procedure TSideBarEditForm.GetData; var i : integer; j : integer; b : boolean; Item : TElSideBarItem; Section : TElSideBarSection; ASection : TElSideBarSection; begin SideBar.BeginUpdate; for i := 0 to SideBar.Sections.Count - 1 do // Iterate begin Section := SideBar.Sections[i]; Section.Enabled := not Section.Disabled; Section.Visible := not Section.Hidden; Section.Inactive := not Section.Active; for j := 0 to Section.Items.Count - 1 do // Iterate begin Item := Section.Items[j]; Item.Enabled := not Item.Disabled; Item.Visible := not Item.Hidden; end; // for end; // for SideBar.EndUpdate; OrigSideBar.SectionIndex := -1; OrigSideBar.BeginUpdate; i := 0; while i <= Pred(OrigSideBar.Sections.Count) do begin b := false; for j := 0 to Pred(SideBar.Sections.Count) do begin if SideBar.Sections[j].Data = OrigSideBar.Sections[i] then begin b := true; break; end; end; if not b then begin OrigSideBar.Sections[i].Free; end else inc(i); end; for i := 0 to Pred(SideBar.Sections.Count) do begin if (SideBar.Sections[i].Data = nil) then SideBar.Sections[i].Data := OrigSideBar.Sections.Add; TElSideBarSection(SideBar.Sections[i].Data).Index := i; TElSideBarSection(SideBar.Sections[i].Data).Assign(SideBar.Sections[i]); end; //OrigSideBar.Sections.Assign(SideBar.Sections); OrigSideBar.SectionIndex := SideBar.SectionIndex; OrigSideBar.ItemIndex := SideBar.ItemIndex; OrigSideBar.EndUpdate; for i := 0 to OrigSideBar.Sections.Count -1 do begin ASection := OrigSideBar.Sections[i]; if i <> OrigSideBar.SectionIndex then if ASection.ContainsControls then ASection.Panel.Visible := false; end; if OrigSideBar.SectionIndex <> -1 then begin ASection := OrigSideBar.Sections[OrigSideBar.SectionIndex]; if ASection.ContainsControls then begin ASection.Panel.Visible := false; OrigSideBar.UpdateChildControl; end; end; (*ASection := FSection; FSection := nil; if ASection <> nil then SectionIndex := ASection.Index else SectionIndex := -1; *) end; procedure TSideBarEditForm.SideBarSectionChange(Sender: TObject); begin with SideBar do begin if SectionIndex <> -1 then begin FCurSection := Sections[SectionIndex]; DeleteSectionBtn.Enabled := true; MoveUpSectionBtn.Enabled := SectionIndex > 0; MoveDownSectionBtn.Enabled := SectionIndex < FCurSection.Collection.Count - 1; VisibleSectionCB.Enabled := true; VisibleSectionCB.Checked := not FCurSection.Hidden; InactiveSectionCB.Enabled := true; InactiveSectionCB.Checked := not FCurSection.Active; EnabledSectionCB.Enabled := true; EnabledSectionCB.Checked := not FCurSection.Disabled; SectionCaptionEdit.Enabled := true; SectionCaptionEdit.Text := FCurSection.Caption; SectionImageSpin.Enabled := true; SectionImageSpin.Value := FCurSection.ImageIndex; SectionTagSpin.Enabled := true; SectionTagSpin.Value := FCurSection.Tag; SectionHintEdit.Enabled := true; SectionHintEdit.Text := FCurSection.Hint; AddItemBtn.Enabled := true; ContainsControlsCB.Checked := FCurSection.ContainsControls; ContainsControlsCB.Enabled := true; end else begin FCurSection := nil; DeleteSectionBtn.Enabled := false; MoveUpSectionBtn.Enabled := false; MoveDownSectionBtn.Enabled := false; VisibleSectionCB.Enabled := false; VisibleSectionCB.Checked := true; EnabledSectionCB.Enabled := false; EnabledSectionCB.Checked := true; InactiveSectionCB.Enabled := false; InactiveSectionCB.Checked := false; SectionCaptionEdit.Enabled := false; SectionCaptionEdit.Text := ''; SectionImageSpin.Enabled := false; SectionImageSpin.Value := -1; SectionTagSpin.Enabled := false; SectionTagSpin.Value := -1; SectionHintEdit.Enabled := false; SectionHintEdit.Text := ''; AddItemBtn.Enabled := false; ContainsControlsCB.Checked := false; ContainsControlsCB.Enabled := false; end; end; SideBarItemChange(SideBar); end; procedure TSideBarEditForm.SideBarItemChange(Sender: TObject); begin with SideBar do begin if ItemIndex <> -1 then begin FCurItem := Sections[SectionIndex].Items[ItemIndex]; DeleteItemBtn.Enabled := true; MoveUpItemBtn.Enabled := ItemIndex > 0; MoveDownItemBtn.Enabled := ItemIndex < FCurItem.Collection.Count - 1; VisibleItemCB.Enabled := true; VisibleItemCB.Checked := not FCurItem.Hidden; EnabledItemCB.Enabled := true; EnabledItemCB.Checked := not FCurItem.Disabled; ItemCaptionEdit.Enabled := true; ItemCaptionEdit.Text := FCurItem.Caption; ItemImageSpin.Enabled := true; ItemImageSpin.Value := FCurItem.ImageIndex; ItemTagSpin.Enabled := true; ItemHintEdit.Enabled := true; ItemHintEdit.Text := FCurItem.Hint; ItemTagSpin.Value := FCurItem.Tag; end else begin FCurItem := nil; DeleteItemBtn.Enabled := false; MoveUpItemBtn.Enabled := false; MoveDownItemBtn.Enabled := false; VisibleItemCB.Enabled := false; VisibleItemCB.Checked := true; EnabledItemCB.Enabled := false; EnabledItemCB.Checked := true; ItemCaptionEdit.Enabled := false; ItemCaptionEdit.Text := ''; ItemImageSpin.Enabled := false; ItemImageSpin.Value := -1; ItemTagSpin.Enabled := false; ItemTagSpin.Value := -1; ItemHintEdit.Enabled := false; ItemHintEdit.Text := ''; end; end; end; procedure TSideBarEditForm.SectionCaptionEditChange(Sender: TObject); begin if FCurSection <> nil then FCurSection.Caption := SectionCaptionEdit.Text; end; procedure TSideBarEditForm.SectionImageSpinChange(Sender: TObject); begin if FCurSection <> nil then FCurSection.ImageIndex := SectionImageSpin.Value; end; procedure TSideBarEditForm.EnabledSectionCBClick(Sender: TObject); begin if FCurSection <> nil then FCurSection.Disabled := not EnabledSectionCB.Checked; end; procedure TSideBarEditForm.VisibleSectionCBClick(Sender: TObject); begin if FCurSection <> nil then FCurSection.Hidden := not VisibleSectionCB.Checked; end; procedure TSideBarEditForm.VisibleItemCBClick(Sender: TObject); begin if FCurItem <> nil then FCurItem.Hidden := not VisibleItemCB.Checked; end; procedure TSideBarEditForm.EnabledItemCBClick(Sender: TObject); begin if FCurItem <> nil then FCurItem.Disabled := not EnabledItemCB.Checked; end; procedure TSideBarEditForm.ItemCaptionEditChange(Sender: TObject); begin if FCurItem <> nil then FCurItem.Caption := ItemCaptionEdit.Text; end; procedure TSideBarEditForm.ItemImageSpinChange(Sender: TObject); begin if FCurItem <> nil then FCurItem.ImageIndex := ItemImageSpin.Value; end; procedure TSideBarEditForm.MoveUpItemBtnClick(Sender: TObject); begin if FCurItem <> nil then if FCurItem.Index > 0 then begin FCurItem.Index := FCurItem.Index - 1; if SideBar.TopIndex = FCurItem.Index + 1 then SideBar.TopIndex := FCurItem.Index; MoveDownItemBtn.Enabled := FCurItem.Index < FCurItem.Collection.Count - 1; MoveUpItemBtn.Enabled := FCurItem.Index > 0; end; end; procedure TSideBarEditForm.MoveDownItemBtnClick(Sender: TObject); begin if FCurItem <> nil then if FCurItem.Index < FCurItem.Collection.Count - 1 then begin FCurItem.Index := FCurItem.Index + 1; MoveDownItemBtn.Enabled := FCurItem.Index < FCurItem.Collection.Count - 1; MoveUpItemBtn.Enabled := FCurItem.Index > 0; end; end; procedure TSideBarEditForm.MoveUpSectionBtnClick(Sender: TObject); begin if FCurSection <> nil then if FCurSection.Index > 0 then begin FCurSection.Index := FCurSection.Index - 1; MoveUpSectionBtn.Enabled := FCurSection.Index > 0; MoveDownSectionBtn.Enabled := FCurSection.Index < FCurSection.Collection.Count - 1; end; end; procedure TSideBarEditForm.MoveDownSectionBtnClick(Sender: TObject); begin if FCurSection <> nil then if FCurSection.Index < FCurSection.Collection.Count - 1 then begin FCurSection.Index := FCurSection.Index + 1; MoveUpSectionBtn.Enabled := FCurSection.Index > 0; MoveDownSectionBtn.Enabled := FCurSection.Index < FCurSection.Collection.Count - 1; end; end; procedure TSideBarEditForm.AddSectionBtnClick(Sender: TObject); begin SideBar.SectionIndex := SideBar.Sections.Add.Index; SideBar.Sections[SideBar.SectionIndex].Active := true; SideBarSectionChange(SideBar); end; procedure TSideBarEditForm.AddItemBtnClick(Sender: TObject); begin SideBar.ItemIndex := FCurSection.Items.Add.Index; SideBar.TopIndex := SideBar.ItemIndex; SideBarItemChange(SideBar); end; procedure TSideBarEditForm.DeleteItemBtnClick(Sender: TObject); begin if FCurItem <> nil then begin FCurItem.Free; SideBarItemChange(SideBar); end; end; procedure TSideBarEditForm.DeleteSectionBtnClick(Sender: TObject); begin if FCurSection <> nil then begin FCurSection.Free; SideBarSectionChange(SideBar); end; end; procedure TSideBarEditForm.SectionTagSpinChange(Sender: TObject); begin if FCurSection <> nil then FCurSection.Tag := SectionTagSpin.Value; end; procedure TSideBarEditForm.ItemTagSpinChange(Sender: TObject); begin if FCurItem <> nil then FCurItem.Tag := ItemTagSpin.Value; end; procedure TSideBarEditForm.SectionHintEditChange(Sender: TObject); begin if FCurSection <> nil then FCurSection.Hint := SectionHintEdit.Text; end; procedure TSideBarEditForm.ItemHintEditChange(Sender: TObject); begin if FCurItem <> nil then FCurItem.Hint := ItemHintEdit.Text; end; procedure TSideBarEditForm.ContainsControlsCBClick(Sender: TObject); begin if FCurSection <> nil then FCurSection.ContainsControls := ContainsControlsCB.Checked; end; procedure TSideBarEditForm.InactiveSectionCBClick(Sender: TObject); begin if FCurSection <> nil then FCurSection.Active := not InactiveSectionCB.Checked; end; end.
unit U_PadraoCrud; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.ExtCtrls, Data.DB, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Vcl.Buttons, 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, Datasnap.Provider, Datasnap.DBClient; type TfrmPadraoCRUD = class(TForm) pnlRodape: TPanel; pgcPrincipal: TPageControl; tabGrid: TTabSheet; tabData: TTabSheet; grdListagem: TDBGrid; btnIncluir: TBitBtn; btnAlterar: TBitBtn; btnExcluir: TBitBtn; btnCancelar: TBitBtn; btnGravar: TBitBtn; btnSair: TBitBtn; pnlBusca: TPanel; btnBuscar: TBitBtn; qryPrincipal: TFDQuery; dsPrincipal: TDataSource; procedure btnIncluirClick(Sender: TObject); procedure btnAlterarClick(Sender: TObject); procedure btnCancelarClick(Sender: TObject); procedure btnGravarClick(Sender: TObject); procedure btnSairClick(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure btnExcluirClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } procedure ModoGrid; procedure ModoForm; public { Public declarations } end; var frmPadraoCRUD: TfrmPadraoCRUD; implementation {$R *.dfm} uses U_DM; procedure TfrmPadraoCRUD.btnAlterarClick(Sender: TObject); begin try qryPrincipal.Edit; ModoForm; except on E: Exception do begin messagedlg(E.ClassName + ': ' + E.Message, mtError, [mbOk],0 ); end; end; end; procedure TfrmPadraoCRUD.btnCancelarClick(Sender: TObject); begin try qryPrincipal.Cancel; ModoGrid; except on E: Exception do begin messagedlg(E.ClassName + ': ' + E.Message, mtError, [mbOk],0 ); end; end; end; procedure TfrmPadraoCRUD.btnExcluirClick(Sender: TObject); begin try qryPrincipal.Delete; qryPrincipal.Refresh; // TODO:Redundancia ?? except on E: Exception do begin messagedlg(E.ClassName + ': ' + E.Message, mtError, [mbOk],0 ); end; end; end; procedure TfrmPadraoCRUD.btnGravarClick(Sender: TObject); begin try qryPrincipal.Post; qryPrincipal.Refresh; // TODO:Redundancia ?? ModoGrid; except on E: Exception do begin messagedlg(E.ClassName + ': ' + E.Message, mtError, [mbOk],0 ); end; end; end; procedure TfrmPadraoCRUD.btnIncluirClick(Sender: TObject); begin try qryPrincipal.Append; ModoForm; except on E: Exception do begin messagedlg(E.ClassName + ': ' + E.Message, mtError, [mbOk],0 ); end; end; end; procedure TfrmPadraoCRUD.btnSairClick(Sender: TObject); begin qryPrincipal.Close; qryPrincipal.Active := false; Close; Sender := nil; end; procedure TfrmPadraoCRUD.FormClose(Sender: TObject; var Action: TCloseAction); begin qryPrincipal.Close; qryPrincipal.Active := false; Sender := nil; end; procedure TfrmPadraoCRUD.FormCreate(Sender: TObject); begin qryPrincipal.Active := true; qryPrincipal.Open; ModoGrid; end; procedure TfrmPadraoCRUD.FormKeyPress(Sender: TObject; var Key: Char); begin if Key=#13 then begin Key := #0; Perform(WM_NEXTDLGCTL,0,0); end; end; procedure TfrmPadraoCRUD.ModoForm; begin tabGrid.TabVisible := false; tabData.TabVisible := true; pgcPrincipal.ActivePage := (tabData); btnIncluir.Enabled := false; btnAlterar.Enabled := false; btnExcluir.Enabled := false; btnCancelar.Enabled := true; btnGravar.Enabled := true; btnSair.Enabled := false; end; procedure TfrmPadraoCRUD.ModoGrid; begin tabGrid.TabVisible := true; tabData.TabVisible := false; pgcPrincipal.ActivePage := (tabGrid); btnIncluir.Enabled := true; btnAlterar.Enabled := true; btnExcluir.Enabled := true; btnCancelar.Enabled := false; btnGravar.Enabled := false; btnSair.Enabled := true; end; end.
{Part 4a of regression test for SPECFUND unit (c) 2010-2013 W.Ehrhardt} unit t_sfd4a; {$i STD.INC} {$ifdef BIT16} {$N+} {$ifndef Windows} {$O+} {$endif} {$endif} interface procedure test_e1; procedure test_ei; procedure test_ei_inv; procedure test_gei; procedure test_ein; procedure test_li; procedure test_en; procedure test_chi; procedure test_shi; procedure test_ci; procedure test_cin; procedure test_cinh; procedure test_si; procedure test_ssi; implementation uses damath, specfund, t_sfd0; {---------------------------------------------------------------------------} procedure test_e1; var x,y,f: double; cnt, failed: integer; const NE = 2; begin cnt := 0; failed := 0; writeln('Function: ','e1'); x := succd(0); {x=0.5^1074} y := e1(x); f := 743.86285625647972945; testrel( 1, NE, y, f, cnt,failed); x := 1e-10; y := e1(x); f := 22.448635265138923980; testrel( 2, NE, y, f, cnt,failed); x := 0.0009765625; y := e1(x); f := 6.3552324648310718026; testrel( 3, NE, y, f, cnt,failed); x := 0.125; y := e1(x); f := 1.6234256405841687915; testrel( 4, NE, y, f, cnt,failed); x := 0.5; y := e1(x); f := 0.5597735947761608118; testrel( 5, NE, y, f, cnt,failed); x := 0.9990234375; y := e1(x); f := 0.2197435427851990964; testrel( 6, NE, y, f, cnt,failed); x := 1.0; y := e1(x); f := 0.2193839343955202737; testrel( 7, NE, y, f, cnt,failed); x := 1.0009765625; y := e1(x); f := 0.2190250276806367220; testrel( 8, NE, y, f, cnt,failed); x := 1.5; y := e1(x); f := 0.1000195824066326519; testrel( 9, NE, y, f, cnt,failed); x := 2.0; y := e1(x); f := 0.4890051070806111957e-1; testrel(10, NE, y, f, cnt,failed); x := 100.0; y := e1(x); f := 0.3683597761682032180e-45; testrel(11, 32, y, f, cnt,failed); {!!!???} x := 706.0; y := e1(x); f := 0.3456823684693928525e-309; testrel(12, NE, y, f, cnt,failed); x := 707.0; y := e1(x); f := 0.0; testabs(13, 1, y, f, cnt,failed); if failed>0 then writeln('*** failed: ',failed,' of ',cnt) else writeln(cnt:4, ' tests OK'); inc(total_cnt, cnt); inc(total_failed, failed); end; {---------------------------------------------------------------------------} procedure test_ei; var x,y,f: double; cnt, failed: integer; const NE = 4; begin cnt := 0; failed := 0; writeln('Function: ','ei'); x := succd(0); {x=0.5^1074} y := ei(x); f := -743.86285625647972945; testrel( 1, NE, y, f, cnt,failed); x := 1e-100; y := ei(x); f := -229.68129363450303554; testrel( 2, NE, y, f, cnt,failed); x := 1e-20; y := ei(x); f := -45.474486194979380820; testrel( 3, NE, y, f, cnt,failed); x := 1e-10; y := ei(x); f := -22.448635264938923980; testrel( 4, NE, y, f, cnt,failed); x := 1e-5; y := ei(x); f := -10.935699800043695504; testrel( 5, NE, y, f, cnt,failed); x := 0.250; y := ei(x); f := -0.54254326466191372953; testrel( 6, NE, y, f, cnt,failed); x := 0.372507410781366634462; y := ei(x); f := 0.31689558510305276553e-22; testabs( 7, NE, y, f, cnt,failed); x := 5.9990234375; y := ei(x); f := 85.92412661441223831; testrel( 8, NE, y, f, cnt,failed); x := 6.0; y := ei(x); f := 85.989762142439204804; testrel( 9, NE, y, f, cnt,failed); x := 6.0009765625; y := ei(x); f := 86.055451106535934443; testrel(10, NE, y, f, cnt,failed); x := 9.9990234375; y := ei(x); f := 2490.0788991846740153; testrel(11, NE, y, f, cnt,failed); x := 10.0; y := ei(x); f := 2492.2289762418777591; testrel(12, NE, y, f, cnt,failed); x := 10.0009765625; y := ei(x); f := 2494.3809438459312504; testrel(13, NE, y, f, cnt,failed); x := 19.9990234375; y := ei(x); f := 25591973.942720267184; testrel(14, NE, y, f, cnt,failed); x := 20.0; y := ei(x); f := 25615652.664056588820; testrel(15, NE, y, f, cnt,failed); x := 20.0009765625; y := ei(x); f := 25639353.363149838071; testrel(16, NE, y, f, cnt,failed); x := 39.9990234375; y := ei(x); f := 6033974287987191.3386; testrel(17, NE, y, f, cnt,failed); x := 40.0; y := ei(x); f := 6039718263611241.5784; testrel(18, NE, y, f, cnt,failed); x := 40.0009765625; y := ei(x); f := 6045467710957239.9226; testrel(19, NE, y, f, cnt,failed); x := 100.0; y := ei(x); f := 0.27155527448538798219e42; testrel(20, NE, y, f, cnt,failed); x := 716.25; y := ei(x); f := 0.16179520553005191768e309; testrel(21, NE, y, f, cnt,failed); x := 717.0; y := ei(x); f := PosInf_d; testabs(22, NE, y, f, cnt,failed); x := predd(0); {x=0.5^1074} y := ei(x); f := -743.86285625647972945; testrel(23, NE, y, f, cnt,failed); x := -1e-10; y := ei(x); f := -22.448635265138923980; testrel(24, NE, y, f, cnt,failed); x := -0.0009765625; y := ei(x); f := -6.3552324648310718026; testrel(25, NE, y, f, cnt,failed); x := -0.125; y := ei(x); f := -1.6234256405841687915; testrel(26, NE, y, f, cnt,failed); x := -0.5; y := ei(x); f := -0.5597735947761608118; testrel(27, NE, y, f, cnt,failed); x := -0.9990234375; y := ei(x); f := -0.2197435427851990964; testrel(28, NE, y, f, cnt,failed); x := -1.0; y := ei(x); f := -0.2193839343955202737; testrel(29, NE, y, f, cnt,failed); x := -1.0009765625; y := ei(x); f := -0.2190250276806367220; testrel(30, NE, y, f, cnt,failed); x := -1.5; y := ei(x); f := -0.1000195824066326519; testrel(31, NE, y, f, cnt,failed); x := -2.0; y := ei(x); f := -0.4890051070806111957e-1; testrel(32, NE, y, f, cnt,failed); x := -100.0; y := ei(x); f := -0.368359776168203218e-45; testrel(33, 32, y, f, cnt,failed); {!!!???} x := -1000.0; y := ei(x); f := 0; testrel(34, NE, y, f, cnt,failed); x := 500.0; y := ei(x); f := 0.2812821397886294e215; testrel(35, NE, y, f, cnt,failed); x := 600.0; y := ei(x); f := 0.6298882891387931e258; testrel(36, NE, y, f, cnt,failed); x := 700; y := ei(x); f := 0.1450978736052561e302; testrel(37, NE, y, f, cnt,failed); if failed>0 then writeln('*** failed: ',failed,' of ',cnt) else writeln(cnt:4, ' tests OK'); inc(total_cnt, cnt); inc(total_failed, failed); end; {---------------------------------------------------------------------------} procedure test_ein; var x,y,f: double; cnt, failed: integer; const NE = 2; NE2 = 4; begin cnt := 0; failed := 0; writeln('Function: ','ein'); {ein := x -> ln(abs(x))-Ei(-x)+gamma;} x := -1e-19; f := -1e-19; y := ein(x); testrel( 1, NE, y, f, cnt,failed); x := 1e-16; f := 0.999999999999999975e-16; y := ein(x); testrel( 2, NE, y, f, cnt,failed); x := 1e-3; f := 0.9997500555451405553e-3; y := ein(x); testrel( 3, NE, y, f, cnt,failed); x := -1e-3; f := -0.1000250055565973889e-2; y := ein(x); testrel( 4, NE, y, f, cnt,failed); x := 0.125; f := 0.1211997638058657238; y := ein(x); testrel( 5, NE, y, f, cnt,failed); x := 0.25; f := 0.2352039382253804363; y := ein(x); testrel( 6, NE2, y, f, cnt,failed); x := 0.5; f := 0.4438420791177483629; y := ein(x); testrel( 7, NE, y, f, cnt,failed); x := 1; f := 0.7965995992970531343; y := ein(x); testrel( 8, NE, y, f, cnt,failed); x := -1; f := -1.317902151454403895; y := ein(x); testrel( 9, NE, y, f, cnt,failed); x := 10; f := 2.879804914864508230; y := ein(x); testrel(10, NE, y, f, cnt,failed); x := 45; f := 4.383878154671852618; y := ein(x); testrel(11, NE, y, f, cnt,failed); x := -45; f := -0.7943916035704453728e18; y := ein(x); testrel(12, NE, y, f, cnt,failed); x := -50; f := -0.1058563689713169096e21; y := ein(x); testrel(13, NE, y, f, cnt,failed); x := -700; f := -0.1450978736052560853e302; y := ein(x); testrel(14, NE, y, f, cnt,failed); x := 1e9; f := 21.30048150184794402; y := ein(x); testrel(15, NE, y, f, cnt,failed); if failed>0 then writeln('*** failed: ',failed,' of ',cnt) else writeln(cnt:4, ' tests OK'); inc(total_cnt, cnt); inc(total_failed, failed); end; {---------------------------------------------------------------------------} procedure test_li; var x,y,f: double; cnt, failed: integer; const NE = 2; NE2 = 10; begin cnt := 0; failed := 0; writeln('Function: ','li'); x := 1+ldexpd(1,-52); y := li(x); f := -35.466437724215623118; testrel( 1, NE, y, f, cnt,failed); x := 1+ldexpd(1,-50); y := li(x); f := -34.080143363095732166; testrel( 2, NE, y, f, cnt,failed); x := 1+ldexpd(1,-40); y := li(x); f := -27.148671557495824769; testrel( 3, NE, y, f, cnt,failed); x := 1+ldexpd(1,-20); y := li(x); f := -13.285727469460253020; testrel( 4, NE, y, f, cnt,failed); x := 1.0009765625; y := li(x); f := -6.3537678991714210449; testrel( 5, NE, y, f, cnt,failed); x := 1.25; y := li(x); f := -0.6864884538258715793; testrel( 6, NE, y, f, cnt,failed); x := 1.45136923488338105028; y := li(x); f := 0; testabs( 7, 2, y, f, cnt,failed); x := 1.5; y := li(x); f := 0.125064986315296356; testrel( 8, NE, y, f, cnt,failed); x := 2.0; y := li(x); f := 1.045163780117492785; testrel( 9, NE, y, f, cnt,failed); x := 10.0; y := li(x); f := 6.165599504787297938; testrel(10, NE, y, f, cnt,failed); x := 100.0; y := li(x); f := 30.12614158407962993; testrel(11, NE, y, f, cnt,failed); x := 1e5; y := li(x); f := 9629.809001050798210; testrel(12, NE, y, f, cnt,failed); x := 1e10; y := li(x); f := 455055614.5866230760; testrel(13, NE, y, f, cnt,failed); x := 1e100; y := li(x); f := 0.436197198714070317e98; testrel(14, NE, y, f, cnt,failed); x := 1e300; y := li(x); f := 0.1449750052669336289e298; testrel(15, NE, y, f, cnt,failed); x := 1-ldexpd(1,-20); y := li(x); f := -13.28572842313456943; testrel(16, NE, y, f, cnt,failed); x := 0.99; y := li(x); f := -4.032958701708463680; testrel(17, NE, y, f, cnt,failed); x := 0.5; y := li(x); f := -0.3786710430610879767; testrel(18, NE, y, f, cnt,failed); x := 1e-8; y := li(x); f := -0.5161659103222966770e-9; testrel(19, NE2, y, f, cnt,failed); {x not exact} x := 0; y := li(x); f := 0; testabs(20, 0, y, f, cnt,failed); x := MaxDouble; y := li(x); f := 0.253631570116784220025684508253e306; testrel(21, NE, y, f, cnt,failed); if failed>0 then writeln('*** failed: ',failed,' of ',cnt) else writeln(cnt:4, ' tests OK'); inc(total_cnt, cnt); inc(total_failed, failed); end; {---------------------------------------------------------------------------} procedure test_en; var x,y,f,r: double; cnt, failed, n, i: integer; const NE = 4; NE2 = 8; begin cnt := 0; failed := 0; writeln('Function: ','en'); n := 2; x := 0.0009765625; f := 0.99281763247803906869; y := en(n,x); testrel( 1, NE, y, f, cnt,failed); x := 0.03125; f := 0.87799799126354567735; y := en(n,x); testrel( 2, NE, y, f, cnt,failed); x := 0.0625; f := 0.79835619401120395932; y := en(n,x); testrel( 3, NE, y, f, cnt,failed); x := 0.1; f := 0.72254502219402050656; y := en(n,x); testrel( 4, NE, y, f, cnt,failed); x := 0.5; f := 0.32664386232455301773; y := en(n,x); testrel( 5, NE, y, f, cnt,failed); x := 1.0; f := 0.14849550677592204792; y := en(n,x); testrel( 6, NE, y, f, cnt,failed); x := 1+ldexpd(1,-30); f := 0.14849550657160483747; y := en(n,x); testrel( 7, NE2, y, f, cnt,failed); {!!! 64-bit} x := 1.0009765625; f := 0.14828143995694106431; y := en(n,x); testrel( 8, NE2, y, f, cnt,failed); {!!! 64-bit} x := 10.0; f := 0.38302404656316087616e-5; y := en(n,x); testrel( 9, NE, y, f, cnt,failed); x := 100.0; f := 0.36478214338803782725e-45; y := en(n,x); testrel(10, NE, y, f, cnt,failed); n := 13; x := 0.0009765625; f := 0.83244602590716266105e-1; y := en(n,x); testrel(11, NE, y, f, cnt,failed); x := 0.03125; f := 0.80540692158877804964e-1; y := en(n,x); testrel(12, NE, y, f, cnt,failed); x := 0.0625; f := 0.77842384880014072595e-1; y := en(n,x); testrel(13, NE, y, f, cnt,failed); x := 0.1; f := 0.74724414880051478920e-1; y := en(n,x); testrel(14, NE, y, f, cnt,failed); x := 0.5; f := 0.48355620944849452221e-1; y := en(n,x); testrel(15, NE, y, f, cnt,failed); x := 1.0; f := 0.28120779972942619757e-1; y := en(n,x); testrel(16, NE, y, f, cnt,failed); x := 1+ldexpd(1,-30); f := 0.28120779944602397927e-1; y := en(n,x); testrel(17, NE, y, f, cnt,failed); x := 1.0009765625; f := 0.28091078897291851192e-1; y := en(n,x); testrel(18, NE, y, f, cnt,failed); x := 10.0; f := 0.20217345582160021599e-5; y := en(n,x); testrel(19, NE, y, f, cnt,failed); x := 100.0; f := 0.32954062049629810941e-45; y := en(n,x); testrel(20, NE, y, f, cnt,failed); n := 75; x := 0.0009765625; f := 0.13500142565573009237e-1; y := en(n,x); testrel(21, NE, y, f, cnt,failed); x := 0.03125; f := 0.13092141932336039234e-1; y := en(n,x); testrel(22, NE, y, f, cnt,failed); x := 0.0625; f := 0.12683911734645245006e-1; y := en(n,x); testrel(23, NE, y, f, cnt,failed); x := 0.1; f := 0.12210805862631421537e-1; y := en(n,x); testrel(24, NE, y, f, cnt,failed); x := 0.5; f := 0.81406079438215685307e-2; y := en(n,x); testrel(25, NE, y, f, cnt,failed); x := 1.0; f := 0.49041759071643911284e-2; y := en(n,x); testrel(26, NE, y, f, cnt,failed); x := 1+ldexpd(1,-30); f := 0.49041759025353230157e-2; y := en(n,x); testrel(27, NE, y, f, cnt,failed); x := 1.0009765625; f := 0.48993243791812648773e-2; y := en(n,x); testrel(28, NE, y, f, cnt,failed); x := 10.0; f := 0.53970351088390947490e-6; y := en(n,x); testrel(29, NE, y, f, cnt,failed); x := 100.0; f := 0.21309424216469978017e-45; y := en(n,x); testrel(30, NE, y, f, cnt,failed); n := 10000; x := 1e-3; f := 0.9991003099443454311e-4; y := en(n,x); testrel(31, NE, y, f, cnt,failed); x := 690; f := 0.2031738389909001492e-303; y := en(n,x); testrel(32, NE, y, f, cnt,failed); for i:=1 to 8000 do begin x := (1+random(2000))/128.0; n := 1+random(100); y := en(n+1,x); r := en(n,x); f := exp(-x); f := (f - x*r)/n; testrel(1000+i, 200, y, f, cnt,failed); end; if failed>0 then writeln('*** failed: ',failed,' of ',cnt) else writeln(cnt:4, ' tests OK'); inc(total_cnt, cnt); inc(total_failed, failed); end; {---------------------------------------------------------------------------} procedure test_gei; var x,y,f,p: double; cnt, failed: integer; const NE = 4; NE2 = 8; NE3 = 50; NEX = 10000; {extreme cases p=-2000} begin cnt := 0; failed := 0; writeln('Function: ','gei'); {Pari: ep(p,x) = x^(p-1)*incgam(1-p,x)} {Maple: ep := (p,x) -> x^(p-1)*GAMMA(1-p,x); } p := 0.5; {-------} y := gei(p, 1e-100); f := 0.1772453850905516027e51; testrel( 1, NE, y, f, cnt,failed); y := gei(p, 0.125); f := 3.093555673422464140; testrel( 2, NE, y, f, cnt,failed); y := gei(p, 1); f := 0.2788055852806619764; testrel( 3, NE, y, f, cnt,failed); y := gei(p, 2); f := 0.57026123992892048276e-1; testrel( 4, NE2, y, f, cnt,failed); y := gei(p, 10); f := 0.4340626507388660447e-5; testrel( 5, NE, y, f, cnt,failed); y := gei(p, 100); f := 0.3701747860408278920e-45; testrel( 6, NE, y, f, cnt,failed); y := gei(p, 700); f := 0.1407521279338407783e-306; testrel( 7, NE, y, f, cnt,failed); p := 21.5; {-------} y := gei(p, 0); f := 0.4878048780487804878e-1; testrel( 8, NE, y, f, cnt,failed); y := gei(p, 0.125); f := 0.4277452796937324777e-1; testrel( 9, NE3, y, f, cnt,failed); y := gei(p, 1); f := 0.1707212867834382249e-1; testrel( 10, NE, y, f, cnt,failed); y := gei(p, 2); f := 0.5990354699843735076e-2; testrel( 11, NE, y, f, cnt,failed); y := gei(p, 10); f := 0.1472523580892865630e-5; testrel( 12, NE, y, f, cnt,failed); y := gei(p, 100); f := 0.3066197121388436857e-45; testrel( 13, NE, y, f, cnt,failed); y := gei(p, 700); f := 0.1366608827306444418e-306; testrel( 14, NE, y, f, cnt,failed); p := 10000.5; {-------} y := gei(p, 0); f := 0.1000050002500125006e-3; testrel( 15, NE, y, f, cnt,failed); y := gei(p, 0.125); f := 0.8825299963561445599e-4; testrel( 16, NE, y, f, cnt,failed); y := gei(p, 1); f := 0.3678610444404259898e-4; testrel( 17, NE, y, f, cnt,failed); y := gei(p, 2); f := 0.1353149832829559993e-4; testrel( 18, NE, y, f, cnt,failed); y := gei(p, 10); f := 0.4535683623622977138e-8; testrel( 19, NE, y, f, cnt,failed); y := gei(p, 100); f := 0.3683422276878591542e-47; testrel(20, NE, y, f, cnt,failed); y := gei(p, 700); f := 0.9215025235602690746e-308; testrel(21, NE, y, f, cnt,failed); p := -0.25; {-------} y := gei(p, 1e-100); f := 0.9064024770554770780e125; testrel(22, NE, y, f, cnt,failed); y := gei(p, 0.125); f := 11.44827590461419247; testrel(23, NE, y, f, cnt,failed); y := gei(p, 1); f := 0.4294433234698169988; testrel(24, NE2, y, f, cnt,failed); y := gei(p, 2); f := 0.7425525943954705813e-1; testrel(25, NE, y, f, cnt,failed); y := gei(p, 10); f := 0.4646166613052861213e-5; testrel(26, NE, y, f, cnt,failed); y := gei(p, 100); f := 0.3729307602820619259e-45; testrel(27, NE, y, f, cnt,failed); y := gei(p, 700); f := 0.1409027727624418935e-306; testrel(28, NE, y, f, cnt,failed); p := -10; {-------} x := 0.8077935669463160887e-27; {2^(-90)} y := gei(p, x); f := 0.3797158626716334819e305; testrel(29, NE, y, f, cnt,failed); y := gei(p, 0.125); f := 0.3117115464744959992e17; testrel(30, NE, y, f, cnt,failed); y := gei(p, 1); f := 0.3628799963538665376e7; testrel(31, NE, y, f, cnt,failed); y := gei(p, 2); f := 1771.860278864947092; testrel(32, NE, y, f, cnt,failed); y := gei(p, 10); f := 0.2115734645500305809e-4; testrel(33, NE, y, f, cnt,failed); y := gei(p, 100); f := 0.4128442039111897090e-45; testrel(34, NE, y, f, cnt,failed); y := gei(p, 737); f := 0.115724212019530449457270901430e-322; {denormal} testrel(35, NE, y, f, cnt,failed); p := -100; {-------} y := gei(p, 0.0625); f := 0.3855865735238997662e280; testrel(36, NE, y, f, cnt,failed); y := gei(p, 0.125); f := 0.1520870867155658967e250; testrel(37, NE, y, f, cnt,failed); y := gei(p, 1); f := 0.9332621544394415268e158; testrel(38, NE, y, f, cnt,failed); y := gei(p, 2); f := 0.3681070139798047821e128; testrel(39, NE, y, f, cnt,failed); y := gei(p, 10); f := 0.9332621544394415268e57; testrel(40, NE, y, f, cnt,failed); y := gei(p, 100); f := 0.4914205718464753026e-44; testrel(41, NE, y, f, cnt,failed); y := gei(p, 700); f := 0.1642824847143085383e-306; testrel(42, NE3, y, f, cnt,failed); p := -2000; {-------} y := gei(p, 600); f := 0.2754219389732493203e177; testrel(43, NEX, y, f, cnt,failed); {!!!!} y := gei(p, 735); f := 1.201392846268951678; testrel(44, NEX, y, f, cnt,failed); {!!!!} y := gei(p, 1000); f := 0.3316275092450633241e-267; testrel(45, NEX, y, f, cnt,failed); {!!!!} if failed>0 then writeln('*** failed: ',failed,' of ',cnt) else writeln(cnt:4, ' tests OK'); inc(total_cnt, cnt); inc(total_failed, failed); end; {---------------------------------------------------------------------------} procedure test_chi; var x,y,f: double; cnt, failed: integer; const NE = 2; NE2 = 4; begin cnt := 0; failed := 0; writeln('Function: ','chi'); x := succd(0); {x=0.5^1074} y := chi(x); f := -743.86285625647972945; testrel( 1, NE, y, f, cnt,failed); x := 1e-20; y := chi(x); f := -45.474486194979380820; testrel( 2, NE, y, f, cnt,failed); x := 1e-10; y := chi(x); f := -22.448635265038923980; testrel( 3, NE, y, f, cnt,failed); x := 0.015625; y := chi(x); f := -3.5816063826810039110; testrel( 4, NE, y, f, cnt,failed); x := 0.250; y := chi(x); f := -0.79341294955282596203; testrel( 5, NE, y, f, cnt,failed); x := 0.52382257138986440645; y := chi(x); f := -0.20862054435986945499e-20; testabs( 6, NE, y, f, cnt,failed); x := 1.0; y := chi(x); f := 0.83786694098020824089; testrel( 7, NE, y, f, cnt,failed); x := 5.9990234375; y := chi(x); f := 42.961883064143711849; testrel( 8, NE2, y, f, cnt,failed); x := 6.0; y := chi(x); f := 42.994701029993521072; testrel( 9, NE, y, f, cnt,failed); x := 6.0009765625; y := chi(x); f := 43.027545713648386065; testrel(10, NE, y, f, cnt,failed); x := 9.9990234375; y := chi(x); f := 1245.0394475116345583; testrel(11, NE, y, f, cnt,failed); x := 10.0; y := chi(x); f := 1246.1144860424544147; testrel(12, NE, y, f, cnt,failed); x := 10.0009765625; y := chi(x); f := 1247.1904698466967636; testrel(13, NE, y, f, cnt,failed); x := 19.9990234375; y := chi(x); f := 12795986.971360133543; testrel(14, NE, y, f, cnt,failed); x := 20.0; y := chi(x); f := 12807826.332028294361; testrel(15, NE, y, f, cnt,failed); x := 20.0009765625; y := chi(x); f := 12819676.681574918986; testrel(16, NE, y, f, cnt,failed); x := 39.9990234375; y := chi(x); f := 3016987143993595.6693; testrel(17, NE, y, f, cnt,failed); x := 40.0; y := chi(x); f := 3019859131805620.7892; testrel(18, NE, y, f, cnt,failed); x := 40.0009765625; y := chi(x); f := 3022733855478619.9613; testrel(19, NE, y, f, cnt,failed); x := 100.0; y := chi(x); f := 0.13577763724269399110e42; testrel(20, NE, y, f, cnt,failed); x := 716.0; y := chi(x); f := 0.630251455302044677765e308; testrel(21, NE, y, f, cnt,failed); x := 718; y := chi(x); f := PosInf_d; testabs(22, 1, y, f, cnt,failed); if failed>0 then writeln('*** failed: ',failed,' of ',cnt) else writeln(cnt:4, ' tests OK'); inc(total_cnt, cnt); inc(total_failed, failed); end; {---------------------------------------------------------------------------} procedure test_shi; var x,y,f: double; cnt, failed: integer; const NE = 2; begin cnt := 0; failed := 0; writeln('Function: ','shi'); x := 0; y := shi(x); f := 0; testabs( 1, 1, y, f, cnt,failed); x := succd(0); {x=0.5^1074} y := shi(x); f := 0.49406564584124654418e-323; testrel( 2, NE, y, f, cnt,failed); x := 1e-10; y := shi(x); f := 1e-10; testrel( 3, NE, y, f, cnt,failed); x := 1e-8; y := shi(x); f := 0.10000000000000000056e-7; testrel( 4, NE, y, f, cnt,failed); x := 0.015625; y := shi(x); f := 0.15625211929178078791e-1; testrel( 5, NE, y, f, cnt,failed); x := 0.250; y := shi(x); f := 0.25086968489091223250; testrel( 6, NE, y, f, cnt,failed); x := -1.0; y := shi(x); f := -1.0572508753757285146; testrel( 7, NE, y, f, cnt,failed); x := 5.9990234375; y := shi(x); f := 42.962243550268526463; testrel( 8, NE, y, f, cnt,failed); x := 6.0; y := shi(x); f := 42.995061112445683731; testrel( 9, NE, y, f, cnt,failed); x := 6.0009765625; y := shi(x); f := 43.027905392887548378; testrel(10, NE, y, f, cnt,failed); x := -9.9990234375; y := shi(x); f := -1245.0394516730394570; testrel(11, NE, y, f, cnt,failed); x := 10.0; y := shi(x); f := 1246.1144901994233444; testrel(12, NE, y, f, cnt,failed); x := 10.0009765625; y := shi(x); f := 1247.1904739992344868; testrel(13, NE, y, f, cnt,failed); x := 19.9990234375; y := shi(x); f := 12795986.971360133641; testrel(14, NE, y, f, cnt,failed); x := 20.0; y := shi(x); f := 12807826.332028294459; testrel(15, NE, y, f, cnt,failed); x := 20.0009765625; y := shi(x); f := 12819676.681574919085; testrel(16, NE, y, f, cnt,failed); x := 39.9990234375; y := shi(x); f := 3016987143993595.6693; testrel(17, NE, y, f, cnt,failed); x := -40.0; y := shi(x); f := -3019859131805620.7892; testrel(18, NE, y, f, cnt,failed); x := 40.0009765625; y := shi(x); f := 3022733855478619.9613; testrel(19, NE, y, f, cnt,failed); x := 100.0; y := shi(x); f := 0.13577763724269399110e42; testrel(20, NE, y, f, cnt,failed); x := -716.0; y := shi(x); f := -0.630251455302044677765e308; testrel(21, NE, y, f, cnt,failed); x := 718; y := shi(x); f := PosInf_d; testabs(22, 1, y, f, cnt,failed); x := -0.0009765625; y := shi(x); f := -0.97656255174014451449e-3; testrel(23, NE, y, f, cnt,failed); x := 0.03125; y := shi(x); f := 0.31251695470678306704e-1; testrel(24, NE, y, f, cnt,failed); x := 0.125; y := shi(x); f := 0.12510855782059272682; testrel(25, NE, y, f, cnt,failed); x := 0.3740234375; y := shi(x); f := 0.37694252496022112043; testrel(26, NE, y, f, cnt,failed); x := -0.375; y := shi(x); f := -0.37794207672312880415; testrel(27, NE, y, f, cnt,failed); x := 0.3759765625; y := shi(x); f := 0.37894174938015373576; testrel(28, NE, y, f, cnt,failed); if failed>0 then writeln('*** failed: ',failed,' of ',cnt) else writeln(cnt:4, ' tests OK'); inc(total_cnt, cnt); inc(total_failed, failed); end; {---------------------------------------------------------------------------} procedure test_ci; var x,y,f: double; cnt, failed: integer; const NE = 2; NE2 = 8; begin cnt := 0; failed := 0; writeln('Function: ','ci'); x := -succd(0); {x=0.5^1074} y := ci(x); f := -743.862856256479729454; testrel( 1, NE, y, f, cnt,failed); x := 1e-20; y := chi(x); f := -45.474486194979380820; testrel( 2, NE, y, f, cnt,failed); x := 0.9e-10; y := ci(x); f := -22.5539957806967502808; testrel( 3, NE, y, f, cnt,failed); x := 1.1e-10; y := ci(x); f := -22.35332508523459911953; testrel( 4, NE, y, f, cnt,failed); x := 0.0009765625; y := ci(x); f := -6.354256379116489861225; testrel( 5, NE, y, f, cnt,failed); x := 0.015625; y := ci(x); f := -3.5817284529935106480; testrel( 6, NE, y, f, cnt,failed); x := -0.125; y := ci(x); f := -1.506129584529639664866; testrel( 7, NE, y, f, cnt,failed); x := 0.5; y := ci(x); f := -0.17778407880661290133; testrel( 8, NE, y, f, cnt,failed); x := 0.6165054856207162337971; y := ci(x); f := -0.13769133124065501538e-22; testabs( 9, NE, y, f, cnt,failed); x := 1.0; y := ci(x); f := 0.337403922900968134663; testrel(10, NE, y, f, cnt,failed); x := 2.0; y := ci(x); f := 0.422980828774864995699; testrel(11, NE, y, f, cnt,failed); x := 3.384180422551186426398; y := ci(x); f := -0.4269722283323267461315e-22; testabs(12, NE, y, f, cnt,failed); x := 3.9990234375; y := ci(x); f := -0.14082200723433856129; testrel(13, NE2, y, f, cnt,failed); x := 4.0; y := ci(x); f := -0.1409816978869304116; testrel(14, NE2, y, f, cnt,failed); x := 4.0009765625; y := ci(x); f := -0.14114116914356792895; testrel(15, NE, y, f, cnt,failed); x := 5.0; y := ci(x); f := -0.1900297496566438786; testrel(16, NE, y, f, cnt,failed); x := 6.427047744050368639638; y := ci(x); f := -0.20042673585252231089e-22; testabs(17, NE, y, f, cnt,failed); x := -8.0; y := ci(x); f := 0.1224338825320095573; testrel(18, NE, y, f, cnt,failed); x := 15.0; y := ci(x); f := 0.4627867767436043960e-1; testrel(19, NE, y, f, cnt,failed); x := 1000.0; y := ci(x); f := 0.82631551109068228200e-3; testrel(20, NE, y, f, cnt,failed); x := 1e10; y := ci(x); f := -0.4875060251748226538e-10; testrel(21, NE, y, f, cnt,failed); if failed>0 then writeln('*** failed: ',failed,' of ',cnt) else writeln(cnt:4, ' tests OK'); inc(total_cnt, cnt); inc(total_failed, failed); end; {---------------------------------------------------------------------------} procedure test_cin; var x,y,f: double; cnt, failed: integer; const NE = 2; begin cnt := 0; failed := 0; writeln('Function: ','cin'); {cin := x-> ln(x)+evalf(gamma)-Ci(x);} x := 0; y := cin(x); f := 0; testrel( 1, NE, y, f, cnt,failed); x := 3e-10; y := cin(x); f := 0.225e-19; testrel( 2, NE, y, f, cnt,failed); x := 9.0e-10; y := cin(x); f := 0.2025e-18; testrel( 3, NE, y, f, cnt,failed); x := 0.0009765625; y := cin(x); f := 0.23841856962765955731e-6; testrel( 4, NE, y, f, cnt,failed); x := -0.125; y := cin(x); f := 0.39037077513365972207e-2; testrel( 5, NE, y, f, cnt,failed); x := 0.5; y := cin(x); f := 0.618525631482004525251e-1; testrel( 6, NE, y, f, cnt,failed); x := -1.0; y := cin(x); f := 0.23981174200056472595; testrel( 7, NE, y, f, cnt,failed); x := 2.0; y := cin(x); f := 0.84738201668661317430; testrel( 8, NE, y, f, cnt,failed); x := 4.0; y := cin(x); f := 2.1044917239083538910; testrel( 9, NE, y, f, cnt,failed); x := 6.0; y := cin(x); f := 2.4370323780228349876; testrel(10, NE, y, f, cnt,failed); x := 6.125; y := cin(x); f := 2.4375465091797009492; testabs(11, NE, y, f, cnt,failed); x := 7.0; y := cin(x); f := 2.4464305354746616473; testrel(12, NE, y, f, cnt,failed); x := -12.0; y := cin(x); f := 3.1119023215736468464; testrel(13, NE, y, f, cnt,failed); x := -13.0; y := cin(x); f := 3.1154008967990350417; testrel(14, NE, y, f, cnt,failed); x := 56.0; y := cin(x); f := 4.6121464046951505440; testrel(15, NE, y, f, cnt,failed); x := 57.0; y := cin(x); f := 4.6128960715754944416; testrel(16, NE, y, f, cnt,failed); x := 100.0; y := cin(x); f := 5.1875346760322347207; testrel(17, NE, y, f, cnt,failed); x := 10000.0; y := cin(x); f := 9.7875865887944400819; testrel(18, NE, y, f, cnt,failed); x := 1e10; y := cin(x); f := 23.603066594890740304; testrel(19, NE, y, f, cnt,failed); x := 1e100; y := cin(x); f := 230.83572496430610126; testrel(20, NE, y, f, cnt,failed); x := 1e308; y := cin(x); f := 709.77342430706760354; testrel(21, NE, y, f, cnt,failed); if failed>0 then writeln('*** failed: ',failed,' of ',cnt) else writeln(cnt:4, ' tests OK'); inc(total_cnt, cnt); inc(total_failed, failed); end; {---------------------------------------------------------------------------} procedure test_cinh; var x,y,f: double; cnt, failed: integer; const NE = 2; begin cnt := 0; failed := 0; writeln('Function: ','cinh'); x := 0; y := cinh(x); f := 0; testrel( 1, NE, y, f, cnt,failed); x := 3e-10; y := cinh(x); f := 0.225e-19; testrel( 2, NE, y, f, cnt,failed); x := 9.0e-10; y := cinh(x); f := 0.2025e-18; testrel( 3, NE, y, f, cnt,failed); x := 0.0009765625; y := cinh(x); f := 0.238418588575465844246e-6; testrel( 4, NE, y, f, cnt,failed); x := -0.125; y := cinh(x); f := 0.390879401472700300929e-2; testrel( 5, NE, y, f, cnt,failed); x := 0.250; y := cinh(x); f := 0.15665746665531796193e-1; testrel( 6, NE, y, f, cnt,failed); x := -1.0; y := cinh(x); f := 0.26065127607867538028; testabs( 7, NE, y, f, cnt,failed); x := 3.0; y := cinh(x); f := 3.2845641411959672083; testrel( 8, NE, y, f, cnt,failed); x := 6.0; y := cinh(x); f := 40.625725895863933210; testrel( 9, NE, y, f, cnt,failed); x := 6.0009765625; y := cinh(x); f := 40.658407832346171103; testrel(10, NE, y, f, cnt,failed); x := -9.9990234375; y := cinh(x); f := 1242.1597444147576618; testrel(11, NE, y, f, cnt,failed); x := -10.0; y := cinh(x); f := 1243.2346852845588361; testrel(12, NE, y, f, cnt,failed); x := -10.0009765625; y := cinh(x); f := 1244.3105714373192462; testrel(13, NE, y, f, cnt,failed); x := 19.9990234375; y := cinh(x); f := 12795983.398461024404; testrel(14, NE, y, f, cnt,failed); x := 20.0; y := cinh(x); f := 12807822.759080355905; testrel(15, NE, y, f, cnt,failed); x := 20.0009765625; y := cinh(x); f := 12819673.108578153597; testrel(16, NE, y, f, cnt,failed); x := 39.9990234375; y := cinh(x); f := 3016987143993591.4032; testrel(17, NE, y, f, cnt,failed); x := 40.0; y := cinh(x); f := 3019859131805616.5231; testrel(18, NE, y, f, cnt,failed); x := 40.0009765625; y := cinh(x); f := 3022733855478615.6952; testrel(19, NE, y, f, cnt,failed); x := 100.0; y := cinh(x); f := 0.13577763724269399110e42; testrel(20, NE, y, f, cnt,failed); x := 400.0; y := chi(x); f := 0.65432364085371386712e171; testrel(21, NE, y, f, cnt,failed); x := 716.0; y := chi(x); f := 0.630251455302044677765e308; testrel(22, NE, y, f, cnt,failed); x := 718; y := chi(x); f := PosInf_d; testabs(23, 1, y, f, cnt,failed); if failed>0 then writeln('*** failed: ',failed,' of ',cnt) else writeln(cnt:4, ' tests OK'); inc(total_cnt, cnt); inc(total_failed, failed); end; {---------------------------------------------------------------------------} procedure test_si; var x,y,f: double; cnt, failed: integer; const NE = 2; begin cnt := 0; failed := 0; writeln('Function: ','si'); x := 0.0; y := si(x); f := 0; testabs( 1, 1, y, f, cnt,failed); x := 1e-15; y := si(x); f := x; testrel( 2, NE, y, f, cnt,failed); x := -1e-7; y := si(x); f := -0.9999999999999994444e-7; testrel( 3, NE, y, f, cnt,failed); x := 0.9e-5; y := si(x); f := 0.8999999999959500000e-5; testrel( 4, NE, y, f, cnt,failed); x := -1.05e-5; y := si(x); f := -0.1049999999993568750e-4; testrel( 5, NE, y, f, cnt,failed); x := 0.015625; y := si(x); f := 0.1562478807392632979e-1; testrel( 6, NE, y, f, cnt,failed); x := -0.25; y := si(x); f := -0.2491335703197571641; testrel( 7, NE, y, f, cnt,failed); x := 1.0; y := si(x); f := 0.9460830703671830150; testrel( 8, NE, y, f, cnt,failed); x := -2.0; y := si(x); f := -1.6054129768026948486; testrel( 9, NE, y, f, cnt,failed); x := 3.9990234375; y := si(x); f := 1.758387849778959366; testrel(10, NE, y, f, cnt,failed); x := -4.0; y := si(x); f := -1.758203138949053058; testrel(11, NE, y, f, cnt,failed); x := 4.0009765625; y := si(x); f := 1.758018317387305653; testrel(12, NE, y, f, cnt,failed); x := -5.0; y := si(x); f := -1.549931244944674137; testrel(13, NE, y, f, cnt,failed); x := 8.0; y := si(x); f := 1.574186821706942052; testrel(14, NE, y, f, cnt,failed); x := -15.0; y := si(x); f := -1.618194443708368739; testrel(15, NE, y, f, cnt,failed); x := 1e10; y := si(x); f := 1.570796326707584657; testrel(16, NE, y, f, cnt,failed); if failed>0 then writeln('*** failed: ',failed,' of ',cnt) else writeln(cnt:4, ' tests OK'); inc(total_cnt, cnt); inc(total_failed, failed); end; {---------------------------------------------------------------------------} procedure test_ssi; var x,y,f: double; cnt, failed: integer; const NE = 2; NE2 = 8; begin cnt := 0; failed := 0; writeln('Function: ','ssi'); x := 0.0; y := ssi(x); f := -Pi_2; testabs( 1, 1, y, f, cnt,failed); x := 1e-15; y := ssi(x); f := -1.570796326794895619; testrel( 2, NE, y, f, cnt,failed); x := -1e-7; y := ssi(x); f := -1.570796426794896619; testrel( 3, NE, y, f, cnt,failed); x := 0.9e-5; y := ssi(x); f := -1.570787326794896660; testrel( 4, NE, y, f, cnt,failed); x := -1.05e-5; y := ssi(x); f := -1.570806826794896555; testrel( 5, NE, y, f, cnt,failed); x := 0.015625; y := ssi(x); f := -1.555171538720970289; testrel( 6, NE, y, f, cnt,failed); x := -0.25; y := ssi(x); f := -1.819929897114653783; testrel( 7, NE, y, f, cnt,failed); x := 1.0; y := ssi(x); f := -0.6247132564277136043; testrel( 8, NE, y, f, cnt,failed); x := 1.9264476603173705820; y := ssi(x); f := -0.111405491355682719e-19; testabs( 9, 1, y, f, cnt,failed); x := 1.9264; y := ssi(x); f := -0.231922614083280179e-4; testabs(10, 1, y, f, cnt,failed); x := 1.9265; y := ssi(x); f := 0.2546818023174051571e-4; testabs(11, 1, y, f, cnt,failed); x := 2.176; y := ssi(x); f := 0.1078833303776372; testabs(12, NE, y, f, cnt,failed); x := 2.177; y := ssi(x); f := 0.1082610476638330915; testabs(13, NE, y, f, cnt,failed); x := 1.676; y := ssi(x); f := -0.1353244503132861735; testabs(14, NE, y, f, cnt,failed); x := 1.677; y := ssi(x); f := -0.1347312987714802452; testabs(15, NE, y, f, cnt,failed); x := 3.9990234375; y := ssi(x); f := 0.1875915229840627467; testrel(16, NE2, y, f, cnt,failed); x := -4.0; y := ssi(x); f := -3.328999465743949677; testrel(17, NE, y, f, cnt,failed); x := 4.0009765625; y := ssi(x); f := 0.1872219905924090342; testrel(18, NE, y, f, cnt,failed); x := 4.8938359526166018016; y := ssi(x); f := 0.4358276613479410518e-20; testabs(19, 1, y, f, cnt,failed); x := -5.0; y := ssi(x); f := -3.120727571739570757; testrel(20, NE, y, f, cnt,failed); x := 8.0; y := ssi(x); f := 0.3390494912045432852e-2; testrel(21, NE2, y, f, cnt,failed); {!!64-bit} x := -15.0; y := ssi(x); f := -3.188990770503265358; testrel(22, NE, y, f, cnt,failed); x := 1e10; y := ssi(x); f := -0.8731196226281053987e-10; testrel(23, NE, y, f, cnt,failed); x := -1e10; y := ssi(x); f := -3.1415926535024812762; testrel(24, NE, y, f, cnt,failed); if failed>0 then writeln('*** failed: ',failed,' of ',cnt) else writeln(cnt:4, ' tests OK'); inc(total_cnt, cnt); inc(total_failed, failed); end; {---------------------------------------------------------------------------} procedure test_ei_inv; var x,y,f: double; cnt, failed: integer; const NE = 4; begin cnt := 0; failed := 0; writeln('Function: ','ei_inv'); f := 700; x := ei(f); y := ei_inv(x); testrel(1, NE, y, f, cnt,failed); f := 0.001953125; x := ei(f); y := ei_inv(x); testrel(2, NE, y, f, cnt,failed); x := -1.5; y := ei_inv(x); f := 0.1116824805322902507; testrel(3, NE, y, f, cnt,failed); x := -2; y := ei_inv(x); f := 0.7070820325089491156e-1; testrel(4, NE, y, f, cnt,failed); x := -4; y := ei_inv(x); {f:= 0.10179079377300351405e-1;} f := 0.2035815875460070281e-1*0.5; testrel(5, NE, y, f, cnt,failed); x := -10; y := ei_inv(x); f := 0.2548957138774709426e-4; testrel(6, NE, y, f, cnt,failed); x := -20; y := ei_inv(x); f := 0.1157254247067129905e-8; testrel(7, NE, y, f, cnt,failed); x := -40; y := ei_inv(x); f := 0.2385278786185194590e-17; testrel(8, NE, y, f, cnt,failed); x := -50; y := ei_inv(x); f := 0.1082914893567529566e-21; testrel(9, NE, y, f, cnt,failed); x := 1e-5; y := ei_inv(x); f := 0.3725099773799074235; testrel(10, NE, y, f, cnt,failed); x := 1e-8; y := ei_inv(x); f := 0.3725074133479596325; testrel(11, NE, y, f, cnt,failed); x := 1e-10; y := ei_inv(x); f := 0.3725074108070325644; testrel(12, NE, y, f, cnt,failed); x := -1e-7; y := ei_inv(x); f := 0.3725073851154372641; testrel(13, NE, y, f, cnt,failed); x := -1e-11; y := ei_inv(x); f := 0.3725074107788000415; testrel(14, NE, y, f, cnt,failed); x := 0.5; y := ei_inv(x); f := 0.5139789904809404574; testrel(15, NE, y, f, cnt,failed); x := 1; y := ei_inv(x); f := 0.6775499178144678440; testrel(16, NE, y, f, cnt,failed); x := 10; y := ei_inv(x); f := 3.009850414759061250; testrel(17, NE, y, f, cnt,failed); x := 1000; y := ei_inv(x); f := 8.957122361339663031; testrel(18, NE, y, f, cnt,failed); x := 1e300; y := ei_inv(x); f := 697.3213370748042106; testrel(19, NE, y, f, cnt,failed); x := -700; y := ei_inv(x); f := 0.5535808900395892233e-304; testrel(20, NE, y, f, cnt,failed); if failed>0 then writeln('*** failed: ',failed,' of ',cnt) else writeln(cnt:4, ' tests OK'); inc(total_cnt, cnt); inc(total_failed, failed); end; end.
unit uRekBank; interface uses uAccount, System.SysUtils, uModel; type TRekBank = class(TAppObject) private FAccount: TAccount; FAlamat: string; FBank: string; FNamaPemegang: string; FNoRek: string; public destructor Destroy; override; published property Account: TAccount read FAccount write FAccount; property Alamat: string read FAlamat write FAlamat; property Bank: string read FBank write FBank; property NamaPemegang: string read FNamaPemegang write FNamaPemegang; property NoRek: string read FNoRek write FNoRek; end; implementation destructor TRekBank.Destroy; begin inherited; FreeAndNil(FAccount); end; end.
unit vg_actions; {$I vg_define.inc} interface uses {$IFNDEF NOVCL} ImgList, Graphics, ActnList, Forms, {$ENDIF} Classes, SysUtils, vg_scene, vgAnyObjectList, vgBitmap ; {$Define _UnknownIsComponent} type _l3Unknown_Parent_ = TCustomImageList; {$Include w:\common\components\rtl\Garant\L3\l3Unknown.imp.pas} TvgImageList = class(_l3Unknown_) private FImages: TvgAnyObjectList; function GetCount: integer; function GetBitmap(Index: integer): TvgBitmap; procedure UpdateList; protected {$I l3DefineCleanup.inc} protected procedure DefineProperties(Filer: TFiler); override; procedure ReadData(Stream: TStream); {$IFDEF KS_COMPILER7_UP}override;{$ENDIF} procedure WriteData(Stream: TStream); {$IFDEF KS_COMPILER7_UP}override;{$ENDIF} procedure ReadImage(Stream: TStream); procedure WriteImage(Stream: TStream); public constructor Create(AOwner: TComponent); override; function Add(Bitmap: TvgBitmap): integer; procedure Clear; property Images[Index: integer]: TvgBitmap read GetBitmap; property Count: integer read GetCount; public // public methods procedure Free(var Dummy: Integer); {* Для ловли просто Free } published property Height default 32; property Width default 32; end; implementation {===============================================================} uses l3Interfaces, l3Base, l3Core, l3Interlocked, Windows ; type _Instance_R_ = TvgImageList; type _l3Unknown_R_ = TvgImageList; {$Include w:\common\components\rtl\Garant\L3\l3Unknown.imp.pas} { TvgImageList } constructor TvgImageList.Create(AOwner: TComponent); begin inherited; FImages := TvgAnyObjectList.Create; Width := 32; Height := 32; end; procedure TvgImageList.Clear; var i: integer; l_C : TvgBitmap; begin inherited Clear; for i := 0 to FImages.Count - 1 do begin l_C := TvgBitmap(FImages[i]); FreeAndNil(l_C); end;//for i FImages.Clear; end; function TvgImageList.Add(Bitmap: TvgBitmap): integer; var B: TvgBitmap; R: TvgRect; begin B := TvgBitmap.Create(Width, Height); R := vgRect(0, 0, Bitmap.Width, Bitmap.Height); vgFitRect(R, vgRect(0, 0, Width, Height)); TvgCanvas(B.Canvas).DrawBitmap(Bitmap, vgRect(0, 0, Bitmap.Width, Bitmap.Height), R, 1); Result := FImages.Add(B); UpdateList; end; procedure TvgImageList.ReadImage(Stream: TStream); var i: integer; S, C: cardinal; M: TMemoryStream; B: TvgBitmap; begin Stream.Read(C, 4); for i := 0 to C - 1 do begin M := TMemoryStream.Create; Stream.Read(S, 4); M.SetSize(S); Stream.Read(M.Memory^, S); B := TvgBitmap.CreateFromStream(M); FImages.Add(B); FreeAndNil(M); end; UpdateList; end; procedure TvgImageList.WriteImage(Stream: TStream); var i: integer; S: cardinal; M: TMemoryStream; begin S := FImages.Count; Stream.Write(S, 4); for i := 0 to FImages.Count - 1 do begin M := TMemoryStream.Create; TvgBitmap(FImages[i]).SaveToStream(M); S := M.Size; Stream.Write(S, 4); Stream.Write(M.Memory^, M.Size); FreeAndNil(M); end; end; procedure TvgImageList.DefineProperties(Filer: TFiler); begin inherited DefineProperties(Filer); Filer.DefineBinaryProperty('Images', ReadImage, WriteImage, FImages.Count > 0); end; function TvgImageList.GetCount: integer; begin Result := FImages.Count; end; function TvgImageList.GetBitmap(Index: integer): TvgBitmap; begin if (Index >= 0) and (Index < Count) then Result := TvgBitmap(FImages[Index]) else Result := nil; end; procedure TvgImageList.UpdateList; var i: integer; B: Graphics.TBitmap; begin if not (csDesigning in ComponentState) then Exit; inherited Clear; for i := 0 to FImages.Count - 1 do begin if (Images[i].Width <> Width) or (Images[i].Height <> Height) then Continue; B := Graphics.TBitmap.Create; B.Assign(Images[i]); inherited AddMasked(B, 0); FreeAndNil(B); end; end; procedure TvgImageList.ReadData(Stream: TStream); begin end; procedure TvgImageList.WriteData(Stream: TStream); begin end; procedure TvgImageList.Free(var Dummy: Integer); begin Assert(false, 'Используйте FreeAndNil'); end; type _Unknown_Child_ = _l3Unknown_R_; {$I l3ImplCleanup.inc} begin Clear; FreeAndNil(FImages); inherited; end; end.
{************************************************************************************************************************** * Classe/Objeto : TFinanceiroPrazosExtratos * Finalidade : pesquisa, alteração, exclusão e inclusão de dados na tabela sistema_financeiro_prazos_extratos * Nível : Model * Autor : Celso Mutti * Data : 01/06/2021 * Versão : 1 * Histórico : 01/06/2021 - Criação - Celso Mutti (1) **************************************************************************************************************************} unit Model.FinanceiroPrazosExtratos; interface uses Common.ENum, FireDAC.Comp.Client, System.SysUtils, DAO.Conexao, System.DateUtils, System.Variants; type TFinanceiroPrazosExtratos = class private FQuinzena: SmallInt; FDiaPagamento: SmallInt; FDiaInicio: SmallInt; FDiasPrazoPagamento: SmallInt; FID: integer; FDiaFinal: SmallInt; FTipo: SmallInt; FAcao: TAcao; FQuery: TFDQuery; FConexao: TConexao; FDataPagamento: TDate; FDataFinal: TDate; FDataInicial: TDate; function Insert(): Boolean; function Update(): Boolean; function Delete(): Boolean; public constructor Create; property ID: integer read FID write fID; // ID do registro property Tipo: SmallInt read FTipo write FTipo; // Tipo de extrato (1 - Expressas, 2 - Periódicos, ...) property Quinzena: SmallInt read FQuinzena write FQuinzena; // Número da quinzena (1ª., 2ª, ...) property DiaInicio: SmallInt read FDiaInicio write FDiaInicio; // Dia da data do início do extrato property DiaFinal: SmallInt read FDiaFinal write FDiaFinal; // Dia da data do final do extrato property DiaPagamento: SmallInt read FDiaPagamento write FDiaPagamento; // Dia da data de pagamento programado property DiasPrazoPagamento: SmallInt read FDiasPrazoPagamento write FDiasPrazoPagamento; // Quantidade de dias a partir da data base para pagagamento property Acao: TAcao read FAcao write FAcao; // Acao de gravação no banco de dados property Query: TFDQuery read FQuery write FQuery; // Query resultado de pesquisa property DataInicial: TDate read FDataInicial write FDataInicial; // Data inicial do período após mpntagem property DataFinal: TDate read FDataFinal write FDataFinal; // Data final do período após mpntagem property DataPagamento: TDate read FDataPagamento write FDataPagamento; // Data do pagamento após mpntagem function Search(aParam : array of variant) : boolean; // realiza pesquisa em banco de dados function Save() : Boolean; // salva, exclue dados no banco de dados function GetField(sField : String; sKey : String; sKeyValue : String) : String; // localiza e retorna o valor de um campo de uma tabela function MountPeriod(iAno, iMes: integer): boolean; // monta as data do período e a data do pagamento; procedure SetupSelf(fdQuery : TFDQuery); // atribui os valores dos campos de uma query às propriedades da classe procedure ClearSelf(); // limpa as propriedades da dos campos da tabela da classe end; const // nome da tabela no banco de dados TABLENAME = 'sistema_financeiro_prazos_extratos'; // script de inclusão na tabela SQLINSERT = 'insert into ' + TABLENAME + ' (id_registro, cod_tipo_extrato, num_quinzena, num_dia_inicio, num_dia_final, ' + 'num_dia_pagamento, qtd_dias_prazo_pagamento) ' + 'value ' + '(:id_registro, :cod_tipo_extrato, :num_quinzena, :num_dia_inicio, :num_dia_final, :num_dia_pagamento, ' + ':qtd_dias_prazo_pagamento)'; // script de alteração de dados na tabela SQLUPDATE = 'update ' + TABLENAME + ' set cod_tipo_extrato = :cod_tipo_extrato, num_quinzena = :num_quinzena, ' + 'num_dia_inicio = :num_dia_inicio, num_dia_final = :num_dia_final, num_dia_pagamento = :num_dia_pagamento, ' + 'qtd_dias_prazo_pagamento = :qtd_dias_prazo_pagamento ' + 'where id_registro = :idregistro'; // script de exclusão da tabela SQLDELETE = 'delete from ' + TABLENAME + ' where id_registro = :idregistro'; // script de pesquisa na tabela SQLSELECT = 'select id_registro, cod_tipo_extrato, num_quinzena, num_dia_inicio, num_dia_final, num_dia_pagamento, ' + 'qtd_dias_prazo_pagamento ' + 'from ' + TABLENAME; implementation { TFinanceiroPrazosExtratos } procedure TFinanceiroPrazosExtratos.ClearSelf; begin FQuinzena := 0; FDiaPagamento := 0; FDiaInicio := 0; FDiasPrazoPagamento := 0; FID := 0; FDiaFinal := 0; FTipo := 0; end; constructor TFinanceiroPrazosExtratos.Create; begin FConexao := TConexao.Create; end; function TFinanceiroPrazosExtratos.Delete: Boolean; var FQueryDelete : TFDQuery; begin try Result := False; FQueryDelete := FConexao.ReturnQuery; FQueryDelete.ExecSQL(SQLDELETE, [FID]); if FQueryDelete.RowsAffected = 0 then Exit; Result := True; finally FQueryDelete.Active := False; FQueryDelete.Connection.Connected := False; FQueryDelete.Free end; end; function TFinanceiroPrazosExtratos.GetField(sField, sKey, sKeyValue: String): String; var FQueryField : TFDQuery; begin try Result := ''; FQueryField := FConexao.ReturnQuery; FQueryField.SQL.Text := 'select ' + sField + ' from ' + TABLENAME + ' where ' + sKey + ' = ' + sKeyValue; FQueryField.Open(); if FQueryField.IsEmpty then Exit; Result := FQueryField.FieldByName(sField).AsString; finally FQueryField.Active := False; FQueryField.Connection.Connected := False; FQueryField.Free; end; end; function TFinanceiroPrazosExtratos.Insert: Boolean; var FQueryInsert : TFDQuery; begin try Result := False; FQueryInsert := FConexao.ReturnQuery; FQueryInsert.ExecSQL(SQLINSERT, [FID, FTipo, FQuinzena, FDiaInicio, FDiaFinal, FDiaPagamento, FDiasPrazoPagamento]); if FQueryInsert.RowsAffected = 0 then Exit; Result := True; finally FQueryInsert.Active := False; FQueryInsert.Connection.Connected := False; FQueryInsert.Free; end; end; function TFinanceiroPrazosExtratos.MountPeriod(iAno, iMes: integer): boolean; var sData : String; iMesData, iAnoData: integer; dtDataPagamento: TDate; begin Result := False; if FDiaFinal >= 30 then begin sData := '01/' + FormatFloat('00', iMes) + '/' + IntToStr(iAno); FDiaFinal := DaysInMonth(StrToDate(sData)); end; if FDiaInicio > FDiaFinal then begin if iMes = 1 then begin iMesData := 12; iAnoData := iAno - 1; sData := FormatFloat('00', FDiaInicio) + '/' + FormatFloat('00', iMesData) + '/' + FormatFloat('0000', iAnoData); end else begin iMesData := iMes - 1; iAnoData := iAno; sData := FormatFloat('00', FDiaInicio) + '/' + FormatFloat('00', iMesData) + '/' + FormatFloat('0000', iAnoData); end; FDataInicial := StrToDate(sData); iMesData := iMes; iAnoData := iAno; sData := FormatFloat('00', FDiaFinal) + '/' + FormatFloat('00', iMesData) + '/' + FormatFloat('0000', iAnoData); FDataFinal := StrToDate(sData); end else begin iMesData := iMes; iAnoData := iAno; sData := FormatFloat('00', FDiaInicio) + '/' + FormatFloat('00', iMesData) + '/' + FormatFloat('0000', iAnoData); FDataInicial := StrToDate(sData); iMesData := iMes; iAnoData := iAno; if FDiaFinal >= 30 then begin FDiaFinal := DaysInMonth(StrToDate(sData)); end; sData := FormatFloat('00', FDiaFinal) + '/' + FormatFloat('00', iMesData) + '/' + FormatFloat('0000', iAnoData); FDataFinal := StrToDate(sData); end; iMesData := iMes; iAnoData := iAno; if FDiaPagamento >= 30 then begin sData := FormatFloat('00', 1) + '/' + FormatFloat('00', iMesData) + '/' + FormatFloat('0000', iAnoData); dtDataPagamento := IncDay(StrToDate(sData),FDiasPrazoPagamento); FDiaPagamento := DaysInMonth(dtDataPagamento); iMesData := MonthOf(dtDataPagamento); iAnoData := YearOf(dtDataPagamento); sData := FormatFloat('00', FDiaPagamento) + '/' + FormatFloat('00', iMesData) + '/' + FormatFloat('0000', iAnoData); FDataPagamento := StrToDate(sData); end else begin sData := FormatFloat('00', FDiaPagamento) + '/' + FormatFloat('00', iMesData) + '/' + FormatFloat('0000', iAnoData); dtDataPagamento := IncDay(StrToDate(sData),FDiasPrazoPagamento); iMesData := MonthOf(dtDataPagamento); iAnoData := YearOf(dtDataPagamento); sData := FormatFloat('00', FDiaPagamento) + '/' + FormatFloat('00', iMesData) + '/' + FormatFloat('0000', iAnoData); FDataPagamento := StrToDate(sData); end; Result := True; end; function TFinanceiroPrazosExtratos.Save: Boolean; begin Result := False; case FAcao of Common.ENum.tacIncluir: Result := Insert(); Common.ENum.tacAlterar: Result := Update(); Common.ENum.tacExcluir: Result := Delete(); end; end; function TFinanceiroPrazosExtratos.Search(aParam: array of variant): boolean; begin Result := False; if Length(aParam) < 2 then Exit; FQuery := FConexao.ReturnQuery; FQuery.SQL.Add(SQLSELECT); if aParam[0] = 'ID' then begin FQuery.SQL.Add('where id_registro = :id_registro'); FQuery.ParamByName('id_registro').AsInteger := aParam[1]; end else if aParam[0] = 'TIPOQUINZENA' then begin FQuery.SQL.Add('where cod_tipo_extrato = :cod_tipo_extrato and num_quinzena = :num_quinzena'); FQuery.ParamByName('cod_tipo_extrato').AsInteger := aParam[1]; FQuery.ParamByName('num_quinzena').AsInteger := aParam[2]; end else if aParam[0] = 'DIASQUINZENA' then begin FQuery.SQL.Add('where cod_tipo_extrato = :cod_tipo_extrato and num_dia_inicio = :num_dia_inicio and num_dia_final = :num_dia_final'); FQuery.ParamByName('cod_tipo_extrato').AsInteger := aParam[1]; FQuery.ParamByName('num_dia_inicio').AsInteger := aParam[2]; FQuery.ParamByName('num_dia_final').AsInteger := aParam[3]; end else if aParam[0] = 'EXISTE' then begin FQuery.SQL.Add('where cod_tipo_extrato = :cod_tipo_extrato and num_quinzena = :num_quinzena and ' + 'num_dia_inicio = :num_dia_inicio and num_dia_final = :num_dia_final'); FQuery.ParamByName('cod_tipo_extrato').AsInteger := aParam[1]; FQuery.ParamByName('num_quinzena').AsInteger := aParam[2]; FQuery.ParamByName('num_dia_inicio').AsInteger := aParam[3]; FQuery.ParamByName('num_dia_final').AsInteger := aParam[4]; end else if aParam[0] = 'FILTRO' then begin if VarToStr(aParam[1]) <> '' then FQuery.SQL.Add('where ' + VarToStr(aParam[1])); end else if aParam[0] = 'APOIO' then begin FQuery.SQL.Clear; FQuery.SQL.Add('select ' + VarToStr(aParam[1]) + ' from ' + TABLENAME + ' where ' + VarToStr(aParam[2])); end; FQuery.Open(); if FQuery.IsEmpty then begin FQuery.Active := False; FQuery.Connection.Connected := False; Exit; end; Result := True; end; procedure TFinanceiroPrazosExtratos.SetupSelf(fdQuery: TFDQuery); begin FQuinzena := fdQuery.FieldByName('num_quinzena').AsInteger; FDiaPagamento := fdQuery.FieldByName('num_dia_pagamento').AsInteger; FDiaInicio := fdQuery.FieldByName('num_dia_inicio').AsInteger; FDiasPrazoPagamento := fdQuery.FieldByName('qtd_dias_prazo_pagamento').AsInteger; FID := fdQuery.FieldByName('id_registro').AsInteger; FDiaFinal := fdQuery.FieldByName('num_dia_final').AsInteger; FTipo := fdQuery.FieldByName('cod_tipo_extrato').AsInteger; end; function TFinanceiroPrazosExtratos.Update: Boolean; var FQueryInsert : TFDQuery; begin try Result := False; FQueryInsert := FConexao.ReturnQuery; FQueryInsert.ExecSQL(SQLUPDATE, [FTipo, FQuinzena, FDiaInicio, FDiaFinal, FDiaPagamento, FDiasPrazoPagamento, FID]); if FQueryInsert.RowsAffected = 0 then Exit; Result := True; finally FQueryInsert.Active := False; FQueryInsert.Connection.Connected := False; FQueryInsert.Free; end; end; end.
// *************************************************************************** // // FMXComponents: Firemonkey Opensource Components Set // // TFMXCallout is a Callout component using INativeCanvas // // 该控件由Aone开发,本人整理收入FMXComponents // http://www.cnblogs.com/onechen/p/7130227.html // // https://github.com/zhaoyipeng/FMXComponents // // *************************************************************************** // // 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. // // *************************************************************************** } //------------------------------------------------------------------------------ // 2017.10.14 Editor by Aone - // 2017.10.14 加入顶点位置调整 CalloutPeakOffset - // - // 本控件修改自 Delphi Berlin 10.1.2 的 TCalloutRectangle (FMX.Objects.pas) - // - // 代码说明: - // 1. 代码内 {+++> 代表我增加的代码 - // 2. 代码内 {---> 代表我删除的代码 - // 3. 未来新版 Delphi 可以自己将 {+++> {---> 移植到新版代码内 - //------------------------------------------------------------------------------ // http://www.cnblogs.com/onechen/ - //------------------------------------------------------------------------------ unit FMX.Callout; {$i NativeDraw.inc} interface {$SCOPEDENUMS ON} uses System.Types, System.UITypes, System.Classes, System.Rtti, System.Messaging, System.SysUtils, FMX.Controls, FMX.Types, FMX.Objects, FMX.Graphics, FMX.Graphics.INativeCanvas, FMX.Graphics.NativeCanvas, FMX.ComponentsCommon; type { TFMXCallout } [ComponentPlatformsAttribute(TFMXPlatforms)] TFMXCallout = class(TRectangle) private FPath: TPathData; FFillPath: TPathData; FCalloutWidth: Single; FCalloutLength: Single; FCalloutPosition: TCalloutPosition; FCalloutOffset: Single; {+++>}FCalloutPeakOffset: Single; {+++>}FNativeDraw: Boolean; procedure SetCalloutWidth(const Value: Single); procedure SetCalloutLength(const Value: Single); procedure SetCalloutPosition(const Value: TCalloutPosition); procedure SetCalloutOffset(const Value: Single); {+++>}procedure SetCalloutPeakOffset(const Value: Single); {+++>}procedure SetNativeDraw(const Value: Boolean); protected procedure RebuildPaths; { inherited } procedure SetXRadius(const Value: Single); override; procedure SetYRadius(const Value: Single); override; procedure SetCorners(const Value: TCorners); override; procedure SetCornerType(const Value: TCornerType); override; procedure SetSides(const Value: TSides); override; procedure Resize; override; procedure Loaded; override; { Building Path } function GeTOneCalloutRect: TRectF; procedure AddCalloutToPath(APath: TPathData; const ARect: TRectF; const ACornerRadiuses: TSizeF); procedure AddRoundCornerToPath(APath: TPathData; const ARect: TRectF; const ACornerSize: TSizeF; const ACorner: TCorner); procedure AddRectCornerToPath(APath: TPathData; const ARect: TRectF; const ACornerSize: TSizeF; const ACorner: TCorner; const ASkipEmptySide: Boolean = True); procedure CreatePath; procedure CreateFillPath; { Painting } procedure Paint; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property Fill; property CalloutWidth: Single read FCalloutWidth write SetCalloutWidth; property CalloutLength: Single read FCalloutLength write SetCalloutLength; property CalloutPosition: TCalloutPosition read FCalloutPosition write SetCalloutPosition default TCalloutPosition.Top; property CalloutOffset: Single read FCalloutOffset write SetCalloutOffset; {+++>}property CalloutPeakOffset: Single read FCalloutPeakOffset write SetCalloutPeakOffset; property Stroke; {+++>}property NativeDraw: Boolean read FNativeDraw write SetNativeDraw; end; implementation { TOneCallout } procedure TFMXCallout.AddCalloutToPath(APath: TPathData; const ARect: TRectF; const ACornerRadiuses: TSizeF); begin case CalloutPosition of TCalloutPosition.Top: begin if CalloutOffset = 0 then begin APath.LineTo(PointF(ARect.Width / 2 - CalloutWidth / 2, ARect.Top)); APath.LineTo(PointF(ARect.Width / 2{+++>} + FCalloutPeakOffset{<+++}, ARect.Top - FCalloutLength)); APath.LineTo(PointF(ARect.Width / 2 + CalloutWidth / 2, ARect.Top)); APath.LineTo(PointF(ARect.Right - ACornerRadiuses.cx, ARect.Top)); end else if CalloutOffset > 0 then begin APath.LineTo(PointF(ARect.Left + FCalloutOffset, ARect.Top)); APath.LineTo(PointF(ARect.Left + FCalloutOffset + (CalloutWidth / 2){+++>} + FCalloutPeakOffset{<+++}, ARect.Top - FCalloutLength)); APath.LineTo(PointF(ARect.Left + FCalloutOffset + CalloutWidth, ARect.Top)); APath.LineTo(PointF(ARect.Right - ACornerRadiuses.cx, ARect.Top)); end else begin APath.LineTo(PointF(ARect.Right - Abs(FCalloutOffset) - CalloutWidth, ARect.Top)); APath.LineTo(PointF(ARect.Right - Abs(FCalloutOffset) - CalloutWidth / 2{+++>} + FCalloutPeakOffset{<+++}, ARect.Top - FCalloutLength)); APath.LineTo(PointF(ARect.Right - Abs(FCalloutOffset), ARect.Top)); APath.LineTo(PointF(ARect.Right - ACornerRadiuses.cx, ARect.Top)); end; end; TCalloutPosition.Left: begin if CalloutOffset = 0 then begin APath.LineTo(PointF(ARect.Left, ARect.Height / 2 + CalloutWidth / 2)); APath.LineTo(PointF(ARect.Left - FCalloutLength, (ARect.Bottom - ARect.Top) / 2{+++>} + FCalloutPeakOffset{<+++})); APath.LineTo(PointF(ARect.Left, ARect.Height / 2 - CalloutWidth / 2)); APath.LineTo(PointF(ARect.Left, ARect.Top + ACornerRadiuses.cy)); end else if CalloutOffset > 0 then begin APath.LineTo(PointF(ARect.Left, ARect.Top + CalloutOffset + CalloutWidth)); APath.LineTo(PointF(ARect.Left - FCalloutLength, ARect.Top + CalloutOffset + CalloutWidth / 2{+++>} + FCalloutPeakOffset{<+++})); APath.LineTo(PointF(ARect.Left, ARect.Top + CalloutOffset)); APath.LineTo(PointF(ARect.Left, ARect.Top + ACornerRadiuses.cy)); end else begin APath.LineTo(PointF(ARect.Left, ARect.Bottom + CalloutOffset + CalloutWidth)); APath.LineTo(PointF(ARect.Left - FCalloutLength, ARect.Bottom + CalloutOffset + CalloutWidth / 2{+++>} + FCalloutPeakOffset{<+++})); APath.LineTo(PointF(ARect.Left, ARect.Bottom + CalloutOffset)); APath.LineTo(PointF(ARect.Left, ARect.Top + ACornerRadiuses.cy)); end; end; TCalloutPosition.Bottom: begin if CalloutOffset = 0 then begin APath.LineTo(PointF(ARect.Width / 2 + CalloutWidth / 2, ARect.Bottom)); APath.LineTo(PointF(ARect.Width / 2{+++>} + FCalloutPeakOffset{<+++}, ARect.Bottom + FCalloutLength)); APath.LineTo(PointF(ARect.Width / 2 - CalloutWidth / 2, ARect.Bottom)); APath.LineTo(PointF(ARect.Left + ACornerRadiuses.cx, ARect.Bottom)); end else if CalloutOffset > 0 then begin APath.LineTo(PointF(ARect.Left + FCalloutOffset + CalloutWidth, ARect.Bottom)); APath.LineTo(PointF(ARect.Left + FCalloutOffset + CalloutWidth / 2{+++>} + FCalloutPeakOffset{<+++}, ARect.Bottom + FCalloutLength)); APath.LineTo(PointF(ARect.Left + FCalloutOffset, ARect.Bottom)); APath.LineTo(PointF(ARect.Left + ACornerRadiuses.cx, ARect.Bottom)); end else begin APath.LineTo(PointF(ARect.Right - Abs(FCalloutOffset), ARect.Bottom)); APath.LineTo(PointF(ARect.Right - Abs(FCalloutOffset) - CalloutWidth / 2{+++>} + FCalloutPeakOffset{<+++}, ARect.Bottom + FCalloutLength)); APath.LineTo(PointF(ARect.Right - Abs(FCalloutOffset) - CalloutWidth, ARect.Bottom)); APath.LineTo(PointF(ARect.Left + ACornerRadiuses.cx, ARect.Bottom)); end; end; TCalloutPosition.Right: begin if CalloutOffset = 0 then begin APath.LineTo(PointF(ARect.Right, ARect.Height / 2 - CalloutWidth / 2)); APath.LineTo(PointF(ARect.Right + FCalloutLength, ARect.Height / 2{+++>} + Tag{<+++})); APath.LineTo(PointF(ARect.Right, ARect.Height / 2 + CalloutWidth / 2)); APath.LineTo(PointF(ARect.Right, ARect.Bottom - ACornerRadiuses.cy)); end else if CalloutOffset > 0 then begin APath.LineTo(PointF(ARect.Right, ARect.Top + CalloutOffset)); APath.LineTo(PointF(ARect.Right + FCalloutLength, ARect.Top + CalloutOffset + CalloutWidth / 2{+++>} + Tag{<+++})); APath.LineTo(PointF(ARect.Right, ARect.Top + CalloutOffset + CalloutWidth)); APath.LineTo(PointF(ARect.Right, ARect.Bottom - ACornerRadiuses.cy)); end else begin APath.LineTo(PointF(ARect.Right, ARect.Bottom + CalloutOffset)); APath.LineTo(PointF(ARect.Right + FCalloutLength, ARect.Bottom + CalloutOffset + CalloutWidth / 2{+++>} + Tag{<+++})); APath.LineTo(PointF(ARect.Right, ARect.Bottom + CalloutOffset + CalloutWidth)); APath.LineTo(PointF(ARect.Right, ARect.Bottom - ACornerRadiuses.cy)); end; end; end; end; procedure TFMXCallout.AddRectCornerToPath(APath: TPathData; const ARect: TRectF; const ACornerSize: TSizeF; const ACorner: TCorner; const ASkipEmptySide: Boolean = True); begin case ACorner of TCorner.TopLeft: begin if (TSide.Left in Sides) or not ASkipEmptySide then APath.LineTo(ARect.TopLeft) else APath.MoveTo(ARect.TopLeft); if (TSide.Top in Sides) or not ASkipEmptySide then APath.LineTo(PointF(ARect.Left + ACornerSize.cx, ARect.Top)) else APath.MoveTo(PointF(ARect.Left + ACornerSize.cx, ARect.Top)); end; TCorner.TopRight: begin if (TSide.Top in Sides) or not ASkipEmptySide then APath.LineTo(PointF(ARect.Right, ARect.Top)) else APath.MoveTo(PointF(ARect.Right, ARect.Top)); if (TSide.Right in Sides) or not ASkipEmptySide then APath.LineTo(PointF(ARect.Right, ARect.Top + ACornerSize.cy)) else APath.MoveTo(PointF(ARect.Right, ARect.Top + ACornerSize.cy)); end; TCorner.BottomLeft: begin if (TSide.Bottom in Sides) or not ASkipEmptySide then APath.LineTo(PointF(ARect.Left, ARect.Bottom)) else APath.MoveTo(PointF(ARect.Left, ARect.Bottom)); if (TSide.Left in Sides) or not ASkipEmptySide then APath.LineTo(PointF(ARect.Left, ARect.Bottom - ACornerSize.cy)) else APath.MoveTo(PointF(ARect.Left, ARect.Bottom - ACornerSize.cy)); end; TCorner.BottomRight: begin if (TSide.Right in Sides) or not ASkipEmptySide then APath.LineTo(PointF(ARect.Right, ARect.Bottom)) else APath.MoveTo(PointF(ARect.Right, ARect.Bottom)); if (TSide.Bottom in Sides) or not ASkipEmptySide then APath.LineTo(PointF(ARect.Right - ACornerSize.cx, ARect.Bottom)) else APath.MoveTo(PointF(ARect.Right - ACornerSize.cx, ARect.Bottom)); end; end; end; procedure TFMXCallout.AddRoundCornerToPath(APath: TPathData; const ARect: TRectF; const ACornerSize: TSizeF; const ACorner: TCorner); var x2: Single; y2: Single; begin x2 := ACornerSize.cx / 2; y2 := ACornerSize.cy / 2; case ACorner of TCorner.TopLeft: begin case CornerType of // TCornerType.Round - default TCornerType.Bevel: APath.LineTo(PointF(ARect.Left + ACornerSize.cx, ARect.Top)); TCornerType.InnerRound: APath.CurveTo(PointF(ARect.Left + x2, ARect.Top + ACornerSize.cy), PointF(ARect.Left + ACornerSize.cx, ARect.Top + y2), PointF(ARect.Left + ACornerSize.cx, ARect.Top)); TCornerType.InnerLine: begin APath.LineTo(PointF(ARect.Left + x2, ARect.Top + ACornerSize.cy)); APath.LineTo(PointF(ARect.Left + ACornerSize.cx, ARect.Top + y2)); APath.LineTo(PointF(ARect.Left + ACornerSize.cx, ARect.Top)); end; else APath.CurveTo(PointF(ARect.Left, ARect.Top + y2), PointF(ARect.Left + x2, ARect.Top), PointF(ARect.Left + ACornerSize.cx, ARect.Top)) end; end; TCorner.TopRight: begin case CornerType of // TCornerType.Round - default TCornerType.Bevel: APath.LineTo(PointF(ARect.Right, ARect.Top + ACornerSize.cy)); TCornerType.InnerRound: APath.CurveTo(PointF(ARect.Right - ACornerSize.cx, ARect.Top + y2), PointF(ARect.Right - x2, ARect.Top + ACornerSize.cy), PointF(ARect.Right, ARect.Top + ACornerSize.cy)); TCornerType.InnerLine: begin APath.LineTo(PointF(ARect.Right - ACornerSize.cx, ARect.Top + y2)); APath.LineTo(PointF(ARect.Right - x2, ARect.Top + ACornerSize.cy)); APath.LineTo(PointF(ARect.Right, ARect.Top + ACornerSize.cy)); end; else APath.CurveTo(PointF(ARect.Right - x2, ARect.Top), PointF(ARect.Right, ARect.Top + y2), PointF(ARect.Right, ARect.Top + ACornerSize.cy)) end; end; TCorner.BottomLeft: begin case CornerType of // TCornerType.Round - default TCornerType.Bevel: APath.LineTo(PointF(ARect.Left, ARect.Bottom - ACornerSize.cy)); TCornerType.InnerRound: APath.CurveTo(PointF(ARect.Left + ACornerSize.cx, ARect.Bottom - y2), PointF(ARect.Left + x2, ARect.Bottom - ACornerSize.cy), PointF(ARect.Left, ARect.Bottom - ACornerSize.cy)); TCornerType.InnerLine: begin APath.LineTo(PointF(ARect.Left + ACornerSize.cx, ARect.Bottom - y2)); APath.LineTo(PointF(ARect.Left + x2, ARect.Bottom - ACornerSize.cy)); APath.LineTo(PointF(ARect.Left, ARect.Bottom - ACornerSize.cy)); end; else APath.CurveTo(PointF(ARect.Left + x2, ARect.Bottom), PointF(ARect.Left, ARect.Bottom - y2), PointF(ARect.Left, ARect.Bottom - ACornerSize.cy)) end; end; TCorner.BottomRight: begin case CornerType of // TCornerType.Round - default TCornerType.Bevel: APath.LineTo(PointF(ARect.Right - ACornerSize.cx, ARect.Bottom)); TCornerType.InnerRound: APath.CurveTo(PointF(ARect.Right - x2, ARect.Bottom - ACornerSize.cy), PointF(ARect.Right - ACornerSize.cx, ARect.Bottom - y2), PointF(ARect.Right - ACornerSize.cx, ARect.Bottom)); TCornerType.InnerLine: begin APath.LineTo(PointF(ARect.Right - x2, ARect.Bottom - ACornerSize.cy)); APath.LineTo(PointF(ARect.Right - ACornerSize.cx, ARect.Bottom - y2)); APath.LineTo(PointF(ARect.Right - ACornerSize.cx, ARect.Bottom)); end; else APath.CurveTo(PointF(ARect.Right, ARect.Bottom - y2), PointF(ARect.Right - x2, ARect.Bottom), PointF(ARect.Right - ACornerSize.cx, ARect.Bottom)) end; end; end; end; constructor TFMXCallout.Create(AOwner: TComponent); begin inherited; {+++>}FNativeDraw := True; FCalloutWidth := 23; FCalloutLength := 11; FPath := TPathData.Create; FFillPath := TPathData.Create; RebuildPaths; end; destructor TFMXCallout.Destroy; begin FreeAndNil(FPath); FreeAndNil(FFillPath); inherited; end; function TFMXCallout.GeTOneCalloutRect: TRectF; var R: TRectF; begin R := GetShapeRect; case CalloutPosition of TCalloutPosition.Top: R.Top := R.Top + FCalloutLength; TCalloutPosition.Left: R.Left := R.Left + FCalloutLength; TCalloutPosition.Bottom: R.Bottom := R.Bottom - FCalloutLength; TCalloutPosition.Right: R.Right := R.Right - FCalloutLength; end; Result := R; end; procedure TFMXCallout.Loaded; begin inherited Loaded; RebuildPaths; end; procedure TFMXCallout.CreateFillPath; var CornerSize: TSizeF; R: TRectF; begin R := GeTOneCalloutRect; CornerSize := TSizeF.Create(XRadius, YRadius); if (R.Width - CornerSize.cx * 2 < 0) and (CornerSize.cx > 0) then CornerSize.cx := XRadius * R.Width / (CornerSize.cx * 2); if (R.Height - CornerSize.cy * 2 < 0) and (CornerSize.cy > 0) then CornerSize.cy := YRadius * R.Height / (CornerSize.cy * 2); FFillPath.Clear; FFillPath.MoveTo(PointF(R.Left, R.Top + CornerSize.cy)); // Top Left Corner if TCorner.TopLeft in Corners then AddRoundCornerToPath(FFillPath, R, CornerSize, TCorner.TopLeft) else AddRectCornerToPath(FFillPath, R, CornerSize, TCorner.TopLeft, False); // Top Side if CalloutPosition = TCalloutPosition.Top then AddCalloutToPath(FFillPath, R, CornerSize) else FFillPath.LineTo(PointF(R.Right - CornerSize.cx, R.Top)); // Top Right Corner if TCorner.TopRight in Corners then AddRoundCornerToPath(FFillPath, R, CornerSize, TCorner.TopRight) else AddRectCornerToPath(FFillPath, R, CornerSize, TCorner.TopRight, False); // Right Side if (FCalloutPosition = TCalloutPosition.Right) then AddCalloutToPath(FFillPath, R, CornerSize) else FFillPath.LineTo(PointF(R.Right, R.Bottom - CornerSize.cy)); // Bottom Right Corner if TCorner.BottomRight in Corners then AddRoundCornerToPath(FFillPath, R, CornerSize, TCorner.BottomRight) else AddRectCornerToPath(FFillPath, R, CornerSize, TCorner.BottomRight, False); // Bottom Side if FCalloutPosition = TCalloutPosition.Bottom then AddCalloutToPath(FFillPath, R, CornerSize) else FFillPath.LineTo(PointF(R.Left + CornerSize.cx, R.Bottom)); // Bottom Left Corner if TCorner.BottomLeft in Corners then AddRoundCornerToPath(FFillPath, R, CornerSize, TCorner.BottomLeft) else AddRectCornerToPath(FFillPath, R, CornerSize, TCorner.BottomLeft, False); // Left Side if FCalloutPosition = TCalloutPosition.Left then AddCalloutToPath(FFillPath, R, CornerSize) else FFillPath.LineTo(PointF(R.Left, R.Top + CornerSize.cy)); end; procedure TFMXCallout.CreatePath; var CornerSize: TSizeF; R: TRectF; begin R := GeTOneCalloutRect; CornerSize := TSizeF.Create(XRadius, YRadius); if (R.Width - CornerSize.cx * 2 < 0) and (CornerSize.cx > 0) then CornerSize.cx := XRadius * R.Width / (CornerSize.cx * 2); if (R.Height - CornerSize.cy * 2 < 0) and (CornerSize.cy > 0) then CornerSize.cy := YRadius * R.Height / (CornerSize.cy * 2); FPath.Clear; FPath.MoveTo(PointF(R.Left, R.Top + CornerSize.cy)); // Top Left Corner if TCorner.TopLeft in Corners then AddRoundCornerToPath(FPath, R, CornerSize, TCorner.TopLeft) else AddRectCornerToPath(FPath, R, CornerSize, TCorner.TopLeft); // Top Side if not (TSide.Top in Sides) then FPath.MoveTo(PointF(R.Right - CornerSize.cx, R.Top)) else begin if CalloutPosition = TCalloutPosition.Top then AddCalloutToPath(FPath, R, CornerSize) else FPath.LineTo(PointF(R.Right - CornerSize.cx, R.Top)); end; // Top Right Corner if TCorner.TopRight in Corners then AddRoundCornerToPath(FPath, R, CornerSize, TCorner.TopRight) else AddRectCornerToPath(FPath, R, CornerSize, TCorner.TopRight); // Right Side if not (TSide.Right in Sides) then FPath.MoveTo(PointF(R.Right, R.Bottom - CornerSize.cy)) else begin if (FCalloutPosition = TCalloutPosition.Right) then AddCalloutToPath(FPath, R, CornerSize) else FPath.LineTo(PointF(R.Right, R.Bottom - CornerSize.cy)); end; // Bottom Right Corner if TCorner.BottomRight in Corners then AddRoundCornerToPath(FPath, R, CornerSize, TCorner.BottomRight) else AddRectCornerToPath(FPath, R, CornerSize, TCorner.BottomRight); // Bottom Side if not (TSide.Bottom in Sides) then FPath.MoveTo(PointF(R.Left + CornerSize.cx, R.Bottom)) else begin if FCalloutPosition = TCalloutPosition.Bottom then AddCalloutToPath(FPath, R, CornerSize) else FPath.LineTo(PointF(R.Left + CornerSize.cx, R.Bottom)); end; // Bottom Left Corner if TCorner.BottomLeft in Corners then AddRoundCornerToPath(FPath, R, CornerSize, TCorner.BottomLeft) else AddRectCornerToPath(FPath, R, CornerSize, TCorner.BottomLeft); // Left Side if not (TSide.Left in Sides) then FPath.MoveTo(PointF(R.Left, R.Top + CornerSize.cy)) else begin if FCalloutPosition = TCalloutPosition.Left then AddCalloutToPath(FPath, R, CornerSize) else FPath.LineTo(PointF(R.Left, R.Top + CornerSize.cy)); end; end; procedure TFMXCallout.Paint; var Canvas: INativeCanvas; Method: TDrawMethod; begin Log.d('Enter TOneCallout.Paint'); if Self.NativeDraw then Method := TDrawMethod.Native else Method := TDrawMethod.Firemonkey; Canvas := Self.Canvas.ToNativeCanvas(Method); Canvas.NativeDraw(LocalRect, procedure begin // 原生繪圖 by Aone, 暱名函數裡加入繪圖方法, 內部會先畫到 Bitmap Canvas.FillPath(FFillPath, AbsoluteOpacity, Fill); Canvas.DrawPath(FPath, AbsoluteOpacity, Stroke); end); // 原生繪圖 by Aone, 結束後會顯示這個 Bitmap end; procedure TFMXCallout.RebuildPaths; begin if not (csReading in ComponentState) and not (csLoading in ComponentState) then begin CreatePath; CreateFillPath; end; end; procedure TFMXCallout.Resize; begin inherited Resize; RebuildPaths; end; procedure TFMXCallout.SetCalloutWidth(const Value: Single); begin if FCalloutWidth <> Value then begin FCalloutWidth := Value; RebuildPaths; Repaint; end; end; procedure TFMXCallout.SetCorners(const Value: TCorners); begin if Value <> Corners then begin inherited SetCorners(Value); RebuildPaths; end; end; procedure TFMXCallout.SetCornerType(const Value: TCornerType); begin if Value <> CornerType then begin inherited SetCornerType(Value); RebuildPaths; Repaint; end; end; {+++>} procedure TFMXCallout.SetNativeDraw(const Value: Boolean); begin if FNativeDraw <> Value then begin FNativeDraw := Value; Repaint; end; end; {<+++} procedure TFMXCallout.SetSides(const Value: TSides); begin if Value <> Sides then begin inherited SetSides(Value); RebuildPaths; Repaint; end; end; procedure TFMXCallout.SetXRadius(const Value: Single); begin if Value <> XRadius then begin inherited SetXRadius(Value); RebuildPaths; Repaint; end; end; procedure TFMXCallout.SetYRadius(const Value: Single); begin if Value <> YRadius then begin inherited SetYRadius(Value); RebuildPaths; Repaint; end; end; procedure TFMXCallout.SetCalloutLength(const Value: Single); begin if FCalloutLength <> Value then begin FCalloutLength := Value; RebuildPaths; Repaint; end; end; procedure TFMXCallout.SetCalloutPosition(const Value: TCalloutPosition); begin if FCalloutPosition <> Value then begin FCalloutPosition := Value; RebuildPaths; Repaint; end; end; procedure TFMXCallout.SetCalloutOffset(const Value: Single); begin if FCalloutOffset <> Value then begin FCalloutOffset := Value; RebuildPaths; Repaint; end; end; {+++>} procedure TFMXCallout.SetCalloutPeakOffset(const Value: Single); begin if FCalloutPeakOffset <> Value then begin FCalloutPeakOffset := Value; RebuildPaths; Repaint; end; end; {<+++} end.
unit BaiduMapAPI.ViewService.iOS; //author:Xubzhlin //Email:371889755@qq.com //百度地图API 地图服务 单元 //官方链接:http://lbsyun.baidu.com/ //TiOSBaiduMapViewService 百度地图 iOS地图服务 interface uses System.Classes, System.Generics.Collections, FMX.Maps, Macapi.ObjectiveC, Macapi.ObjCRuntime, iOSapi.CoreLocation, iOSapi.Foundation, FMX.ZOrder.iOS, iOSapi.UIKit, iOSapi.CoreGraphics, iOSapi.CocoaTypes, iOSapi.BaiduMapAPI_Base, iOSapi.BaiduMapAPI_Map, BaiduMapAPI.ViewService; type TiOSBaiduMapViewService = class; TBMKMapViewDelegate = class(TOCLocal, BMKMapViewDelegate) private [Weak] FViewService: TiOSBaiduMapViewService; public constructor Create(const ViewService: TiOSBaiduMapViewService); procedure mapViewDidFinishLoading(mapView: BMKMapView); cdecl; procedure mapViewDidFinishRendering(mapView: BMKMapView); cdecl; [MethodName('mapView:onDrawMapFrame:')] procedure mapViewOnDrawMapFrame(mapView: BMKMapView; onDrawMapFrame: BMKMapStatus); cdecl; [MethodName('mapView:regionWillChangeAnimated:')] procedure mapViewRegionWillChangeAnimated(mapView: BMKMapView; regionWillChangeAnimated: Boolean); cdecl; [MethodName('mapView:regionDidChangeAnimated:')] procedure mapViewRegionDidChangeAnimated(mapView: BMKMapView; regionDidChangeAnimated: Boolean); cdecl; [MethodName('mapView:viewForAnnotation:')] function mapViewViewForAnnotation(mapView: BMKMapView; viewForAnnotation: Pointer): BMKAnnotationView; cdecl; [MethodName('mapView:didAddAnnotationViews:')] procedure mapViewDidAddAnnotationViews(mapView: BMKMapView; didAddAnnotationViews: NSArray); cdecl; [MethodName('mapView:didSelectAnnotationView:')] procedure mapViewDidSelectAnnotationView(mapView: BMKMapView; didSelectAnnotationView: BMKAnnotationView); cdecl; [MethodName('mapView:didDeselectAnnotationView:')] procedure mapViewDidDeselectAnnotationView(mapView: BMKMapView; didDeselectAnnotationView: BMKAnnotationView); cdecl; [MethodName('mapView:annotationView:didChangeDragState:fromOldState:')] procedure mapViewAnnotationViewDidChangeDragStateFromOldState (mapView: BMKMapView; annotationView: BMKAnnotationView; didChangeDragState: BMKAnnotationViewDragState; fromOldState: BMKAnnotationViewDragState); cdecl; [MethodName('mapView:annotationViewForBubble:')] procedure mapViewAnnotationViewForBubble(mapView: BMKMapView; annotationViewForBubble: BMKAnnotationView); cdecl; [MethodName('mapView:viewForOverlay:')] function mapViewViewForOverlay(mapView: BMKMapView; viewForOverlay: Pointer) : BMKOverlayView; cdecl; [MethodName('mapView:didAddOverlayViews:')] procedure mapViewDidAddOverlayViews(mapView: BMKMapView; didAddOverlayViews: NSArray); cdecl; [MethodName('mapView:onClickedBMKOverlayView:')] procedure mapViewOnClickedBMKOverlayView(mapView: BMKMapView; onClickedBMKOverlayView: BMKOverlayView); cdecl; [MethodName('mapView:onClickedMapPoi:')] procedure mapViewOnClickedMapPoi(mapView: BMKMapView; onClickedMapPoi: BMKMapPoi); cdecl; [MethodName('mapView:onClickedMapBlank:')] procedure mapViewOnClickedMapBlank(mapView: BMKMapView; onClickedMapBlank: CLLocationCoordinate2D); cdecl; [MethodName('mapview:onDoubleClick:')] procedure mapviewOnDoubleClick(mapView: BMKMapView; onDoubleClick: CLLocationCoordinate2D); cdecl; [MethodName('mapview:onLongClick:')] procedure mapviewOnLongClick(mapView: BMKMapView; onLongClick: CLLocationCoordinate2D); cdecl; [MethodName('mapview:onForceTouch:force:maximumPossibleForce:') ] procedure mapviewOnForceTouchForceMaximumPossibleForce(mapView: BMKMapView; onForceTouch: CLLocationCoordinate2D; force: CGFloat; maximumPossibleForce: CGFloat); cdecl; procedure mapStatusDidChanged(mapView: BMKMapView); cdecl; [MethodName('mapview:baseIndoorMapWithIn:baseIndoorMapInfo:') ] procedure mapviewBaseIndoorMapWithInBaseIndoorMapInfo(mapView: BMKMapView; baseIndoorMapWithIn: Boolean; baseIndoorMapInfo: BMKBaseIndoorMapInfo); cdecl; end; TiOSBaiduMapViewService = class(TBaiduMapViewService) private FMapView:BMKMapView; FMapViewDelegate:TBMKMapViewDelegate; FLocationInitBoolean:Boolean; FMapObjects:TDictionary<Pointer, TMapObjectBase>; procedure InitInstance; procedure RealignView; function GetMapObject<T: TMapObjectBase>(const Key: Pointer): T; procedure PutMapObject<T: TMapObjectBase>(const Key: Pointer; const MapObject: T); procedure RemoveMapObject(const Key: Pointer); protected procedure DoShowBaiduMap; override; procedure DoUpdateBaiduMapFromControl; override; procedure DoSetVisible(const Value: Boolean); override; function DoAddMarker(const Descriptor: TMapMarkerDescriptor):TBaiduMapMarker; override; function DoAddPolyline(const Descriptor: TMapPolylineDescriptor):TMapPolyline; override; function DoAddPolygon(const Descriptor: TMapPolygonDescriptor):TMapPolygon; override; function DoAddCircle(const Descriptor: TMapCircleDescriptor): TMapCircle; override; procedure DoSetCenterCoordinate(const Coordinate:TMapCoordinate); override; public constructor Create(AKey:String); override; destructor Destroy; override; property MapView: BMKMapView read FMapView; end; implementation uses System.SysUtils, FMX.Forms, FMX.Controls, FMX.Platform.iOS, FMX.Helpers.iOS, Macapi.Helpers; type TiOSBMKMarker = class(TBaiduMapMarker) private FAnnotation: BMKPointAnnotation; FVisible: Boolean; [Weak] FViewService: TiOSBaiduMapViewService; FAnnotationView: BMKAnnotationView; public constructor Create(const Descriptor: TMapMarkerDescriptor; const ViewService: TiOSBaiduMapViewService); reintroduce; function Id: Pointer; destructor Destroy; override; procedure Remove; override; procedure SetVisible(const Value: Boolean); override; function AnnotationView: BMKAnnotationView; end; TiOSBMKPolyline = class(TMapPolyline) private FPolyline: BMKPolyline; FVisible: Boolean; [Weak] FViewService: TiOSBaiduMapViewService; public constructor Create(const Descriptor: TMapPolylineDescriptor; const ViewService: TiOSBaiduMapViewService); reintroduce; destructor Destroy; override; function Id: Pointer; procedure Remove; override; procedure SetVisible(const Value: Boolean); override; function ToString: string; override; function PolylineView:BMKPolylineView; end; TiOSBMKPolygon = class(TMapPolygon) private FPolygon: BMKPolygon; FVisible: Boolean; [Weak] FViewService: TiOSBaiduMapViewService; public constructor Create(const Descriptor: TMapPolygonDescriptor; const ViewService: TiOSBaiduMapViewService); reintroduce; destructor Destroy; override; function Id: Pointer; procedure Remove; override; procedure SetVisible(const Value: Boolean); override; function PolygonView:BMKPolygonView; end; TiOSBMKCircle = class(TMapCircle) private FCircle: BMKCircle; FVisible: Boolean; [Weak] FViewService: TiOSBaiduMapViewService; public constructor Create(const Descriptor: TMapCircleDescriptor; const ViewService: TiOSBaiduMapViewService); reintroduce; destructor Destroy; override; function Id: Pointer; procedure Remove; override; procedure SetVisible(const Value: Boolean); override; function CircleView: BMKCircleView; end; procedure StateSwitch(var State: Boolean; const NewValue: Boolean; SetProc: TProc; ResetProc: TProc); var OldState: Boolean; begin OldState := State; State := NewValue; if NewValue and not OldState then SetProc else if not NewValue and OldState then ResetProc; end; { TiOSBaiduMapViewService } constructor TiOSBaiduMapViewService.Create(AKey: String); begin inherited Create(AKey); FMapObjects:= TDictionary<Pointer, TMapObjectBase>.Create; end; destructor TiOSBaiduMapViewService.Destroy; var Form:TCommonCustomForm; ZOrderManager:TiOSZOrderManager; begin Form := TCommonCustomForm(Control.Root); {$IFDEF IOS} ZOrderManager := WindowHandleToPlatform(Form.Handle).ZOrderManager; if (ZOrderManager <> nil) and (Control <> nil) then begin ZOrderManager.UpdateOrderAndBounds(Control, FMapView); ZOrderManager.RemoveLink(Control); end; {$ENDIF} FMapObjects.DisposeOf; FMapViewDelegate.DisposeOf; FMapView:=nil; inherited; end; function TiOSBaiduMapViewService.DoAddCircle( const Descriptor: TMapCircleDescriptor): TMapCircle; begin Result := TiOSBMKCircle.Create(Descriptor, Self); PutMapObject<TMapCircle>(TiOSBMKCircle(Result).Id, Result); Result.SetVisible(True); end; function TiOSBaiduMapViewService.DoAddMarker( const Descriptor: TMapMarkerDescriptor): TBaiduMapMarker; begin Result := TiOSBMKMarker.Create(Descriptor, Self); PutMapObject<TBaiduMapMarker>(TiOSBMKMarker(Result).Id, Result); Result.SetVisible(True); end; function TiOSBaiduMapViewService.DoAddPolygon( const Descriptor: TMapPolygonDescriptor): TMapPolygon; begin Result := TiOSBMKPolygon.Create(Descriptor, Self); PutMapObject<TMapPolygon>(TiOSBMKPolygon(Result).Id, Result); Result.SetVisible(True); end; function TiOSBaiduMapViewService.DoAddPolyline( const Descriptor: TMapPolylineDescriptor): TMapPolyline; begin Result := TiOSBMKPolyline.Create(Descriptor, Self); PutMapObject<TMapPolyline>(TiOSBMKPolyline(Result).Id, Result); Result.SetVisible(True); end; procedure TiOSBaiduMapViewService.DoShowBaiduMap; begin InitInstance; end; procedure TiOSBaiduMapViewService.InitInstance; begin FMapView:=TBMKMapView.Wrap(TBMKMapView.Alloc.init); FMapView.SetMapType(BMKMapTypeStandard); //FMapView.setUserTrackingMode(BMKUserTrackingModeFollow); FMapView.setHidden(False); FMapViewDelegate:=TBMKMapViewDelegate.Create(Self); FMapView.setDelegate(FMapViewDelegate.GetObjectID); FMapView.retain; //SharedApplication.keyWindow.rootViewController.View.addSubview(FMapView); RealignView; end; procedure TiOSBaiduMapViewService.PutMapObject<T>(const Key: Pointer; const MapObject: T); var MObject: TMapObjectBase; begin if FMapObjects.TryGetValue(Key, MObject) then FMapObjects[Key] := MapObject else FMapObjects.Add(Key, MapObject); end; procedure TiOSBaiduMapViewService.RealignView; var Form: TCommonCustomForm; {$IFDEF IOS} ZOrderManager: TiOSZOrderManager; {$ELSE} View: INativeView; Bounds: TRectF; {$ENDIF} begin if FMapView <> nil then begin if (Control <> nil) and not (csDesigning in Control.ComponentState) and (Control.Root is TCommonCustomForm) then begin Form := TCommonCustomForm(Control.Root); {$IFDEF IOS} ZOrderManager := WindowHandleToPlatform(Form.Handle).ZOrderManager; ZOrderManager.UpdateOrderAndBounds(Control, FMapView); {$ELSE} Bounds := TRectF.Create(0,0,FWebControl.Width,FWebControl.Height); Bounds.Fit(FWebControl.AbsoluteRect); View := WindowHandleToPlatform(Form.Handle).View; View.addSubview(FWebView); if SameValue(Bounds.Width, 0) or SameValue(Bounds.Height, 0) then FWebView.setHidden(True) else begin TNativeWebViewHelper.SetBounds(FWebView, Bounds, View.bounds.size.height); FWebView.setHidden(not FWebControl.ParentedVisible); end; {$ENDIF} end else FMapView.setHidden(True); end; end; procedure TiOSBaiduMapViewService.RemoveMapObject(const Key: Pointer); begin FMapObjects.Remove(Key); end; procedure TiOSBaiduMapViewService.DoUpdateBaiduMapFromControl; begin RealignView; end; function TiOSBaiduMapViewService.GetMapObject<T>(const Key: Pointer): T; var TmpResult: TMapObjectBase; begin if FMapObjects.TryGetValue(Key, TmpResult) then try Result := TmpResult as T; except on EInvalidCast do Result := nil; end; end; procedure TiOSBaiduMapViewService.DoSetCenterCoordinate( const Coordinate: TMapCoordinate); var Coordinate2D:CLLocationCoordinate2D; begin if FMapView<>nil then begin FMapView.setCenterCoordinate(CLLocationCoordinate2D(Coordinate)); end; end; procedure TiOSBaiduMapViewService.DoSetVisible(const Value: Boolean); begin end; { TiOSBMKMaker } function TiOSBMKMarker.AnnotationView: BMKAnnotationView; var Pin: BMKPinAnnotationView; Image: UIImage; begin if FAnnotationView <> nil then Exit(FAnnotationView); if Descriptor.Icon <> nil then begin Result := TBMKAnnotationView.Wrap(TBMKAnnotationView.Alloc.initWithAnnotation((FAnnotation as ILocalObject).GetObjectID, nil)); Image := BitmapToUIImage(Descriptor.Icon); Result.setImage(Image); Result.setUserInteractionEnabled(Descriptor.Draggable); Result.setDraggable(Descriptor.Draggable); Result.setCanShowCallout(True); Result.setCenterOffset(CGPointMake(Image.size.width * (Descriptor.Origin.X - 0.5), - Image.size.height * (Descriptor.Origin.Y - 0.5))); end else begin Pin := TBMKPinAnnotationView.Wrap(TBMKPinAnnotationView.Alloc.initWithAnnotation((FAnnotation as ILocalObject).GetObjectID, nil)); Pin.setUserInteractionEnabled(Descriptor.Draggable); Pin.setCanShowCallout(True); Pin.setDraggable(Descriptor.Draggable); Pin.setUserInteractionEnabled(Descriptor.Draggable); Result := Pin; end; FAnnotationView := Result; end; constructor TiOSBMKMarker.Create(const Descriptor: TMapMarkerDescriptor; const ViewService: TiOSBaiduMapViewService); begin inherited Create(Descriptor); FViewService := ViewService; FAnnotation := TBMKPointAnnotation.Wrap(TBMKPointAnnotation.Alloc.init); FAnnotation.setCoordinate(CLLocationCoordinate2D(Descriptor.Position)); FAnnotation.setTitle(StrToNSStr(Descriptor.Title)); FAnnotation.setSubtitle(StrToNSStr(Descriptor.Snippet)); end; destructor TiOSBMKMarker.Destroy; begin Remove; inherited; end; function TiOSBMKMarker.Id: Pointer; begin Result := (FAnnotation as ILocalObject).GetObjectId; end; procedure TiOSBMKMarker.Remove; begin if FAnnotation <> nil then begin SetVisible(False); FViewService.RemoveMapObject(Id); FViewService.MapView.removeAnnotation(Id); if FAnnotationView <> nil then begin FAnnotationView.prepareForReuse; FAnnotationView.release; end; FAnnotation.release; FAnnotation := nil; end; inherited; end; procedure TiOSBMKMarker.SetVisible(const Value: Boolean); begin inherited; StateSwitch(FVisible, Value, procedure begin FViewService.MapView.addAnnotation((FAnnotation as ILocalObject).GetObjectID); end, procedure begin // MKView can be nil when TMapView is being destroyed if FViewService.MapView <> nil then FViewService.MapView.removeAnnotation((FAnnotation as ILocalObject).GetObjectID); end); end; { TBMKPolyline } constructor TiOSBMKPolyline.Create(const Descriptor: TMapPolylineDescriptor; const ViewService: TiOSBaiduMapViewService); var i:integer; P:Pointer; begin inherited Create(Descriptor); FViewService := ViewService; FPolyline:=TBMKPolyline.OCClass.polylineWithCoordinatesCount(Descriptor.Points.Points, Length(Descriptor.Points.Points)); end; destructor TiOSBMKPolyline.Destroy; begin Remove; FPolyline.release; FPolyline := nil; inherited; end; function TiOSBMKPolyline.Id: Pointer; begin Result := (FPolyline as ILocalObject).GetObjectID; end; procedure TiOSBMKPolyline.Remove; begin inherited; SetVisible(False); end; procedure TiOSBMKPolyline.SetVisible(const Value: Boolean); begin inherited; StateSwitch(FVisible, Value, procedure begin FViewService.MapView.addOverlay((FPolyline as ILocalObject).GetObjectID) end, procedure begin FViewService.MapView.removeOverlay((FPolyline as ILocalObject).GetObjectID); end); end; function TiOSBMKPolyline.ToString: string; begin end; function TiOSBMKPolyline.PolylineView: BMKPolylineView; begin Result := TBMKPolylineView.Wrap(TBMKPolylineView.Alloc.initWithPolyline(FPolyline)); Result.setFillColor(AlphaColorToUIColor(Descriptor.StrokeColor)); Result.setStrokeColor(AlphaColorToUIColor(Descriptor.StrokeColor)); Result.setLineWidth(Descriptor.StrokeWidth / FViewService.Scale); end; { TBMKMapViewDelegate } constructor TBMKMapViewDelegate.Create( const ViewService: TiOSBaiduMapViewService); begin inherited Create; FViewService:=ViewService; end; procedure TBMKMapViewDelegate.mapStatusDidChanged(mapView: BMKMapView); begin end; procedure TBMKMapViewDelegate.mapViewAnnotationViewDidChangeDragStateFromOldState( mapView: BMKMapView; annotationView: BMKAnnotationView; didChangeDragState, fromOldState: BMKAnnotationViewDragState); begin end; procedure TBMKMapViewDelegate.mapViewAnnotationViewForBubble( mapView: BMKMapView; annotationViewForBubble: BMKAnnotationView); var Marker:TBaiduMapMarker; begin if (FViewService<>nil) and (annotationViewForBubble<>nil) then begin Marker:=FViewService.GetMapObject<TBaiduMapMarker>( TBMKPointAnnotation.Wrap(annotationViewForBubble.annotation)); if Marker<>nil then FViewService.DoMarkerClick(Marker); end; end; procedure TBMKMapViewDelegate.mapviewBaseIndoorMapWithInBaseIndoorMapInfo( mapView: BMKMapView; baseIndoorMapWithIn: Boolean; baseIndoorMapInfo: BMKBaseIndoorMapInfo); begin end; procedure TBMKMapViewDelegate.mapViewDidAddAnnotationViews(mapView: BMKMapView; didAddAnnotationViews: NSArray); begin end; procedure TBMKMapViewDelegate.mapViewDidAddOverlayViews(mapView: BMKMapView; didAddOverlayViews: NSArray); begin end; procedure TBMKMapViewDelegate.mapViewDidDeselectAnnotationView( mapView: BMKMapView; didDeselectAnnotationView: BMKAnnotationView); begin end; procedure TBMKMapViewDelegate.mapViewDidFinishLoading(mapView: BMKMapView); begin end; procedure TBMKMapViewDelegate.mapViewDidFinishRendering(mapView: BMKMapView); begin end; procedure TBMKMapViewDelegate.mapViewDidSelectAnnotationView( mapView: BMKMapView; didSelectAnnotationView: BMKAnnotationView); begin end; procedure TBMKMapViewDelegate.mapViewOnClickedBMKOverlayView( mapView: BMKMapView; onClickedBMKOverlayView: BMKOverlayView); var i:Integer; Ovl:NSObject; begin Ovl := TNSObject.Wrap(onClickedBMKOverlayView); if Ovl.isKindOfClass(objc_getClass('BMKCircleView')) then i:=0 else if Ovl.isKindOfClass(objc_getClass('BMKPolygonView')) then i := 1 else if Ovl.isKindOfClass(objc_getClass('BMKPolylineView')) then i := 2; end; procedure TBMKMapViewDelegate.mapViewOnClickedMapBlank(mapView: BMKMapView; onClickedMapBlank: CLLocationCoordinate2D); begin end; procedure TBMKMapViewDelegate.mapViewOnClickedMapPoi(mapView: BMKMapView; onClickedMapPoi: BMKMapPoi); begin end; procedure TBMKMapViewDelegate.mapviewOnDoubleClick(mapView: BMKMapView; onDoubleClick: CLLocationCoordinate2D); begin end; procedure TBMKMapViewDelegate.mapViewOnDrawMapFrame(mapView: BMKMapView; onDrawMapFrame: BMKMapStatus); begin end; procedure TBMKMapViewDelegate.mapviewOnForceTouchForceMaximumPossibleForce( mapView: BMKMapView; onForceTouch: CLLocationCoordinate2D; force, maximumPossibleForce: CGFloat); begin end; procedure TBMKMapViewDelegate.mapviewOnLongClick(mapView: BMKMapView; onLongClick: CLLocationCoordinate2D); begin end; procedure TBMKMapViewDelegate.mapViewRegionDidChangeAnimated( mapView: BMKMapView; regionDidChangeAnimated: Boolean); begin end; procedure TBMKMapViewDelegate.mapViewRegionWillChangeAnimated( mapView: BMKMapView; regionWillChangeAnimated: Boolean); begin end; function TBMKMapViewDelegate.mapViewViewForAnnotation(mapView: BMKMapView; viewForAnnotation: Pointer): BMKAnnotationView; var Marker: TiOSBMKMarker; begin Result := nil; Marker := FViewService.GetMapObject<TiOSBMKMarker>((TBMKPointAnnotation.Wrap(viewForAnnotation) as ILocalObject).GetObjectID); if Marker <> nil then Result := Marker.AnnotationView; end; function TBMKMapViewDelegate.mapViewViewForOverlay(mapView: BMKMapView; viewForOverlay: Pointer): BMKOverlayView; function CircleView(O: NSObject): BMKCircleView; var C: TiOSBMKCircle; begin Result := nil; C := TiOSBMKCircle(FViewService.GetMapObject<TMapCircle>((O as ILocalObject).GetObjectID)); if (C <> nil) and C.FVisible then Result := C.CircleView; end; function PolygonView(O: NSObject): BMKPolygonView; var P: TiOSBMKPolygon; begin Result := nil; P := TiOSBMKPolygon(FViewService.GetMapObject<TMapPolygon>((O as ILocalObject).GetObjectID)); if (P <> nil) and P.FVisible then Result := P.PolygonView; end; function PolylineView(O: NSObject): BMKPolylineView; var L: TiOSBMKPolyline; begin Result := nil; L := TiOSBMKPolyline(FViewService.GetMapObject<TMapPolyline>((O as ILocalObject).GetObjectID)); if (L <> nil) and L.FVisible then Result := L.PolylineView; end; var Ovl: NSObject; begin Result := nil; Ovl := TNSObject.Wrap(viewForOverlay); if Ovl.isKindOfClass(objc_getClass('BMKCircle')) then Result := CircleView(Ovl) else if Ovl.isKindOfClass(objc_getClass('BMKPolygon')) then Result := PolygonView(Ovl) else if Ovl.isKindOfClass(objc_getClass('BMKPolyline')) then Result := PolylineView(Ovl); end; { TiOSBMKPolygon } constructor TiOSBMKPolygon.Create(const Descriptor: TMapPolygonDescriptor; const ViewService: TiOSBaiduMapViewService); begin inherited Create(Descriptor); FViewService := ViewService; FPolygon := TBMKPolygon.OCClass.polygonWithCoordinates(Descriptor.Outline.Points, Length(Descriptor.Outline.Points)); end; destructor TiOSBMKPolygon.Destroy; begin Remove; FPolygon.release; FPolygon := nil; inherited; end; function TiOSBMKPolygon.Id: Pointer; begin Result := (FPolygon as ILocalObject).GetObjectID; end; function TiOSBMKPolygon.PolygonView: BMKPolygonView; begin Result := TBMKPolygonView.Wrap(TBMKPolygonView.Alloc.initWithPolygon(FPolygon)); Result.setFillColor(AlphaColorToUIColor(Descriptor.FillColor)); Result.setStrokeColor(AlphaColorToUIColor(Descriptor.StrokeColor)); Result.setLineWidth(Descriptor.StrokeWidth / FViewService.Scale); end; procedure TiOSBMKPolygon.Remove; begin inherited; SetVisible(False); end; procedure TiOSBMKPolygon.SetVisible(const Value: Boolean); begin inherited; StateSwitch(FVisible, Value, procedure begin FViewService.MapView.addOverlay((FPolygon as ILocalObject).GetObjectID) end, procedure begin FViewService.MapView.removeOverlay((FPolygon as ILocalObject).GetObjectID); end); end; { TiOSBMKCircle } function TiOSBMKCircle.CircleView: BMKCircleView; begin Result := TBMKCircleView.Wrap(TBMKCircleView.Alloc.initWithCircle(FCircle)); Result.setFillColor(AlphaColorToUIColor(Descriptor.FillColor)); Result.setStrokeColor(AlphaColorToUIColor(Descriptor.StrokeColor)); Result.setLineWidth(Descriptor.StrokeWidth / FViewService.Scale); end; constructor TiOSBMKCircle.Create(const Descriptor: TMapCircleDescriptor; const ViewService: TiOSBaiduMapViewService); begin inherited Create(Descriptor); FViewService := ViewService; FCircle := TBMKCircle.OCClass.circleWithCenterCoordinate(CLLocationCoordinate2D(Descriptor.Center), Descriptor.Radius); end; destructor TiOSBMKCircle.Destroy; begin Remove; FCircle.release; FCircle := nil; inherited; end; function TiOSBMKCircle.Id: Pointer; begin Result := (FCircle as ILocalObject).GetObjectID; end; procedure TiOSBMKCircle.Remove; begin inherited; SetVisible(False); end; procedure TiOSBMKCircle.SetVisible(const Value: Boolean); begin inherited; StateSwitch(FVisible, Value, procedure begin FViewService.MapView.addOverlay((FCircle as ILocalObject).GetObjectID) end, procedure begin FViewService.MapView.removeOverlay((FCircle as ILocalObject).GetObjectID); end); end; end.
unit uUnit; interface uses glr_render2d, uObjects; (* type { TUnit } TUnit = class (TglrSprite) protected fBulletOwner: TBulletOwner; fWeaponDir: TglrVec2f; fT, fSmokeT: Single; // for shooting fBonusTriple, fBonusRicochet: Boolean; fBonusT: array[TBonusType] of Single; procedure SetEnabled(const aEnabled: Boolean); virtual; public HealthMax: Integer; FireThreshold, RotateSpeed, DirectSpeed: Single; MainWeaponVelocity, MainWeaponDispersion: Single; AltWeaponVelocity: Single; MainWeaponDamage, AltWeaponDamage: Integer; Health: Integer; Weapon: TglrSprite; AltWeaponCount: Integer; constructor Create(); virtual; destructor Destroy(); override; procedure Update(const dt: Double; axisX, axisY: Integer); virtual; procedure Fire(); procedure FireAlternative(); procedure GetKilled(); virtual; property Enabled: Boolean read fVisible write SetEnabled; end; { TPlayer } TPlayer = class (TUnit) protected fHealthAnimateT, fGameOverT: Single; procedure SetEnabled(const aEnabled: Boolean); override; public FrontBumper: TglrSprite; BonusInfo, HealthText, AltWeaponText: TglrText; constructor Create(); override; destructor Destroy(); override; procedure Update(const dt: Double; axisX, axisY: Integer); override; procedure GetKilled(); override; end; { TEnemy } TEnemy = class (TUnit) protected procedure SetEnabled(const aEnabled: Boolean); override; public class var _HealthMax: Integer; _FireThreshold, _RotateSpeed, _DirectSpeed: Single; _MainWeaponVelocity, _MainWeaponDispersion: Single; _AltWeaponVelocity: Single; _MainWeaponDamage, _AltWeaponDamage: Integer; constructor Create(); override; procedure Update(const dt: Double; axisX, axisY: Integer); override; procedure GetKilled(); override; end; { TEnemyManager } TEnemyManager = class (TglrPool<TEnemy>) private fT: Single; fBatch: TglrSpriteBatch; public EnemySpawnInterval: Single; EnemySpawnCount: Integer; WaveCount: Integer; constructor Create(aBatch: TglrSpriteBatch); virtual; procedure Update(const dt: Double); procedure RenderSelf(); end; *) implementation end.
unit IdSSLDotNET; interface {$i IdCompilerDefines.inc} {*******************************************************} { } { Indy SSL Support for Microsoft.NET 2.0 } { } { Copyright (C) 2007 Indy Pit Crew } { Original author J. Peter Mugaas } { 2007-Aug-22 } { } {*******************************************************} uses Classes, IdException, IdGlobal, IdIOHandler, IdSocketHandle, IdSSL, IdThread, IdYarn, System.Collections, System.IO, System.Net.Sockets, System.Net.Security, System.Security.Authentication, System.Security.Cryptography.X509Certificates; const DEF_clientCertificateRequired = False; DEF_checkCertificateRevocation = True; type TOnValidatePeerCertificate = procedure (ASender : TObject; ACertificate : X509Certificate; AChain : X509Chain; AsslPolicyErrors : SslPolicyErrors; var VValid : Boolean) of object; TOnLocalCertificateSelectionCallback = procedure (ASender : TObject; AtargetHost : String; AlocalCertificates : X509CertificateCollection; AremoteCertificate : X509Certificate; AacceptableIssuers : array of String; VCert : X509Certificate) of object; TIdSSLIOHandlerSocketNET = class(TIdSSLIOHandlerSocketBase) protected FenabledSslProtocols: System.Security.Authentication.SslProtocols; FOnValidatePeerCertificate : TOnValidatePeerCertificate; FOnLocalCertificateSelection : TOnLocalCertificateSelectionCallback; FSSL : SslStream; FServerCertificate : X509Certificate; FClientCertificates : X509CertificateCollection; FOnSSLHandshakeDone : TNotifyEvent; FclientCertificateRequired : Boolean; FcheckCertificateRevocation : Boolean; procedure OpenEncodedConnection; virtual; //Ssl certificate validation callback function ValidatePeerCertificate( sender : System.&Object; certificate : X509Certificate; chain : X509Chain; sslPolicyErrors : SslPolicyErrors) : Boolean; function LocalCertificateSelectionCallback ( sender : System.&Object; targetHost : String; localCertificates : X509CertificateCollection; remoteCertificate : X509Certificate; acceptableIssuers : array of String) : X509Certificate; function RecvEnc(var VBuffer: TIdBytes): Integer; override; function SendEnc(const ABuffer: TIdBytes; const AOffset, ALength: Integer): Integer; override; procedure SetPassThrough(const Value: Boolean); override; procedure InitComponent; override; procedure ConnectClient; override; // function GetCipherAlgorithm: CipherAlgorithmType; function GetCipherStrength: Integer; function GetHashAlgorithm: HashAlgorithmType; function GetHashStrength: Integer; function GetIsEncrypted: Boolean; function GetIsSigned: Boolean; function GetKeyExchangeAlgorithm: ExchangeAlgorithmType; function GetKeyExchangeStrength: Integer; function GetRemoteCertificate: X509Certificate; function GetSslProtocol: SslProtocols; public procedure Close; override; procedure StartSSL; override; function Clone : TIdSSLIOHandlerSocketBase; override; property CipherAlgorithm : CipherAlgorithmType read GetCipherAlgorithm; property CipherStrength : Integer read GetCipherStrength; property HashAlgorithm : HashAlgorithmType read GetHashAlgorithm; property HashStrength : Integer read GetHashStrength; property IsEncrypted : Boolean read GetIsEncrypted; property IsSigned : Boolean read GetIsSigned; property KeyExchangeAlgorithm : ExchangeAlgorithmType read GetKeyExchangeAlgorithm; property KeyExchangeStrength : Integer read GetKeyExchangeStrength; property RemoteCertificate : X509Certificate read GetRemoteCertificate; property SslProtocol : SslProtocols read GetSslProtocol; published property enabledSslProtocols : System.Security.Authentication.SslProtocols read FenabledSslProtocols write FenabledSslProtocols; property ServerCertificate : X509Certificate read FServerCertificate write FServerCertificate; property ClientCertificates : X509CertificateCollection read FClientCertificates write FClientCertificates; property clientCertificateRequired : Boolean read FclientCertificateRequired write FclientCertificateRequired; property checkCertificateRevocation : Boolean read FcheckCertificateRevocation write FcheckCertificateRevocation; property OnSSLHandshakeDone : TNotifyEvent read FOnSSLHandshakeDone write FOnSSLHandshakeDone; property OnLocalCertificateSelection : TOnLocalCertificateSelectionCallback read FOnLocalCertificateSelection write FOnLocalCertificateSelection; property OnValidatePeerCertificate : TOnValidatePeerCertificate read FOnValidatePeerCertificate write FOnValidatePeerCertificate; end; TIdServerIOHandlerSSLNET = class(TIdServerIOHandlerSSLBase) protected FOnValidatePeerCertificate : TOnValidatePeerCertificate; FOnLocalCertificateSelection : TOnLocalCertificateSelectionCallback; FOnSSLHandshakeDone : TNotifyEvent; FenabledSslProtocols : System.Security.Authentication.SslProtocols; FServerCertificate : X509Certificate; FclientCertificateRequired : Boolean; FcheckCertificateRevocation : Boolean; procedure InitComponent; override; procedure SetIOHandlerValues(AIO : TIdSSLIOHandlerSocketNET); published public destructor Destroy; override; procedure Init; override; procedure Shutdown; override; function MakeClientIOHandler : TIdSSLIOHandlerSocketBase; override; // function MakeFTPSvrPort : TIdSSLIOHandlerSocketBase; override; function MakeFTPSvrPasv : TIdSSLIOHandlerSocketBase; override; function Accept(ASocket: TIdSocketHandle; AListenerThread: TIdThread; AYarn: TIdYarn): TIdIOHandler; override; published property enabledSslProtocols : System.Security.Authentication.SslProtocols read FenabledSslProtocols write FenabledSslProtocols; property ServerCertificate : X509Certificate read FServerCertificate write FServerCertificate; property clientCertificateRequired : Boolean read FclientCertificateRequired write FclientCertificateRequired; property checkCertificateRevocation : Boolean read FcheckCertificateRevocation write FcheckCertificateRevocation; property OnSSLHandshakeDone : TNotifyEvent read FOnSSLHandshakeDone write FOnSSLHandshakeDone; property OnLocalCertificateSelection : TOnLocalCertificateSelectionCallback read FOnLocalCertificateSelection write FOnLocalCertificateSelection; property OnValidatePeerCertificate : TOnValidatePeerCertificate read FOnValidatePeerCertificate write FOnValidatePeerCertificate; end; EIdSSLNetException = class(EIdException); EIdSSLCertRequiredForSvr = class(EIdSSLNetException); EIdSSLNotAuthenticated = class(EIdSSLNetException); implementation uses IdResourceStringsSSLDotNet, IdStack, SysUtils; { TIdSSLIOHandlerSocketNET } function TIdSSLIOHandlerSocketNET.Clone: TIdSSLIOHandlerSocketBase; begin Result := TIdSSLIOHandlerSocketNET.Create(nil); TIdSSLIOHandlerSocketNET(Result).FenabledSslProtocols := FenabledSslProtocols; TIdSSLIOHandlerSocketNET(Result).FOnValidatePeerCertificate := FOnValidatePeerCertificate; TIdSSLIOHandlerSocketNET(Result).FOnLocalCertificateSelection := FOnLocalCertificateSelection; TIdSSLIOHandlerSocketNET(Result).FServerCertificate := FServerCertificate; TIdSSLIOHandlerSocketNET(Result).FClientCertificates := FClientCertificates; TIdSSLIOHandlerSocketNET(Result).FOnSSLHandshakeDone := FOnSSLHandshakeDone; end; procedure TIdSSLIOHandlerSocketNET.Close; begin if Assigned(FSSL) then begin FSSL.Close; FreeAndNil(FSSL); end; inherited; end; procedure TIdSSLIOHandlerSocketNET.ConnectClient; var LPassThrough: Boolean; begin // RLebeau 1/11/07: In case a proxy is being used, pass through // any data from the base class unencrypted when setting up that // connection. We should do this anyway since SSL hasn't been // initialized yet! LPassThrough := fPassThrough; fPassThrough := True; try inherited ConnectClient; finally fPassThrough := LPassThrough; end; StartSSL; end; function TIdSSLIOHandlerSocketNET.GetCipherAlgorithm: CipherAlgorithmType; begin if Assigned(FSSL) then begin Result := FSSL.CipherAlgorithm; end else begin Result := System.Security.Authentication.CipherAlgorithmType.None; end; end; function TIdSSLIOHandlerSocketNET.GetCipherStrength: Integer; begin if Assigned(FSSL) then begin Result := FSSL.CipherStrength; end else begin Result := 0; end; end; function TIdSSLIOHandlerSocketNET.GetHashAlgorithm: HashAlgorithmType; begin if Assigned(FSSL) then begin Result := FSSL.HashAlgorithm; end else begin Result := HashAlgorithmType.None; end; end; function TIdSSLIOHandlerSocketNET.GetHashStrength: Integer; begin if Assigned(FSSL) then begin Result := FSSL.HashStrength; end else begin Result := 0; end; end; function TIdSSLIOHandlerSocketNET.GetIsEncrypted: Boolean; begin if Assigned(FSSL) then begin Result := FSSL.IsEncrypted; end else begin Result := False; end; end; function TIdSSLIOHandlerSocketNET.GetIsSigned: Boolean; begin if Assigned(FSSL) then begin Result := FSSL.IsSigned; end else begin Result := False; end; end; function TIdSSLIOHandlerSocketNET.GetKeyExchangeAlgorithm: ExchangeAlgorithmType; begin if Assigned(FSSL) then begin Result := FSSL.KeyExchangeAlgorithm; end else begin Result := ExchangeAlgorithmType.None; end; end; function TIdSSLIOHandlerSocketNET.GetKeyExchangeStrength: Integer; begin if Assigned(FSSL) then begin Result := FSSL.KeyExchangeStrength; end else begin Result := 0; end; end; function TIdSSLIOHandlerSocketNET.GetRemoteCertificate: X509Certificate; begin if Assigned(FSSL) then begin Result := FSSL.RemoteCertificate; end else begin Result := nil; end; end; function TIdSSLIOHandlerSocketNET.GetSslProtocol: SslProtocols; begin if Assigned(FSSL) then begin Result := FSSL.SslProtocol; end else begin Result := SslProtocols.None; end; end; procedure TIdSSLIOHandlerSocketNET.InitComponent; begin inherited; FenabledSslProtocols := System.Security.Authentication.SslProtocols.Default; FclientCertificateRequired := DEF_clientCertificateRequired; FcheckCertificateRevocation := DEF_checkCertificateRevocation; end; function TIdSSLIOHandlerSocketNET.LocalCertificateSelectionCallback( sender: TObject; targetHost: String; localCertificates: X509CertificateCollection; remoteCertificate: X509Certificate; acceptableIssuers: array of String): X509Certificate; var i : Integer; LIssuer : String; begin Result := nil; if Assigned(FOnLocalCertificateSelection) then begin FOnLocalCertificateSelection(Self,targetHost,localCertificates,remoteCertificate,Acceptableissuers,Result); end else begin if Assigned(acceptableIssuers) and (Length(acceptableIssuers)>0) and Assigned(localCertificates) and (localCertificates.Count > 0) then begin // Use the first certificate that is from an acceptable issuer. for I := 0 to LocalCertificates.Count -1 do begin LIssuer := LocalCertificates[i].Issuer; if (System.Array.IndexOf(acceptableIssuers, Lissuer)>-1) then begin Result := LocalCertificates[i]; Exit; end; end; end; end; if (localCertificates <> nil) and (localCertificates.Count > 0) then begin Result := localCertificates[0]; end; end; procedure TIdSSLIOHandlerSocketNET.OpenEncodedConnection; begin FSSL := System.Net.Security.SslStream.Create( System.Net.Sockets.NetworkStream.Create(FBinding.Handle,False),False, ValidatePeerCertificate,LocalCertificateSelectionCallback); if IsPeer then begin if Assigned(FServerCertificate) then begin FSSL.AuthenticateAsServer(FServerCertificate,FclientCertificateRequired,FenabledSslProtocols,FcheckCertificateRevocation); end else begin raise EIdSSLCertRequiredForSvr.Create(RSSSLNETCertificateRequired); end; end else begin if Assigned(FClientCertificates) then begin FSSL.AuthenticateAsClient(FHost,FClientCertificates,FenabledSslProtocols,True); if not FSSL.IsMutuallyAuthenticated then begin raise EIdSSLNotAuthenticated.Create(RSSSLNETNotAuthenticated); end; end else begin FSSL.AuthenticateAsClient(FHost,nil,FenabledSslProtocols,True); if not FSSL.IsAuthenticated then begin raise EIdSSLNotAuthenticated.Create(RSSSLNETNotAuthenticated); end; end; end; if Assigned(FOnSSLHandshakeDone) then begin FOnSSLHandshakeDone(Self); end; end; function TIdSSLIOHandlerSocketNET.RecvEnc(var VBuffer: TIdBytes): Integer; begin Result := FSSL.Read(VBuffer,0,Length(VBuffer)); end; function TIdSSLIOHandlerSocketNET.SendEnc(const ABuffer: TIdBytes; const AOffset, ALength: Integer): Integer; begin FSSL.Write(ABuffer,AOffset,ALength); Result := ALength; end; procedure TIdSSLIOHandlerSocketNET.SetPassThrough(const Value: Boolean); begin if fPassThrough <> Value then begin if not Value then begin if BindingAllocated then begin OpenEncodedConnection; end; end; fPassThrough := Value; end; end; procedure TIdSSLIOHandlerSocketNET.StartSSL; begin if not PassThrough then begin OpenEncodedConnection; end; end; function TIdSSLIOHandlerSocketNET.ValidatePeerCertificate(sender: TObject; certificate: X509Certificate; chain: X509Chain; sslPolicyErrors: SslPolicyErrors): Boolean; begin if Assigned(FOnValidatePeerCertificate) then begin FOnValidatePeerCertificate(sender,certificate,chain,sslPolicyErrors, Result); end else begin { This is a workaround for a quirk. If using this as a server, the validation routine may be called even though there may not be a client certificate and FclientCertificateRequired was set to false. It might be by design though. } case sslPolicyErrors of System.Net.Security.SslPolicyErrors.None : Result := True; System.Net.Security.SslPolicyErrors.RemoteCertificateNotAvailable : begin if IsPeer and (not FclientCertificateRequired) then begin Result := True; end else begin Result := False; end; end; else Result := False; end; end; end; { TIdServerIOHandlerSSLNET } function TIdServerIOHandlerSSLNET.Accept(ASocket: TIdSocketHandle; AListenerThread: TIdThread; AYarn: TIdYarn): TIdIOHandler; var LIO : TIdSSLIOHandlerSocketNET; begin LIO := TIdSSLIOHandlerSocketNET.Create(nil); LIO.PassThrough := True; LIO.IsPeer := True; LIO.Open; if LIO.Binding.Accept(ASocket.Handle) then begin SetIOHandlerValues(LIO); Result := LIO; end else begin Result := nil; FreeAndNil(LIO); end; end; destructor TIdServerIOHandlerSSLNET.Destroy; begin inherited; end; procedure TIdServerIOHandlerSSLNET.Init; begin inherited; end; procedure TIdServerIOHandlerSSLNET.InitComponent; begin inherited InitComponent; FenabledSslProtocols := System.Security.Authentication.SslProtocols.Default; FclientCertificateRequired := DEF_clientCertificateRequired; FcheckCertificateRevocation := DEF_checkCertificateRevocation; end; function TIdServerIOHandlerSSLNET.MakeClientIOHandler: TIdSSLIOHandlerSocketBase; var LIO : TIdSSLIOHandlerSocketNET; begin LIO := TIdSSLIOHandlerSocketNET.Create(nil); LIO.PassThrough := True; LIO.IsPeer := False; SetIOHandlerValues(LIO); Result := LIO; end; function TIdServerIOHandlerSSLNET.MakeFTPSvrPasv: TIdSSLIOHandlerSocketBase; var LIO : TIdSSLIOHandlerSocketNET; begin LIO := TIdSSLIOHandlerSocketNET.Create(nil); LIO.PassThrough := True; LIO.IsPeer := True; SetIOHandlerValues(LIO); Result := LIO; end; function TIdServerIOHandlerSSLNET.MakeFTPSvrPort: TIdSSLIOHandlerSocketBase; var LIO : TIdSSLIOHandlerSocketNET; begin LIO := TIdSSLIOHandlerSocketNET.Create(nil); LIO.PassThrough := True; LIO.IsPeer := True; SetIOHandlerValues(LIO); Result := LIO; end; procedure TIdServerIOHandlerSSLNET.SetIOHandlerValues( AIO: TIdSSLIOHandlerSocketNET); begin AIO.FServerCertificate := FServerCertificate; AIO.FclientCertificateRequired := FclientCertificateRequired; // AIO.FClientCertificates := FClientCertificates; AIO.FcheckCertificateRevocation := FcheckCertificateRevocation; AIO.FOnSSLHandshakeDone := FOnSSLHandshakeDone; AIO.FenabledSslProtocols := FenabledSslProtocols; AIO.FOnLocalCertificateSelection := FOnLocalCertificateSelection; AIO.FOnValidatePeerCertificate := FOnValidatePeerCertificate; end; procedure TIdServerIOHandlerSSLNET.Shutdown; begin inherited; end; initialization RegisterSSL('Indy SSL Support for Microsoft.NET 2.0','Indy Pit Crew', {do not localize} 'Copyright © 1993 - 2007'#10#13 + {do not localize} 'Chad Z. Hower (Kudzu) and the Indy Pit Crew. All rights reserved.', {do not localize} 'Open SSL Support DLL Delphi and C++Builder interface', {do not localize} 'http://www.indyproject.org/'#10#13 + {do not localize} 'Original Author - J. Peter Mugaas', {do not localize} TIdSSLIOHandlerSocketNET, TIdServerIOHandlerSSLNET); end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpPbeParametersGenerator; {$I ..\..\Include\CryptoLib.inc} interface uses ClpICipherParameters, ClpIPbeParametersGenerator, ClpCryptoLibTypes; resourcestring SEmptyPassword = 'Password can''t be empty'; SEmptySalt = 'Salt can''t be empty'; SIterationtooSmall = 'Iteration must be greater than zero.'; type /// <summary> /// base class for all Password Based Encryption (Pbe) parameter generator /// classes. /// </summary> TPbeParametersGenerator = class abstract(TInterfacedObject, IPbeParametersGenerator) strict protected var FmPassword, FmSalt: TCryptoLibByteArray; FmIterationCount: Int32; /// <returns> /// the password byte array. /// </returns> function GetPassword: TCryptoLibByteArray; virtual; /// <returns> /// the salt byte array. /// </returns> function GetSalt: TCryptoLibByteArray; virtual; /// <returns> /// the iteration count. /// </returns> function GetIterationCount: Int32; virtual; public procedure Init(const password, salt: TCryptoLibByteArray; iterationCount: Int32); virtual; /// <value> /// the password byte array. /// </value> property password: TCryptoLibByteArray read GetPassword; /// <value> /// the salt byte array. /// </value> property salt: TCryptoLibByteArray read GetSalt; /// <value> /// the iteration count. /// </value> property iterationCount: Int32 read GetIterationCount; /// <summary> /// Generate derived parameters for a key of length keySize. /// </summary> /// <param name="algorithm"> /// a parameters object representing a key. /// </param> /// <param name="keySize"> /// the length, in bits, of the key required. /// </param> /// <returns> /// a parameters object representing a key. /// </returns> function GenerateDerivedParameters(const algorithm: String; keySize: Int32) : ICipherParameters; overload; virtual; abstract; /// <summary> /// Generate derived parameters for a key of length keySize and iv /// of length ivSize. /// </summary> /// <param name="algorithm"> /// a parameters object representing a key. /// </param> /// <param name="keySize"> /// the length, in bits, of the key required. /// </param> /// <param name="ivSize"> /// the length, in bits, of the iv required. /// </param> /// <returns> /// a parameters object representing a key and an iv. /// </returns> function GenerateDerivedParameters(const algorithm: String; keySize, ivSize: Int32): ICipherParameters; overload; virtual; abstract; /// <summary> /// Generate derived parameters for a key of length keySize, /// specifically <br />for use with a MAC. /// </summary> /// <param name="keySize"> /// the length, in bits, of the key required. /// </param> /// <returns> /// a parameters object representing a key. /// </returns> function GenerateDerivedMacParameters(keySize: Int32): ICipherParameters; virtual; abstract; end; implementation { TPbeParametersGenerator } function TPbeParametersGenerator.GetIterationCount: Int32; begin result := FmIterationCount; end; function TPbeParametersGenerator.GetPassword: TCryptoLibByteArray; begin result := System.Copy(FmPassword); end; function TPbeParametersGenerator.GetSalt: TCryptoLibByteArray; begin result := System.Copy(FmSalt); end; procedure TPbeParametersGenerator.Init(const password, salt: TCryptoLibByteArray; iterationCount: Int32); begin if (password = Nil) then begin raise EArgumentNilCryptoLibException.CreateRes(@SEmptyPassword); end; if (salt = Nil) then begin raise EArgumentNilCryptoLibException.CreateRes(@SEmptySalt); end; if (iterationCount < 1) then raise EArgumentCryptoLibException.CreateRes(@SIterationtooSmall); FmPassword := System.Copy(password); FmSalt := System.Copy(salt); FmIterationCount := iterationCount; end; end.
Unit Dt_Lock; { $Id: DT_LOCK.PAS,v 1.41 2013/06/11 08:04:01 fireton Exp $ } // $Log: DT_LOCK.PAS,v $ // Revision 1.41 2013/06/11 08:04:01 fireton // - function GetLockJournalName // // Revision 1.40 2011/07/20 08:02:37 voba // - k : 236721575 // // Revision 1.39 2009/12/23 08:33:43 voba // - bug fix : проблемы с захватом семейства (таблица ctrl) // // Revision 1.38 2009/11/20 13:43:21 voba // - bug fix: Tl3BuuferedFilter не корректно работает в режиме почитали, пописали, почитали. Пришлось сделать в DT_Jour собственную буфферизацию // // Revision 1.37 2009/11/18 10:17:25 voba // - opt. // // Revision 1.36 2009/06/23 07:32:59 voba // - стандартизация доступа к атрибутам // // Revision 1.35 2009/03/02 08:24:50 voba // - заменил function FamTblName и MainTblName на одну TblName с указанием Family // - заменил две verload function TablePassword на одну с указанием Family // // Revision 1.34 2008/12/17 11:10:39 voba // - bug fix откручена проверка прав на удаления при залочке // // Revision 1.33 2008/03/20 09:48:36 lulin // - cleanup. // // Revision 1.32 2008/02/22 16:57:41 lulin // - упорядочиваем примеси. // // Revision 1.31 2008/02/07 14:44:41 lulin // - класс _Tl3LongintList переехал в собственный модуль. // // Revision 1.30 2007/12/18 08:42:54 fireton // - пакетный захват (и отпускание) документов // // Revision 1.29 2007/11/22 14:38:58 fireton // - приводим информацию о всех пользователей, захвативших документ // // Revision 1.28 2007/08/28 14:42:02 narry // - range check error // // Revision 1.27 2007/08/14 20:25:14 lulin // - bug fix: не собиралася Архивариус. // // Revision 1.26 2007/07/25 11:07:47 narry // - возврат номера пользователя, захватившего документ // // Revision 1.25 2007/07/24 12:32:33 narry // - рефакторинг системы сообщений // // Revision 1.24 2007/04/25 07:52:37 fireton // - Рефакторинг. Уходим от прямых упоминаний имен таблиц в пользу перечислимых типов в DT_Types // // Revision 1.23 2007/03/26 09:34:03 fireton // - изменился формат l3System.FreeLocalMem // // Revision 1.22 2006/11/16 10:48:31 fireton // - подготовка к большому UserID // // Revision 1.21 2006/06/23 11:20:59 narry // -merge // // Revision 1.20.22.1 2006/06/19 09:09:54 voba // - add func LinkServer.GetSelfMask // // Revision 1.20 2005/10/17 11:29:54 voba // no message // // Revision 1.19 2004/09/21 12:04:20 lulin // - Release заменил на Cleanup. // // Revision 1.18 2004/09/14 15:58:14 lulin // - удален модуль Str_Man - используйте вместо него - l3String. // // Revision 1.17 2004/08/03 08:52:51 step // замена dt_def.pas на DtDefine.inc // // Revision 1.16 2004/06/22 13:55:39 step // изменен тип выбрасываемого исключения в TLockServer.FullLockDoc // // Revision 1.15 2004/05/18 09:51:46 step // change: GlobalHTServer.MaxFamilyID --> GlobalHTServer.FamilyTbl.MaxFamilyID; // // Revision 1.14 2004/05/18 09:12:46 step // change: GlobalFamPaths[] --> GlobalHtServer.FamilyTbl.FamilyPath() // // Revision 1.13 2003/10/02 13:54:42 voba // - new method: PreventLockDoc // // Revision 1.12 2003/06/23 14:26:59 voba // - переписал TLockServer.LockDoc, некорректно работала из-за раделения прав на гиперссылки, метки и блоки // // Revision 1.11 2003/04/16 09:17:03 voba // - bug fix: неправильно тестировался флаг acfDelete. // // Revision 1.10 2003/01/21 11:27:13 demon // - new behavior: процедура LockDoc теперь не позволяет захватить документ // при получении 0 эффективной (LockMask) или разрешенной (MaxMask) маски прав. // // Revision 1.9 2001/09/17 06:52:17 demon // - byg fix: before unlock family all other tbls now closed, and after unlock all opened // // Revision 1.8 2000/12/15 15:36:16 law // - вставлены директивы Log. // {$I DtDefine.inc} Interface uses l3Base, l3String, l3LongintList, Dt_Types, Dt_Jour, Dt_Sab; Type TLockRec = Record Journal: TAbstractJournal; Count : LongInt; end; PFamilyLocks = ^TFamilyLocks; TFamilyLocks = Array[0..$fff] of TLockRec; TLockServer = Class(Tl3Base) protected Locks : PFamilyLocks; Function CompareSysData(Var OldSysData,NewSysData) : Boolean; Procedure OpenJournal(aFamily : TFamilyID); Procedure Cleanup; override; public Constructor Create; {$IfDef Win32} Reintroduce; {$endIf Win32} procedure BatchLockDoc(aFamily: TFamilyID; aDocList: ISab; aRightsNeeded: Longint; var theLockHandles: Tl3LongintList; var theAcceptedDocs, theRejectedDocs: ISab); procedure BatchUnlockDoc(aFamily: TFamilyID; aLockHandles: Tl3LongintList); Procedure OptimizeMem; Procedure ReallocLocks(NewMaxFamId : TFamilyID); Procedure DelFamilyLocks(aFamily : TFamilyID); Procedure InitFamilyLocks(aFamily : TFamilyID); Function LockDoc(aFamily : TFamilyID; aDocID : TDocID; Var MaxMask,LockMask : LongInt) : TJLHandle; function LockDocByMask(aFamily : TFamilyID; aDocID : TDocID; aMaxMask : LongInt; var aLockMask : LongInt) : TJLHandle; Function FullLockDoc(aFamily : TFamilyID; aDocID : TDocID) : TJLHandle; function PreventLockDoc(aFamily : TFamilyID; aDocID : TDocID) : TJLHandle; {* - Залочка для предотвращения захвата документа с другого компьютера. В случае если документ был захвачен с другого компьютера возвращает -1. Для повторного захвата с текущей станции прозрачна.} Procedure UnLockDoc(aFamily : TFamilyID; aLockHandle : TJLHandle); Function LockFamily(aFamily : TFamilyID) : boolean; Procedure UnLockFamily(aFamily : TFamilyID); procedure WhoLockDoc(aFamily : TFamilyID; aDocID : TDocID; var Stations : TStationNameArray; var UserIDs : TUserIDArray; aIgnoredLockHandle : TJLHandle = -1); end; const LockServer : TLockServer = Nil; function GetLockJournalName(const aFamily: TFamilyID): string; Implementation uses HT_Dll, HT_Const, l3Bits, l3RecList, Dt_Const, Dt_Doc, Dt_Serv, Dt_err, SysUtils, Dt_LinkServ ; const JourPrefix = 'LOCK'; Constructor TLockServer.Create; Begin Inherited Create(Nil); l3System.GetLocalMem(Locks,(GlobalHtServer.FamilyTbl.MaxFamilyID+1)*SizeOf(TLockRec)); l3FillChar(Locks^,(GlobalHtServer.FamilyTbl.MaxFamilyID+1)*SizeOf(TLockRec)); end; procedure TLockServer.BatchLockDoc(aFamily: TFamilyID; aDocList: ISab; aRightsNeeded: Longint; var theLockHandles: Tl3LongintList; var theAcceptedDocs, theRejectedDocs: ISab); var l_RejCursor: ISabCursor; l_AccCursor: ISabCursor; procedure AddToRejected(aID: TDocID); var l_ID : TDocID; begin l_ID := aID; if theRejectedDocs <> nil then l_RejCursor.AddItem(@l_ID) else begin theRejectedDocs := MakeValueSet(aDocList.Table, fId_Fld, @l_ID, 1); l_RejCursor := theRejectedDocs.MakeSabCursor([fID_Fld], cmForward); end; end; procedure AddToAccepted(aID: TDocID); var l_ID : TDocID; begin l_ID := aID; if theAcceptedDocs <> nil then l_AccCursor.AddItem(@l_ID) else begin theAcceptedDocs := MakeValueSet(aDocList.Table, fId_Fld, @l_ID, 1); l_AccCursor := theAcceptedDocs.MakeSabCursor([fID_Fld], cmForward); end; end; function l_Iterator(aRec : Pointer): Boolean; register; var l_DocID : TDocID; l_LockHandle: TJLHandle; l_MaxMask, l_LockMask : LongInt; begin Result := True; l_DocID := TDocID(aRec^); l_LockHandle := LockDoc(aFamily, l_DocID, l_MaxMask, l_LockMask); if l_LockHandle < 0 then begin AddToRejected(l_DocID); Exit; end; if not l3TestMask(l_LockMask, aRightsNeeded) then begin UnLockDoc(aFamily, l_LockHandle); AddToRejected(l_DocID); Exit; end; theLockHandles.Add(l_LockHandle); AddToAccepted(l_DocID); end; var l_Proc : TdtRecAccessProc; begin theLockHandles.Clear; theRejectedDocs := nil; theAcceptedDocs := nil; l_Proc := L2RecAccessProc(@l_Iterator); try aDocList.IterateRecords(l_Proc, [fId_Fld]); finally FreeRecAccessProc(l_Proc); end; end; procedure TLockServer.BatchUnlockDoc(aFamily: TFamilyID; aLockHandles: Tl3LongintList); function l_Iterator(Data: Pointer; Index: Longint): Boolean; register; begin UnLockDoc(aFamily, TJLHandle(Data^)); Result := True; end; begin aLockHandles.IterateAllF(l3L2IA(@l_Iterator)); end; Procedure TLockServer.Cleanup; Var I : TFamilyID; Begin For I:=0 to GlobalHtServer.FamilyTbl.MaxFamilyID do If Locks^[I].Journal<>Nil then l3Free(Locks^[I].Journal); l3System.FreeLocalMem(Locks); Inherited; end; Function TLockServer.CompareSysData(Var OldSysData,NewSysData) : Boolean; Begin If LongInt(OldSysData) = acFullBlock then Begin Result:=True; LongInt(NewSysData):=0; exit; end; LongInt(NewSysData):=Not LongInt(OldSysData) and LongInt(NewSysData); Result:=(LongInt(NewSysData)=0); end; Procedure TLockServer.OptimizeMem; Var I : TFamilyID; Begin For I:=0 to GlobalHtServer.FamilyTbl.MaxFamilyID do If (Locks^[I].Count=0) and (Locks^[I].Journal<>Nil) then l3Free(Locks^[I].Journal); end; Procedure TLockServer.ReallocLocks(NewMaxFamId : TFamilyID); Begin l3System.ReAllocLocalMem(Locks,(NewMaxFAmID+1)*SizeOf(TLockRec)); end; Procedure TLockServer.DelFamilyLocks(aFamily : TFamilyID); Begin If Assigned(Locks^[aFamily].Journal) then l3Free(Locks^[aFamily].Journal); Locks^[aFamily].Count:=0 end; function GetLockJournalName(const aFamily: TFamilyID): string; begin if aFamily = MainTblsFamily then Result := GlobalHtServer.FamilyTbl.FamilyPath(aFamily)+JourPrefix+'.jor' else Result := GlobalHtServer.FamilyTbl.FamilyPath(aFamily)+JourPrefix+IntToHex(aFamily,3)+'.jor'; end; Procedure TLockServer.OpenJournal(aFamily : TFamilyID); Var CurName : ShortString; Begin CurName := GetLockJournalName(aFamily); Locks^[aFamily].Journal:=TAbstractJournal.Create(GlobalHtServer.CurStationName, CurName); Locks^[aFamily].Journal.CompareSysData:=CompareSysData; end; procedure TLockServer.InitFamilyLocks(aFamily : TFamilyID); begin if Locks^[aFamily].Journal = nil then OpenJournal(aFamily); end; function TLockServer.LockDoc(aFamily : TFamilyID;aDocID : TDocID; var MaxMask,LockMask : LongInt) : TJLHandle; begin (* Получение максимальной маски прав для данного aDocID *) MaxMask := LinkServer(aFamily).GetMask(aDocID); Result := LockDocByMask(aFamily, aDocID, MaxMask, LockMask); end; function TLockServer.LockDocByMask(aFamily : TFamilyID; aDocID : TDocID; aMaxMask : LongInt; var aLockMask : LongInt) : TJLHandle; var lSaveLockMask : Longint; begin Result := -1; if Locks^[aFamily].Journal = nil then OpenJournal(aFamily); (* Дополнение маски прав до непротиворечивого состояния *) if (aMaxMask and acgTextDependMask <> 0) then aLockMask := aMaxMask or acgTextDependMask else aLockMask := aMaxMask; if aLockMask = 0 then Exit; (* Попытка захвата документа с заданной маской прав *) Result := Locks^[aFamily].Journal.Lock(aDocID, aLockMask); lSaveLockMask := aLockMask; if (Result = -1) then Exit; (* если не удалось захватить все права, связанные с редактированием текста, то срезаем остальные*) if (aLockMask and acgTextDependMask <> acgTextDependMask) then aLockMask := aLockMask and not acgTextDependMask; (* восстанавливаем разрешенный объем прав *) aLockMask := aLockMask and aMaxMask; (* Освобождение захваченного документа, если маска после захвата получилась равной 0 *) if (aLockMask = 0) then begin Locks^[aFamily].Journal.UnLock(Result); Result := -1; end else if lSaveLockMask <> aLockMask then (*корректируем объем захваченных прав*) Locks^[aFamily].Journal.SetNewSysData(Result, aLockMask); end; Function TLockServer.FullLockDoc(aFamily : TFamilyID; aDocID : TDocID) : TJLHandle; var CurMask : LongInt; begin Result:=-1; if Locks^[aFamily].Journal=nil then OpenJournal(aFamily); CurMask:=LinkServer(aFamily).GetSelfMask; CurMask:=acFullBlock; try Result:=Locks^[aFamily].Journal.Lock(aDocID,CurMask,dtlExclusive); if Result<>-1 then Inc(Locks^[aFamily].Count); except Result:=-1; end; end; function TLockServer.PreventLockDoc(aFamily : TFamilyID; aDocID : TDocID) : TJLHandle; var lCurMask : longint; begin Result := -1; if Locks^[aFamily].Journal=nil then OpenJournal(aFamily); lCurMask := acFullBlock; try Result := Locks^[aFamily].Journal.Lock(aDocID, lCurMask, dtlPrevent); if Result <> -1 then Inc(Locks^[aFamily].Count); except Result := -1; end; end; Procedure TLockServer.UnLockDoc(aFamily : TFamilyID;aLockHandle : TJLHandle); Begin If aLockHandle > 0 then begin Locks^[aFamily].Journal.UnLock(aLockHandle); If Locks^[aFamily].Count<>0 then Dec(Locks^[aFamily].Count); end; end; Function TLockServer.LockFamily(aFamily : TFamilyID) : boolean; begin if aFamily = MainTblsFamily then Result := GlobalHtServer.LockAll else begin GlobalHtServer.CloseAllTbls(aFamily); try try GlobalHtServer.Family[aFamily].Lock(TAB_PRIVATE); Result := True; except Result := false; end; finally GlobalHtServer.OpenClosedTbls; end; end; end; procedure TLockServer.UnLockFamily(aFamily : TFamilyID); begin if aFamily = MainTblsFamily then GlobalHtServer.UnLockAll else begin GlobalHtServer.CloseAllTbls(aFamily); try GlobalHtServer.Family[aFamily].Unlock; finally GlobalHtServer.OpenClosedTbls; end; end; end; procedure TLockServer.WhoLockDoc(aFamily : TFamilyID;aDocID : TDocID; var Stations : TStationNameArray; var UserIDs : TUserIDArray; aIgnoredLockHandle : TJLHandle = -1); var l_LockList : Tl3RecList;//of TJourRec I: Integer; begin Stations := nil; UserIDs := nil; if Locks^[aFamily].Journal = nil then OpenJournal(aFamily); l_LockList := Tl3RecList.Create(SizeOf(TJourRec)); try if Locks^[aFamily].Journal.CheckLock(aDocID, l_LockList,aIgnoredLockHandle) then begin SetLength(Stations, l_LockList.Count); SetLength(UserIDs, l_LockList.Count); for I := 0 to Pred(l_LockList.Count) do begin Stations[I]:=l3ArrayToString(PJourRec(l_LockList.ItemSlot(I)).rStationName, SizeOf(TStationID)); // Придется пока считать, что все пользователи без исключения в качестве имени станции используют свой номер в Hex UserIDs[I]:= StrToIntDef('$'+Stations[I], 0); end; end; finally l3Free(l_LockList); end; end; end.
(*-------------------------------------------------------------*) (* Neuhold Michael *) (* Some initial tests with standard Function *) (*-------------------------------------------------------------*) PROGRAM TestStdFunction; FUNCTION Power(x, y: REAL): REAL; BEGIN Power := Exp(Ln(x)*y); END; BEGIN WriteLn('Round');(* banker's rounding to the next even Integer *) WriteLn('Round(2.49) = ', Round (2.49)); WriteLn('Round(2.5) = ', Round (2.5)); WriteLn('Round(2.51) = ', Round (2.51)); WriteLn; WriteLn('Round(2.49) = ', Round (3.49)); WriteLn('Round(2.5) = ', Round (3.5)); WriteLn('Round(2.51) = ', Round (3.51)); WriteLn; WriteLn('Trunc(3,51) = ', Trunc(3.51)); WriteLn('Int(3,51) = ', Int(3.51)); WriteLn('Frac(3,51) = ', Frac(3.51)); WriteLn; WriteLn('Power(3.5, 2.71) = ', Power(3.5, 2.71)); WriteLn('Odd(3) = ', Odd(3)); END.
unit TestFramework.DataValidators.TestTCurrencyDataValidator; interface uses TestFramework, System.SysUtils, System.Variants, Interfaces.IDataValidator, DataValidators.TCurrencyDataValidator; type TestTCurrencyDataValidator = class(TTestCase) strict private FCurrencyDataValidator: IDataValidator; public procedure SetUp; override; procedure TearDown; override; published procedure TestParse_Currency; procedure TestParse_StringCurrency_Valid; procedure TestParse_StringCurrency_Invalid; end; implementation procedure TestTCurrencyDataValidator.SetUp; begin FCurrencyDataValidator := TCurrencyDataValidator.Create; end; procedure TestTCurrencyDataValidator.TearDown; begin end; procedure TestTCurrencyDataValidator.TestParse_Currency; var ReturnValue: Boolean; AValue: Variant; begin AValue := 2450.70; ReturnValue := FCurrencyDataValidator.Parse(AValue); Check(ReturnValue = True); end; procedure TestTCurrencyDataValidator.TestParse_StringCurrency_Invalid; var ReturnValue: Boolean; AValue: Variant; begin AValue := '12,50.44'; ReturnValue := FCurrencyDataValidator.Parse(AValue); Check(ReturnValue = False); end; procedure TestTCurrencyDataValidator.TestParse_StringCurrency_Valid; var ReturnValue: Boolean; AValue: Variant; begin AValue := '1250.44'; ReturnValue := FCurrencyDataValidator.Parse(AValue); Check(ReturnValue = True); end; initialization // Register any test cases with the test runner RegisterTest(TestTCurrencyDataValidator.Suite); end.
unit TextEditorVisitorPrim; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "TestFormsTest" // Автор: Люлин А.В. // Модуль: "w:/common/components/gui/Garant/Daily/TextEditorVisitorPrim.pas" // Начат: 07.05.2010 17:42 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<TestCase::Class>> Shared Delphi Operations For Tests::TestFormsTest::Everest::TTextEditorVisitorPrim // // Тест, работающий с текстом документа через редактор, но не изменяющий его // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! interface {$If defined(nsTest) AND not defined(NoVCM)} uses TextViaEditorProcessorPrim, PrimTextLoad_Form ; {$IfEnd} //nsTest AND not NoVCM {$If defined(nsTest) AND not defined(NoVCM)} type TTextEditorVisitorPrim = {abstract} class(TTextViaEditorProcessorPrim) {* Тест, работающий с текстом документа через редактор, но не изменяющий его } protected // overridden protected methods function GetFolder: AnsiString; override; {* Папка в которую входит тест } function GetModelElementGUID: AnsiString; override; {* Идентификатор элемента модели, который описывает тест } protected // protected methods procedure VisitText(const aStr: AnsiString = 'Load'); {* Собственно процедура обработки текста } procedure DoVisit(aForm: TPrimTextLoadForm); virtual; abstract; {* Обработать текст } function TreatExceptionAsSuccess: Boolean; virtual; end;//TTextEditorVisitorPrim {$IfEnd} //nsTest AND not NoVCM implementation {$If defined(nsTest) AND not defined(NoVCM)} uses l3Base, k2OperationContainer, TestFrameWork ; {$IfEnd} //nsTest AND not NoVCM {$If defined(nsTest) AND not defined(NoVCM)} // start class TTextEditorVisitorPrim procedure TTextEditorVisitorPrim.VisitText(const aStr: AnsiString = 'Load'); //#UC START# *4BE4196E0367_4BE418BB001F_var* var l_F : _FormClass_; l_Raise : Boolean; l_DisableLog : Boolean; //#UC END# *4BE4196E0367_4BE418BB001F_var* begin //#UC START# *4BE4196E0367_4BE418BB001F_impl* l_F := MakeForm; try l_F.Show; l_Raise := TreatExceptionAsSuccess; l_DisableLog := l_Raise; if l_DisableLog then l3System.DisableExceptionToLog; try Load(l_F, KPage + '.evd', aStr); try try DoVisit(l_F); finally Check(not Tk2OperationContainer.CheckWasExceptionInFreeInOwner); end;//try..finally except if l_Raise then {l_Raise := false} Exit // - чтобы не пропустить ситуацию, когда тест вдруг стал проходить else raise; end;//try..except finally if l_DisableLog then l3System.EnableExceptionToLog; end;//try..finally Check(not l_Raise, 'Тест проходить не должен, т.к. текст не влезает в бумагу'); finally l_F.Free; end;//try..finally //#UC END# *4BE4196E0367_4BE418BB001F_impl* end;//TTextEditorVisitorPrim.VisitText function TTextEditorVisitorPrim.TreatExceptionAsSuccess: Boolean; //#UC START# *4BFD1B5A0200_4BE418BB001F_var* //#UC END# *4BFD1B5A0200_4BE418BB001F_var* begin //#UC START# *4BFD1B5A0200_4BE418BB001F_impl* Result := false; //#UC END# *4BFD1B5A0200_4BE418BB001F_impl* end;//TTextEditorVisitorPrim.TreatExceptionAsSuccess function TTextEditorVisitorPrim.GetFolder: AnsiString; {-} begin Result := 'Everest'; end;//TTextEditorVisitorPrim.GetFolder function TTextEditorVisitorPrim.GetModelElementGUID: AnsiString; {-} begin Result := '4BE418BB001F'; end;//TTextEditorVisitorPrim.GetModelElementGUID {$IfEnd} //nsTest AND not NoVCM end.
unit uMinPrioQueue; {$MODE OBJFPC} {$ModeSwitch advancedrecords} interface uses SysUtils; type TIntegerArray = Array of Integer; TNode = record name, idx, key: Integer; edges: TIntegerArray; procedure Init(const aName: Integer; const aEdges: TIntegerArray); end; TNodeArray = Array of TNode; TMinPrioQueue = class(TObject) private nodes: TNodeArray; len, size: Integer; procedure Swap(x, y: Integer); function Parent(i: Integer): Integer; function Left(i: Integer): Integer; function Right(i: Integer): Integer; procedure Heapify(i: Integer); public constructor Create; procedure Insert(node: TNode; key: Integer); procedure DecreaseKey(node: TNode; key: Integer); function GetMin: TNode; end; implementation procedure TNode.Init(const aName: Integer; const aEdges: TIntegerArray); begin name := aName; idx := -1; key := MAXINT; edges := aEdges; end; { The first element of nodes is nodes[1]!! For Left and Right methods to work we leave a position unoccupied } constructor TMinPrioQueue.Create; begin len := 0; size := 1; end; function TMinPrioQueue.Parent(i: Integer): Integer; begin Result := i div 2; end; function TMinPrioQueue.Left(i: Integer): Integer; begin Result := 2 * i; end; function TMinPrioQueue.Right(i: Integer): Integer; begin Result := 2 * i + 1; end; procedure TMinPrioQueue.Swap(x, y: Integer); var tmp: TNode; begin tmp := nodes[x]; nodes[x] := nodes[y]; nodes[y] := tmp; nodes[x].idx := x; nodes[y].idx := y; end; procedure TMinPrioQueue.DecreaseKey(node: TNode; key: Integer); begin if key > nodes[node.idx].key then raise Exception.Create('DecreaseKey: new priority is larger than current one'); nodes[node.idx].key := key; (* While the parent has less priority exchange the node with it's parent *) while (node.idx > 1) and (nodes[Parent(node.idx)].key > nodes[node.idx].key) do Swap(node.idx, Parent(node.idx)); end; procedure TMinPrioQueue.Insert(node: TNode; key: Integer); begin len := len + 1; if (len >= size) then size := size * 2; SetLength(nodes, size); node.idx := len; nodes[len] := node; DecreaseKey(node, key); end; procedure TMinPrioQueue.Heapify(i: Integer); var smallest: Integer; begin if (Left(i) <= len) and (nodes[Left(i)].key < nodes[i].key) then smallest := Left(i) else smallest := i; if (Right(i) <= Len) and (nodes[Right(i)].key < nodes[i].key) then smallest := Right(i); if smallest <> i then begin Swap(i, smallest); Heapify(smallest); end; end; function TMinPrioQueue.GetMin: TNode; var min: TNode; begin if len < 1 then raise Exception.Create('GetMin: heap underflow'); min := nodes[1]; nodes[1] := nodes[len]; len := len - 1; if (len < size div 2) then size := size div 2; SetLength(Nodes, size); Heapify(1); Result := min; end; BEGIN END.
{ RxTimeEdit unit Copyright (C) 2005-2010 Lagunov Aleksey alexs@yandex.ru and Lazarus team original conception from rx library for Delphi (c) 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 with the following modification: As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules,and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your 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. } unit RxTimeEdit; {$I rx.inc} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, rxspin, MaskEdit, LMessages, LCLType; type { TCustomRxTimeEdit } TCustomRxTimeEdit = class(TCustomMaskEdit) private FButton: TRxSpinButton; FButtonNeedsFocus: Boolean; FOnButtonClick : TNotifyEvent; procedure CheckButtonVisible; function GetButtonHint: TTranslateString; function GetTime: TTime; procedure SetButtonHint(const AValue: TTranslateString); procedure SetButtonNeedsFocus(const AValue: Boolean); procedure SetTime(const AValue: TTime); procedure DoChangeValue(AValue:integer); procedure WMSetFocus(var Message: TLMSetFocus); message LM_SETFOCUS; procedure WMKillFocus(var Message: TLMKillFocus); message LM_KILLFOCUS; protected procedure SetParent(AParent: TWinControl); override; procedure DoPositionButton; virtual; procedure UpClick(Sender: TObject); virtual; procedure DownClick(Sender: TObject); virtual; property ButtonOnlyWhenFocused: Boolean read FButtonNeedsFocus write SetButtonNeedsFocus default False; property OnButtonClick : TNotifyEvent read FOnButtonClick write FOnButtonClick; property ButtonHint: TTranslateString read GetButtonHint write SetButtonHint; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Time:TTime read GetTime write SetTime; end; type TRxTimeEdit = class(TCustomRxTimeEdit) published property AutoSize; property AutoSelect; property Align; property Anchors; property BorderSpacing; property ButtonOnlyWhenFocused; property ButtonHint; property CharCase; property Color; // property DirectInput; property DragCursor; property DragMode; property EchoMode; property Enabled; // property Flat; property Font; // property Glyph; property MaxLength; // property NumGlyphs; property OnButtonClick; property OnChange; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEditingDone; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnMouseWheel; property OnMouseWheelDown; property OnMouseWheelUp; property OnStartDrag; property OnUTF8KeyPress; property ParentColor; property ParentFont; property ParentShowHint; property PasswordChar; property PopupMenu; property ReadOnly; property ShowHint; property TabOrder; property TabStop; property Text; property Visible; end; implementation { TCustomRxTimeEdit } procedure TCustomRxTimeEdit.CheckButtonVisible; begin If Assigned(FButton) then FButton.Visible:=(csdesigning in ComponentState) or (Visible and (Focused or not FButtonNeedsFocus)); end; function TCustomRxTimeEdit.GetButtonHint: TTranslateString; begin Result:=FButton.Hint; end; function TCustomRxTimeEdit.GetTime: TTime; begin Result:=StrToTimeDef(Text, 0); end; procedure TCustomRxTimeEdit.SetButtonHint(const AValue: TTranslateString); begin if AValue = '' then FButton.Hint:=Hint else FButton.Hint:=AValue; end; procedure TCustomRxTimeEdit.SetButtonNeedsFocus(const AValue: Boolean); begin if FButtonNeedsFocus<>AValue then begin FButtonNeedsFocus:=AValue; CheckButtonVisible; end; end; procedure TCustomRxTimeEdit.SetTime(const AValue: TTime); begin Text:=TimeToStr(AValue); end; procedure TCustomRxTimeEdit.DoChangeValue(AValue: integer); var S:ShortString; H1, M2, S3:Integer; i,p:integer; procedure IncHour; begin H1:=H1+AValue; if H1>23 then H1:=0 else if H1<0 then H1:=23; end; procedure IncMin; begin M2:=M2+AValue; if M2>59 then M2:=0 else if M2<0 then M2:=59 else exit; IncHour; end; procedure IncSec; begin S3:=S3+AValue; if S3>59 then S3:=0 else if S3<0 then S3:=59 else exit; IncMin; end; begin S:=Text; for i:=1 to Length(S) do if S[i]=' ' then S[i]:='0'; H1:=StrToInt(S[1]+S[2]); M2:=StrToInt(S[4]+S[5]); S3:=StrToInt(S[7]+S[8]); P:=GetSelStart; if P < 3 then IncHour else if P < 6 then IncMin else IncSec; Text:=Format('%2.2d'+ DefaultFormatSettings.TimeSeparator +'%2.2d'+ DefaultFormatSettings.TimeSeparator +'%2.2d', [H1, M2, S3]); SetSelStart(P); end; procedure TCustomRxTimeEdit.WMSetFocus(var Message: TLMSetFocus); begin FButton.Visible:=True; inherited; end; procedure TCustomRxTimeEdit.WMKillFocus(var Message: TLMKillFocus); begin if FButtonNeedsFocus then FButton.Visible:=False; inherited; end; procedure TCustomRxTimeEdit.SetParent(AParent: TWinControl); begin inherited SetParent(AParent); if FButton <> nil then begin DoPositionButton; CheckButtonVisible; end; end; procedure TCustomRxTimeEdit.DoPositionButton; begin if FButton = nil then exit; FButton.Parent := Parent; FButton.Visible := Visible; FButton.AnchorToCompanion(akLeft,0,Self); // if FButton.Width = 0 then FButton.Width:=26;//Height; end; procedure TCustomRxTimeEdit.UpClick(Sender: TObject); begin if not ReadOnly then begin DoChangeValue(1); if Assigned(FOnButtonClick) then FOnButtonClick(Self); end; end; procedure TCustomRxTimeEdit.DownClick(Sender: TObject); begin if not ReadOnly then begin DoChangeValue(-1); if Assigned(FOnButtonClick) then FOnButtonClick(Self); end; end; constructor TCustomRxTimeEdit.Create(AOwner: TComponent); begin inherited Create(AOwner); FButton := TRxSpinButton.Create(Self); FButton.FocusControl := Self; FButton.Width := Self.Height; FButton.Height := Self.Height; FButton.FreeNotification(Self); FButton.ControlStyle := FButton.ControlStyle + [csNoDesignSelectable]; FButton.OnTopClick := @UpClick; FButton.OnBottomClick := @DownClick; EditMask:='!#0'+DefaultFormatSettings.TimeSeparator + '00'+DefaultFormatSettings.TimeSeparator + '00;1;_'; end; destructor TCustomRxTimeEdit.Destroy; begin if FButton <> nil then FreeAndNil(FButton); inherited Destroy; end; end.
unit DocNumberQueryKeywordsPack; {* Набор слов словаря для доступа к экземплярам контролов формы DocNumberQuery } // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\Document\DocNumberQueryKeywordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "DocNumberQueryKeywordsPack" MUID: (A40358DFC617) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)} uses l3IntfUses , vtLabel {$If Defined(Nemesis)} , nscComboBox {$IfEnd} // Defined(Nemesis) , vtCheckBox ; {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) implementation {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)} uses l3ImplUses , DocNumberQuery_Form , tfwControlString {$If NOT Defined(NoVCL)} , kwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) , tfwScriptingInterfaces , tfwPropertyLike , TypInfo , tfwTypeInfo , TtfwClassRef_Proxy , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes ; type Tkw_Form_DocNumberQuery = {final} class(TtfwControlString) {* Слово словаря для идентификатора формы DocNumberQuery ---- *Пример использования*: [code] 'aControl' форма::DocNumberQuery TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Form_DocNumberQuery Tkw_DocNumberQuery_Control_Label1 = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола Label1 ---- *Пример использования*: [code] контрол::Label1 TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_DocNumberQuery_Control_Label1 Tkw_DocNumberQuery_Control_Label1_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола Label1 ---- *Пример использования*: [code] контрол::Label1:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_DocNumberQuery_Control_Label1_Push Tkw_DocNumberQuery_Control_edNumber = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола edNumber ---- *Пример использования*: [code] контрол::edNumber TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_DocNumberQuery_Control_edNumber Tkw_DocNumberQuery_Control_edNumber_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола edNumber ---- *Пример использования*: [code] контрол::edNumber:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_DocNumberQuery_Control_edNumber_Push Tkw_DocNumberQuery_Control_cbInternal = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола cbInternal ---- *Пример использования*: [code] контрол::cbInternal TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_DocNumberQuery_Control_cbInternal Tkw_DocNumberQuery_Control_cbInternal_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола cbInternal ---- *Пример использования*: [code] контрол::cbInternal:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_DocNumberQuery_Control_cbInternal_Push TkwDocNumberQueryFormLabel1 = {final} class(TtfwPropertyLike) {* Слово скрипта .TDocNumberQueryForm.Label1 } private function Label1(const aCtx: TtfwContext; aDocNumberQueryForm: TDocNumberQueryForm): TvtLabel; {* Реализация слова скрипта .TDocNumberQueryForm.Label1 } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwDocNumberQueryFormLabel1 TkwDocNumberQueryFormEdNumber = {final} class(TtfwPropertyLike) {* Слово скрипта .TDocNumberQueryForm.edNumber } private function edNumber(const aCtx: TtfwContext; aDocNumberQueryForm: TDocNumberQueryForm): TnscComboBox; {* Реализация слова скрипта .TDocNumberQueryForm.edNumber } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwDocNumberQueryFormEdNumber TkwDocNumberQueryFormCbInternal = {final} class(TtfwPropertyLike) {* Слово скрипта .TDocNumberQueryForm.cbInternal } private function cbInternal(const aCtx: TtfwContext; aDocNumberQueryForm: TDocNumberQueryForm): TvtCheckBox; {* Реализация слова скрипта .TDocNumberQueryForm.cbInternal } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwDocNumberQueryFormCbInternal function Tkw_Form_DocNumberQuery.GetString: AnsiString; begin Result := 'DocNumberQueryForm'; end;//Tkw_Form_DocNumberQuery.GetString class function Tkw_Form_DocNumberQuery.GetWordNameForRegister: AnsiString; begin Result := 'форма::DocNumberQuery'; end;//Tkw_Form_DocNumberQuery.GetWordNameForRegister function Tkw_DocNumberQuery_Control_Label1.GetString: AnsiString; begin Result := 'Label1'; end;//Tkw_DocNumberQuery_Control_Label1.GetString class procedure Tkw_DocNumberQuery_Control_Label1.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtLabel); end;//Tkw_DocNumberQuery_Control_Label1.RegisterInEngine class function Tkw_DocNumberQuery_Control_Label1.GetWordNameForRegister: AnsiString; begin Result := 'контрол::Label1'; end;//Tkw_DocNumberQuery_Control_Label1.GetWordNameForRegister procedure Tkw_DocNumberQuery_Control_Label1_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('Label1'); inherited; end;//Tkw_DocNumberQuery_Control_Label1_Push.DoDoIt class function Tkw_DocNumberQuery_Control_Label1_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::Label1:push'; end;//Tkw_DocNumberQuery_Control_Label1_Push.GetWordNameForRegister function Tkw_DocNumberQuery_Control_edNumber.GetString: AnsiString; begin Result := 'edNumber'; end;//Tkw_DocNumberQuery_Control_edNumber.GetString class procedure Tkw_DocNumberQuery_Control_edNumber.RegisterInEngine; begin inherited; TtfwClassRef.Register(TnscComboBox); end;//Tkw_DocNumberQuery_Control_edNumber.RegisterInEngine class function Tkw_DocNumberQuery_Control_edNumber.GetWordNameForRegister: AnsiString; begin Result := 'контрол::edNumber'; end;//Tkw_DocNumberQuery_Control_edNumber.GetWordNameForRegister procedure Tkw_DocNumberQuery_Control_edNumber_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('edNumber'); inherited; end;//Tkw_DocNumberQuery_Control_edNumber_Push.DoDoIt class function Tkw_DocNumberQuery_Control_edNumber_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::edNumber:push'; end;//Tkw_DocNumberQuery_Control_edNumber_Push.GetWordNameForRegister function Tkw_DocNumberQuery_Control_cbInternal.GetString: AnsiString; begin Result := 'cbInternal'; end;//Tkw_DocNumberQuery_Control_cbInternal.GetString class procedure Tkw_DocNumberQuery_Control_cbInternal.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtCheckBox); end;//Tkw_DocNumberQuery_Control_cbInternal.RegisterInEngine class function Tkw_DocNumberQuery_Control_cbInternal.GetWordNameForRegister: AnsiString; begin Result := 'контрол::cbInternal'; end;//Tkw_DocNumberQuery_Control_cbInternal.GetWordNameForRegister procedure Tkw_DocNumberQuery_Control_cbInternal_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('cbInternal'); inherited; end;//Tkw_DocNumberQuery_Control_cbInternal_Push.DoDoIt class function Tkw_DocNumberQuery_Control_cbInternal_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::cbInternal:push'; end;//Tkw_DocNumberQuery_Control_cbInternal_Push.GetWordNameForRegister function TkwDocNumberQueryFormLabel1.Label1(const aCtx: TtfwContext; aDocNumberQueryForm: TDocNumberQueryForm): TvtLabel; {* Реализация слова скрипта .TDocNumberQueryForm.Label1 } begin Result := aDocNumberQueryForm.Label1; end;//TkwDocNumberQueryFormLabel1.Label1 class function TkwDocNumberQueryFormLabel1.GetWordNameForRegister: AnsiString; begin Result := '.TDocNumberQueryForm.Label1'; end;//TkwDocNumberQueryFormLabel1.GetWordNameForRegister function TkwDocNumberQueryFormLabel1.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtLabel); end;//TkwDocNumberQueryFormLabel1.GetResultTypeInfo function TkwDocNumberQueryFormLabel1.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwDocNumberQueryFormLabel1.GetAllParamsCount function TkwDocNumberQueryFormLabel1.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TDocNumberQueryForm)]); end;//TkwDocNumberQueryFormLabel1.ParamsTypes procedure TkwDocNumberQueryFormLabel1.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству Label1', aCtx); end;//TkwDocNumberQueryFormLabel1.SetValuePrim procedure TkwDocNumberQueryFormLabel1.DoDoIt(const aCtx: TtfwContext); var l_aDocNumberQueryForm: TDocNumberQueryForm; begin try l_aDocNumberQueryForm := TDocNumberQueryForm(aCtx.rEngine.PopObjAs(TDocNumberQueryForm)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aDocNumberQueryForm: TDocNumberQueryForm : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(Label1(aCtx, l_aDocNumberQueryForm)); end;//TkwDocNumberQueryFormLabel1.DoDoIt function TkwDocNumberQueryFormEdNumber.edNumber(const aCtx: TtfwContext; aDocNumberQueryForm: TDocNumberQueryForm): TnscComboBox; {* Реализация слова скрипта .TDocNumberQueryForm.edNumber } begin Result := aDocNumberQueryForm.edNumber; end;//TkwDocNumberQueryFormEdNumber.edNumber class function TkwDocNumberQueryFormEdNumber.GetWordNameForRegister: AnsiString; begin Result := '.TDocNumberQueryForm.edNumber'; end;//TkwDocNumberQueryFormEdNumber.GetWordNameForRegister function TkwDocNumberQueryFormEdNumber.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TnscComboBox); end;//TkwDocNumberQueryFormEdNumber.GetResultTypeInfo function TkwDocNumberQueryFormEdNumber.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwDocNumberQueryFormEdNumber.GetAllParamsCount function TkwDocNumberQueryFormEdNumber.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TDocNumberQueryForm)]); end;//TkwDocNumberQueryFormEdNumber.ParamsTypes procedure TkwDocNumberQueryFormEdNumber.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству edNumber', aCtx); end;//TkwDocNumberQueryFormEdNumber.SetValuePrim procedure TkwDocNumberQueryFormEdNumber.DoDoIt(const aCtx: TtfwContext); var l_aDocNumberQueryForm: TDocNumberQueryForm; begin try l_aDocNumberQueryForm := TDocNumberQueryForm(aCtx.rEngine.PopObjAs(TDocNumberQueryForm)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aDocNumberQueryForm: TDocNumberQueryForm : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(edNumber(aCtx, l_aDocNumberQueryForm)); end;//TkwDocNumberQueryFormEdNumber.DoDoIt function TkwDocNumberQueryFormCbInternal.cbInternal(const aCtx: TtfwContext; aDocNumberQueryForm: TDocNumberQueryForm): TvtCheckBox; {* Реализация слова скрипта .TDocNumberQueryForm.cbInternal } begin Result := aDocNumberQueryForm.cbInternal; end;//TkwDocNumberQueryFormCbInternal.cbInternal class function TkwDocNumberQueryFormCbInternal.GetWordNameForRegister: AnsiString; begin Result := '.TDocNumberQueryForm.cbInternal'; end;//TkwDocNumberQueryFormCbInternal.GetWordNameForRegister function TkwDocNumberQueryFormCbInternal.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtCheckBox); end;//TkwDocNumberQueryFormCbInternal.GetResultTypeInfo function TkwDocNumberQueryFormCbInternal.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwDocNumberQueryFormCbInternal.GetAllParamsCount function TkwDocNumberQueryFormCbInternal.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TDocNumberQueryForm)]); end;//TkwDocNumberQueryFormCbInternal.ParamsTypes procedure TkwDocNumberQueryFormCbInternal.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству cbInternal', aCtx); end;//TkwDocNumberQueryFormCbInternal.SetValuePrim procedure TkwDocNumberQueryFormCbInternal.DoDoIt(const aCtx: TtfwContext); var l_aDocNumberQueryForm: TDocNumberQueryForm; begin try l_aDocNumberQueryForm := TDocNumberQueryForm(aCtx.rEngine.PopObjAs(TDocNumberQueryForm)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aDocNumberQueryForm: TDocNumberQueryForm : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(cbInternal(aCtx, l_aDocNumberQueryForm)); end;//TkwDocNumberQueryFormCbInternal.DoDoIt initialization Tkw_Form_DocNumberQuery.RegisterInEngine; {* Регистрация Tkw_Form_DocNumberQuery } Tkw_DocNumberQuery_Control_Label1.RegisterInEngine; {* Регистрация Tkw_DocNumberQuery_Control_Label1 } Tkw_DocNumberQuery_Control_Label1_Push.RegisterInEngine; {* Регистрация Tkw_DocNumberQuery_Control_Label1_Push } Tkw_DocNumberQuery_Control_edNumber.RegisterInEngine; {* Регистрация Tkw_DocNumberQuery_Control_edNumber } Tkw_DocNumberQuery_Control_edNumber_Push.RegisterInEngine; {* Регистрация Tkw_DocNumberQuery_Control_edNumber_Push } Tkw_DocNumberQuery_Control_cbInternal.RegisterInEngine; {* Регистрация Tkw_DocNumberQuery_Control_cbInternal } Tkw_DocNumberQuery_Control_cbInternal_Push.RegisterInEngine; {* Регистрация Tkw_DocNumberQuery_Control_cbInternal_Push } TkwDocNumberQueryFormLabel1.RegisterInEngine; {* Регистрация DocNumberQueryForm_Label1 } TkwDocNumberQueryFormEdNumber.RegisterInEngine; {* Регистрация DocNumberQueryForm_edNumber } TkwDocNumberQueryFormCbInternal.RegisterInEngine; {* Регистрация DocNumberQueryForm_cbInternal } TtfwTypeRegistrator.RegisterType(TypeInfo(TDocNumberQueryForm)); {* Регистрация типа TDocNumberQueryForm } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtLabel)); {* Регистрация типа TvtLabel } TtfwTypeRegistrator.RegisterType(TypeInfo(TnscComboBox)); {* Регистрация типа TnscComboBox } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtCheckBox)); {* Регистрация типа TvtCheckBox } {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) end.
unit ParsingTools; interface type IParsTools = interface ['{ACC6F3C9-2C01-42C7-A08D-36B93C69F6E5}'] // private function GetItems(const AIndex: integer): IParsTools; procedure SetItems(const AIndex: integer; const Value: IParsTools); // public // текущее значение function Data: string; // Находит первое вхождение из Data function First(const AFrom, ATo: string): string; // Находит все вхождения из Data function All(const AFrom, ATo: string): TArray<string>; // Находит первое вхождение из Data и возвращает интерфейс для дальнейших действий function FirstAnd(const AFrom, ATo: string): IParsTools; // Находит все вхождения из Data и возвращает интерфейс для дальнейших действий function AllAnd(const AFrom, ATo: string): IParsTools; // Содержит массив интерфейсов после метода AllAnd property Items[const AIndex: integer]: IParsTools read GetItems write SetItems; default; // Количество в массиве после метода AllAnd function ItemsCount: integer; end; function ParsingTool(const AData: string): IParsTools; implementation uses System.SysUtils; type TParsTools = class(TInterfacedObject, IParsTools) private FData_: string; // readonly FItems: TArray<IParsTools>; function GetItems(const AIndex: integer): IParsTools; procedure SetItems(const AIndex: integer; const Value: IParsTools); protected constructor Create(const AData: string); overload; constructor Create(const AItems: TArray<IParsTools>); overload; public class function Pars(const AText: string): IParsTools; function Data: string; function First(const AFrom, ATo: string): string; function FirstAnd(const AFrom, ATo: string): IParsTools; function All(const AFrom, ATo: string): TArray<string>; function AllAnd(const AFrom, ATo: string): IParsTools; property Items[const AIndex: integer]: IParsTools read GetItems write SetItems; default; function ItemsCount: integer; end; { TParsTools } function TParsTools.All(const AFrom, ATo: string): TArray<string>; var TagAPosition: integer; TagBPosition: integer; LData: string; lResult: string; begin LData := FData_; while true do begin TagAPosition := LData.IndexOf(AFrom); if TagAPosition < 0 then break; LData := LData.Remove(0, TagAPosition + AFrom.Length); TagBPosition := LData.IndexOf(ATo); if TagBPosition < 0 then break; lResult := LData.Substring(0, TagBPosition); LData := LData.Substring(TagBPosition + ATo.Length); if not lResult.IsEmpty then begin SetLength(Result, Length(Result) + 1); Result[High(Result)] := lResult; end; end; end; function TParsTools.AllAnd(const AFrom, ATo: string): IParsTools; var LData: TArray<string>; LItems: TArray<IParsTools>; I: integer; begin LData := All(AFrom, ATo); SetLength(LItems, Length(LData)); for I := Low(LData) to High(LData) do LItems[I] := TParsTools.Create(LData[I]); Result := TParsTools.Create(LItems); end; constructor TParsTools.Create(const AItems: TArray<IParsTools>); begin FItems := AItems; end; constructor TParsTools.Create(const AData: string); begin FData_ := AData; end; function TParsTools.Data: string; begin Result := FData_; end; class function TParsTools.Pars(const AText: string): IParsTools; begin Result := TParsTools.Create(AText); end; function TParsTools.First(const AFrom, ATo: string): string; var TagAPosition: integer; TagBPosition: integer; LData: string; begin LData := FData_; TagAPosition := LData.IndexOf(AFrom); if TagAPosition < 0 then raise ERangeError.CreateFmt('Tag A: %s not found', [AFrom]); LData := LData.Remove(0, TagAPosition + AFrom.Length); TagBPosition := LData.IndexOf(ATo); if TagBPosition < 0 then raise ERangeError.CreateFmt('Tag B: %s not found', [ATo]); Result := LData.Remove(TagBPosition); end; function TParsTools.FirstAnd(const AFrom, ATo: string): IParsTools; var LText: string; begin LText := First(AFrom, ATo); Result := TParsTools.Create(LText); end; function TParsTools.GetItems(const AIndex: integer): IParsTools; begin Result := FItems[AIndex]; end; function TParsTools.ItemsCount: integer; begin Result := Length(FItems); end; procedure TParsTools.SetItems(const AIndex: integer; const Value: IParsTools); begin FItems[AIndex] := Value; end; function ParsingTool(const AData: string): IParsTools; begin Result := TParsTools.Pars(AData); end; end.
unit fb2txt_engine; interface uses MSXML2_TLB, Windows,fb2_hyph_TLB,Classes; Type TData= Array of byte; TTXTConverter = class Private XSLVar,DOM:IXMLDOMDocument2; ProcessorVar:IXSLProcessor; HyphControlerVar:IFB2Hyphenator; Function GetXSL:IXMLDOMDocument2; Procedure SetXSL(AXSL:IXMLDOMDocument2); Function GetProcessor:IXSLProcessor; Function ConvertDOM:TData; Function WrapText(S,Before:WideString):WideString; Public SkipDescr:Boolean; TextWidth,CodePage:Integer; Indent,BR:String; WrapList,SpacePositions:TStringList; WideUsed:Bool; IgnoreBold,IgnoreItalic:Boolean; property Processor:IXSLProcessor read GetProcessor; property XSL:IXMLDOMDocument2 read GetXSL write SetXsl; property HyphControler:IFB2Hyphenator read HyphControlerVar write HyphControlerVar; Constructor Create; Procedure Convert(ADOM:IDispatch;FN:String); destructor Destroy; override; end; Function ExportDOM(AParent:THandle;DOM:IDispatch;FN,BR:String; SkipDescr, Hyphenate:Boolean; TextWidth,IndentCount,CodePage:Integer;AIgnoreBold,AIgnoreItalic:Boolean):HResult; implementation uses SysUtils,EncodingWarn,save_txt_dialog; Const TrimSym:WideString=' '#9#10#13; Wrapchars:WideString=',;;:.?!=…'; Function LineEmpty(const S:WideString):Boolean; Var I:Integer; Begin Result:=True; for I:=1 to Length(S) do if Pos(S[I],TrimSym)=0 then Begin Result:=False; exit; end; end; Function SimplifyString(S:WideString;safe:boolean):WideString; Var I:Integer; StartSpace,EndSpace:Boolean; Begin Result:=''; StartSpace:=Pos(S[1],TrimSym)<>0; if StartSpace and LineEmpty(S) then begin if Safe then Result:=' '; Exit; end; EndSpace:=Pos(S[Length(S)],TrimSym)<>0; While Pos(S[1],TrimSym)<>0 do Delete(S,1,1); While Pos(S[Length(S)],TrimSym)<>0 do SetLength(S,Length(S)-1); I:=1; While I<length(S) do Begin if (Pos(S[I],TrimSym)<>0) then Begin S[I]:=' '; while (I<length(S)) and (Pos(S[I+1],TrimSym)<>0) do Delete(S,I+1,1); end; Inc(I); end; if StartSpace and safe then S:=' '+S; if EndSpace and safe then S:=S+' '; Result:=S; end; Function UnderlineText(S:WideString):WideString; Var I:Integer; StartSpace,EndSpace:Boolean; Begin StartSpace:=Pos(S[1],TrimSym)<>0; EndSpace:=Pos(S[Length(S)],TrimSym)<>0; S:=SimplifyString(S,false); For I:=1 to Length(S) do if S[I]=' ' then S[I]:='_'; S:='_'+S+'_'; if StartSpace then S:=' '+S; if EndSpace then S:=S+' '; Result:=S; end; Function TTXTConverter.WrapText; var LastWrapPos,PrevWrapPos,I:Integer; Function FitString(S:String):String; Var MustAddSpaces,FloatingSpaces,StandingSpaces:Integer; I,I1,R:Integer; Begin Result:=S; MustAddSpaces:=TextWidth-Length(S); if MustAddSpaces = 0 then exit; SpacePositions.Clear; For I:=Length(Before)+1 to Length(S) do if S[I]=' ' then SpacePositions.AddObject('',Pointer(I)); if SpacePositions.Count=0 then exit; FloatingSpaces:= MustAddSpaces mod SpacePositions.Count; StandingSpaces:= MustAddSpaces div SpacePositions.Count; While FloatingSpaces>0 do Begin R:=Random(SpacePositions.Count); if SpacePositions[R]='' then Begin SpacePositions[R]:=' '; Dec(FloatingSpaces); end; end; For I:=0 to SpacePositions.Count-1 do For I1:=1 to StandingSpaces do SpacePositions[I]:=SpacePositions[I]+' '; For I:= SpacePositions.Count-1 downto 0 do Insert(SpacePositions[I],Result,Integer(SpacePositions.Objects[I])); end; Begin S:=SimplifyString(S,false); S:=Before+S; if TextWidth<=0 then Begin Result:=S; Exit; end; WrapList.Clear; Result:=''; PrevWrapPos:=1; LastWrapPos:=1; For I:=Length(Before)+1 to Length(S) do Begin if (S[I]= ' ') or ((I>1) and (Pos(S[I-1],Wrapchars)>0)) then LastWrapPos:=I; if I-PrevWrapPos>=TextWidth then Begin if LastWrapPos>PrevWrapPos then Begin WrapList.Add(Result+Copy(S,PrevWrapPos,LastWrapPos-PrevWrapPos)); end else Begin WrapList.Add(Result+Copy(S,PrevWrapPos,I-PrevWrapPos)); LastWrapPos:=I-1; end; PrevWrapPos:=LastWrapPos+1; end; end; For I:=0 to WrapList.Count-1 do Result:=Result+FitString(WrapList[I])+BR; Result:=Result+Copy(S,PrevWrapPos,MaxInt); end; Function TTXTConverter.GetXSL; Var ModulePath:String; XTmp:IXMLDOMDocument2; Begin If XSLVar=Nil then Begin SetLength(ModulePath,2000); GetModuleFileName(HInstance,@ModulePath[1],1999); SetLength(ModulePath,Pos(#0,ModulePath)-1); ModulePath:=ExtractFileDir(ModulePath); ModulePath:=IncludeTrailingPathDelimiter(ModulePath); XTmp:=CoFreeThreadedDOMDocument40.Create; if not XTmp.load(ModulePath+'FB2_2_txt.xsl') then Raise Exception.Create(XTmp.parseError.reason); XSL:=XTmp; end; Result:=XSLVar; end; Procedure TTXTConverter.SetXSL; Var Template:IXSLTemplate; Begin XSLVar:=AXSL; Template := CoXSLTemplate40.Create; Template._Set_stylesheet(XSL); ProcessorVar:=Template.createProcessor; end; Function TTXTConverter.GetProcessor; Begin if (ProcessorVar=Nil) then GetXSL; Result:=ProcessorVar; end; Constructor TTXTConverter.Create; Begin XSLVar:=Nil; HyphControlerVar:=Nil; SkipDescr:=False; TextWidth:=-1; Indent:=''; CodePage:=CP_ACP; BR:=#10; WrapList:=TStringList.Create; SpacePositions:=TStringList.Create; IgnoreBold:=False; IgnoreItalic:=False; end; destructor TTXTConverter.Destroy; Begin WrapList.Free; SpacePositions.Free; end; Function TTXTConverter.ConvertDOM; Var NodeList,NoteNodes:IXMLDOMNodeList; NoteNode,NoteSectionTitle,NoteSectionBody:IXMLDOMNode; I,I1:Integer; S,LinkTarget:WideString; XDoc1:IXMLDOMDocument2; Function NoteMeaningLess(S:String):String; const MLessChars:WideString=' ,.;:''"?!01234567890@#$%^&*()-_+=[]{}|\/~'#160#10#13#9; Var I:Integer; Begin Result:=''; For I:=1 to Length(S) do if pos(S[I],MLessChars)=0 then Begin Result:=S; Exit; end; end; Begin // this thing is to fix strange DOM from FBE, not knowing that // http://www.gribuser.ru/xml/fictionbook/2.0 is a default namespace // for attributes %[ ] XDoc1:=CoFreeThreadedDOMDocument40.Create; XDoc1.loadXML(Dom.XML); Dom:=XDoc1; Dom.async:=False; Dom.setProperty('SelectionLanguage','XPath'); Dom.setProperty('SelectionNamespaces', 'xmlns:fb="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:xlink="http://www.w3.org/1999/xlink"'); if not IgnoreItalic then Begin NodeList:=Dom.selectNodes('//fb:emphasis'); if NodeList<>Nil then for I:=0 to NodeList.length-1 do Begin S:=NodeList.item[I].text; if not LineEmpty(S) then NodeList.item[I].text:=UnderlineText(S); end; end; if not IgnoreBold then Begin NodeList:=Dom.selectNodes('//fb:strong'); if NodeList<>Nil then for I:=0 to NodeList.length-1 do Begin S:=NodeList.item[I].text; if not LineEmpty(S) then NodeList.item[I].text:=WideUpperCase(S); end; end; NodeList:=Dom.selectNodes('//fb:a[@type = ''note'']'); if NodeList<>Nil then for I:=0 to NodeList.length-1 do Begin // NoteNode:=NodeList.item[I].attributes.getNamedItem('xlink:href'); // NodeList.item[I].setProperty('SelectionNamespaces', 'xmlns:fb="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:xlink="http://www.w3.org/1999/xlink"'); NoteNode:=NodeList.item[I].selectSingleNode('@xlink:href'); If (NoteNode<>Nil) then Begin LinkTarget:=NoteNode.text; if LinkTarget[1]='#' then LinkTarget:=Copy(LinkTarget,2,MaxInt); NoteNodes:=Dom.selectNodes('//fb:body[@name=''notes'']//fb:section[@id = '''+LinkTarget+''']/*[name() !=''title'']'); NoteSectionTitle:=Dom.selectSingleNode('//fb:body[@name=''notes'']//fb:section[@id = '''+LinkTarget+''']/fb:title'); S:=''; if (NoteNodes<>Nil) and (NoteNodes.length>0) or (NoteSectionTitle<>Nil) then Begin if NoteSectionTitle<> Nil then S:=NoteMeaningLess(NoteSectionTitle.text); if (S<>'') and (NoteNodes<>Nil) and (NoteNodes.length>0) then S:=S+ ': '; if NoteNodes<>Nil then For I1:=0 to NoteNodes.length-1 do Begin if S<>'' then S:=S+' '; S:=S + NoteNodes[I1].text; end; if not LineEmpty(S) then NodeList.item[I].text:=NoteMeaningLess(NodeList.item[I].text)+'['+S+'] '; end; end; end; if HyphControler<>Nil then HyphControler.Hyphenate(DOM); NodeList:=Dom.selectNodes('//*[name()!=''binary'' and name()!=''strong'' and name()!=''emphasis'' and name()!=''a'' and name()!=''p'']/text()|//fb:title/fb:p'); if NodeList<>Nil then for I:=0 to NodeList.length-1 do Begin S:=NodeList.item[I].text; if not LineEmpty(S) then NodeList.item[I].text:=WrapText(S,''); end; if TextWidth > 0 then begin NodeList:=Dom.selectNodes('//fb:p[not(parent::fb:title)]|//fb:v|//fb:td'); if NodeList<>Nil then for I:=0 to NodeList.length-1 do Begin S:=NodeList.item[I].text; if not LineEmpty(S) then NodeList.item[I].text:=WrapText(S,Indent) else if TextWidth > 0 then NodeList.item[I].text:=''; end; end else Begin NodeList:=Dom.selectNodes('//fb:p[not(parent::fb:title)]/text()|//fb:v/text()|//fb:td/text()|//fb:strong/text()|//fb:emphasis/text()|//fb:style/text()|//fb:sub/text()|//fb:strikethrough/text()|//fb:sup/text()'); if NodeList<>Nil then for I:=0 to NodeList.length-1 do NodeList.item[I].text:=SimplifyString(NodeList.item[I].xml,True); end; Processor.addParameter('skipannotation',Integer(SkipDescr),''); Processor.addParameter('brstr',BR,''); Processor.addParameter('dblbr',Integer(Indent=''),''); if TextWidth <= 0 then Processor.addParameter('indent-str',Indent,''); Processor.input:=DOM; Processor.transform; S:=Processor.output; WideUsed:=False; if CodePage = CP_UTF8 then Begin SetLength(Result,WideCharToMultiByte(CodePage,0,PWideChar(S),-1,@Result[0],0,Nil,Nil)); WideCharToMultiByte(CodePage,0,PWideChar(S),Length(S),@Result[0],Length(Result),Nil,Nil) end else if CodePage <> CP_UTF16 then Begin SetLength(Result,WideCharToMultiByte(CodePage,WC_COMPOSITECHECK or WC_DEFAULTCHAR,PWideChar(S),-1,@Result[0],0,Nil,@WideUsed)); WideCharToMultiByte(CodePage,WC_COMPOSITECHECK or WC_DEFAULTCHAR,PWideChar(S),Length(S),@Result[0],Length(Result),Nil,@WideUsed) end else Begin SetLength(Result,Length(S)*2); Move(S[1],Result[1],Length(S)*SizeOf(WideChar)); end; end; Procedure TTXTConverter.Convert; Var F:TFileStream; ResultText:TData; OutVar:IXMLDOMDocument2; Begin if ADOM=Nil then Begin MessageBox(0,'NILL document value, please provide valid IXMLDOMDocument2 on input.','Error',mb_ok or MB_ICONERROR); Exit; end; if ADOM.QueryInterface(IID_IXMLDOMDocument2,OutVar) <> S_OK then Begin MessageBox(0,'Invalid IDispatch interface on enter, should be called with IXMLDOMDocument2','Error',MB_OK or MB_ICONERROR); exit; end; DOM:=OutVar; Try ResultText:=ConvertDOM; F:=TFileStream.Create(FN,fmCreate); F.Write(ResultText[0],Length(ResultText)); F.Free; except on E: Exception do MessageBox(0,PChar(E.Message),'Error',mb_ok or MB_ICONERROR); end end; Function ExportDOM; Var Converter:TTXTConverter; I:Integer; HyphDescrDOM:IXMLDOMDocument2; Begin Converter:=TTXTConverter.Create; Converter.SkipDescr:=SkipDescr; For I:=1 to IndentCount do Converter.Indent:=Converter.Indent+' '; if Hyphenate then Begin Converter.HyphControler:=CoFB2Hyphenator.Create; HyphDescrDOM:=CoFreeThreadedDOMDocument40.Create; HyphDescrDOM.preserveWhiteSpace:=True; HyphDescrDOM.loadXML('<device name="Fixed width text"><displays><display-mode name="Default" width="'+IntToStr(TextWidth)+'"/></displays><fonts><font name="Default"><font-size name="Default"><normal default-width="1"/><strong default-width="1"/><emphasis default-width="1"/><strongemphasis default-width="1"/></font-size></font></fonts></device>'); Converter.HyphControler.deviceDescr:=HyphDescrDOM; Converter.HyphControler.currentDeviceSize:='Default'; Converter.HyphControler.currentFont:='Default'; Converter.HyphControler.currentFontSize:='Default'; Converter.HyphControler.strPrefix:=Converter.Indent; end; Converter.TextWidth:=TextWidth; Converter.CodePage:=CodePage; Converter.BR:=BR; Converter.IgnoreBold:=AIgnoreBold; Converter.IgnoreItalic:=AIgnoreItalic; Converter.Convert(DOM,FN); if Converter.WideUsed then with TEncWarn.Create(Nil) do Begin ShowModal; end; Converter.Free; end; end.
unit MPWS.WebServerModule; interface uses System.SysUtils, System.Classes, Web.HTTPApp; type TWebServerModule = class(TWebModule) procedure WebModuleDefaultHandlerAction(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); end; var WebModuleClass: TComponentClass = TWebServerModule; implementation {%CLASSGROUP 'System.Classes.TPersistent'} uses // IdHTTPWebBrokerBridge needs to be in the uses clause so that WebRequestHandler is set first Web.WebReq, IdHTTPWebBrokerBridge; {$R *.dfm} procedure TWebServerModule.WebModuleDefaultHandlerAction(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); begin Response.Content := '<html>' + '<head><title>Web Server Application</title></head>' + '<body>Web Server Application</body>' + '</html>'; end; initialization if WebRequestHandler <> nil then WebRequestHandler.WebModuleClass := WebModuleClass; end.
unit supportptr; interface const PtrSIZE=sizeof(pointer); // 32bit = 4, 64bit = 8 PtrShiftCNT=PtrSIZE shr 1; // 32bit = 2, 64bit = 4 type ppointer=^pointer; pint=^integer; pbyte=^byte; procedure MoveMemory(Destination: Pointer; Source: Pointer; Length: integer); procedure CopyMemory(Destination: Pointer; Source: Pointer; Length: integer); procedure FillMemory(Destination: Pointer; Length: integer; Fill: Byte); procedure ZeroMemory(Destination: Pointer; Length: integer); procedure PtrMOVE(Source: Pointer; Destination: Pointer; Length: integer); procedure PtrFILL(Destination: Pointer; Length: integer; Fill: Byte); function PtrINC(addr:pointer; offset:cardinal):pointer; implementation function PtrINC(addr:pointer; offset:cardinal):pointer; begin {$IFDEF VER150} result:=pointer(cardinal(addr)+offset) {$ELSE} result:=addr+offset {$ENDIF} end; procedure PtrFILL(Destination: Pointer; Length: integer; Fill: Byte); begin {$IFDEF VER150} FillChar(Destination^, Length, Fill); {$ELSE} fillbyte(Destination^, Length, Fill); {$ENDIF} end; procedure PtrMOVE(Source: Pointer; Destination: Pointer; Length: integer); begin Move(Source^, Destination^, Length); end; procedure MoveMemory(Destination: Pointer; Source: Pointer; Length: integer); begin Move(Source^, Destination^, Length); end; procedure CopyMemory(Destination: Pointer; Source: Pointer; Length: integer); begin Move(Source^, Destination^, Length); end; procedure FillMemory(Destination: Pointer; Length: integer; Fill: Byte); begin {$IFDEF VER150} FillChar(Destination^, Length, Fill); {$ELSE} fillbyte(Destination^, Length, Fill); {$ENDIF} end; procedure ZeroMemory(Destination: Pointer; Length: integer); begin {$IFDEF VER150} FillChar(Destination^, Length, 0); {$ELSE} fillbyte(Destination^, Length, 0); {$ENDIF} end; end.
unit exedexes_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} nz80,main_engine,controls_engine,gfx_engine,sn_76496,ay_8910, rom_engine,pal_engine,sound_engine,timer_engine; function iniciar_exedexes_hw:boolean; implementation const exedexes_rom:array[0..2] of tipo_roms=( (n:'11m_ee04.bin';l:$4000;p:0;crc:$44140dbd),(n:'10m_ee03.bin';l:$4000;p:$4000;crc:$bf72cfba), (n:'09m_ee02.bin';l:$4000;p:$8000;crc:$7ad95e2f)); exedexes_snd_rom:tipo_roms=(n:'11e_ee01.bin';l:$4000;p:0;crc:$73cdf3b2); exedexes_pal:array[0..7] of tipo_roms=( (n:'02d_e-02.bin';l:$100;p:0;crc:$8d0d5935),(n:'03d_e-03.bin';l:$100;p:$100;crc:$d3c17efc), (n:'04d_e-04.bin';l:$100;p:$200;crc:$58ba964c),(n:'06f_e-05.bin';l:$100;p:$300;crc:$35a03579), (n:'l04_e-10.bin';l:$100;p:$400;crc:$1dfad87a),(n:'c04_e-07.bin';l:$100;p:$500;crc:$850064e0), (n:'l09_e-11.bin';l:$100;p:$600;crc:$2bb68710),(n:'l10_e-12.bin';l:$100;p:$700;crc:$173184ef)); exedexes_char:tipo_roms=(n:'05c_ee00.bin';l:$2000;p:0;crc:$cadb75bd); exedexes_sprites:array[0..1] of tipo_roms=( (n:'j11_ee10.bin';l:$4000;p:0;crc:$bc83e265),(n:'j12_ee11.bin';l:$4000;p:$4000;crc:$0e0f300d)); exedexes_tiles1:tipo_roms=(n:'h01_ee08.bin';l:$4000;p:0;crc:$96a65c1d); exedexes_tiles2:array[0..1] of tipo_roms=( (n:'a03_ee06.bin';l:$4000;p:0;crc:$6039bdd1),(n:'a02_ee05.bin';l:$4000;p:$4000;crc:$b32d8252)); exedexes_tilesbg_pos:array[0..1] of tipo_roms=( (n:'c01_ee07.bin';l:$4000;p:0;crc:$3625a68d),(n:'h04_ee09.bin';l:$2000;p:$4000;crc:$6057c907)); exedexes_dip_a:array [0..5] of def_dip=( (mask:$3;name:'Difficulty';number:4;dip:((dip_val:$2;dip_name:'Easy'),(dip_val:$3;dip_name:'Normal'),(dip_val:$1;dip_name:'Hard'),(dip_val:$0;dip_name:'Hardest'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c;name:'Lives';number:4;dip:((dip_val:$8;dip_name:'1'),(dip_val:$4;dip_name:'2'),(dip_val:$c;dip_name:'3'),(dip_val:$0;dip_name:'5'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$10;name:'2 Players Game';number:2;dip:((dip_val:$0;dip_name:'1 Credit'),(dip_val:$10;dip_name:'2 Credit'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$20;name:'Languaje';number:2;dip:((dip_val:$0;dip_name:'English'),(dip_val:$20;dip_name:'Japanese'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$40;name:'Freeze';number:2;dip:((dip_val:$40;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); exedexes_dip_b:array [0..4] of def_dip=( (mask:$7;name:'Coin A';number:8;dip:((dip_val:$0;dip_name:'4C 1C'),(dip_val:$1;dip_name:'3C 1C'),(dip_val:$2;dip_name:'2C 1C'),(dip_val:$7;dip_name:'1C 1C'),(dip_val:$6;dip_name:'1C 2C'),(dip_val:$5;dip_name:'1C 3C'),(dip_val:$4;dip_name:'1C 4C'),(dip_val:$3;dip_name:'1C 5C'),(),(),(),(),(),(),(),())), (mask:$38;name:'Coin B';number:8;dip:((dip_val:$0;dip_name:'4C 1C'),(dip_val:$8;dip_name:'3C 1C'),(dip_val:$10;dip_name:'2C 1C'),(dip_val:$38;dip_name:'1C 1C'),(dip_val:$30;dip_name:'1C 2C'),(dip_val:$28;dip_name:'1C 3C'),(dip_val:$20;dip_name:'1C 4C'),(dip_val:$18;dip_name:'1C 5C'),(),(),(),(),(),(),(),())), (mask:$40;name:'Allow Continue';number:2;dip:((dip_val:$0;dip_name:'No'),(dip_val:$40;dip_name:'Yes'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$80;name:'Demo Sounds';number:2;dip:((dip_val:$0;dip_name:'Off'),(dip_val:$80;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); var scroll_x,scroll_y,scroll_bg:word; sound_command:byte; sc2on,sc1on,objon,chon:boolean; procedure update_video_exedexes; var f,color,nchar,x,y:word; attr:byte; procedure draw_sprites(pri:byte); var f,color,nchar,x,y:word; atrib:byte; begin for f:=127 downto 0 do begin atrib:=buffer_sprites[(f*32)+1]; if ((atrib and $40)=pri) then begin nchar:=buffer_sprites[f*32]; atrib:=buffer_sprites[(f*32)+1]; color:=(atrib and $0f) shl 4; y:=240-(buffer_sprites[(f*32)+3]-((atrib and $80) shl 1)); x:=buffer_sprites[(f*32)+2]; put_gfx_sprite(nchar,color,(atrib and $20)<>0,(atrib and $10)<>0,3); actualiza_gfx_sprite(x,y,4,3); end; end; end; begin if sc2on then scroll__y(1,4,1792-scroll_bg) else fill_full_screen(4,0); if objon then draw_sprites($40); if sc1on then scroll_x_y(2,4,scroll_x,1792-scroll_y); if objon then draw_sprites(0); if chon then begin //chars activos for f:=$3ff downto 0 do begin //Chars if gfx[0].buffer[f] then begin x:=f div 32; y:=31-(f mod 32); attr:=memoria[f+$d400]; color:=(attr and $3F) shl 2; nchar:=memoria[f+$d000]+((attr and $80) shl 1); put_gfx_mask(x*8,y*8,nchar,color,3,0,$cf,$ff); gfx[0].buffer[f]:=false; end; end; actualiza_trozo(0,0,256,256,3,0,0,256,256,4); end; actualiza_trozo_final(16,0,224,256,4); copymemory(@buffer_sprites,@memoria[$f000],$1000); end; procedure eventos_exedexes; begin if event.arcade then begin if arcade_input.left[0] then marcade.in1:=(marcade.in1 and $fd) else marcade.in1:=(marcade.in1 or $2); if arcade_input.right[0] then marcade.in1:=(marcade.in1 and $fe) else marcade.in1:=(marcade.in1 or $1); if arcade_input.up[0] then marcade.in1:=(marcade.in1 and $F7) else marcade.in1:=(marcade.in1 or $8); if arcade_input.but0[0] then marcade.in1:=(marcade.in1 and $ef) else marcade.in1:=(marcade.in1 or $10); if arcade_input.but1[0] then marcade.in1:=(marcade.in1 and $df) else marcade.in1:=(marcade.in1 or $20); if arcade_input.down[0] then marcade.in1:=(marcade.in1 and $fb) else marcade.in1:=(marcade.in1 or $4); if arcade_input.left[1] then marcade.in2:=(marcade.in2 and $fd) else marcade.in2:=(marcade.in2 or $2); if arcade_input.right[1] then marcade.in2:=(marcade.in2 and $fe) else marcade.in2:=(marcade.in2 or $1); if arcade_input.up[1] then marcade.in2:=(marcade.in2 and $F7) else marcade.in2:=(marcade.in2 or $8); if arcade_input.but0[1] then marcade.in2:=(marcade.in2 and $ef) else marcade.in2:=(marcade.in2 or $10); if arcade_input.but1[1] then marcade.in2:=(marcade.in2 and $df) else marcade.in2:=(marcade.in2 or $20); if arcade_input.down[1] then marcade.in2:=(marcade.in2 and $fb) else marcade.in2:=(marcade.in2 or $4); if arcade_input.start[0] then marcade.in0:=(marcade.in0 and $fe) else marcade.in0:=(marcade.in0 or $1); if arcade_input.start[1] then marcade.in0:=(marcade.in0 and $fd) else marcade.in0:=(marcade.in0 or $2); if arcade_input.coin[0] then marcade.in0:=(marcade.in0 and $bf) else marcade.in0:=(marcade.in0 or $40); if arcade_input.coin[1] then marcade.in0:=(marcade.in0 and $7f) else marcade.in0:=(marcade.in0 or $80); end; end; procedure exedexes_hw_principal; var f:byte; frame_m,frame_s:single; begin init_controls(false,false,false,true); frame_m:=z80_0.tframes; frame_s:=z80_1.tframes; while EmuStatus=EsRuning do begin for f:=0 to $ff do begin //main z80_0.run(frame_m); frame_m:=frame_m+z80_0.tframes-z80_0.contador; //sonido z80_1.run(frame_s); frame_s:=frame_s+z80_1.tframes-z80_1.contador; case f of 239:begin z80_0.im0:=$d7; //rst 10 z80_0.change_irq(HOLD_LINE); update_video_exedexes; end; 255:begin z80_0.im0:=$cf; //rst 8 z80_0.change_irq(HOLD_LINE); end; end; end; eventos_exedexes; video_sync; end; end; function exedexes_getbyte(direccion:word):byte; begin case direccion of $0..$bfff,$d000..$d7ff,$e000..$ffff:exedexes_getbyte:=memoria[direccion]; $c000:exedexes_getbyte:=marcade.in0; $c001:exedexes_getbyte:=marcade.in1; $c002:exedexes_getbyte:=marcade.in2; $c003:exedexes_getbyte:=marcade.dswa; $c004:exedexes_getbyte:=marcade.dswb; end; end; procedure exedexes_putbyte(direccion:word;valor:byte); begin case direccion of 0..$bfff:; //ROM $c800:sound_command:=valor; $c804:if chon<>((valor and $80)<>0) then begin chon:=(valor and $80)<>0; if chon then fillchar(gfx[0].buffer,$400,1); end; $d000..$d7ff:if memoria[direccion]<>valor then begin gfx[0].buffer[direccion and $3ff]:=true; memoria[direccion]:=valor; end; $d800:scroll_y:=(scroll_y and $700) or valor; $d801:scroll_y:=(scroll_y and $ff) or ((valor and $7) shl 8); $d802:scroll_x:=(scroll_x and $700) or valor; $d803:scroll_x:=(scroll_x and $ff) or ((valor and $7) shl 8); $d804:scroll_bg:=(scroll_bg and $700) or valor; $d805:scroll_bg:=(scroll_bg and $ff) or ((valor and $7) shl 8); $d807:begin sc2on:=(valor and $10)<>0; sc1on:=(valor and $20)<>0; objon:=(valor and $40)<>0; end; $e000..$ffff:memoria[direccion]:=valor; end; end; function exedexes_snd_getbyte(direccion:word):byte; begin case direccion of 0..$47ff:exedexes_snd_getbyte:=mem_snd[direccion]; $6000:exedexes_snd_getbyte:=sound_command; end; end; procedure exedexes_snd_putbyte(direccion:word;valor:byte); begin case direccion of 0..$3fff:; //ROM $4000..$47ff:mem_snd[direccion]:=valor; $8000:ay8910_0.Control(valor); $8001:ay8910_0.Write(valor); $8002:sn_76496_0.Write(valor); $8003:sn_76496_1.Write(valor); end; end; procedure exedexes_snd_irq; begin z80_1.change_irq(HOLD_LINE); end; procedure exedexes_sound; begin ay8910_0.update; sn_76496_0.Update; sn_76496_1.Update; end; //Main procedure reset_exedexes_hw; begin z80_0.reset; z80_1.reset; AY8910_0.reset; sn_76496_0.reset; sn_76496_1.reset; reset_audio; marcade.in0:=$ff; marcade.in1:=$ff; marcade.in2:=$ff; scroll_x:=0; scroll_y:=0; sc2on:=true; sc1on:=true; objon:=true; end; function iniciar_exedexes_hw:boolean; var colores:tpaleta; f:word; memoria_temp:array[0..$7fff] of byte; const ps_x:array[0..15] of dword=(0, 1, 2, 3, 8+0, 8+1, 8+2, 8+3, 32*8+0, 32*8+1, 32*8+2, 32*8+3, 33*8+0, 33*8+1, 33*8+2, 33*8+3); pt_x:array[0..31] of dword=(0, 1, 2, 3, 8+0, 8+1, 8+2, 8+3, 64*8+0, 64*8+1, 64*8+2, 64*8+3, 65*8+0, 65*8+1, 65*8+2, 65*8+3, 128*8+0, 128*8+1, 128*8+2, 128*8+3, 129*8+0, 129*8+1, 129*8+2, 129*8+3, 192*8+0, 192*8+1, 192*8+2, 192*8+3, 193*8+0, 193*8+1, 193*8+2, 193*8+3); pt_y:array[0..31] of dword=(0*16, 1*16, 2*16, 3*16, 4*16, 5*16, 6*16, 7*16, 8*16, 9*16, 10*16, 11*16, 12*16, 13*16, 14*16, 15*16, 16*16, 17*16, 18*16, 19*16, 20*16, 21*16, 22*16, 23*16, 24*16, 25*16, 26*16, 27*16, 28*16, 29*16, 30*16, 31*16); procedure poner_bg; var f,pos,color:word; x,y,atrib,nchar:byte; flipx,flipy:boolean; begin for f:=0 to $fff do begin x:=f div 64; y:=f mod 64; pos:=((y*32 and $e0) shr 5) + ((x*32 and $e0) shr 2) + ((y*32 and $3f00) shr 1); atrib:=memoria_temp[pos+$4000]; nchar:=atrib and $3f; color:=(memoria_temp[pos+(8*8)+$4000]) shl 2; flipx:=(atrib and $40)<>0; flipy:=(atrib and $80)<>0; put_gfx_flip(x*32,(63-y)*32,nchar,color,1,1,flipx,flipy); end; end; procedure poner_fg; var f,pos:word; x,y,nchar:byte; begin for f:=0 to $1fff do begin x:=f div 128; y:=f mod 128; pos:=((y*16 and $f0) shr 4)+(x*16 and $f0)+(y*16 and $700)+((x*16 and $700) shl 3); nchar:=memoria_temp[pos]; put_gfx_trans(x*16,(127-y)*16,nchar,0,2,2); end; end; begin llamadas_maquina.bucle_general:=exedexes_hw_principal; llamadas_maquina.reset:=reset_exedexes_hw; iniciar_exedexes_hw:=false; iniciar_audio(false); screen_init(1,2048,2048); screen_mod_scroll(1,2048,256,2047,2048,256,2047); screen_init(2,2048,2048,true); screen_mod_scroll(2,2048,256,2047,2048,256,2047); screen_init(3,256,256,true); screen_init(4,256,512,false,true); iniciar_video(224,256); //Main CPU z80_0:=cpu_z80.create(4000000,256); z80_0.change_ram_calls(exedexes_getbyte,exedexes_putbyte); //Sound CPU z80_1:=cpu_z80.create(3000000,256); z80_1.change_ram_calls(exedexes_snd_getbyte,exedexes_snd_putbyte); z80_1.init_sound(exedexes_sound); //Sound Chips AY8910_0:=ay8910_chip.create(1500000,AY8910,0.1); sn_76496_0:=sn76496_chip.Create(3000000,0.36); sn_76496_1:=sn76496_chip.Create(3000000,0.36); timers.init(z80_1.numero_cpu,3000000/(4*60),exedexes_snd_irq,nil,true); //cargar roms if not(roms_load(@memoria,exedexes_rom)) then exit; //cargar ROMS sonido if not(roms_load(@mem_snd,exedexes_snd_rom)) then exit; //convertir chars if not(roms_load(@memoria_temp,exedexes_char)) then exit; init_gfx(0,8,8,512); gfx_set_desc_data(2,0,16*8,4,0); convert_gfx(0,0,@memoria_temp,@pt_x,@pt_y,false,true); //tiles 32x32 if not(roms_load(@memoria_temp,exedexes_tiles1)) then exit; init_gfx(1,32,32,64); gfx_set_desc_data(2,0,256*8,0,4); convert_gfx(1,0,@memoria_temp,@pt_x,@pt_y,false,true); //tiles 16x16 if not(roms_load(@memoria_temp,exedexes_tiles2)) then exit; init_gfx(2,16,16,256); gfx[2].trans[0]:=true; gfx_set_desc_data(4,0,64*8,$4000*8+4,$4000*8+0,4,0); convert_gfx(2,0,@memoria_temp,@ps_x,@pt_y,false,true); //convertir sprites if not(roms_load(@memoria_temp,exedexes_sprites)) then exit; init_gfx(3,16,16,256); gfx[3].trans[0]:=true; gfx_set_desc_data(4,0,64*8,$4000*8+4,$4000*8+0,4,0); convert_gfx(3,0,@memoria_temp,@ps_x,@pt_y,false,true); //poner la paleta y clut if not(roms_load(@memoria_temp,exedexes_pal)) then exit; for f:=0 to $ff do begin colores[f].r:=pal4bit(memoria_temp[f]); colores[f].g:=pal4bit(memoria_temp[f+$100]); colores[f].b:=pal4bit(memoria_temp[f+$200]); end; set_pal(colores,256); for f:=0 to $ff do begin gfx[0].colores[f]:=memoria_temp[$300+f]+$c0; gfx[1].colores[f]:=memoria_temp[$400+f]; gfx[2].colores[f]:=memoria_temp[$500+f]+$40; gfx[3].colores[f]:=memoria_temp[$600+f]+(memoria_temp[$700+f] shl 4)+$80; end; //El fondo es fijo, no cambia lo pongo despues de la paleta if not(roms_load(@memoria_temp,exedexes_tilesbg_pos)) then exit; poner_bg; poner_fg; //DIP marcade.dswa:=$df; marcade.dswa_val:=@exedexes_dip_a; marcade.dswb:=$ff; marcade.dswb_val:=@exedexes_dip_b; //final reset_exedexes_hw; iniciar_exedexes_hw:=true; end; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, ExtCtrls, StrUtils, StdCtrls, Unit2, Menus; type TTrades = packed record Ticket : integer; Lot : double; Symbol : string[30]; Swap : double; Commission : double; Profit : double; TotalProfit: double; OrderType : integer; // Order types { 0 - Buy 1 - Sell 2 - Pending Buy Limit 3 - Pending Sell Limit 4 - Pending Buy Stop 5 - Pending Sell Stop } end; TData = packed record account : integer; refresh : integer; trade_line: integer; trades : Array of TTrades; end; TTradeMain = class(TForm) Timer1: TTimer; OpenDialog1: TOpenDialog; Panel1: TPanel; ProgressBar1: TProgressBar; Timer2: TTimer; ListBox1: TListBox; PopupMenu1: TPopupMenu; Show1: TMenuItem; procedure FormCreate(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure Timer2Timer(Sender: TObject); procedure ProgressBar1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); private { Private declarations } public { Public declarations } end; var TradeMain : TTradeMain; a_file: string; iData: TData; fo : TTradeForm; implementation {$R *.dfm} function ShowTotalProfit: boolean; var t : double; i : integer; begin t := 0; for i := 0 to Length( iData.trades )-1 do begin If ( iData.trades[i].OrderType = 0 ) or ( iData.trades[i].OrderType = 1 ) then t := t + iData.trades[i].TotalProfit; end; TradeMain.Caption := 'Refresh: ' + IntToStr( iData.refresh ) + 's | Total profit: $' + FloatToStr( t ); end; function ShowData( data: TListBox ): boolean; var s : string; n, i : integer; fo: TTradeForm; find: boolean; begin find := False; TradeMain.ProgressBar1.Position := TradeMain.ProgressBar1.Max; data.Clear; s := ''; for n:= 0 to Length( iData.trades )-1 do begin for i:= 0 to Screen.FormCount -1 do Begin If screen.Forms[i].Caption = IntToStr( iData.trades[n].Ticket ) then begin find := True; break; end else find := False; End; If find = true then fo := Screen.forms[i] as TTradeForm else fo := TTradeForm.Create(TradeMain); fo.BorderStyle := bsNone; If find = false then begin fo.Left := 0; fo.Top := n * 20; fo.Width := 300; fo.Height := 20; end; fo.FormStyle := fsStayOnTop; fo.PopupMode := pmExplicit; fo.PopupParent := TradeMain; fo.Caption := FloatToStr( iData.trades[n].Ticket ); fo.SYMBOL.Caption := iData.trades[n].Symbol; fo.LOT.Caption := FloatToStr( iData.trades[n].Lot ); fo.Commission.Caption := FloatToStr( iData.trades[n].Commission ); fo.Swap.Caption := FloatToStr( iData.trades[n].Swap ); fo.Profit.Caption := FloatToStr( iData.trades[n].Profit ); fo.TotalProfit.Caption := FloatToStr( iData.trades[n].TotalProfit ); fo.AutoSize := False; fo.AutoSize := True; If find = false then fo.Show; s := iData.trades[n].Symbol +' # ' + FloatToStr(iData.trades[n].Lot) +' # ' + FloatToStr(iData.trades[n].Commission) +' # ' + FloatToStr(iData.trades[n].Swap) +' # ' + FloatToStr(iData.trades[n].Profit) +' # ' + FloatToStr(iData.trades[n].TotalProfit) +' # ' + IntToStr(iData.trades[n].OrderType) +' # ' + FloatToStr(iData.trades[n].Ticket); data.Items.Add( s ); end; end; procedure TTradeMain.FormCreate(Sender: TObject); var f : TextFile; begin If FileExists( ExtractFilePath(Application.ExeName) + 'conf.conf' ) = false then a_file := '' else begin AssignFile( f, ExtractFilePath(Application.ExeName) + 'conf.conf' ); Reset( f ); ReadLn( f, a_file ); CloseFile( f ); If FileExists( a_file ) = False then a_file := ''; end; end; procedure TTradeMain.ProgressBar1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin If Button = mbRight then TradeMain.Hide; end; procedure TTradeMain.Timer1Timer(Sender: TObject); var f, c : TextFile; s, settings, temp : string; i: integer; dd: TStringList; begin If Length( a_file ) = 0 then begin Timer1.Enabled := False; If OpenDialog1.Execute then begin a_file := OpenDialog1.FileName; Timer1.Enabled := True; AssignFile( c, ExtractFilePath(Application.ExeName) + 'conf.conf' ); Rewrite( c ); WriteLn( c, a_file ); CloseFile( c ); end; end else begin Timer1.Enabled := False; SetLength( iData.trades, 0 ); AssignFile( f, a_file ); Reset( f ); while not Eof( f ) do begin ReadLn( f, s ); If AnsiContainsText( s, 'Setting' ) then begin ReadLn( f, settings ); //showmessage(settings); temp := Copy( settings, 0, Pos( '|', settings )-1); //Form1.Caption := temp; iData.account := StrToInt( temp ); temp := Copy( settings, Pos( '|' , settings )+1, Length( settings ) - Pos( '|', settings )); iData.refresh := StrToInt( temp ); //Form1.Caption := 'Refresh: ' + IntToStr( iData.refresh ) + 's'; Timer1.Interval := iData.refresh * 1000; ProgressBar1.Max := Timer1.Interval; ProgressBar1.Position := Timer2.Interval; Timer2.Enabled := True; Timer1.Enabled := True; repeat ReadLn( f, s ); If AnsiContainsText( s, 'symbol' ) = true then begin iData.trade_line := FilePos( f ); break; end; until Eof( f ); ListBox1.Clear; repeat ReadLn( f, s ); If Length( s ) > 0 then begin s := StringReplace( s, '.', ',', [rfReplaceAll] ); dd := TStringList.Create; dd.Clear; dd.Delimiter := '|'; dd.DelimitedText := s; s := ''; SetLength( iData.trades, Length( iData.trades ) +1 ); for i := 0 to dd.Count -1 do begin case i of 0 : iData.trades[Length( iData.trades )-1].Symbol := dd[i]; 1 : iData.trades[Length( iData.trades )-1].Lot := StrToFloat(dd[i]); 2 : iData.trades[Length( iData.trades )-1].Commission := StrToFloat(dd[i]); 3 : iData.trades[Length( iData.trades )-1].Swap := StrToFloat(dd[i]); 4 : iData.trades[Length( iData.trades )-1].Profit := StrToFloat(dd[i]); 5 : iData.trades[Length( iData.trades )-1].TotalProfit := StrToFloat(dd[i]); 6 : iData.trades[Length( iData.trades )-1].OrderType := StrToInt(dd[i]); 7 : iData.trades[Length( iData.trades )-1].Ticket := StrToInt(dd[i]); end; end; dd.Free; end else break; until Eof( f ); end; end; CloseFile( f ); ShowData( ListBox1 ); ShowTotalProfit; end; end; procedure TTradeMain.Timer2Timer(Sender: TObject); var i : integer; begin Application.ProcessMessages; If ProgressBar1.Position < Timer1.Interval then ProgressBar1.StepBy( Timer2.Interval ) else ProgressBar1.Position := 0; end; end.
unit CacheLinks; interface procedure SetLogPath(aPath : string); procedure ClearCacheLog; procedure RecordLinks(links : string; remove : boolean); procedure SetLogVer(ver : integer); function GetLogVer : integer; procedure WarpLog(ver : integer); function CreateLink(aPath, info : string; MaxTries : integer) : boolean; function DeleteLink(aPath : string; MaxTries : integer) : boolean; implementation uses Classes, SysUtils, SyncObjs, Windows, CompStringsParser; const tidAddLink = '+' + #9; tidRemLink = '-' + #9; var Lock : TCriticalsection = nil; ThePath : string = ''; LogVer : integer = 0; procedure SetLogPath(aPath : string); begin ThePath := aPath; end; procedure ClearCacheLog; var F : TextFile; begin Lock.Enter; try Assign(F, ThePath); try Rewrite(F); finally Close(F); end; finally Lock.Leave; end; end; procedure LogToFile(Info : string); var LogFile : Text; begin AssignFile(LogFile, ThePath); try Append(LogFile); except Rewrite(LogFile); end; try Writeln(LogFile, Info); finally CloseFile(LogFile); end; end; procedure RecordLinks(links : string; remove : boolean); begin if ThePath <> '' then begin Lock.Enter; try if remove then LogToFile(tidRemLink + IntToStr(LogVer) + #9 + links) else LogToFile(tidAddLink + IntToStr(LogVer) + #9 + links); finally Lock.Leave; end; end; end; function CreateLink(aPath, info : string; MaxTries : integer) : boolean; var tries : integer; TxtFile : Text; begin result := false; tries := 0; while not result and (tries < MaxTries) do begin inc(tries); AssignFile(TxtFile, aPath); try Rewrite(TxtFile); try if info <> '' then WriteLn(TxtFile, info); result := true; finally CloseFile(TxtFile); end; result := true; except Sleep(20); end; end; end; function DeleteLink(aPath : string; MaxTries : integer) : boolean; var tries : integer; begin result := false; tries := 0; while not result and (tries < MaxTries) do begin try inc(tries); result := SysUtils.DeleteFile(aPath); except result := false; end; if not result then Sleep(50); end; end; function UndoAction(str : string; CurVer : integer) : boolean; var fsch : char; path : string; aux : string; p : integer; ver : integer; begin if str <> '' then begin fsch := str[1]; p := 3; aux := GetNextStringUpTo(str, p, #9); ver := StrToInt(aux); if ver > CurVer then begin result := true; inc(p); path := GetNextStringUpTo(str, p, #9); case fsch of '+' : begin DeleteLink(path, 5); end; '-' : begin CreateLink(path, '', 5); end; end; end else result := false; end else result := true; end; procedure SetLogVer(ver : integer); begin LogVer := ver; end; function GetLogVer : integer; begin result := LogVer; end; procedure WarpLog(ver : integer); var Log : TStringList; i : integer; begin try Log := TStringList.Create; try if FileExists(ThePath) then Log.LoadFromFile(ThePath); i := pred(Log.Count); while (i >= 0) and UndoAction(Log[i], ver) do begin Log.Delete(i); dec(i); end; Log.SaveToFile(ThePath); finally Log.Free; end; except // >> end; end; initialization Lock := TCriticalsection.Create; finalization Lock.Free; Lock := nil; end.
unit evExcept; { Библиотека "Эверест" } { Автор: Люлин А.В. } { Модуль: evExcept - описание исключительных ситуаций} { Начат: 03.06.97 17:37 } { $Id: evExcept.pas,v 1.17 2015/06/23 10:23:56 dinishev Exp $ } // $Log: evExcept.pas,v $ // Revision 1.17 2015/06/23 10:23:56 dinishev // Расширенное сообщение с номерами и названиями блоков. // // Revision 1.16 2015/06/22 08:21:28 dinishev // {Requestlink:602478379} // // Revision 1.15 2015/05/21 11:46:03 lulin // - развязываем зависимости. // // Revision 1.14 2015/05/21 11:39:36 lulin // - развязываем зависимости. // // Revision 1.1 2015/05/21 11:37:08 lulin // - развязываем зависимости. // // Revision 1.12 2015/01/23 10:41:26 dinishev // {Requestlink:570533036} // // Revision 1.11 2011/04/04 14:57:09 lulin // {RequestLink:255980313}. // // Revision 1.10 2010/07/23 08:39:04 fireton // - механизм "перезапуска" цепочки searcher'ов // // Revision 1.9 2010/06/30 08:46:25 oman // - fix: {RequestLink:220595917} // // Revision 1.8 2007/12/04 12:47:01 lulin // - перекладываем ветку в HEAD. // // Revision 1.7.24.4 2007/08/29 15:33:19 lulin // - cleanup. // // Revision 1.7.24.3 2006/12/06 12:24:09 oman // - fix: Если на печати колонтитулы не оставляют места для // основного текста - бросаем исключение - текст исключения (cq23103) // // Revision 1.7.24.2 2006/12/04 13:46:40 oman // - fix: Если на печати колонтитулы не оставляют места для // основного текста - бросаем исключение (cq23103) // // Revision 1.7.24.1 2006/03/01 10:48:46 lulin // - cleanup. // // Revision 1.7 2004/07/16 12:36:41 law // - bug fix: неправильно обрабатывали PgUp/PgDn когда курсора не было видно. // // Revision 1.6 2001/03/12 12:48:22 law // - bug fix: exception при инициализации курсоров выделения, а также применение k2_tiJustification к выделению. // // Revision 1.5 2000/12/15 15:10:35 law // - вставлены директивы Log. // {$Include k2Define.inc } interface uses SysUtils, k2Except ; type EevException = class(Exception); EevWarning = class(EevException); EevSearchFailed = class(EevWarning); EevReadOnly = Ek2ReadOnly; EevLimitReached = Ek2LimitReached; EevPrintError = class(EevException); EevInvalidPrintMargins = class(EevPrintError); EevNothingToPrint = class(EevException); EevSearcherRestart = class(Exception); EevUnstableProcessWhileInsertUserComment = class(EevException); EevTooLargeColumnWidth = class(EevException); EevDoubleHandleInNestedBlocks = class(EevException); const ev_errTooLargeColumnWidth = 'Недопустимое значение ширины колонки.'; ev_warSearchFailed = 'Поиск не дал результатов'; ev_warInvalidMargins = 'Область печати выходит за границы бумажного листа. '+ 'Отредактируйте настройки размера бумаги и колонтитулов и повторите попытку печати.'; ev_errDoubleHandleInNestedBlocks = 'В документе найдены вложенные блоки с одинаковыми номерами: %d и %d, имена блоков %s и %s'; implementation end.
unit uSceneSellect; interface uses uScene, Graphics, uGraph, uButton, uResFont, uSceneDelChar; type TSceneSellect = class(TSceneCustom) private FPath: string; FSavePos: Integer; FTopPCFile: Integer; FLogo: TBitmap; FGraph: TGraph; FTemp: TBitmap; FFont: TResFont; FBack: TBitmap; FHBack: TBitmap; FUBack: TBitmap; FRBack: TBitmap; FHL, FVL: TBitmap; FIsLoad: Boolean; FSceneDelChar: TSceneDelChar; FSaveMenuPos: Integer; FBtn: array[1..8] of TButton; IsShowInfo: Boolean; IsShowRumours: Boolean; procedure Load; procedure SaveMenu; procedure Start; function InSF: Boolean; procedure DrawInfo(); procedure DelChar(); procedure DrawRumours(); procedure LoadEvents; procedure DrawStat(); public //** Конструктор. constructor Create; destructor Destroy; override; procedure DoGame(); procedure Reload(); function SavePos(): Integer; function MouseDown(Button: TMouseBtn; X, Y: Integer): Boolean; override; function MouseMove(X, Y: Integer): Boolean; override; procedure Draw(); override; function Click(Button: TMouseBtn): Boolean; override; function Keys(var Key: Word): Boolean; override; procedure LoadMenu; end; var SceneSellect: TSceneSellect; implementation uses SysUtils, Forms, uMain, uSaveLoad, uUtils, uGUI, Types, uVars, uInvBox, uMap, uSounds, uSCR, uSceneMenu, uBox, uSceneRace, uGUIBorder, uIni, uSceneLoad, uMsg, uScript, uServer, uStrUtils, uRumours, uColors, uSceneSkill, uTimeVars, uAlerts; { TSceneSellect } function TSceneSellect.Click(Button: TMouseBtn): Boolean; var I: Integer; K: Word; begin Result := True; case Button of mbLeft: begin // Back if FBtn[1].MouseOver then begin FSaveMenuPos := 0; IsGame := False; Sound.PlayClick(); SceneManager.SetScene(SceneMenu); end; // New PC if FBtn[2].MouseOver then begin VM.ClearGameVars; IsGame := False; PCName := ''; Sound.PlayClick(); SceneManager.SetScene(SceneRace); end; // OK if FBtn[3].MouseOver then Start; // Up if FBtn[4].MouseOver then begin K := 38; Keys(K); end; // Down if FBtn[5].MouseOver then begin K := 40; Keys(K); end; // Info if FBtn[6].MouseOver then DrawInfo; // Rumours if FBtn[7].MouseOver then DrawRumours; // Delete char if FBtn[8].MouseOver then DelChar; // Saves if InSF then begin I := (MouseY - 25) div 70 + 1; if (I <= GetSavePCCount) then begin if (I + FTopPCFile - 1 = FSavePos) then Exit; FSavePos := I + FTopPCFile - 1; Sound.PlayClick(4); end; end; end; mbDblLeft: if InSF then Start(); end; end; constructor TSceneSellect.Create; begin FSaveMenuPos := 1; FSavePos := 1; FTopPCFile := 1; FIsLoad := False; IsShowInfo := False; IsShowRumours := False; end; destructor TSceneSellect.Destroy; var I: Byte; begin for I := Low(FBtn) to High(FBtn) do FBtn[I].Free; FSceneDelChar.Free; FHBack.Free; FUBack.Free; FRBack.Free; FBack.Free; FLogo.Free; FGraph.Free; FFont.Free; FHL.Free; FVL.Free; inherited; end; procedure TSceneSellect.DoGame; var B: Boolean; S: TServer; L: TSceneLoad; begin L := TSceneLoad.Create; SceneManager.SetScene(L); AlertMessage := ''; Screen.Cursor := 5; ShowLogLevel := 1; Msg.Clear; Run('Init.pas'); B := False; TV.Clear; SceneSkill.Free; SceneSkill := TSceneSkill.Create; if FileExists(SavePath) then LoadGame else begin // Сообщаем, что в мир пришла новая личность :) S := TServer.Create; try S.Get(Format('addevent.php?aa=1&bb=%s&cc=%d&dd=%d&ee=0', [VM.GetStr('Hero.Name'), VM.GetInt('Hero.Race'), VM.GetInt('Hero.Gender')])); finally S.Free end; B := True; end; Run('Load.pas'); if B then L.Story(); SceneManager.Clear(); Screen.Cursor := 1; IsMenu := False; IsGame := True; fMain.RefreshBox; L.Free; // Добавляем в скрипты константы из движка VM.SetInt('Game.InvMaxLoad', InvMaxLoad); if B then Run('Game.pas'); end; procedure TSceneSellect.Draw; const VX = 380; VY = -50; var I, J, P: Integer; // SZ: TSize; S: string; PCImg: TBitmap; SC: ShortInt; begin if not FIsLoad then Load; PCImg := TBitMap.Create; PCImg.Transparent := True; FTemp := Graphics.TBitmap.Create; if (FSavePos < 1) then FSavePos := 1; FTemp.Assign(FLogo); with FTemp.Canvas do begin IsGame := False; VM.ClearGameVars; InvBox.Clear; Font.Size := 24; Font.Name := FFont.FontName; Brush.Style := bsClear; FBtn[1].Sellected := FSaveMenuPos = 0; FBtn[2].Sellected := FSaveMenuPos = 1; FBtn[3].Sellected := FSaveMenuPos = 2; for I := Low(FBtn) to High(FBtn) do FBtn[I].Draw; Draw(0, 0, FLogo); if IsShowInfo then Draw(10, 10, FHBack); if IsShowRumours then Draw(10, 10, FUBack); // SC := GetSavePCCount; if (SC <= 7) then J := SC else J := FTopPCFile + 6; for i := FTopPCFile to J do begin S := GetSavePCName(I); LoadPCForMenu(S); P := VY + 8 + (70 * (i + 1 - FTopPCFile)); if (SC > 0) and (FSavePos - FTopPCFile = (i - FTopPCFile)) and (FSaveMenuPos = 2) then begin Font.Color := cNormRare; if IsShowInfo then DrawStat; Font.Style := [fsBold]; Draw(VX + 25, P - 5, FHL); Draw(VX + 25, P - 5 + FVL.Height, FHL); Draw(VX + 25, P - 5, FVL); Draw(VX + 25 + FHL.Width - 1, P - 5, FVL); end else begin Font.Style := []; Font.Color := cDarkRare; end; Font.Size := 24; TextOut(VX + 70, P - 1, S); Font.Style := []; Font.Size := 14; S := VM.GetStr('Hero.RaceName') + ', ' + VM.GetStr('Hero.ClassName') + ', ' + VM.GetStr('Hero.Level') + ' уровень'; TextOut(VX + 70, P + 35, S); PCImg.Assign(Map.HeroImage); Draw(VX + 32, P + 12, PCImg); VM.ClearGameVars; InvBox.Clear; end; end; SCR.BG.Canvas.Draw(0, 0, FTemp); FTemp.Free; PCImg.Free; end; procedure TSceneSellect.DrawInfo; begin Sound.PlayClick(4); IsShowInfo := not IsShowInfo; if IsShowRumours then IsShowRumours := False; Draw; end; procedure TSceneSellect.DrawRumours; begin Sound.PlayClick(4); IsShowRumours := not IsShowRumours; if IsShowRumours then LoadEvents; if IsShowInfo then IsShowInfo := False; Draw; end; procedure TSceneSellect.DrawStat; var X, Y: Integer; procedure Add(N: string; V: string); begin with FTemp.Canvas do begin TextOut(X, Y, N); TextOut((X + 170) - TextWidth(V), Y, V); end; if (X = 20) then X := 200 else begin X := 20; Inc(Y, 20); end; end; begin with FTemp.Canvas do begin Font.Style := []; Font.Size := 14; X := 20; Y := 20; Add('Побед', VM.GetStr('Hero.Kills')); Add('Поражений', VM.GetStr('Hero.Deads')); Add('Глубина', VM.GetStr('Hero.Deep')); Add('Шаги', VM.GetStr('Hero.Step')); end; end; procedure TSceneSellect.LoadEvents; var J, Y, A: Integer; S: TServer; R: string; V, U: TSplitResult; procedure Add(T: string); var I: Integer; H: TSplitResult; begin H := Explode(40, Trim(T)); for I := 0 to High(H) do begin FUBack.Canvas.TextOut(10, Y, H[I]); Inc(Y, 20); end; Inc(Y, 5); end; begin try S := TServer.Create; try R := Trim(S.Get('events.php')); with FUBack.Canvas do begin Draw(0, 0, FRBack); Font.Style := []; Font.Size := 14; Font.Name := FFont.FontName; Brush.Style := bsClear; Font.Color := cNormRare; Y := 11; end; if (R = '') then Add('Невозможно соединиться с сервером!') else try V := Explode(string('|'), R); if (High(V) > 0) then Add(RumBegin()); FUBack.Canvas.Font.Color := cDarkRare; if (High(V) > 0) then for J := High(V) - 1 downto 0 do begin A := 0; if (V[J] = '') then Continue; U := Explode(string(','), V[J]); if (Trim(U[0]) <> '') then A := StrToInt(Trim(U[0])); case A of // Новый персонаж 1: Add(NewPC(U[1], StrToInt(U[2]), StrToInt(U[3]))); // 2: ; // 3: Add(NewLevel(U[1], StrToInt(U[2]), StrToInt(U[3]), StrToInt(U[4]))); // 4: Add(Death(U[1], StrToInt(U[2]), StrToInt(U[3]), U[4])); end; end; FUBack.Canvas.Font.Color := cNormRare; if (High(V) > 0) then Add(RumEnd()); except end; finally S.Free; end; except Box('Ошибка чтения данных с сервера!'); end; end; function TSceneSellect.InSF: Boolean; begin Result := InRange(MouseX, 405, 715) and InRange(MouseY, 25, 515) end; function TSceneSellect.Keys(var Key: Word): Boolean; var I, J: Integer; begin TransKeys(Key); Result := True; I := GetSavePCCount; case Key of 13: begin case FSaveMenuPos of 0: begin Sound.PlayClick(); SceneManager.SetScene(SceneMenu); end; 1: begin VM.ClearGameVars; IsGame := False; PCName := ''; Sound.PlayClick(); SceneManager.SetScene(SceneRace); Exit; end; 2: begin Start(); Exit; end; end; end; 37: begin Dec(FSaveMenuPos); if (FSaveMenuPos < 0) then begin FSaveMenuPos := 2; if (I = 0) then FSaveMenuPos := 1; end; Sound.PlayClick(4); fMain.RefreshBox; Exit; end; 38: if (FSaveMenuPos <> 2) then FSaveMenuPos := 2 else begin if (FSavePos > 1) then begin Sound.PlayClick(4); Dec(FSavePos); end; if (FSavePos < FTopPCFile) and (FTopPCFile > 1) then Dec(FTopPCFile); fMain.RefreshBox; Exit; end; 39: begin Inc(FSaveMenuPos); if (I = 0) then J := 1 else J := 2; if (FSaveMenuPos > J) then FSaveMenuPos := 0; Sound.PlayClick(4); fMain.RefreshBox; Exit; end; 40: if (FSaveMenuPos <> 2) then FSaveMenuPos := 2 else begin if (FSavePos < I) then begin Inc(FSavePos); Sound.PlayClick(4); end; if (FSavePos > 7) and (GetSavePCCount > FTopPCFile + 6) then Inc(FTopPCFile); fMain.RefreshBox; Exit; end; 27: begin Sound.PlayClick; SceneManager.SetScene(SceneMenu); end; end; end; procedure TSceneSellect.Load; begin FIsLoad := True; FPath := Path + 'Data\HoD.ini'; FGraph := TGraph.Create(Path + 'Data\Images\Screens\'); FFont := TResFont.Create; FFont.LoadFromFile(Path + 'Data\Fonts\' + Ini.FontName); FLogo := Graphics.TBitmap.Create; FGraph.LoadImage('Tavern.jpg', FLogo); GUIBorder.Make(FLogo); FBack := Graphics.TBitmap.Create; FBack.LoadFromFile('Data\Images\GUI\BG.bmp'); FBack.Height := 516; FBack.Width := 400; FBack.Canvas.Font.Name := FFont.FontName; FRBack := Graphics.TBitmap.Create; FRBack.Assign(FBack); FRBack.Width := 370; GUIBorder.Make(FRBack); FRBack.Canvas.Font.Name := FFont.FontName; FHBack := Graphics.TBitmap.Create; FHBack.Assign(FBack); GUIBorder.Make(FBack); FHBack.Height := 60; FHBack.Width := 370; GUIBorder.Make(FHBack); FHBack.Canvas.Font.Name := FFont.FontName; FUBack := Graphics.TBitmap.Create; FUBack.Assign(FRBack); FUBack.Canvas.Font.Name := FFont.FontName; FLogo.Canvas.Draw(390, 10, FBack); FBtn[1] := TButton.Create(10, 540, FLogo.Canvas, 'Назад'); FBtn[2] := TButton.Create(220, 540, FLogo.Canvas, 'Новый'); FBtn[3] := TButton.Create(590, 540, FLogo.Canvas, 'Играть'); FBtn[4] := TButton.Create(728, 22, FLogo.Canvas, 'FB7.bmp', btShort); FBtn[5] := TButton.Create(728, 464, FLogo.Canvas, 'FB6.bmp', btShort); FBtn[6] := TButton.Create(430, 540, FLogo.Canvas, 'Info.bmp', btShort); FBtn[7] := TButton.Create(480, 540, FLogo.Canvas, 'BCub.bmp', btShort); FBtn[8] := TButton.Create(530, 540, FLogo.Canvas, 'Del.bmp', btShort); FVL := Graphics.TBitmap.Create; FVL.LoadFromFile('Data\Images\GUI\VLine.bmp'); FVL.Height := 70; FHL := Graphics.TBitmap.Create; FHL.LoadFromFile('Data\Images\GUI\HLine.bmp'); FHL.Width := 310; end; procedure TSceneSellect.LoadMenu; var C, I: Integer; begin FSavePos := 1; FTopPCFile := 1; IsShowRumours := False; ScanSaveDir(Path + 'Saves'); C := GetSavePCCount; if (C > 0) then begin FSaveMenuPos := 2; for I := 0 to C do if (GetSavePCName(I) = Ini.Read('Menu', 'LastPC', '')) then begin FSavePos := I; if FSavePos > 7 then FTopPCFile := FSavePos - 7 + 1; Exit; end; end else FSaveMenuPos := 1; end; function TSceneSellect.MouseDown(Button: TMouseBtn; X, Y: Integer): Boolean; var I: Byte; begin Result := False; for I := Low(FBtn) to High(FBtn) do FBtn[I].MouseDown(X, Y); SceneManager.Draw; end; function TSceneSellect.MouseMove(X, Y: Integer): Boolean; var I: Byte; begin Result := False; for I := Low(FBtn) to High(FBtn) do FBtn[I].Draw; SceneManager.Draw; end; procedure TSceneSellect.SaveMenu; begin Ini.Write('Menu', 'LastPC', GetSavePCName(FSavePos)); end; procedure TSceneSellect.Start; begin if GetSavePCName(FSavePos) <> '' then begin Sound.PlayClick(); VM.SetStr('Hero.Name', GetSavePCName(FSavePos)); SceneManager.DeleteScene(Enum); SaveMenu; DoGame; end; end; procedure TSceneSellect.DelChar; begin Sound.PlayClick(4); FSceneDelChar := TSceneDelChar.Create; SceneManager.SetScene(FSceneDelChar); end; function TSceneSellect.SavePos: Integer; begin Result := FSavePos; end; procedure TSceneSellect.Reload; begin FIsLoad := False; end; initialization SceneSellect := TSceneSellect.Create; finalization SceneSellect.Free; end.
//Exercicio 99: Fazer uma função que transforme horas, minutos e segundos em segundos. { Solução em Portugol Algoritmo Exercicio 99; Var H,M,S,RESULTADO: inteiro; Procedimento ConversorSegundos(aux: inteiro;Var resultado: inteiro); Var h,m,s: inteiro; Inicio exiba("Digite um número de horas:"); leia(h); enquanto(h < 0)faça exiba("Digite um número de horas válido."); leia(h); fimenquanto; exiba("Digite um número de minutos:"); leia(m); enquanto(m < 0)faça exiba("Digite um número de minutos válido."); leia(m); fimenquanto; exiba("Digite um número de segundos:"); leia(s); enquanto(s < 0)faça exiba("Digite um número de segundos válido."); leia(s); fimenquanto; resultado <- h * 3600 + m * 60 + s; Fim; Inicio Aux = 0; exiba("Programa que converte Horas, Minutos, Segundos em Segundos."); ConversorSegundos(Aux,RESULTADO); exiba(H," horas, ",M," minutos e ",S," segundos equivalem a ", RESULTADO," segundos."); Fim. } // Solução em Pascal Program Exercicio99; uses crt; Var Aux,RESULTADO: integer; Procedure ConversorHorario(aux: integer; Var resultado: integer); Var h,m,s: integer; Begin writeln('Digite um número de horas:'); readln(h); while(h < 0)do Begin writeln('Digite um número de horas válido.'); readln(h); End; writeln('Digite um número de minutos:'); readln(m); while(m < 0)do Begin writeln('Digite um número de minutos válido.'); readln(m); End; writeln('Digite um número de segundos:'); readln(s); while(s < 0)do Begin writeln('Digite um número de segundos válido.'); readln(s); End; resultado := h * 3600 + m * 60 + s; write(h,' horas, ',m,' minutos e ',s,' segundos equivalem a '); End; Begin Aux := 0; writeln('Programa que converte Horas, Minutos, Segundos em Segundos.'); ConversorHorario(Aux,RESULTADO); writeln(RESULTADO,' segundos.'); repeat until keypressed; end.
unit MvvmControls; {$mode objfpc}{$H+} interface uses Messages, Controls, StdCtrls, Forms, MvvmInterfaces, MvvmClasses; type TMvvmLabel = class(TLabel, IBoundControl) private FBindingName : string; procedure BindingSourceChanged(Source: IBindingSource); function GetBindingName() : string; procedure SetBindingName(const Value: string); public property BindingName : string read GetBindingName write SetBindingName; end; TMvvmForm = class(TForm, IView, IEventListener) private FBindingSource : IBindingSource; function GetBindingSource() : IBindingSource; procedure SetBindingSource(const Value: IBindingSource); procedure UpdateBoundControls(const Control: TControl; const PropertyName: string = ''); procedure CMSourceChanged(var Msg: TMessage); message CM_SOURCECHANGED; public property BindingSource : IBindingSource read FBindingSource write SetBindingSource; destructor Destroy(); override; end; implementation uses SysUtils, Classes; { TMvvmLabel } function TMvvmLabel.GetBindingName() : string; begin Result := FBindingName; end; procedure TMvvmLabel.SetBindingName(const Value: string); begin FBindingName := Value; end; procedure TMvvmLabel.BindingSourceChanged(Source: IBindingSource); begin Caption := Source.GetProperty(FBindingName); end; { TMvvmForm } destructor TMvvmForm.Destroy(); begin TEventManager.Current.RemoveListener(Self); inherited; end; function TMvvmForm.GetBindingSource() : IBindingSource; begin Result := FBindingSource; end; procedure TMvvmForm.SetBindingSource(const Value: IBindingSource); begin if (GetCurrentThreadId() <> MainThreadID) then raise Exception.Create('Non-GUI thread'); if (FBindingSource <> nil) then TEventManager.Current.RemoveListener(Self, FBindingSource); FBindingSource := Value; if (FBindingSource <> nil) then begin TEventManager.Current.AddListener(Self, Handle, FBindingSource); UpdateBoundControls(Self); end; end; procedure TMvvmForm.CMSourceChanged(var Msg: TMessage); var MessageID : integer; PropertyName : string; begin MessageID := Msg.LParam; PropertyName := TEventManager.Current.GetMessage(MessageID); if (PropertyName = '') then exit; UpdateBoundControls(Self, PropertyName); end; procedure TMvvmForm.UpdateBoundControls(const Control: TControl; const PropertyName: string = ''); var i : integer; View : IView; BoundControl : IBoundControl; begin if Supports(Control, IView, View) then if (View.BindingSource <> Self.BindingSource) then exit; if Supports(Control, IBoundControl, BoundControl) then if (BoundControl.BindingName <> '') then if (BoundControl.BindingName = PropertyName) or (PropertyName = '') then BoundControl.BindingSourceChanged(BindingSource); if (Control is TWinControl) then for i := 0 to TWinControl(Control).ControlCount-1 do UpdateBoundControls(TWinControl(Control).Controls[i], PropertyName); end; end.
unit ZMWUtils19; (* ZMWUtils19.pas - Windows file functions supporting Unicode names 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 modified 2008-08-28 ---------------------------------------------------------------------------*) interface uses Windows, SysUtils; function FindLastW(const ws: widestring; const wc: widechar): integer; function FindFirstW(const ws: widestring; const wc: widechar): integer; function ExtractFilePathW(const path: widestring): widestring; function DelimitPathW(const Path: widestring; Sep: Boolean): widestring; function DirExistsW(const Fname: WideString): boolean; function ForceDirectoryW(const Dir: widestring): boolean; function FileCreateW(const fname: widestring): cardinal; implementation uses ZMStructs19; function FindLastW(const ws: widestring; const wc: widechar): integer; var i: integer; begin Result := -1; for i := 1 to Length(ws) - 1 do if ws[i] = wc then begin Result := i; end; end; function FindFirstW(const ws: widestring; const wc: widechar): integer; begin for Result := 1 to Length(ws) - 1 do if ws[Result] = wc then Exit; Result := -1; end; function ExtractFilePathW(const path: widestring): widestring; var d, c: integer; begin Result := ''; c := FindFirstW(path, ':'); d := FindLastW(path, PathDelim); if (d > c) and (d >= 1) then Result := Copy(path, 1, pred(d)); end; function DelimitPathW(const Path: widestring; Sep: Boolean): widestring; begin Result := Path; if Length(Path) = 0 then begin if Sep then Result := PathDelim{'\'}; exit; end; // if (AnsiLastChar(Path)^ = PathDelim) <> Sep then if (Path[Length(Path)] = PathDelim) <> Sep then begin if Sep then Result := Path + PathDelim else Result := Copy(Path, 1, pred(Length(Path))); end; end; function DirExistsW(const Fname: WideString): boolean; var Code: DWORD; begin Result := True; // current directory exists if Fname <> '' then begin Code := GetFileAttributesW(PWideChar(Fname)); Result := (Code <> MAX_UNSIGNED) and ((FILE_ATTRIBUTE_DIRECTORY and Code) <> 0); end; end; function ForceDirectoryW(const Dir: widestring): boolean; var sDir: widestring; begin Result := True; if Dir <> '' then begin sDir := DelimitPathW(Dir, False); if DirExistsW(sDir) or (ExtractFilePathW(sDir) = sDir) then exit; // avoid 'c:\xyz:\' problem. if ForceDirectoryW(ExtractFilePathW(sDir)) then Result := CreateDirectoryW(PWideChar(sDir), nil) else Result := False; end; end; function FileCreateW(const fname: widestring): cardinal; begin Result := CreateFileW(pWideChar(fname), GENERIC_WRITE, 0, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); end; end.