text
stringlengths
14
6.51M
{ *************************************************************************** Copyright (c) 2016-2019 Kike Pérez Unit : Quick.ORM.RestClient.Cross Description : Rest ORM Client access by http, httpapi or websockets mobile Author : Kike Pérez Version : 1.5 Created : 02/06/2017 Modified : 08/05/2019 This file is part of QuickORM: https://github.com/exilon/QuickORM Uses Synopse mORMot framework. Copyright (C) 2017 Arnaud Bouchez Synopse Informatique - https://synopse.info *************************************************************************** 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 Quick.ORM.RestClient.Cross; {$i QuickORM.inc} {$INCLUDE synopse.inc} interface uses Classes, SysUtils, SynCrossPlatformJSON, SynCrossPlatformREST, SynCrossPlatformCrypto, SynCrossPlatformSpecific, //SynCrtSock, //mORMot, //mORMotSQLite3, //mORMotHttpClient, Quick.ORM.Engine; //Quick.ORM.Security.GUI; const DEF_CONNECTION_TIMEOUT = 20000; type TAuthLogin = class private fUserName : RawUTF8; fHashedPassword : RawUTF8; function ComputeHashedPassword(const aPasswordPlain, aHashSalt: RawUTF8): RawUTF8; procedure HashPassword(value : RawUTF8); public property UserName : RawUTF8 read fUserName write fUserName; property UserPass : RawUTF8 write HashPassword; property HashedPassword : RawUTF8 read fHashedPassword write fHashedPassword; end; THTTPClientOptions = class private fAuthMode : TAuthMode; fProtocol : TSrvProtocol; fConnectionTimeout : Integer; fSendTimeout : Integer; fReceiveTimeout : Integer; fConnectTimeout : Integer; fWSEncryptionKey : RawUTF8; fNamedPipe : RawUTF8; public property AuthMode : TAuthMode read fAuthMode write fAuthMode; property Protocol : TSrvProtocol read fProtocol write fProtocol; property ConnectionTimeout : Integer read fConnectionTimeout write fConnectionTimeout; property SendTimeout : Integer read fSendTimeout write fSendTimeout; property ReceiveTimeout : Integer read fReceiveTimeout write fReceiveTimeout; property ConnectTimeout : Integer read fConnectTimeout write fConnectTimeout; property WSEncryptionKey : RawUTF8 read fWSEncryptionKey write fWSEncryptionKey; property NamedPipe : RawUTF8 read fNamedPipe write fNamedPipe; constructor Create; end; //Client with DB access througth an http server TORMDataBaseConnection = class private fModel : TSQLModel; fIncludedClasses : TSQLRecordClassArray; faRootURI : RawUTF8; public property Model : TSQLModel read fModel write fModel; property IncludedClasses : TSQLRecordClassArray read fIncludedClasses write fIncludedClasses; property aRootURI : RawUTF8 read faRootURI write faRootURI; constructor Create; destructor Destroy; override; end; TORMServiceClient = class private fORMClient : TORMClient; fMethodInterface : TGUID; fInstanceImplementation : TServiceInstanceImplementation; fEnabled : Boolean; public constructor Create; property MethodInterface : TGUID read fMethodInterface write fMethodInterface; property InstanceImplementation : TServiceInstanceImplementation read fInstanceImplementation write fInstanceImplementation; property Enabled : Boolean read fEnabled write fEnabled; procedure SetORM(fORM : TORMClient); function SetRestMethod(out Obj) : Boolean; end; TConnectEvent = procedure of object; TConnectErrorEvent = procedure of object; TORMRestClient = class private fDataBase : TORMDataBaseConnection; fHost : RawUTF8; fPort : Integer; fHTTPOptions : THTTPClientOptions; fService : TORMServiceClient; fLogin : TAuthLogin; fOnConnect : TConnectEvent; fOnConnectError : TConnectErrorEvent; public ORM : TORMClient; property Login : TAuthLogin read fLogin write fLogin; property Host : RawUTF8 read fHost write fHost; property Port : Integer read fPort write fPort; property DataBase : TORMDataBaseConnection read fDataBase write fDataBase; property HTTPOptions : THTTPClientOptions read fHTTPOptions write fHTTPOptions; property Service : TORMServiceClient read fService write fService; property OnConnect : TConnectEvent read fOnConnect write fOnConnect; property OnConnectError : TConnectErrorEvent read fOnConnectError write fOnConnectError; constructor Create; destructor Destroy; override; function Connect(const aServer : string; aPort : Integer) : Boolean; overload; function Connect : Boolean; overload; function LoginPrompt(ShowHostPrompt : Boolean = True) : Boolean; function ActionAllowed(const Action : string) : Boolean; end; var /// THttpRequest timeout default value for DNS resolution // - leaving to 0 will let system default value be used HTTP_DEFAULT_RESOLVETIMEOUT: integer = 0; /// THttpRequest timeout default value for remote connection // - default is 60 seconds // - used e.g. by THttpRequest, TSQLHttpClientRequest and TSQLHttpClientGeneric HTTP_DEFAULT_CONNECTTIMEOUT: integer = 60000; /// THttpRequest timeout default value for data sending // - default is 30 seconds // - used e.g. by THttpRequest, TSQLHttpClientRequest and TSQLHttpClientGeneric // - you can override this value by setting the corresponding parameter in // THttpRequest.Create() constructor HTTP_DEFAULT_SENDTIMEOUT: integer = 30000; /// THttpRequest timeout default value for data receiving // - default is 30 seconds // - used e.g. by THttpRequest, TSQLHttpClientRequest and TSQLHttpClientGeneric // - you can override this value by setting the corresponding parameter in // THttpRequest.Create() constructor HTTP_DEFAULT_RECEIVETIMEOUT: integer = 30000; implementation {TAuthLogin} function TAuthLogin.ComputeHashedPassword(const aPasswordPlain, aHashSalt: RawUTF8): RawUTF8; const TSQLAUTHUSER_SALT = 'salt'; begin if aHashSalt='' then Result := SHA256(TSQLAUTHUSER_SALT+aPasswordPlain) else SHA256(aHashSalt+aPasswordPlain); end; procedure TAuthLogin.HashPassword(value : RawUTF8); begin fHashedPassword := ComputeHashedPassword(value,''); end; {TORMDataBaseConnection Class} constructor TORMDataBaseConnection.Create; begin inherited; faRootURI := DEF_ROOTURI; end; destructor TORMDataBaseConnection.Destroy; begin if Assigned(fModel) then fModel.Free; inherited; end; {THTTPClientOptions Class} constructor THTTPClientOptions.Create; begin inherited; fProtocol := spHTTP_Socket; fConnectionTimeout := DEF_CONNECTION_TIMEOUT; fAuthMode := amNoAuthentication; fSendTimeout := HTTP_DEFAULT_SENDTIMEOUT; fReceiveTimeout := HTTP_DEFAULT_RECEIVETIMEOUT; fConnectTimeout := HTTP_DEFAULT_CONNECTTIMEOUT; fWSEncryptionKey := DEF_ENCRYPTIONKEY; fNamedPipe := DEF_NAMEDPIPE; end; {TORMServiceClient Class} constructor TORMServiceClient.Create; begin inherited; fEnabled := False; end; procedure TORMServiceClient.SetORM(fORM : TORMClient); begin fORMClient := fORM; end; function TORMServiceClient.SetRestMethod(out Obj) : Boolean; begin // falta saber como resolver Result := fORMClient.Services.Resolve(fMethodInterface, obj); end; {TORMRestClient Class} constructor TORMRestClient.Create; begin inherited; fDataBase := TORMDataBaseConnection.Create; fLogin := TAuthLogin.Create; fLogin.UserName := 'User'; fLogin.UserPass := ''; fHTTPOptions := THTTPClientOptions.Create; fService := TORMServiceClient.Create; end; destructor TORMRestClient.Destroy; begin if Assigned(ORM) then ORM.Free; if Assigned(fLogin) then fLogin.Free; if Assigned(fHTTPOptions) then fHTTPOptions.Free; if Assigned(fDataBase) then fDataBase.Free; if Assigned(fService) then fService.Free; inherited; end; function TORMRestClient.Connect(const aServer : string; aPort : Integer) : Boolean; begin fHost := aServer; fPort := aPort; Result := Connect; end; function TORMRestClient.Connect : Boolean; begin Result := False; try //not needed in client mode if fHTTPOptions.AuthMode in [TAuthMode.amDefault,TAuthMode.amSimple] then fDataBase.IncludedClasses := fDataBase.IncludedClasses + [TORMAuthUser] + [TORMAuthGroup]; fDataBase.Model := TSQLModel.Create(fDataBase.IncludedClasses,fDataBase.aRootURI); //Protocol initialization case fHTTPOptions.Protocol of spHTTP_Socket: begin ORM := TSQLRestClientHTTP.Create(fHost,fPort,fDataBase.Model,True,False,'','',fHTTPOptions.SendTimeout,fHTTPOptions.ReceiveTimeout,fHTTPOptions.ConnectionTimeout); TSQLRestClientHTTP(ORM).KeepAlive := fHTTPOptions.ConnectionTimeout; end; spHTTP_SSL: begin ORM := TSQLRestClientHTTP.Create(fHost,fPort,fDataBase.Model,True,True,'','',fHTTPOptions.SendTimeout,fHTTPOptions.ReceiveTimeout,fHTTPOptions.ConnectionTimeout); TSQLRestClientHTTP(ORM).KeepAlive := fHTTPOptions.ConnectionTimeout; end; spHTTP_AES: begin raise Exception.Create('Protocol not implemented yet!'); ORM := TSQLRestClientHTTP.Create(fHost,fPort,fDataBase.Model,True,False,'','',fHTTPOptions.SendTimeout,fHTTPOptions.ReceiveTimeout,fHTTPOptions.ConnectionTimeout); TSQLRestClientHTTP(ORM).KeepAlive := fHTTPOptions.ConnectionTimeout; //ORM := TSQLHttpClientWinHTTP.Create(fHost,IntToStr(fPort), fDataBase.Model, True, '', '', fHTTPOptions.SendTimeout, fHTTPOptions.ReceiveTimeout, fHTTPOptions.ConnectTimeout); //TSQLHttpClientWinHTTP(ORM).KeepAliveMS := fHTTPOptions.ConnectionTimeout; //TSQLHttpClientWinHTTP(ORM).Compression := [hcSynShaAes]; end; spHTTP_WebSocket: begin raise Exception.Create('Protocol not implemented yet!'); //ORM := TSQLHttpClientWebsockets.Create(fHost,IntToStr(fPort), fDataBase.Model, fHTTPOptions.SendTimeout, fHTTPOptions.ReceiveTimeout, fHTTPOptions.ConnectTimeout); //TSQLHttpClientWebsockets(ORM).KeepAliveMS := fHTTPOptions.ConnectionTimeout; end; spWebSocketBidir_JSON: begin raise Exception.Create('Protocol not implemented yet!'); //ORM := TSQLHttpClientWebsockets.Create(fHost,IntToStr(fPort), fDataBase.Model, fHTTPOptions.SendTimeout, fHTTPOptions.ReceiveTimeout, fHTTPOptions.ConnectTimeout); //TSQLHttpClientWebsockets(ORM).KeepAliveMS := fHTTPOptions.ConnectionTimeout; //(ORM as TSQLHttpClientWebsockets).WebSocketsUpgrade('', True); end; spWebSocketBidir_Binary: begin raise Exception.Create('Protocol not implemented yet!'); //ORM := TSQLHttpClientWebsockets.Create(fHost,IntToStr(fPort), fDataBase.Model, fHTTPOptions.SendTimeout, fHTTPOptions.ReceiveTimeout, fHTTPOptions.ConnectTimeout); //TSQLHttpClientWebsockets(ORM).KeepAliveMS := fHTTPOptions.ConnectionTimeout; //(ORM as TSQLHttpClientWebsockets).WebSocketsUpgrade('', False); end; spWebSocketBidir_BinaryAES: begin raise Exception.Create('Protocol not implemented yet!'); //ORM := TSQLHttpClientWebsockets.Create(fHost,IntToStr(fPort), fDataBase.Model, fHTTPOptions.SendTimeout, fHTTPOptions.ReceiveTimeout, fHTTPOptions.ConnectTimeout); //TSQLHttpClientWebsockets(ORM).KeepAliveMS := fHTTPOptions.ConnectionTimeout; //(ORM as TSQLHttpClientWebsockets).WebSocketsUpgrade(fHTTPOptions.WSEncryptionKey, False); end; else begin raise Exception.Create('Protocol not available!'); end; end; Result := ORM.Connect; //Check TimeSync with Server if (not ORM.Connect) or (ORM.ServerTimeStamp = 0) then begin Result := False; //raise Exception.Create('Can''t connect to server'); end; //Authmode initialization if Result then case fHTTPOptions.AuthMode of amNoAuthentication: //No user Authentication begin //nothing to do here Result := True; //shows as connected ever ??? end; amSimple: begin //TSQLRestServerAuthenticationNone (uses user/pass but not signature on client side) raise Exception.Create('Authmethod not implemented yet!'); //Result := TSQLRestServerAuthenticationNone.ClientSetUser(ORM,fLogin.UserName,fLogin.HashedPassword,passHashed); end; amDefault: //TSQLRestServerAuthenticationDefault (uses user/pass with signature on client side) begin Result := ORM.SetUser(TSQLRestServerAuthenticationDefault,fLogin.UserName,fLogin.HashedPassword,True); end; amHttpBasic: //TSQLRestServerAuthenticationHttpBasic begin raise Exception.Create('Authmethod not implemented yet!'); //Result := TSQLRestServerAuthenticationHttpBasic.ClientSetUser(ORM,fLogin.UserName,fLogin.HashedPassword,passHashed); end; else begin raise Exception.Create('Authentication mode not available'); end; end; if Result then begin //Service initialization if fService.Enabled then begin fService.SetORM(ORM); //mirar como resolver ORM.ServiceDefine([fService.fMethodInterface],fService.fInstanceImplementation); end; end; finally if Result then begin if Assigned(fOnConnect) then fOnConnect; end else begin if Assigned(fOnConnectError) then fOnConnectError; end end; end; function TORMRestClient.LoginPrompt(ShowHostPrompt : Boolean = True) : Boolean; //var // LoginGUI : TORMLoginGUI; begin {Result := False; LoginGUI := TORMLoginGUI.Create; try LoginGUI.Host := fHost; LoginGUI.Port := fPort; if LoginGUI.LoginPrompt(True) then begin fHost := LoginGUI.Host; fPort := LoginGUI.Port; fLogin.UserName := LoginGUI.UserName; fLogin.HashedPassword := LoginGUI.UserPass; Result := Connect; end; finally LoginGUI.Free; end;} end; function TORMRestClient.ActionAllowed(const Action : string) : Boolean; begin //Result := Self.fMyAuthGroup.AppAction(Action).Allowed; end; end.
unit adpMRU; { TadpMRU Full source code of a TadpMRU component, a non-visual component which simplifies implementing a "Most Recently Used" file list in a menu (or a popup menu). The TadpMRU component allows for quick selection of a file that was recently accessed (opened) in an application. How to use: http://delphi.about.com/library/weekly/aa112503a.htm ............................................. Modified by Gary McIntosh to use ini files and have multiple sections using ini files. To move last menu item clicked to top of the menu list and all others down one position. .............................................. Zarko Gajic, BSCS About Guide to Delphi Programming http://delphi.about.com how to advertise: http://delphi.about.com/library/bladvertise.htm free newsletter: http://delphi.about.com/library/blnewsletter.htm forum: http://forums.about.com/ab-delphi/start/ .............................................. } interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.IniFiles, System.Classes, System.Win.Registry, VCL.Menus, Vcl.Dialogs, GEMComponentsGlobal; type TMRUClickEvent = procedure(Sender: TObject; const FileName: String) of object; TadpMRU = class(TComponent) private FItems : TStringList; FMaxItems : cardinal; FShowFullPath : boolean; FRegistryPath : string; FIniFilePath : string; FParentMenuItem : TMenuItem; FOnClick : TMRUClickEvent; FUseIniFile : Boolean; fGroupIndex : byte; fRadioItem : Boolean; FVersion : string; fSectionIniNameReg : string; procedure SetMaxItems(const Value: cardinal); procedure SetUseIniFile(const Value: Boolean); procedure SetShowFullPath(const Value: boolean); procedure SetRegistryPath(const Value: string); procedure SetParentMenuItem(const Value: TMenuItem); procedure LoadMRU; procedure SaveMRU; procedure ItemsChange(Sender: TObject); procedure ClearParentMenu; procedure SetIniFilePath(const Value: string); function GetVersion: string; procedure SetSectionIniNameReg(const Value: string); function GetTheItems: TStringList; procedure SetVersion(const Value: string); protected procedure Loaded; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure DoClick(Sender: TObject); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure AddItem(const aSection, aFileName: string; aResetIFNewSection: Boolean = false); function RemoveItem(const FileName : string) : boolean; procedure SetupNewSection(const aSection: string); function GetSectionNames: TStrings; published property IniFilePath: string read FIniFilePath write SetIniFilePath; property GroupIndex: Byte read fGroupIndex write fGroupIndex; property MaxItems: cardinal read FMaxItems write SetMaxItems default 7; property ShowFullPath: boolean read FShowFullPath write SetShowFullPath default True; property RegistryPath: string read FRegistryPath write SetRegistryPath; property ParentMenuItem: TMenuItem read FParentMenuItem write SetParentMenuItem; property RadioItem: boolean read fRadioItem write fRadioItem default False; property UseIniFile: Boolean read FUseIniFile write SetUseIniFile;// default True; property Version: string read GetVersion write SetVersion; property StartingSection: string read fSectionIniNameReg write SetSectionIniNameReg; property TheItems: TStringList read GetTheItems; property OnClick: TMRUClickEvent read FOnClick write FOnClick; end; //procedure Register; implementation type TMRUMenuItem = class(TMenuItem); //to be able to recognize MRU menu item when deleting //procedure Register; //begin // RegisterComponents('Gary"s Stuff', [TadpMRU]); //end; { TadpMRU } constructor TadpMRU.Create(AOwner: TComponent); begin inherited; FParentMenuItem := nil; FItems := TStringList.Create; FItems.OnChange := ItemsChange; // FMaxItems := 4; FShowFullPath := True; // FUseIniFile := True; // fGroupIndex := 0; // RadioItem := False; fVersion := VersionAdpMRU; // fHint := ''; // fCheckedMenuItem := -1; end; (*Create*) procedure TadpMRU.Loaded; begin inherited; if not (csDesigning in ComponentState) then if FUseIniFile then begin if FIniFilePath <> '' then LoadMRU; end else begin if FRegistryPath <> '' then LoadMRU; end; end; (*Loaded*) destructor TadpMRU.Destroy; begin if not (csDesigning in ComponentState) then SaveMRU; FItems.OnChange := nil; FItems.Free; inherited; end; (*Destroy*) procedure TadpMRU.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (Operation = opRemove) and (AComponent = FParentMenuItem) then FParentMenuItem := nil; end; (*Notification*) procedure TadpMRU.AddItem(const aSection, aFileName: string; aResetIFNewSection: Boolean = false); begin if aFileName <> '' then begin Trim(aSection); if aSection <> '' then begin if (fSectionIniNameReg <> aSection) and aResetIFNewSection and FUseIniFile then begin // showmessage('reset '+aSection+ ' '+ fSectionIniNameReg); SaveMRU; fSectionIniNameReg := aSection; LoadMRU; end else begin fSectionIniNameReg := aSection; // showmessage('not reset '+fSectionIniNameReg); end; end; FItems.BeginUpdate; // showmessage('Stuff '+fSectionIniNameReg+' '+aFileName); try if FItems.IndexOf(aFileName) > -1 then FItems.Delete(FItems.IndexOf(aFileName)); FItems.Insert(0, aFileName); while Cardinal(FItems.Count) > MaxItems do FItems.Delete(MaxItems); finally FItems.EndUpdate; ItemsChange(Self); end; end; end; (*AddItem*) function TadpMRU.RemoveItem(const FileName: string): boolean; begin if FItems.IndexOf(FileName) > -1 then begin FItems.Delete(FItems.IndexOf(FileName)); Result := True; end else Result := False; end; (*RemoveItem*) //procedure TadpMRU.SetHint(const Value: string); //begin // if Value <> FHint then // fHint := Value; //end; procedure TadpMRU.SetIniFilePath(const Value: string); begin if (FIniFilePath <> Value) then begin FIniFilePath := Value; LoadMRU; end; end; (*SetIniFilePath*) procedure TadpMRU.SetUseIniFile(const Value: Boolean); begin if (FUseIniFile <> Value) then begin FUseIniFile := Value; ItemsChange(Self); end; end; (*SetUseIniFile*) procedure TadpMRU.SetMaxItems(const Value: Cardinal); begin if Value <> FMaxItems then begin if Value < 1 then FMaxItems := 1 else if Value > Cardinal(MaxInt) then FMaxItems := MaxInt - 1 else begin FMaxItems := Value; FItems.BeginUpdate; try while Cardinal(FItems.Count) > MaxItems do FItems.Delete(FItems.Count - 1); finally FItems.EndUpdate; end; end; end; ItemsChange(Self); end; (*SetMaxItems*) procedure TadpMRU.SetRegistryPath(const Value: string); begin if FRegistryPath <> Value then begin FRegistryPath := Value; LoadMRU; end; end; (*SetRegistryPath*) procedure TadpMRU.SetSectionIniNameReg(const Value: string); begin if (fSectionIniNameReg <> Value) then begin SaveMRU; fSectionIniNameReg := Value; LoadMRU; ItemsChange(Self); end; end; procedure TadpMRU.SetShowFullPath(const Value: boolean); begin if FShowFullPath <> Value then begin FShowFullPath := Value; ItemsChange(Self); end; end; //procedure TadpMRU.SetTheItems(const Value: TStringList); //begin // FItems := Value; //end; // procedure TadpMRU.SetupNewSection(const aSection: string); begin if (fSectionIniNameReg <> aSection) then begin SaveMRU; fSectionIniNameReg := aSection; LoadMRU; ItemsChange(Self); end; end; procedure TadpMRU.SetVersion(const Value: string); begin FVersion := VersionAdpMRU; end; function TadpMRU.GetSectionNames: TStrings; begin result := nil; if FUseIniFile and FileExists(FIniFilePath) then with TIniFile.Create(FIniFilePath) do try ReadSections(result); finally Free; end; end; function TadpMRU.GetTheItems: TStringList; begin Result := FItems; end; function TadpMRU.GetVersion: string; begin result := VersionAdpMRU;//VersionAdpMRU; end; (*SetShowFullPath*) procedure TadpMRU.LoadMRU; var i: cardinal; s: string; begin if FUseIniFile then begin if FileExists(FIniFilePath) then with TIniFile.Create(FIniFilePath) do begin FItems.BeginUpdate; FItems.Clear; try for i := 1 to FMaxItems do if ValueExists(fSectionIniNameReg, fSectionIniNameReg+IntToStr(i)) then begin s := ReadString(fSectionIniNameReg, fSectionIniNameReg+IntToStr(i),'None'); FItems.Add(s); end; finally FItems.EndUpdate; Free; end; end; end else begin with TRegistry.Create do try RootKey := HKEY_CURRENT_USER; if OpenKey(FRegistryPath, False) then begin FItems.BeginUpdate; FItems.Clear; try for i := 1 to FMaxItems do if ValueExists(fSectionIniNameReg+IntToStr(i)) then FItems.Add(ReadString(fSectionIniNameReg+IntToStr(i))); finally FItems.EndUpdate; end; CloseKey; end; finally Free; end; end; end; (*LoadMRU*) procedure TadpMRU.SaveMRU; var i: integer; begin if FUseIniFile then begin with TIniFile.Create(FIniFilePath) do try EraseSection(fSectionIniNameReg); for i := 0 to -1 + FItems.Count do WriteString(fSectionIniNameReg, fSectionIniNameReg+IntToStr(i+1), FItems[i]); finally Free; end; end else begin with TRegistry.Create do try RootKey := HKEY_CURRENT_USER; if OpenKey(FRegistryPath, True) then begin //delete old mru i:=1; while ValueExists(fSectionIniNameReg+IntToStr(i)) do begin DeleteValue(fSectionIniNameReg+IntToStr(i)); Inc(i); end; //write new mru for i := 0 to -1 + FItems.Count do WriteString(fSectionIniNameReg+IntToStr(i+1),FItems[i]); CloseKey; end; finally Free; end; end; end; (*SaveMRU*) procedure TadpMRU.ItemsChange(Sender: TObject); var i: Integer; NewMenuItem: TMenuItem; FileName: String; begin if ParentMenuItem <> nil then begin ClearParentMenu; for i := 0 to -1 + FItems.Count do begin if ShowFullPath then FileName := StringReplace(FItems[I], '&', '&&', [rfReplaceAll, rfIgnoreCase]) else FileName := StringReplace(ExtractFileName(FItems[i]), '&', '&&', [rfReplaceAll, rfIgnoreCase]); NewMenuItem := TMRUMenuItem.Create(Self); NewMenuItem.GroupIndex := fGroupIndex; if fRadioItem then NewMenuItem.RadioItem := True; NewMenuItem.Caption := Format('%s', [FileName]); // if fHint <> '' then // NewMenuItem.Hint := fHint; NewMenuItem.Tag := i; NewMenuItem.OnClick := DoClick; ParentMenuItem.Add(NewMenuItem); end; end; end; (*ItemsChange*) procedure TadpMRU.ClearParentMenu; var i:integer; begin if Assigned(ParentMenuItem) then for i:= -1 + ParentMenuItem.Count downto 0 do if ParentMenuItem.Items[i] is TMRUMenuItem then ParentMenuItem.Delete(i); end; (*ClearParentMenu*) procedure TadpMRU.DoClick(Sender: TObject); var ListIndex: Integer; S: string; begin if Assigned(FOnClick) and (Sender is TMRUMenuItem) then begin FOnClick(Self, FItems[TMRUMenuItem(Sender).Tag]); TMRUMenuItem(Sender).checked := True; // fCheckedMenuItem := TMRUMenuItem(Sender).Tag; s := StringReplace(TMRUMenuItem(Sender).Caption, '&', '',[rfReplaceAll, rfIgnoreCase]); ListIndex := FItems.IndexOf(s); // ShowMessage(TMRUMenuItem(Sender).Caption+' '+IntToStr(ListIndex)); if ListIndex > -1 then begin FItems.BeginUpdate; FItems.Move(ListIndex, 0); ItemsChange(Self); FItems.EndUpdate; end; end; end;(*DoClick*) procedure TadpMRU.SetParentMenuItem(const Value: TMenuItem); begin if FParentMenuItem <> Value then begin ClearParentMenu; FParentMenuItem := Value; ItemsChange(Self); end; end; (*SetParentMenuItem*) (*adpMRU.pas*) end.
unit libLinks; interface uses Windows, ShellApi, SysUtils, FileUtil, ShlObj, ComObj, ActiveX, Registry; function CreateShortcut(const CmdLine, Args, WorkDir, LinkFile: string):IPersistFile; function CreateShortcuts(vPath: string): string; function CreateAppPath(vPath, vExeName: string): string; procedure DeleteShortcuts(vPath: string); procedure CreateAutoRunLoader; procedure DeleteAutoRunLoader; procedure ToRecycle(AHandle: THandle; const ADirName: String); implementation procedure ToRecycle(AHandle: THandle; const ADirName: String); var SHFileOpStruct: TSHFileOpStruct; DirName: PChar; BufferSize: Cardinal; begin BufferSize := Length(ADirName) +1 +1; GetMem(DirName, BufferSize); try FillChar(DirName^, BufferSize, 0); StrCopy(DirName, PChar(ADirName)); with SHFileOpStruct do begin Wnd := AHandle; wFunc := FO_DELETE; pFrom := DirName; pTo := nil; fFlags := FOF_ALLOWUNDO or FOF_NOCONFIRMATION or FOF_SILENT; fAnyOperationsAborted := True; hNameMappings := nil; lpszProgressTitle := nil; end; if SHFileOperation(SHFileOpStruct) <> 0 then RaiseLastWin32Error; finally FreeMem(DirName, BufferSize); end; end; function CreateShortcut(const CmdLine, Args, WorkDir, LinkFile: string):IPersistFile; var MyObject : IUnknown; MySLink : IShellLink; MyPFile : IPersistFile; WideFile : WideString; begin MyObject := CreateComObject(CLSID_ShellLink); MySLink := MyObject as IShellLink; MyPFile := MyObject as IPersistFile; with MySLink do begin SetPath(PChar(CmdLine)); SetArguments(PChar(Args)); SetWorkingDirectory(PChar(WorkDir)); end; WideFile := LinkFile; MyPFile.Save(PWChar(WideFile), False); Result := MyPFile; end; function CreateShortcuts(vPath: string): string; var Directory, ExecDir: String; MyReg: TRegIniFile; begin MyReg := TRegIniFile.Create( 'Software\MicroSoft\Windows\CurrentVersion\Explorer'); ExecDir := vPath; Directory := MyReg.ReadString('Shell Folders', 'Programs', '') + '\' + 'PrivateDialer'; CreateDir(Directory); MyReg.Free; CreateAutoRunLoader; CreateShortcut(ExecDir + '\PrivateDialer.exe', '', ExecDir, Directory + '\PrivateDialer.lnk'); CreateShortcut(ExecDir + '\Provider.exe', '', ExecDir, Directory + '\Provider.lnk'); CreateShortcut(ExecDir + '\Readme.txt', '', ExecDir, Directory + '\Readme.lnk'); CreateShortcut(ExecDir + '\Install.exe', '', ExecDir, Directory + '\Uninstall.lnk'); Result := Directory; end; function CreateAppPath(vPath, vExeName: string): string; var MyReg: TRegIniFile; begin MyReg := TRegIniFile.Create( 'Software\MicroSoft\Windows\CurrentVersion\App Paths\' + vExeName); MyReg.WriteString(vExeName, 'Path', vPath); Result := MyReg.ReadString(vExeName, 'Path', vPath); MyReg.Free; end; procedure DeleteShortcuts(vPath: string); var Directory, ExecDir: String; MyReg: TRegIniFile; sa : string; begin MyReg := TRegIniFile.Create( 'Software\MicroSoft\Windows\CurrentVersion\Explorer'); ExecDir := vPath; Directory := MyReg.ReadString('Shell Folders', 'Programs', '') + '\' + 'PrivateDialer'; MyReg.DeleteKey('Shell Folders', 'Programs'+'\' + 'PrivateDialer'); MyReg.Free; sa := Directory + '\*.lnk'; DeleteFilesEx(sa); RemoveDir(Directory); DeleteAutoRunLoader; end; procedure CreateAutoRunLoader; var MyReg: TRegIniFile; begin MyReg := TRegIniFile.Create( 'Software\MicroSoft\Windows\CurrentVersion'); MyReg.WriteString('Run', 'LoadRasDriver', 'rundll32.exe loader.dll,RunDll'); MyReg.Free; end; procedure DeleteAutoRunLoader; var MyReg: TRegIniFile; begin MyReg := TRegIniFile.Create( 'Software\MicroSoft\Windows\CurrentVersion'); MyReg.DeleteKey('Run', 'LoadRasDriver'); MyReg.Free; end; end.
unit ConfiguracaoBO; interface uses Data.SqlExpr, SysUtils, Forms, Windows, Util, ConfiguracaoDAO, Configuracao; type TConfiguracaoBO = class private { private declarations } public function ObterConfiguracao:TConfiguracao; procedure Salvar(Configuracao: TConfiguracao); end; implementation { TConfiguracaoBO } function TConfiguracaoBO.ObterConfiguracao: TConfiguracao; var ConfiguracaoDAO: TConfiguracaoDAO; begin try ConfiguracaoDAO := TConfiguracaoDAO.Create; Result := ConfiguracaoDAO.ObterConfiguracao(); FreeAndNil(ConfiguracaoDAO); except on E: Exception do begin raise Exception.Create(E.Message); end; end; end; procedure TConfiguracaoBO.Salvar(Configuracao: TConfiguracao); var ConfiguracaoDAO: TConfiguracaoDAO; begin try ConfiguracaoDAO := TConfiguracaoDAO.Create; ConfiguracaoDAO.Salvar(Configuracao); FreeAndNil(ConfiguracaoDAO); except on E: Exception do begin raise Exception.Create(E.Message); end; end; end; end.
unit multiloglcl; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Graphics, multilog; type { TLCLLogger } TLCLLogger = class(TLogger) private public procedure SendBitmap(const AText: String; ABitmap: TBitmap); //inline; procedure SendBitmap(Classes: TDebugClasses; const AText: String; ABitmap: TBitmap); procedure SendColor(const AText: String; AColor: TColor); //inline; procedure SendColor(Classes: TDebugClasses; const AText: String; AColor: TColor); end; function ColorToStr(Color: TColor): String; implementation uses IntfGraphics, GraphType, FPimage, FPWriteBMP; function ColorToStr(Color: TColor): String; begin case Color of clBlack : Result:='clBlack'; clMaroon : Result:='clMaroon'; clGreen : Result:='clGreen'; clOlive : Result:='clOlive'; clNavy : Result:='clNavy'; clPurple : Result:='clPurple'; clTeal : Result:='clTeal'; clGray {clDkGray} : Result:='clGray/clDkGray'; clSilver {clLtGray} : Result:='clSilver/clLtGray'; clRed : Result:='clRed'; clLime : Result:='clLime'; clYellow : Result:='clYellow'; clBlue : Result:='clBlue'; clFuchsia : Result:='clFuchsia'; clAqua : Result:='clAqua'; clWhite : Result:='clWhite'; clCream : Result:='clCream'; clNone : Result:='clNone'; clDefault : Result:='clDefault'; clMoneyGreen : Result:='clMoneyGreen'; clSkyBlue : Result:='clSkyBlue'; clMedGray : Result:='clMedGray'; clScrollBar : Result:='clScrollBar'; clBackground : Result:='clBackground'; clActiveCaption : Result:='clActiveCaption'; clInactiveCaption : Result:='clInactiveCaption'; clMenu : Result:='clMenu'; clWindow : Result:='clWindow'; clWindowFrame : Result:='clWindowFrame'; clMenuText : Result:='clMenuText'; clWindowText : Result:='clWindowText'; clCaptionText : Result:='clCaptionText'; clActiveBorder : Result:='clActiveBorder'; clInactiveBorder : Result:='clInactiveBorder'; clAppWorkspace : Result:='clAppWorkspace'; clHighlight : Result:='clHighlight'; clHighlightText : Result:='clHighlightText'; clBtnFace : Result:='clBtnFace'; clBtnShadow : Result:='clBtnShadow'; clGrayText : Result:='clGrayText'; clBtnText : Result:='clBtnText'; clInactiveCaptionText : Result:='clInactiveCaptionText'; clBtnHighlight : Result:='clBtnHighlight'; cl3DDkShadow : Result:='cl3DDkShadow'; cl3DLight : Result:='cl3DLight'; clInfoText : Result:='clInfoText'; clInfoBk : Result:='clInfoBk'; clHotLight : Result:='clHotLight'; clGradientActiveCaption : Result:='clGradientActiveCaption'; clGradientInactiveCaption : Result:='clGradientInactiveCaption'; clForm : Result:='clForm'; { //todo find the conflicts clColorDesktop : Result:='clColorDesktop'; cl3DFace : Result:='cl3DFace'; cl3DShadow : Result:='cl3DShadow'; cl3DHiLight : Result:='cl3DHiLight'; clBtnHiLight : Result:='clBtnHiLight'; } else Result := 'Unknow Color'; end;//case Result := Result + ' ($' + IntToHex(Color, 6) + ')'; end; procedure SaveBitmapToStream(Bitmap: TBitmap; Stream: TStream); var IntfImg: TLazIntfImage; ImgWriter: TFPCustomImageWriter; RawImage: TRawImage; begin // adapted from LCL code IntfImg := nil; ImgWriter := nil; try IntfImg := TLazIntfImage.Create(0,0); IntfImg.LoadFromBitmap(Bitmap.Handle, Bitmap.MaskHandle); IntfImg.GetRawImage(RawImage); if RawImage.IsMasked(True) then ImgWriter := TLazWriterXPM.Create else begin ImgWriter := TFPWriterBMP.Create; TFPWriterBMP(ImgWriter).BitsPerPixel := IntfImg.DataDescription.Depth; end; IntfImg.SaveToStream(Stream, ImgWriter); Stream.Position := 0; finally IntfImg.Free; ImgWriter.Free; end; end; { TLCLLogger } procedure TLCLLogger.SendBitmap(const AText: String; ABitmap: TBitmap); begin SendBitmap(DefaultClasses,AText,ABitmap); end; procedure TLCLLogger.SendBitmap(Classes: TDebugClasses; const AText: String; ABitmap: TBitmap); var AStream: TStream; begin if Classes * ActiveClasses = [] then Exit; if ABitmap <> nil then begin AStream := TMemoryStream.Create; //use custom function to avoid bug in TBitmap.SaveToStream SaveBitmapToStream(ABitmap, AStream); end else AStream := nil; //SendStream free AStream SendStream(ltBitmap, AText, AStream); end; procedure TLCLLogger.SendColor(const AText: String; AColor: TColor); begin SendColor(DefaultClasses, AText, AColor); end; procedure TLCLLogger.SendColor(Classes: TDebugClasses; const AText: String; AColor: TColor); begin if Classes * ActiveClasses = [] then Exit; SendStream(ltValue, AText + ' = ' + ColorToStr(AColor),nil); end; end.
unit Delphi.Mocks.Examples.Implement; interface uses Delphi.Mocks.Example.ProjectSaveCheckVisitor; type {$M+} TExample_InterfaceImplementTests = class published procedure Implement_Single_Interface; procedure Implement_Multiple_Interfaces; procedure SetupAndVerify_Mulitple_Interfaces; procedure SetupAndVerify_Object_And_Interfaces; end; {$M-} implementation uses Rtti, TypInfo, SysUtils, Delphi.Mocks; { TExample_InterfaceImplementTests } procedure TExample_InterfaceImplementTests.Implement_Single_Interface; var visitorSUT : IVisitor; mockElement : TMock<IElement>; mockProject : TMock<IProject>; projectAsValue : TValue; pInfo : PTypeInfo; dud : IProject; begin //Test that when we visit a project, and its dirty, we save. //CREATE - The visitor system under test. visitorSUT := TProjectSaveCheck.Create; //CREATE - Element mock we require. mockElement := TMock<IElement>.Create; mockProject := TMock<IProject>.Create; projectAsValue := TValue.From(mockProject.Instance); //SETUP - return mock project when IProject is asked for. pInfo := TypeInfo(IProject); mockElement.Setup.WillReturn(projectAsValue).When.QueryInterface(GetTypeData(pInfo).GUID, dud); //SETUP - mock project will show as dirty and will expect to be saved. mockProject.Setup.WillReturn(true).When.IsDirty; mockProject.Setup.Expect.Once.When.Save; try //TEST - Visit the mock element with visitorSUT.Visit(mockElement); //VERIFY - Make sure that save was indeed called. mockProject.Verify; //I don't expect to get here as an exception will be raised in Visit. The //mock can't return project via query interface as this is overriden internally //by the mocking library. //Didn't use CheckException to simpilfy this test. //Assert.Fail; except //Assert.Pass; end; end; procedure TExample_InterfaceImplementTests.Implement_Multiple_Interfaces; var visitorSUT : IVisitor; mockElement : TMock<IElement>; begin //Test that when we visit a project, and its dirty, we save. //CREATE - The visitor system under test. visitorSUT := TProjectSaveCheck.Create; //CREATE - Element mock we require. mockElement := TMock<IElement>.Create; //SETUP - Add the IProject interface as an implementation for the mock mockElement.Implement<IProject>; //SETUP - mock project will show as dirty and will expect to be saved. mockElement.Setup<IProject>.WillReturn(true).When.IsDirty; mockElement.Setup<IProject>.Expect.Once.When.Save; //TEST - Visit the mock element with visitorSUT.Visit(mockElement); //VERIFY - Make sure that save was indeed called. mockElement.VerifyAll; end; procedure TExample_InterfaceImplementTests.SetupAndVerify_Mulitple_Interfaces; begin end; //This test fails at this time. Something to implement later. Need to make TObjectProxy pass //the query interface call to the TProxyVirtualInterface list to be queried. procedure TExample_InterfaceImplementTests.SetupAndVerify_Object_And_Interfaces; var visitorSUT : IVisitor; mockElement : TMock<TElement>; setup : IMockSetup<IProject>; begin //Test that when we visit a project, and its dirty, we save. //CREATE - The visitor system under test. visitorSUT := TProjectSaveCheck.Create; //CREATE - Element mock we require. mockElement := TMock<TElement>.Create; //SETUP - Add the IProject interface as an implementation for the mock mockElement.Implement<IProject>; //SETUP - mock project will show as dirty and will expect to be saved. setup := mockElement.Setup<IProject>; setup.WillReturn(true).When.IsDirty; setup.Expect.Once.When.Save; //TEST - Visit the mock element with visitorSUT.Visit(mockElement); //VERIFY - Make sure that save was indeed called. mockElement.VerifyAll; end; initialization end.
{$ifdef license} (* Copyright 2020 ChapmanWorld LLC ( https://chapmanworld.com ) Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *) {$endif} unit cwThreading.Internal.ForLoopTask.Standard; {$ifdef fpc} {$mode delphiunicode} {$modeswitch nestedprocvars} {$endif} interface uses cwThreading ; type TForLoopTask = class(TInterfacedObject, ITask) private fStart: nativeuint; fStop: nativeuint; {$ifndef fpc} fOnExecute: TOnExecute; {$endif} {$ifdef fpc} fOnExecuteG: TOnExecuteGlobal; fOnExecuteO: TOnExecuteOfObject; fOnExecuteN: TOnExecuteNested; {$endif} strict private //- ITask -// procedure Execute; public {$ifndef fpc} constructor Create( const Start, Stop: nativeuint; const OnExecute: TOnExecute ); reintroduce; overload; {$endif} {$ifdef fpc} constructor Create( const Start, Stop: nativeuint; const OnExecute: TOnExecuteGlobal ); reintroduce; overload; constructor Create( const Start, Stop: nativeuint; const OnExecute: TOnExecuteOfObject ); reintroduce; overload; constructor Create( const Start, Stop: nativeuint; const OnExecute: TOnExecuteNested ); reintroduce; overload; {$endif} end; implementation procedure TForLoopTask.Execute; begin {$ifndef fpc} if assigned(fOnExecute) then fOnExecute( fStart, fStop ); {$endif} {$ifdef fpc} if assigned(fOnExecuteG) then fOnExecuteG( fStart, fStop ); if assigned(fOnExecuteO) then fOnExecuteO( fStart, fStop ); if assigned(fOnExecuteN) then fOnExecuteN( fStart, fStop ); {$endif} end; {$ifndef fpc} constructor TForLoopTask.Create(const Start, Stop: nativeuint; const OnExecute: TOnExecute); begin inherited Create; fOnExecute := OnExecute; end; {$endif} {$ifdef fpc} constructor TForLoopTask.Create(const Start, Stop: nativeuint; const OnExecute: TOnExecuteGlobal); begin inherited Create; fOnExecuteG := OnExecute; fOnExecuteO := nil; fOnExecuteN := nil; fStart := Start; fStop := Stop; end; {$endif} {$ifdef fpc} constructor TForLoopTask.Create(const Start, Stop: nativeuint; const OnExecute: TOnExecuteOfObject); begin inherited Create; fOnExecuteG := nil; fOnExecuteO := OnExecute; fOnExecuteN := nil; fStart := Start; fStop := Stop; end; {$endif} {$ifdef fpc} constructor TForLoopTask.Create(const Start, Stop: nativeuint; const OnExecute: TOnExecuteNested); begin inherited Create; fOnExecuteG := nil; fOnExecuteO := nil; fOnExecuteN := OnExecute; fStart := Start; fStop := Stop; end; {$endif} end.
unit MainFormU; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.StdCtrls, System.Threading, System.Actions, FMX.ActnList; type TSMSSendingForm = class(TForm) btnSendNext: TButton; ToolBar1: TToolBar; Label1: TLabel; SendTimer: TTimer; ActionList1: TActionList; actSendSMS: TAction; Label2: TLabel; btnStartSending: TButton; procedure actSendSMSExecute(Sender: TObject); procedure btnStartSendingClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var SMSSendingForm: TSMSSendingForm; implementation {$R *.fmx} uses SMS.ServiceU; procedure TSMSSendingForm.actSendSMSExecute(Sender: TObject); begin GetSMSService.SendNextSMS; end; procedure TSMSSendingForm.btnStartSendingClick(Sender: TObject); begin SendTimer.Enabled := not SendTimer.Enabled; if SendTimer.Enabled then begin Label2.Text := 'Sending Service Started...'; Label2.FontColor := TAlphaColorRec.Red; btnStartSending.Text := 'Stop Sending Service'; btnStartSending.FontColor := TAlphaColorRec.Red; end else begin Label2.Text := 'Sending Service Stopped...'; Label2.FontColor := TAlphaColorRec.Blue; btnStartSending.Text := 'Start Sending Service'; btnStartSending.FontColor := TAlphaColorRec.Blue; end; end; end.
{******************************************** AnsiString version of delphi Unicode Tinifile ********************************************} unit Alcinoe.IniFiles; {$R-,T-,H+,X+} interface {$I Alcinoe.inc} {$IFNDEF ALCompilerVersionSupported} {$MESSAGE WARN 'Check if System.IniFiles was not updated and adjust the IFDEF'} {$ENDIF} uses System.SysUtils, System.Classes, Alcinoe.StringUtils, Alcinoe.StringList; type EALIniFileException = class(Exception); TALCustomIniFile = class(TObject) private FFileName: AnsiString; protected const SectionNameSeparator: AnsiString = '\'; procedure InternalReadSections(const Section: AnsiString; Strings: TALStringsA; SubSectionNamesOnly, Recurse: Boolean); virtual; public constructor Create(const FileName: AnsiString); function SectionExists(const Section: AnsiString): Boolean; virtual; function ReadString(const Section, Ident, Default: AnsiString): AnsiString; virtual; abstract; procedure WriteString(const Section, Ident, Value: AnsiString); virtual; abstract; function ReadInteger(const Section, Ident: AnsiString; Default: Integer): Integer; virtual; procedure WriteInteger(const Section, Ident: AnsiString; Value: Integer); virtual; function ReadInt64(const Section, Ident: AnsiString; Default: Int64): Int64; virtual; procedure WriteInt64(const Section, Ident: AnsiString; Value: Int64); virtual; function ReadBool(const Section, Ident: AnsiString; Default: Boolean): Boolean; virtual; procedure WriteBool(const Section, Ident: AnsiString; Value: Boolean); virtual; function ReadBinaryStream(const Section, Name: AnsiString; Value: TStream): Integer; virtual; function ReadDate(const Section, Name: AnsiString; Default: TDateTime; const AFormatSettings: TALFormatSettingsA): TDateTime; virtual; function ReadDateTime(const Section, Name: AnsiString; Default: TDateTime; const AFormatSettings: TALFormatSettingsA): TDateTime; virtual; function ReadFloat(const Section, Name: AnsiString; Default: Double; const AFormatSettings: TALFormatSettingsA): Double; virtual; function ReadTime(const Section, Name: AnsiString; Default: TDateTime; const AFormatSettings: TALFormatSettingsA): TDateTime; virtual; procedure WriteBinaryStream(const Section, Name: AnsiString; Value: TStream); virtual; procedure WriteDate(const Section, Name: AnsiString; Value: TDateTime; const AFormatSettings: TALFormatSettingsA); virtual; procedure WriteDateTime(const Section, Name: AnsiString; Value: TDateTime; const AFormatSettings: TALFormatSettingsA); virtual; procedure WriteFloat(const Section, Name: AnsiString; Value: Double; const AFormatSettings: TALFormatSettingsA); virtual; procedure WriteTime(const Section, Name: AnsiString; Value: TDateTime; const AFormatSettings: TALFormatSettingsA); virtual; procedure ReadSection(const Section: AnsiString; Strings: TALStringsA); virtual; abstract; procedure ReadSections(Strings: TALStringsA); overload; virtual; abstract; procedure ReadSections(const Section: AnsiString; Strings: TALStringsA); overload; virtual; procedure ReadSubSections(const Section: AnsiString; Strings: TALStringsA; Recurse: Boolean = False); virtual; procedure ReadSectionValues(const Section: AnsiString; Strings: TALStringsA); virtual; abstract; procedure EraseSection(const Section: AnsiString); virtual; abstract; procedure DeleteKey(const Section, Ident: AnsiString); virtual; abstract; procedure UpdateFile; virtual; abstract; function ValueExists(const Section, Ident: AnsiString): Boolean; virtual; property FileName: AnsiString read FFileName; end; TALIniFile = class(TALCustomIniFile) public destructor Destroy; override; function ReadString(const Section, Ident, Default: AnsiString): AnsiString; override; procedure WriteString(const Section, Ident, Value: AnsiString); override; procedure ReadSection(const Section: AnsiString; Strings: TALStringsA); override; procedure ReadSections(Strings: TALStringsA); override; procedure ReadSectionValues(const Section: AnsiString; Strings: TALStringsA); override; procedure EraseSection(const Section: AnsiString); override; procedure DeleteKey(const Section, Ident: AnsiString); override; procedure UpdateFile; override; end; implementation uses Winapi.Windows, System.RTLConsts, System.Ansistrings, System.IOUtils, Alcinoe.Files; {**************************************************************} constructor TALCustomIniFile.Create(const FileName: AnsiString); begin FFileName := FileName; end; {**************************************************************************} function TALCustomIniFile.SectionExists(const Section: AnsiString): Boolean; var S: TALStringsA; begin S := TALStringListA.Create; try ReadSection(Section, S); Result := S.Count > 0; finally S.Free; end; end; {*************************************************************************************************} function TALCustomIniFile.ReadInteger(const Section, Ident: AnsiString; Default: Integer): Integer; var IntStr: AnsiString; begin IntStr := ReadString(Section, Ident, ''); if (Length(IntStr) > 2) and (IntStr[1] = '0') and ((IntStr[2] = 'X') or (IntStr[2] = 'x')) then IntStr := '$' + ALCopyStr(IntStr, 3, Maxint); Result := ALStrToIntDef(IntStr, Default); end; {****************************************************************************************} procedure TALCustomIniFile.WriteInteger(const Section, Ident: AnsiString; Value: Integer); begin WriteString(Section, Ident, ALIntToStrA(Value)); end; {*******************************************************************************************} function TALCustomIniFile.ReadInt64(const Section, Ident: AnsiString; Default: Int64): Int64; var IntStr: AnsiString; begin IntStr := ReadString(Section, Ident, ''); if (Length(IntStr) > 2) and (IntStr[1] = '0') and ((IntStr[2] = 'X') or (IntStr[2] = 'x')) then IntStr := '$' + ALCopyStr(IntStr, 3, Maxint); Result := ALStrToInt64Def(IntStr, Default); end; {************************************************************************************} procedure TALCustomIniFile.WriteInt64(const Section, Ident: AnsiString; Value: Int64); begin WriteString(Section, Ident, ALIntToStrA(Value)); end; {**********************************************************************************************} function TALCustomIniFile.ReadBool(const Section, Ident: AnsiString; Default: Boolean): Boolean; begin Result := ALStrToBool(ReadString(Section, Ident, ALBoolToStrA(Default))); end; {********************************************************************************************************************************************} function TALCustomIniFile.ReadDate(const Section, Name: AnsiString; Default: TDateTime; const AFormatSettings: TALFormatSettingsA): TDateTime; var DateStr: AnsiString; begin DateStr := ReadString(Section, Name, ''); Result := Default; if DateStr <> '' then try Result := ALStrToDate(DateStr, AFormatSettings); except on EConvertError do // Ignore EConvertError exceptions else raise; end; end; {************************************************************************************************************************************************} function TALCustomIniFile.ReadDateTime(const Section, Name: AnsiString; Default: TDateTime; const AFormatSettings: TALFormatSettingsA): TDateTime; var DateStr: AnsiString; begin DateStr := ReadString(Section, Name, ''); Result := Default; if DateStr <> '' then try Result := ALStrToDateTime(DateStr, AFormatSettings); except on EConvertError do // Ignore EConvertError exceptions else raise; end; end; {***************************************************************************************************************************************} function TALCustomIniFile.ReadFloat(const Section, Name: AnsiString; Default: Double; const AFormatSettings: TALFormatSettingsA): Double; var FloatStr: AnsiString; begin FloatStr := ReadString(Section, Name, ''); Result := Default; if FloatStr <> '' then try Result := ALStrToFloat(FloatStr, AFormatSettings); except on EConvertError do // Ignore EConvertError exceptions else raise; end; end; {********************************************************************************************************************************************} function TALCustomIniFile.ReadTime(const Section, Name: AnsiString; Default: TDateTime; const AFormatSettings: TALFormatSettingsA): TDateTime; var TimeStr: AnsiString; begin TimeStr := ReadString(Section, Name, ''); Result := Default; if TimeStr <> '' then try Result := ALStrToTime(TimeStr, AFormatSettings); except on EConvertError do // Ignore EConvertError exceptions else raise; end; end; {*********************************************************************************************************************************} procedure TALCustomIniFile.WriteDate(const Section, Name: AnsiString; Value: TDateTime; const AFormatSettings: TALFormatSettingsA); begin WriteString(Section, Name, ALDateToStrA(Value, AFormatSettings)); end; {*************************************************************************************************************************************} procedure TALCustomIniFile.WriteDateTime(const Section, Name: AnsiString; Value: TDateTime; const AFormatSettings: TALFormatSettingsA); begin WriteString(Section, Name, ALDateTimeToStrA(Value, AFormatSettings)); end; {*******************************************************************************************************************************} procedure TALCustomIniFile.WriteFloat(const Section, Name: AnsiString; Value: Double; const AFormatSettings: TALFormatSettingsA); begin WriteString(Section, Name, ALFloatToStrA(Value, AFormatSettings)); end; {*********************************************************************************************************************************} procedure TALCustomIniFile.WriteTime(const Section, Name: AnsiString; Value: TDateTime; const AFormatSettings: TALFormatSettingsA); begin WriteString(Section, Name, ALTimeToStrA(Value, AFormatSettings)); end; {*************************************************************************************} procedure TALCustomIniFile.WriteBool(const Section, Ident: AnsiString; Value: Boolean); begin WriteString(Section, Ident, ALBoolToStrA(Value)); end; {*******************************************************************************} function TALCustomIniFile.ValueExists(const Section, Ident: AnsiString): Boolean; var S: TALStringsA; begin S := TALStringListA.Create; try ReadSection(Section, S); Result := S.IndexOf(Ident) > -1; finally S.Free; end; end; {*****************************************} function TALCustomIniFile.ReadBinaryStream( const Section, Name: AnsiString; Value: TStream): Integer; var Text: AnsiString; Stream: TMemoryStream; Pos: Integer; begin Text := ReadString(Section, Name, ''); if Text <> '' then begin if Value is TMemoryStream then Stream := TMemoryStream(Value) else Stream := TMemoryStream.Create; try Pos := Stream.Position; Stream.SetSize(Stream.Size + Length(Text) div 2); HexToBin(PAnsiChar(Text), PAnsiChar(Integer(Stream.Memory) + Stream.Position), Length(Text) div 2); Stream.Position := Pos; if Value <> Stream then Value.CopyFrom(Stream, Length(Text) div 2); Result := Stream.Size - Pos; finally if Value <> Stream then Stream.Free; end; end else Result := 0; end; {********************************************************************************************} procedure TALCustomIniFile.WriteBinaryStream(const Section, Name: AnsiString; Value: TStream); var Text: AnsiString; Stream: TBytesStream; begin SetLength(Text, (Value.Size - Value.Position) * 2); if Length(Text) > 0 then begin if Value is TBytesStream then Stream := TBytesStream(Value) else Stream := TBytesStream.Create; try if Stream <> Value then begin Stream.CopyFrom(Value, Value.Size - Value.Position); Stream.Position := 0; end; BinToHex( PAnsiChar(Integer(Stream.Bytes) + Stream.Position), PAnsiChar(Text), Stream.Size - Stream.Position); finally if Value <> Stream then Stream.Free; end; end; WriteString(Section, Name, Text); end; {**************************************************************************************************************************************} procedure TALCustomIniFile.InternalReadSections(const Section: AnsiString; Strings: TALStringsA; SubSectionNamesOnly, Recurse: Boolean); var SLen, SectionLen, SectionEndOfs, I: Integer; S, SubSectionName: AnsiString; AllSections: TALStringListA; begin AllSections := TALStringListA.Create; try ReadSections(AllSections); SectionLen := Length(Section); // Adjust end offset of section name to account for separator when present. SectionEndOfs := (SectionLen + 1) + Integer(SectionLen > 0); Strings.BeginUpdate; try for I := 0 to AllSections.Count - 1 do begin S := AllSections[I]; SLen := Length(S); if (SectionLen = 0) or (SubSectionNamesOnly and (SLen > SectionLen) and ALSameTextA(Section, ALCopyStr(S, 1, SectionLen))) or (not SubSectionNamesOnly and (SLen >= SectionLen) and ALSameTextA(Section, ALCopyStr(S, 1, SectionLen))) then begin SubSectionName := ALCopyStr(S, SectionEndOfs, SLen + 1 - SectionEndOfs); if not Recurse and (ALPosA(SectionNameSeparator, SubSectionName) <> 0) then Continue; if SubSectionNamesOnly then S := SubSectionName; Strings.Add(S); end; end; finally Strings.EndUpdate; end; finally AllSections.Free; end; end; {***************************************************************************************} procedure TALCustomIniFile.ReadSections(const Section: AnsiString; Strings: TALStringsA); begin InternalReadSections(Section, Strings, False, True); end; {********************************************************************************************************************} procedure TALCustomIniFile.ReadSubSections(const Section: AnsiString; Strings: TALStringsA; Recurse: Boolean = False); begin InternalReadSections(Section, Strings, True, Recurse); end; {****************************} destructor TALIniFile.Destroy; begin UpdateFile; // flush changes to disk inherited Destroy; end; {************************************************************************************} function TALIniFile.ReadString(const Section, Ident, Default: AnsiString): AnsiString; var Buffer: array[0..2047] of AnsiChar; begin SetString( Result, Buffer, GetPrivateProfileStringA( PAnsiChar(Section), PAnsiChar(Ident), PAnsiChar(Default), Buffer, Length(Buffer), PAnsiChar(FFileName))); end; {************************************************************************} procedure TALIniFile.WriteString(const Section, Ident, Value: AnsiString); begin if not WritePrivateProfileStringA( PAnsiChar(Section), PAnsiChar(Ident), PAnsiChar(Value), PAnsiChar(FFileName)) then raise EALIniFileException.CreateResFmt(@SIniFileWriteError, [FileName]); end; {******************************************************} procedure TALIniFile.ReadSections(Strings: TALStringsA); const CStdBufSize = 16384; // chars var P, LBuffer: PAnsiChar; LCharCount: Integer; LLen: Integer; begin LBuffer := nil; try // try to read the file in a 16Kchars buffer GetMem(LBuffer, CStdBufSize); Strings.BeginUpdate; try Strings.Clear; LCharCount := GetPrivateProfileStringA( nil, nil, nil, LBuffer, CStdBufSize, PAnsiChar(FFileName)); // the buffer is too small; approximate the buffer size to fit the contents if LCharCount = CStdBufSize - 2 then begin LCharCount := Tfile.GetSize(String(FFileName)); ReallocMem(LBuffer, LCharCount); LCharCount := GetPrivateProfileStringA( nil, nil, nil, LBuffer, LCharCount, PAnsiChar(FFileName)); end; // chars were read from the file; get the section names if LCharCount <> 0 then begin P := LBuffer; while LCharCount > 0 do begin Strings.Add(P); LLen := System.Ansistrings.StrLen(P) + 1; Inc(P, LLen); Dec(LCharCount, LLen); end; end; finally Strings.EndUpdate; end; finally FreeMem(LBuffer); end; end; {********************************************************************************} procedure TALIniFile.ReadSection(const Section: AnsiString; Strings: TALStringsA); var Buffer, P: PAnsiChar; CharCount: Integer; BufSize: Integer; {~~~~~~~~~~~~~~~~~~~~~~~} procedure ReadStringData; begin Strings.BeginUpdate; try Strings.Clear; if CharCount <> 0 then begin P := Buffer; while P^ <> #0 do begin Strings.Add(P); Inc(P, System.Ansistrings.StrLen(P) + 1); end; end; finally Strings.EndUpdate; end; end; begin BufSize := 1024; while True do begin GetMem(Buffer, BufSize); try CharCount := GetPrivateProfileStringA( PAnsiChar(Section), nil, nil, Buffer, BufSize, PAnsiChar(FFileName)); if CharCount < BufSize - 2 then begin ReadStringData; Break; end; finally FreeMem(Buffer, BufSize); end; BufSize := BufSize * 4; end; end; {**************************************************************************************} procedure TALIniFile.ReadSectionValues(const Section: AnsiString; Strings: TALStringsA); var KeyList: TALStringListA; I: Integer; begin KeyList := TALStringListA.Create; try ReadSection(Section, KeyList); Strings.BeginUpdate; try Strings.Clear; for I := 0 to KeyList.Count - 1 do Strings.Add(KeyList[I] + '=' + ReadString(Section, KeyList[I], '')) finally Strings.EndUpdate; end; finally KeyList.Free; end; end; {***********************************************************} procedure TALIniFile.EraseSection(const Section: AnsiString); begin if not WritePrivateProfileStringA(PAnsiChar(Section), nil, nil, PAnsiChar(FFileName)) then raise EALIniFileException.CreateResFmt(@SIniFileWriteError, [FileName]); end; {***************************************************************} procedure TALIniFile.DeleteKey(const Section, Ident: AnsiString); begin WritePrivateProfileStringA(PAnsiChar(Section), PAnsiChar(Ident), nil, PAnsiChar(FFileName)); end; {******************************} procedure TALIniFile.UpdateFile; begin WritePrivateProfileStringA(nil, nil, nil, PAnsiChar(FFileName)); end; end.
{******************************************************************************} { } { Indy (Internet Direct) - Internet Protocols Simplified } { } { https://www.indyproject.org/ } { https://gitter.im/IndySockets/Indy } { } {******************************************************************************} { } { This file is part of the Indy (Internet Direct) project, and is offered } { under the dual-licensing agreement described on the Indy website. } { (https://www.indyproject.org/license/) } { } { Copyright: } { (c) 1993-2020, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { } {******************************************************************************} { } { Originally written by: Fabian S. Biehn } { fbiehn@aagon.com (German & English) } { } { Contributers: } { Here could be your name } { } {******************************************************************************} unit IdOpenSSLHeaders_rand; interface // Headers for OpenSSL 1.1.1 // rand.h {$i IdCompilerDefines.inc} uses IdCTypes, IdGlobal, IdOpenSSLConsts, IdOpenSSLHeaders_ossl_typ; type rand_meth_st_seed = function (const buf: Pointer; num: TIdC_INT): TIdC_INT; cdecl; rand_meth_st_bytes = function (buf: PByte; num: TIdC_INT): TIdC_INT; cdecl; rand_meth_st_cleanup = procedure; cdecl; rand_meth_st_add = function (const buf: Pointer; num: TIdC_INT; randomness: TIdC_DOUBLE): TIdC_INT; cdecl; rand_meth_st_pseudorand = function (buf: PByte; num: TIdC_INT): TIdC_INT; cdecl; rand_meth_st_status = function: TIdC_INT; cdecl; rand_meth_st = record seed: rand_meth_st_seed; bytes: rand_meth_st_bytes; cleanup: rand_meth_st_cleanup; add: rand_meth_st_add; pseudorand: rand_meth_st_pseudorand; status: rand_meth_st_status; end; var function RAND_set_rand_method(const meth: PRAND_METHOD): TIdC_INT; function RAND_get_rand_method: PRAND_METHOD; function RAND_set_rand_engine(engine: PENGINE): TIdC_INT; function RAND_OpenSSL: PRAND_METHOD; function RAND_bytes(buf: PByte; num: TIdC_INT): TIdC_INT; function RAND_priv_bytes(buf: PByte; num: TIdC_INT): TIdC_INT; procedure RAND_seed(const buf: Pointer; num: TIdC_INT); procedure RAND_keep_random_devices_open(keep: TIdC_INT); procedure RAND_add(const buf: Pointer; num: TIdC_INT; randomness: TIdC_DOUBLE); function RAND_load_file(const file_: PIdAnsiChar; max_bytes: TIdC_LONG): TIdC_INT; function RAND_write_file(const file_: PIdAnsiChar): TIdC_INT; function RAND_status: TIdC_INT; function RAND_query_egd_bytes(const path: PIdAnsiChar; buf: PByte; bytes: TIdC_INT): TIdC_INT; function RAND_egd(const path: PIdAnsiChar): TIdC_INT; function RAND_egd_bytes(const path: PIdAnsiChar; bytes: TIdC_INT): TIdC_INT; function RAND_poll: TIdC_INT; implementation end.
unit PageSheetUnit; interface uses Windows, SysUtils, Messages, Classes, Controls, Dialogs, ComCtrls, DialogUnit, EditFrame, ScannerUnit, Graphics, TypInfo, SynEdit, SynEditTypes, FreeBasicRTTI, SynEditMiscClasses, TypesUnit; type TPageSheet=class(TTabSheet) private fScanTree, fObjTree:TTreeView; fNode:TTreeNode; fScanner:TScanner; fSaved:boolean; fFileName:string; fFrame:TEditor; fDialog:TDialog; fHasDialog:boolean; fNameChanged, fSetHasDialog:TNotifyEvent; fDependencies, fExported:TStrings; procedure SetDialog(v:TDialog); procedure SetHasDialog(v:boolean); procedure SetSaved(v:boolean); procedure SetFileName(v:string); procedure SetObjTree(v:TTreeView); protected procedure SetName(const v:TComponentName);override; public Project:TProject; constructor Create(AOwner:TComponent); override; destructor Destroy; override; function Dispose:integer; procedure SilentSave(v:string); procedure Save; procedure SaveAs; procedure Select(v:TObject); function Find(v:string;where:integer=0;o:TObject=nil):TPoint; function InsertDialog:string; procedure InsertControl( o:TControl); procedure DeleteControl(o:TControl); procedure UpdateControl(o:TControl;pn:string='';pv:string=''); procedure UpdateControlName(o:TControl); function UpdateEvent(o:TControl;evn,prms:string):string; property Dependencies:TStrings read fDependencies; property Exported:TStrings read fExported; property Node:TTreeNode read fNode write fNode; property ObjTree:TTreeView read fObjTree write SetObjTree; property Scanner:TScanner read fScanner; property ScanTree:TTreeView read fScanTree write fScanTree; property Frame:TEditor read fFrame; property Dialog:TDialog read fDialog write SetDialog; property HasDialog:boolean read fhasdialog write SetHasDialog; property Saved:boolean read fSaved write SetSaved; property FileName:string read fFileName write SetFileName; property OnNameChanged:TNotifyEvent read fNameChanged write fNameChanged; property OnSetHasDialog:TNotifyEvent read fSetHasDialog write fSetHasDialog; end; var CanFreeDialog:boolean; PagesList:TStringList; oldName:string; implementation uses MainUnit, ContainerUnit, ObjectsTreeUnit, CodeUnit, InspectorUnit, HelperUnit, InstallClassUnit; constructor TPageSheet.Create(AOwner:TComponent); begin inherited; fScanner:=TScanner.create; fFrame:=TEditor.Create(self); fFrame.Align:=alClient; fFrame.Parent:=self; Saved:=true; PagesList.AddObject(Name,self) ; fScanTree:=Code.TreeView; fScanner.Tree:=fScanTree; fScanner.Edit:=fFrame.Edit; fDependencies:=TStringList.Create; fExported:=TStringList.Create; end; destructor TPageSheet.Destroy; var i:integer; begin if fDialog<>nil then begin Inspector.Reset; fDialog.Page:=nil; if CanFreeDialog then begin if Launcher.ideMode=mdVB then if fDialog.Sheet<>nil then fDialog.Sheet.Free else fDialog.Free; end; end; i:=PagesList.IndexOfObject(self); if i>-1 then PagesList.Delete(i); if Project<>nil then begin i:=Project.Files.IndexOfObject(self); if i>-1 then Project.Files.Objects[i]:=nil else begin i:=Project.Files.IndexOf(ffilename); if i>-1 then Project.Files.Objects[i]:=nil; end; if Project.Page=self then Project.Page:=nil; Activeresult.Edit.Lines.Add(project.filename); end; fScanner.Free; if ActiveEditor=self then ActiveEditor:=nil; if ActiveObject=self then ActiveObject:=nil; fDependencies.Free; fExported.Free; inherited; end; procedure TPageSheet.SetObjTree(v:TTreeView); begin fObjTree:=v; if v<>nil then fNode:=v.Items.AddChildObject(ActiveProject.node,Name,self) end; procedure TPageSheet.SetName(const v:TComponentName); var i:integer; begin inherited; i:=PagesList.IndexOfObject(self); if i>-1 then PagesList[i]:=Name; if fNode<>nil then fNode.Text:=Name; if assigned(fNameChanged) then fNameChanged(self); end; procedure TPageSheet.SetDialog(v:TDialog); begin fDialog:=v; if v<>nil then begin Name:=v.Name; Caption:=Name; end; end; procedure TPageSheet.SetHasDialog(v:boolean); begin fHasDialog:=v; if v then if fDialog=nil then begin ActiveDialog:=TDialog.Create(nil); Dialog:=ActiveDialog; fDialog.Page:=self; fDialog.DropdownMenu:=Main.menuWindows; fDialog.Show; oldName:=fDialog.Name; if assigned(fsethasdialog) then fsethasdialog(self); end; if not v then if fDialog<>nil then begin fDialog.Free; fDialog:=nil; end; end; procedure TPageSheet.SetSaved(v:boolean); begin fSaved:=v; if v then if Caption<>'' then if pos('*',Caption)>0 then Caption:=StringReplace(Caption,'*','',[rfreplaceall]); if not v then if Caption<>'' then if pos('*',Caption)=0 then Caption:='*'+Caption; end; procedure TPageSheet.SetFileName(v:string); begin if self=nil then exit; if FileExists(v) then begin fFileName:=v; fFrame.Edit.Lines.LoadFromFile(v); Caption:=ExtractFileName(v); end else begin if (pos(#10,v)>1) then fFrame.Edit.Text:=v else fFileName:=v; end end; procedure TPageSheet.Save; begin if FileExists(fFileName) then begin fFrame.Edit.Lines.SaveToFile(fFileName); Saved:=true; Scanner.Scan; end else SaveAs; end; procedure TPageSheet.SilentSave(v:string); begin if v<>'' then begin fFrame.Edit.Lines.SaveToFile(v); Saved:=true end end; procedure TPageSheet.SaveAs; var s:string; begin if fFrame=nil then exit; with TSaveDialog.Create(nil) do begin options:=options+[ofoverwriteprompt]; Filter:=Launcher.Filter; if Filter='' then Filter:='FreeBasic file(*.bas)|*.bas|FreeBasic include (*.bi)|*.bi|HTML file (*.html)|*.html|RTF file (*.rtf)|*.rtf|Text file (*.txt)|*.txt|All files (*.*)|*.*'; FileName:=fFileName; if FileName='' then FileName:=Self.Name; if Execute then begin s:=GetFilterByIndex(FilterIndex,Filter); s:=ExtractFileExt(s); if s='*.' then fFileName:=FileName else fFileName:=ChangeFileExt(FileName,s); if pos('html',lowercase(s))>0 then begin fFrame.ExporterHTML.ExportAll(fFrame.Edit.Lines); fFrame.ExporterHTML.SaveToFile(fFileName); exit end ; if pos('rtf',lowercase(s))>0 then begin fFrame.ExporterRTF.ExportAll(fFrame.Edit.Lines); fFrame.ExporterRTF.SaveToFile(fFileName); exit end ; fFrame.Edit.Lines.SaveToFile(fFileName); Caption:=ExtractFileName(fFileName); if fNode<>nil then fNode.Text:=Caption; Saved:=true; Scanner.Scan; end; Free; end end; function TPageSheet.Dispose:integer; var s:string; begin if FileExists(fFileName) then s:=fFileName else s:=StringReplace(Caption,'*','',[rfreplaceall]); result:=mrok; if not fSaved or not FileExists(fFileName) then case messageDlg(format('The %s page was modified.'#10'Do you want to save?',[s]),mtConfirmation,[mbyes,mbno,mbcancel],0) of mryes:if FileExists(fFileName) then Save else SaveAs; mrcancel:begin result:=mrcancel; end; end; if result=mrCancel then Exit; try Free except messageDlg('Internal error $em: can''t free memory.',mtError,[mbok],0); end ; end; function TPageSheet.InsertDialog:string; var t,ifl:string; begin result:=''; Launcher.Lib.MainType:=Launcher.Lib.TypExists(Launcher.Lib.MainTypeName); if Launcher.Lib.MainType=nil then begin messageDlg('The MainType in library are not set.'#10'No form will be created.',mtInformation,[mbok],0); exit; end; ifl:=Launcher.Lib.MainFile; if ifl='' then ifl:=Launcher.Lib.MainFile; if Launcher.Lib.MainType=nil then begin if messageDlg('Type has no Extends. Set MainType in library',mtError,[mbok],0)=mryes then exit; end ; if pos('type ',lowercase(fFrame.Edit.Text))=0 then if pos(lowercase(fDialog.Name),lowercase(fFrame.Edit.Text))=0 then if pos('extends ',lowercase(fFrame.Edit.Text))=0 then begin fDialog.Page:=Self; if fDialog.Typ.Hosted<>'' then if fDialog.Typ.Hosted[1] in ['Q','q'] then fDialog.Name:=copy(fDialog.Typ.Hosted,2,length(fDialog.Typ.Hosted)) else fDialog.Name:=fDialog.Typ.Hosted; t:=fDialog.Typ.Extends; fDialog.Visible:=true; with fFrame.Edit.Lines do begin if pos('-include ',lowercase(Launcher.Switch))=0 then begin Add(format('#include once "%s"',[ifl])); Add(''); end; AddObject(format('type %s extends %s',[fDialog.Typ.Hosted,t]),fDialog); AddObject(' public:',fDialog); Add(' declare operator cast as any ptr'); Add(' declare constructor'); AddObject('end type',fDialog); Add(''); Add(format('var %s=%s',[fDialog.Name,fDialog.Typ.Hosted])); Add(''); Add(format('operator %s.cast as any ptr',[fDialog.Typ.Hosted])); Add(' return @this'); Add('end operator'); Add(''); AddObject(format('constructor %s',[fDialog.Typ.Hosted]),fDialog); AddObject(format(' this.Name="%s"',[fDialog.Name]),fDialog); AddObject(format(' this.Text="%s"',[fDialog.Caption]),fDialog); AddObject(format(' this.SetBounds(%d,%d,%d,%d)',[fDialog.Left,fDialog.Top,fDialog.Width,fDialog.Height]),fDialog); AddObject(' this.Parent=0',fDialog); AddObject('end constructor',fDialog); Add(''); end; end ; fScanner.Execute; Inspector.Dialog:=fDialog; end; procedure TPageSheet.InsertControl( o:TControl); var i,x:integer; s,ifl:string; wasInserted:boolean; begin for i:=0 to fFrame.Edit.Lines.Count-1 do begin s:=trim(fFrame.Edit.Lines[i]); if fFrame.Edit.Lines.Objects[i]=fDialog then begin if (pos('end ',lowercase(s))>0) and (pos(' constructor',lowercase(s))>0) then begin fFrame.Edit.Lines.InsertObject(i,format(' %s.Parent=this',[o.Name]),o); fFrame.Edit.Lines.InsertObject(i,format(' %s.SetBounds(%d,%d,%d,%d)',[o.Name,o.Left,o.Top,o.Width,o.Height]),o); fFrame.Edit.Lines.InsertObject(i,format(' %s.Name="%s"',[o.Name,o.Name]),o); fFrame.Edit.Lines.InsertObject(i,format(' %s.Canvas.Color=%s',[o.Name,StringReplace(ColorToString(TContainer(o).Color),'$','&H',[])]),o); fFrame.Edit.Lines.InsertObject(i,format(' %s.Align=%d',[o.Name,integer(o.Align)]),o); if GetPropInfo(o,'text')<>nil then fFrame.Edit.Lines.InsertObject(i,format(' %s.Text="%s"',[o.Name,GetPropValue(o,'text')]),o); Scanner.Execute; break end end end; wasInserted:=false; for i:=0 to fFrame.Edit.Lines.Count-1 do begin s:=trim(fFrame.Edit.Lines[i]); if fFrame.Edit.Lines.Objects[i]=fDialog then begin if (pos('public:',lowercase(s))>0) then begin fFrame.Edit.Lines.InsertObject(i,format(' as %s %s',[TContainer(o).Hosted,o.Name]),o); wasInserted:=true; Saved:=false; break end end end ; if wasInserted=false then begin for i:=0 to fFrame.Edit.Lines.Count-1 do begin s:=trim(fFrame.Edit.Lines[i]); if fFrame.Edit.Lines.Objects[i]=fDialog then begin if (pos('end ',lowercase(s))>0) and (pos(' type',lowercase(s))>0) then begin fFrame.Edit.Lines.InsertObject(i,format(' as %s %s',[TContainer(o).Hosted,o.Name]),o); Saved:=false; break end; end end end ; if FileExists(TContainer(o).Typ.Module) then begin x:=-1; if CompareText(TContainer(o).Typ.Module,Launcher.Lib.MainFile)<>0 then begin for i:=0 to fFrame.Edit.Lines.Count-1 do begin s:=trim(fFrame.Edit.Lines[i]); if pos('#include',lowercase(s))>0 then x:=i; end end; ifl:=format('#include once "%s"',[ChangeFileExt(TContainer(o).Typ.Module,'.bas')]); wasInserted:=pos(lowercase(ifl),lowercase(fFrame.Edit.Text))>0; if (wasInserted=false) and (x>-1) then begin ifl:=format('#include once "%s"',[ChangeFileExt(TContainer(o).Typ.Module,'.bas')]); fFrame.Edit.Lines.Insert(x+1,ifl); end; end; fScanner.Execute ; end; procedure TPageSheet.DeleteControl(o:TControl); var i:integer; begin if (Self=nil) or (o=nil) then exit; for i:=fFrame.Edit.Lines.Count-1 downto 0 do begin if fFrame.Edit.Lines.Objects[i]=o then if o=fDialog then begin if messageDlg(format('You do not have permission to delete this.'#10'%s',[fDialog.Name]),mtInformation,[mbok],0)=mrok then exit; end else fFrame.Edit.Lines.Delete(i); end; fScanner.Scan; //ObjectsTree.UpdateItems; //Inspector.UpdateItems end; procedure TPageSheet.UpdateControl(o:TControl;pn:string='';pv:string=''); var i,x:integer; s,ln,lp,lv,n:string; begin if (self=nil) or (o=nil) then exit; if fFrame.Edit=nil then exit; i:=0; repeat ln:=fFrame.Edit.Lines[i]; if Ln<>'' then begin if (fFrame.Edit.Lines.Objects[i]=o) then begin if (pn='') and (pv='') then if pos('setbounds',lowercase(Ln))>0 then begin s:=''; for x:=1 to length(Ln) do if Ln[x]=' ' then s:=s+' '; if o=fDialog then n:='this' else n:=o.Name; Frame.Edit.Lines[i]:=format('%s%s.SetBounds(%d,%d,%d,%d)',[s,n,o.Left,o.Top,o.Width,o.Height]); //Saved:=false end ; if pos(lowercase(pn),lowercase(Ln))>0 then begin s:=Frame.Edit.Lines[i]; lp:=copy(s,1,pos('=',s)-1); lv:=copy(s,pos('=',s)+1,length(s)); if pos('"',s)>0 then lv:='"'+StringReplace(lv,lv,pv,[])+'"' else lv:=StringReplace(lv,lv,pv,[]); Frame.Edit.Lines[i]:=lp+'='+lv; Saved:=false end ; end end; inc(i); until i>Frame.Edit.Lines.Count-1; end; procedure TPageSheet.UpdateControlName(o:TControl); var eso:TSynSearchOptions; begin if o=nil then exit; if oldName='' then exit; try eso:=[ssoReplaceAll,ssoWholeWord,ssoEntireScope]; fFrame.Edit.SearchReplace(oldName,TWincontrol(o).Name,eso); except messageDlg('Internal error $cn-can''t change the name.',mtError,[mbok],0) end end; function TPageSheet.UpdateEvent(o:TControl;evn,prms:string):string; var i,x:integer; s,ln,lv,lp:string; fn:boolean; sp, DLG:string; T:TType; L:TStrings; F:TField; B:TBufferCoord; begin result:=''; if (self=nil) or (o=nil) then exit; if fFrame.Edit=nil then exit; if evn='' then exit; if pos(lowercase(evn),lowercase(Frame.Edit.Text))>0 then exit; L:=TStringList.Create; i:=0; fn:=false; F:=nil; repeat ln:=fFrame.Edit.Lines[i]; if Ln<>'' then begin if (fFrame.Edit.Lines.Objects[i]=o) then begin if (pos(lowercase(evn),lowercase(Ln))>0) then begin fn:=true; s:=Frame.Edit.Lines[i]; lp:=copy(s,1,pos('=',s)-1); lv:=copy(s,pos('=',s)+1,length(s)); if pos('"',s)>0 then lv:='"'+StringReplace(lv,lv,evn,[])+'"' else lv:=StringReplace(lv,lv,evn,[]); Frame.Edit.Lines[i]:=lp+'='+lv; Saved:=false end ; end; if fn=false then begin end; end; inc(i); until i>Frame.Edit.Lines.Count-1; s:= format('declare static sub %s%s%s',[o.Name,evn,prms]); if o.InheritsFrom(TDialog) then T:=TDialog(o).Typ else if o.InheritsFrom(TContainer) then T:=TContainer(o).Typ else T:=nil; if T<>nil then begin RTTIGetFields(T.Extends,L); if evn<>'' then i:=L.IndexOf(evn); if i>-1 then begin F:=TField(L.Objects[i]); if F<>nil then begin F.Value:=Format('@%s%s',[o.Name,evn]); UpdateControl(o,evn,F.Value); end end else F:=nil; end; if pos(lowercase(s),lowercase(Frame.Edit.Text))=0 then begin i:=pos('public:',lowercase(Frame.Edit.Text)); if i=-1 then i:=pos('end create',lowercase(Frame.Edit.Text)); if i>-1 then begin B:=Frame.Edit.CharIndexToRowCol(i); for x:=1 to B.Char-2 do sp:=sp+' '; Frame.Edit.Lines.InsertObject(B.Line,sp+s,o); end end ; s:= format('%s.%s',[o.Name,evn]); if pos(lowercase(s),lowercase(Frame.Edit.Text))=0 then begin i:=pos('end constructor',lowercase(Frame.Edit.Text)); if i>0 then begin B:=Frame.Edit.CharIndexToRowCol(i); for x:=1 to B.Char-2 do sp:=sp+' '; if F<>nil then if Scanner.Variables.IndexOf(o.Name)=-1 then begin Frame.Edit.Lines.InsertObject(B.Line-1,sp+s+'='+F.Value,o); if TContainer(o).AssignedEvents.IndexOf(evn)=-1 then TContainer(o).AssignedEvents.AddObject(evn,F); end else begin Frame.Edit.Lines.InsertObject(B.Line-1,sp+'this.'+evn+'='+F.Value,o) ; if TDialog(o).AssignedEvents.IndexOf(evn)=-1 then TDialog(o).AssignedEvents.AddObject(evn,F); end end end; if (pos('type',lowercase(Frame.Edit.Text))>0) and (pos(' extends ',lowercase(Frame.Edit.Text))>0) then dlg:=trim(copy(Frame.Edit.Text,pos('type',lowercase(Frame.Edit.Text))+4,pos(' extends ',lowercase(Frame.Edit.Text))-pos('type',lowercase(Frame.Edit.Text))-4)); prms:=StringReplace(prms,'byref','byref Sender',[]); prms:=StringReplace(prms,'BYREF','BYREF Sender',[]); result:=Format('sub %s.%s%s%s',[dlg,o.Name,evn,prms]); L.Clear; L.Add(''); L.AddObject(result,o) ; L.AddObject(' '' your code here',o) ; L.AddObject('end sub',o) ; Frame.Edit.Lines.AddStrings(L); Scanner.Execute; L.Free; end; procedure TPageSheet.Select(v:TObject); var i:integer; M:TSynEditMark; begin for i:=0 to fFrame.Edit.Lines.Count-1 do if fFrame.Edit.Lines.Objects[i]=v then begin M:=TSynEditMark.Create; M.ImageIndex:=1; fFrame.Edit.Marks.Add(M) end end; function TPageSheet.Find(v:string;where:integer=0;o:TObject=nil):TPoint; var i,j,x:integer; tk:string; L:TStrings; begin result:=point(-1,-1); L:=TStringList.Create; if pos(',',v)>0 then v:=StringReplace(v,',',#10,[rfReplaceAll]); L.Text:=v; for j:=0 to L.Count-1 do begin for i:=where to fFrame.Edit.Lines.Count-1 do begin x:=pos(lowercase(L[j]),lowercase(fFrame.Edit.Lines[i])); if x>0 then begin if x<length(fFrame.Edit.Lines[i]) then begin tk:=copy(fFrame.Edit.Lines[i],x,x+length(v)+1); if tk<>'' then if tk[length(tk)] in [' ','.','='] then begin if o=fFrame.Edit.Lines.Objects[i] then begin if (result.X=x) and (result.y=i) then result:=point(x,i); break end end end end; end end ; L.Free; end; initialization PagesList:=TStringList.Create; PagesList.OnChange:=Main.PagesListChange; finalization PagesList.Free; end.
{******************************************************************************} { } { WiRL: RESTful Library for Delphi } { } { Copyright (c) 2015-2019 WiRL Team } { } { https://github.com/delphi-blocks/WiRL } { } {******************************************************************************} unit WiRL.Diagnostics.Resources; interface uses System.Classes, System.SysUtils, WiRL.Core.JSON, WiRL.Core.Registry, WiRL.Core.Classes, WiRL.Core.Application, WiRL.Core.Declarations, WiRL.Core.Attributes, WiRL.http.Accept.MediaType, WiRL.Core.MessageBodyWriter, WiRL.Core.Auth.Context, WiRL.http.URL, WiRL.Core.Engine, WiRL.Diagnostics.Manager; type [Path('manager')] TDiagnosticsResource = class private protected [Context] URL: TWiRLURL; public [GET] [Produces(TMediaType.APPLICATION_JSON)] function RetrieveAll: TJSONObject; [GET][Path('app')] [Produces(TMediaType.APPLICATION_JSON)] function RetrieveApp: TJSONObject; end; [Path('resources')] TResourcesResource = class private protected [Context] Engine: TWiRLEngine; public [GET] [Produces(TMediaType.APPLICATION_JSON)] function RetrieveAll: TJSONValue; end; implementation { TDiagnosticsResource } function TDiagnosticsResource.RetrieveAll: TJSONObject; begin Result := TWiRLDiagnosticsManager.Instance.ToJSON; end; function TDiagnosticsResource.RetrieveApp: TJSONObject; function ToString(const AArray: TArray<string>): string; var LString: string; begin Result := ''; for LString in AArray do begin if Result <> '' then Result := Result + ', '; Result := Result + LString; end; end; var LObj: TJSONObject; LAppName: string; begin if URL.HasSubResources then LAppName := URL.SubResources[0] else raise Exception.Create('No app name provided'); LObj := nil; TWiRLDiagnosticsManager.Instance.RetrieveAppInfo(LAppName, procedure(AInfo: TWiRLDiagnosticAppInfo) begin LObj := AInfo.ToJSON; end ); LObj.AddPair('app', LAppName); Result := LObj; end; { TResourcesResource } function TResourcesResource.RetrieveAll: TJSONValue; var LApplications: TJSONArray; begin LApplications := TJSONArray.Create; Engine.EnumerateApplications( procedure(AName: string; AApplication: TWiRLApplication) var LObj: TJSONObject; LResources: TJSONArray; LResource: string; begin LResources := TJSONArray.Create; for LResource in AApplication.Resources do LResources.Add(LResource); LObj := TJSONObject.Create; LObj.AddPair(AName, LResources); LApplications.AddElement(LObj); end ); Result := LApplications; end; initialization TWiRLResourceRegistry.Instance.RegisterResource<TDiagnosticsResource>(nil); TWiRLResourceRegistry.Instance.RegisterResource<TResourcesResource>(nil); end.
unit UCellIDSearch; { ClickForms Application } { Bradford Technologies, Inc. } { All Rights Reserved } { Source Code Copyrighted 1998 - 2011 by Bradford Technologies, Inc. } { This is procedure for finding a cell by its cellID and CellXID } { It can be extended to find cells by other properties } interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls,ComCtrls, Grids_ts, TSGrid, osAdvDbGrid, UContainer, UForms; type TCellIDSearch = class(TAdvancedForm) btnSearch: TButton; inputCellID: TEdit; btnSave: TButton; StatusBar1: TStatusBar; CellList: TosAdvDbGrid; btnPrint: TButton; rbtnXMLID: TRadioButton; rbtnCellID: TRadioButton; procedure ProcessClick(Sender: TObject); procedure btnSaveClick(Sender: TObject); procedure CellListButtonClick(Sender: TObject; DataCol, DataRow: Integer); procedure btnPrintClick(Sender: TObject); procedure inputCellIDKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure rbtnXMLIDClick(Sender: TObject); procedure rbtnCellIDClick(Sender: TObject); private FSearchCellID: Integer; FDoc: TContainer; FfilePath: String; InCellID: String; procedure DoCellIDSearch; procedure ValidateUserInput; procedure SearchForCellIdentifier(CellIDTyp: Integer); // procedure SearchForCellXID; procedure WriteSearchResults; procedure ClearCellList; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; var CellIDSearch: TCellIDSearch; procedure FindCellByAttribute(doc: Tcontainer); implementation uses UGlobals, UUtil1, UStatus, UCell; const cCellID = 1; cCellXID = 2; {$R *.dfm} procedure FindCellByAttribute(Doc: TContainer); begin if CellIDSearch = nil then CellIDSearch := TCellIDSearch.Create(Doc); CellIDSearch.Show; end; constructor TCellIDSearch.Create(AOwner: TComponent); begin inherited Create(Nil); FDoc := TContainer(AOwner); FfilePath := 'C:\AppraisalWorld\CellID.txt'; end; destructor TCellIDSearch.Destroy; begin CellIDSearch := nil; //set the var to nil inherited; end; procedure TCellIDSearch.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TCellIDSearch.ValidateUserInput; begin InCellID:= inputCellID.Text; FSearchCellID := StrToIntDef(inputCellID.Text, 0); //check if the user entered ID if (FSearchCellID <= 0) then raise exception.create('You must enter a vaild Cell ID for searching.'); end; procedure TCellIDSearch.SearchForCellIdentifier(CellIDTyp: Integer); var numForms, f,p,c,n, CellXID, CellID: Integer; fID, pgNum, cellNum: Integer; found,foundMatch: Boolean; begin FDoc := TContainer(GetTopMostContainer); //get the doc if not assigned(FDoc) or (FDoc.docForm.count = 0) then raise exception.create('There are no forms to search.'); n := 1; found := False; numForms := Fdoc.docForm.count; for f := 0 to numForms -1 do //for each form for p := 0 to FDoc.docForm[f].frmPage.Count -1 do //for each page if assigned(FDoc.docForm[f].frmPage[p].pgData) then for c := 0 to FDoc.docForm[f].frmPage[p].pgData.count-1 do //for each cell begin CellID := FDoc.docForm[f].frmPage[p].pgData[c].FCellID; //load the cell ids CellXID := FDoc.docForm[f].frmPage[p].pgData[c].FCellXID; foundMatch := False; if CellIDTyp = cCellID then foundMatch := (CellID = FSearchCellID) else if CellIDTyp = cCellXID then foundMatch := (CellXID = FSearchCellID); if foundMatch then begin fID := FDoc.docForm[f].frmSpecs.fFormUID; pgNum := p +1; cellNum := c +1; if n > 1 then CellList.Rows := n; //create a new row, if more than 1 CellList.Cell[1,n] := IntToStr(fID); CellList.Cell[2,n] := IntToStr(pgNum); CellList.Cell[3,n] := IntToStr(cellNum); CellList.Cell[4,n] := IntToStr(CellID); CellList.Cell[5,n] := IntToStr(CellXID); Inc(n); found := True; end; end; if not found then //feedback if not found begin CellList.Cell[1,1] := '0'; CellList.Cell[2,1] := '0'; CellList.Cell[3,1] := '0'; if CellIDTyp = cCellID then begin CellList.Cell[4,1] := IntToStr(FSearchCellID); CellList.Cell[5,1] := 0; end else begin CellList.Cell[4,1] := 0; CellList.Cell[5,1] := IntToStr(FSearchCellID); end; end; end; (* procedure TCellIDSearch.SearchForCellXID; var numForms, f,p,c,n, CellID,CellXID: Integer; fID, pgNum, cellNum: Integer; found: Boolean; begin FDoc := TContainer(GetTopMostContainer); //get the doc if not assigned(FDoc) or (FDoc.docForm.count = 0) then raise exception.create('There are no forms to search.'); n := 1; found := False; numForms := Fdoc.docForm.count; for f := 0 to numForms -1 do //for each form for p := 0 to FDoc.docForm[f].frmPage.Count -1 do //for each page if assigned(FDoc.docForm[f].frmPage[p].pgData) then for c := 0 to FDoc.docForm[f].frmPage[p].pgData.count-1 do //for each cell begin CellID := FDoc.docForm[f].frmPage[p].pgData[c].FCellID; //load the cell id CellXID := FDoc.docForm[f].frmPage[p].pgData[c].FCellXID; //load the cell ids if (CellXID = FSearchCellID) then begin fID := FDoc.docForm[f].frmSpecs.fFormUID; pgNum := p +1; cellNum := c +1; if n > 1 then CellList.Rows := n; //create a new row, if more than 1 CellList.Cell[1,n] := IntToStr(fID); CellList.Cell[2,n] := IntToStr(pgNum); CellList.Cell[3,n] := IntToStr(cellNum); CellList.Cell[4,n] := IntToStr(FSearchCellID); CellList.Cell[5,n] := IntToStr(FSearchCellID); Inc(n); found := True; end; end; if not found then //feedback if not found begin CellList.Cell[1,1] := '0'; CellList.Cell[2,1] := '0'; CellList.Cell[3,1] := '0'; CellList.Cell[4,1] := IntToStr(FSearchCellID); end; end; *) procedure TCellIDSearch.ClearCellList; begin CellList.Rows := 0; //lazy delete CellList.Rows := 1; //reset to 1 end; procedure TCellIDSearch.DoCellIDSearch; begin ClearCellList; try ValidateUserInput; if rbtnCellID.Checked then SearchForCellIdentifier(cCellID) else SearchForCellIdentifier(cCellXID); except on E: Exception do ShowNotice(E.message); end; end; procedure TCellIDSearch.ProcessClick(Sender: TObject); begin DoCellIDSearch end; procedure TCellIDSearch.btnSaveClick(Sender: TObject); begin WriteSearchResults; end; procedure TCellIDSearch.CellListButtonClick(Sender: TObject; DataCol,DataRow: Integer); var strFmID, strPgNo, strCellNo: String; cell: TBaseCell; theCell: CellUID; begin strFmID := CellList.Cell[1, DataRow]; //no variants strPgNo := CellList.Cell[2, DataRow]; strCellNo := CellList.Cell[3, DataRow]; theCell.formID := StrToInt(strFmID); theCell.pg := StrToInt(strPgNo) - 1; theCell.num := StrToInt(strCellNo) - 1; theCell.Occur := 0; theCell.form := -1; cell := FDoc.GetCell(theCell); //do this for save ones if assigned(cell) then FDoc.Switch2NewCell(Cell, cNotClicked); end; procedure TCellIDSearch.btnPrintClick(Sender: TObject); begin inputCellID.text := ''; //clear the input field ClearCellList; end; procedure TCellIDSearch.inputCellIDKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if(Key = VK_RETURN) then DoCellIDSearch; end; //procedure not used - expand to write out results procedure TCellIDSearch.WriteSearchResults; var err: Integer; output: string; hFile : Integer; begin // output:= output+ 'The form '+ doc.docForm[f].frmSpecs.fFormName +#13#10+ ' Page '+ doc.docForm[f].frmPage[p].pgDesc.PgName; // found:= true; // output:= output+ ' Cell ' + IntToStr(c+1) +#13#10; if (FileExists(FfilePath)) then DeleteFile(FfilePath); hFile := FileCreate(FfilePath, fmOpenWrite); try err:= FileWrite(hFile, PChar(output)^, Length(output)); if (err>0) then ShowNotice('The data was saved to file "'+ FfilePath + '".' + #13#10) //+output) else ShowNotice ('Error: The data was not saved'); finally FileClose (hFile); end; end; procedure TCellIDSearch.rbtnXMLIDClick(Sender: TObject); begin CellList.Col[4].Heading := 'XML ID'; end; procedure TCellIDSearch.rbtnCellIDClick(Sender: TObject); begin CellList.Col[4].Heading := 'Cell ID'; end; (* procedure TCellIDSeach.ProcessClick(Sender: TObject); var doc: TContainer; tmpForm: TDocForm; numForms, f,p,c, CellID, result: Integer; ID: TFormUID; output: string; found: WordBool; begin if (FileExists(filePath)) then DeleteFile(filePath); ValidateUserInput; //check user input doc := TContainer(GetTopMostContainer); if (doc=nil) then begin ShowNotice('Document is not opened.'); Close; end else begin numForms := doc.docForm.count; output:= 'Cell Id ' + InCellID + ' found:'+#13#10; found:= false; if (doc <> nil) and (numForms > 0) then for f := 0 to numForms -1 do //for each form for p := 0 to doc.docForm[f].frmPage.Count -1 do //for each page for c := 0 to doc.docForm[f].frmPage[p].pgDesc.PgCellSeqCount -1 do //for each cell begin CellID := doc.docForm[f].frmPage[p].pgData[c].FCellID; //load the cell ids if (CellID = StrToInt(InCellID)) then begin output:= output+ 'The form '+ doc.docForm[f].frmSpecs.fFormName +#13#10+ ' Page '+ doc.docForm[f].frmPage[p].pgDesc.PgName; found:= true; output:= output+ ' Cell ' + IntToStr(c+1) +#13#10; end; end; if found then begin hFile := FileCreate(filePath, fmOpenWrite); result:= FileWrite(hFile, PChar(output)^, Length(output)); if (result>0) then ShowNotice('The data saved to file: '+ filePath + #13#10) //+output) else ShowNotice ('Error: Data was not saved'); FileClose (hFile); Close; end else ShowNotice('Cell Id not Found'); output:=''; end; end; *) end.
unit cProVenda; interface uses classes, controls, SysUtils,ExtCtrls, Dialogs, ZAbstractConnection, ZConnection, ZAbstractRODataset, ZAbstractDataset, ZDataset,DB, DBClient, UEnum, cControleEstoque; Type TVenda = class private ConexaoDB:TZConnection; //passando a conexão em tempo de criação da classe F_VendaId:integer; F_ClienteId:integer; F_dataVenda:TDateTime; F_totalVenda:Double; function InserirItens(cds: TclientDataSet; IdVenda: Integer): Boolean; function ApagarItens(cds: TClientDataSet): Boolean; function EsteItemExiste(vendaId, produtoId: Integer): Boolean; function InNot(cds:TclientDataSet):String; function AtualizarItem(cds: TclientDataSet): Boolean; procedure RetornarEstoque(sCodigo: String; Acao: TAcaoExcluirEstoque); procedure BaixarEstoque(produtoId: Integer; Quantidade: Double); public constructor Create(aConexao:TZConnection); destructor Destroy; override; function Inserir(cds:TclientDataSet):Boolean; function Atualizar (cds:TclientDataSet):Boolean; function Apagar:Boolean; function Selecionar(id: integer; var cds:TClientDataSet): Boolean; published property vendaId :integer read F_VendaId write F_VendaId; property clienteId :integer read F_ClienteId write F_ClienteId; property dataVenda :TDateTime read F_dataVenda write F_dataVenda; property totalVenda:Double read F_totalVenda write F_totalVenda; end; implementation { TVenda } constructor TVenda.Create(aConexao: TZConnection); begin ConexaoDB:= aConexao; end; destructor TVenda.Destroy; begin inherited; end; {$Region 'CRUD'} function TVenda.Apagar: Boolean; var Qry:TZQuery; begin if MessageDlg('Apagar o Registro: '+#13+#13+ 'Venda Nr: '+IntToStr(vendaId), mtConfirmation, [mbYes, mbNo],0)=mrNo then begin Result:=false; Abort; end; try Result:=true; ConexaoDB.StartTransaction; Qry:= TZQuery.Create(nil); Qry.Connection:=ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('DELETE FROM VENDASITENS where vendaId=:vendaId'); Qry.ParamByName('vendaId').AsInteger:= vendaId; try Qry.ExecSQL; Qry.SQL.Clear; Qry.SQL.Add('DELETE FROM VENDAS where vendaId=:vendaId'); Qry.ParamByName('vendaId').AsInteger:= vendaId; Qry.ExecSQL; ConexaoDB.Commit; except ConexaoDB.Rollback; result:=false; end; finally if Assigned(Qry)then FreeAndNil(Qry); end; end; function TVenda.Atualizar(cds:TclientDataSet): Boolean; var Qry:TZQuery; begin try Result:=true; ConexaoDB.StartTransaction; Qry:= TZQuery.Create(nil); Qry.Connection:=ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add(' Update vendas '+ 'set clienteId =:clienteId ,'+ 'dataVenda =:dataVenda, '+ 'totalVenda =:totalVenda ' + 'where vendaId =:vendaId'); Qry.ParamByName('vendaId').AsInteger:=Self.F_VendaId; Qry.ParamByName('clienteId').AsInteger:=Self.F_clienteId; Qry.ParamByName('dataVenda').AsDateTime:=Self.F_dataVenda; Qry.ParamByName('totalVenda').AsFloat:=Self.F_totalVenda; try Qry.ExecSQL; //Apagar Itens no banco de dados que foram apagados na tela ApagarItens(cds); cds.First; while not cds.Eof do begin if EsteItemExiste(Self.F_VendaId, cds.FieldByName('produtoId').AsInteger) then AtualizarItem(cds) else begin InserirItens(cds, Self.vendaId); end; cds.Next; end; except result:=false; ConexaoDB.Rollback; end; ConexaoDB.Commit; finally if Assigned(Qry)then FreeAndNil(Qry); end; end; function TVenda.Inserir(cds:TclientDataSet): Boolean; var Qry:TZQuery; IdVendaGerado:Integer; begin try result:=true; ConexaoDB.StartTransaction; Qry:= TZQuery.Create(nil); Qry.Connection:=ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('INSERT INTO VENDAS (clienteId, dataVenda, totalVenda ) '+ ' VALUES (:clienteId ,:dataVenda, :totalVenda )' ); Qry.ParamByName('clienteId').AsInteger :=self.F_clienteId; Qry.ParamByName('dataVenda').AsDateTime :=self.F_dataVenda; Qry.ParamByName('totalVenda').AsFloat :=self.F_totalVenda; try Qry.ExecSQL; //Recupera o ID gerado do Insert Qry.SQL.Clear; Qry.SQL.Add(' SELECT SCOPE_IDENTITY() AS ID '); Qry.Open; //Id da tabela pai - VENDA IdVendaGerado := Qry.FieldByName('ID').AsInteger; {$region 'Gravar itens na tabela de vendas'} cds.First; while not cds.Eof do begin InserirItens(cds, IdVendaGerado); cds.Next; end; {$endRegion} ConexaoDB.Commit; except ConexaoDB.Rollback; result:=false; end; finally if Assigned(Qry)then FreeAndNil(Qry); end; end; function TVenda.Selecionar(id: integer; var cds:TClientDataSet): Boolean; var Qry:TZQuery; begin result:=true; try Qry:= TZQuery.Create(nil); Qry.Connection:=ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add( 'select vendaId,'+ ' clienteId, '+ ' dataVenda, '+ ' totalVenda'+ ' From vendas '+ ' Where vendaId =:vendaId'); Qry.ParamByName('vendaId').Value:=id; try Qry.Open; Self.F_vendaId := Qry.FieldByName('vendaId').AsInteger; Self.F_clienteId:= Qry.FieldByName('ClienteId').AsInteger; Self.F_dataVenda:= Qry.FieldByName('dataVenda').AsDateTime; Self.F_totalVenda:= Qry.FieldByName('totalVenda').AsFloat; {$Region 'SELECIONAR na tabela VendasItens'} cds.First; while not cds.Eof do begin cds.Delete; end; Qry.Close; Qry.SQL.Clear; Qry.SQL.Add( 'SELECT a.ProdutoId,'+ ' b.Nome, '+ ' a.ValorUnitario, '+ ' a.Quantidade,'+ ' a.TotalProduto'+ ' From vendasItens as a '+ ' INNER JOIN produtos as b on (a.produtoId = b.produtoId) '+ ' Where a.vendaId =:vendaId'); Qry.ParamByName('vendaId').Value:=Self.F_VendaId; Qry.Open; //Ler a Query e coloca no ClientDataSet Qry.First ; while not Qry.Eof do begin cds.Append; cds.FieldByName('produtoId').AsInteger := Qry.FieldByName('ProdutoId').AsInteger; cds.FieldByName('nomeProduto').AsString := Qry.FieldByName('Nome').AsString; cds.FieldByName('ValorUnitario').AsFloat := Qry.FieldByName('ValorUnitario').AsFloat; cds.FieldByName('quantidade').AsFloat := Qry.FieldByName('Quantidade').AsFloat; cds.FieldByName('ValorTotalProduto').AsFloat := Qry.FieldByName('TotalProduto').AsFloat; cds.Post; Qry.Next; end; cds.First; {$endRegion} except result:=false; end; finally if Assigned(Qry)then FreeAndNil(Qry); end; end; function TVenda.EsteItemExiste(vendaId: Integer; produtoId:Integer): Boolean; var Qry:TZQuery; begin try Qry:=TZQuery.Create(nil); Qry.Connection:=ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('SELECT Count(vendaId) AS Qtde '+ ' FROM VendasItens '+ ' WHERE vendaId=:vendaId and produtoId=:produtoId '); Qry.ParamByName('vendaId').AsInteger :=vendaId; Qry.ParamByName('produtoId').AsInteger :=produtoId; Try Qry.Open; if Qry.FieldByName('Qtde').AsInteger>0 then Result:=true else Result:=False; {$endRegion} Except Result:=false; End; finally if Assigned(Qry) then FreeAndNil(Qry); end; end; function TVenda.InserirItens(cds:TclientDataSet; IdVenda:Integer):Boolean; var Qry:TZQuery; begin try Result:=true; Qry:=TZQuery.Create(nil); Qry.Connection:=ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('INSERT INTO vendasItens(VendaId, ProdutoId, ValorUnitario, Quantidade, TotalProduto )'+ ' VALUES (:VendaId, :ProdutoId, :ValorUnitario, :Quantidade, :TotalProduto) '); Qry.ParamByName('vendaId').AsInteger :=IdVenda; Qry.ParamByName('ProdutoId').AsInteger :=cds.FieldByName('produtoId').AsInteger; Qry.ParamByName('ValorUnitario').AsFloat :=cds.FieldByName('ValorUnitario').AsFloat; Qry.ParamByName('Quantidade').AsFloat :=cds.FieldByName('quantidade').AsFloat; Qry.ParamByName('TotalProduto').AsFloat :=cds.FieldByName('ValorTotalProduto').AsFloat; try Qry.ExecSQL; BaixarEstoque(cds.FieldByName('produtoId').AsInteger, cds.FieldByName('quantidade').AsFloat); Except Result:=false; end; finally if Assigned(Qry) then FreeAndNil(Qry) end; end; function TVenda.AtualizarItem(cds:TClientDataSet): Boolean; var Qry:TZQuery; begin try Result:=true; RetornarEstoque(cds.FieldByName('produtoId').AsString, aeeAlterar); Qry:=TZQuery.Create(nil); Qry.Connection:=ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('UPDATE VendasItens '+ ' SET ValorUnitario=:ValorUnitario, '+ ' Quantidade=:Quantidade, '+ ' TotalProduto=:TotalProduto '+ ' WHERE vendaId=:vendaId AND produtoId=:produtoId '); Qry.ParamByName('vendaId').AsInteger :=Self.F_vendaId; Qry.ParamByName('produtoId').AsInteger :=cds.FieldByName('produtoId').AsInteger; Qry.ParamByName('ValorUnitario').AsFloat:=cds.FieldByName('valorUnitario').AsFloat; Qry.ParamByName('Quantidade').AsFloat :=cds.FieldByName('quantidade').AsFloat; Qry.ParamByName('TotalProduto').AsFloat :=cds.FieldByName('valorTotalProduto').AsFloat; Try ConexaoDB.StartTransaction; Qry.ExecSQL; ConexaoDB.Commit; // BaixarEstoque(cds.FieldByName('produtoId').AsInteger, cds.FieldByName('quantidade').AsFloat); Except ConexaoDB.Rollback; Result:=false; End; finally if Assigned(Qry) then FreeAndNil(Qry); end; end; function TVenda.ApagarItens(cds:TClientDataSet):Boolean; var Qry:TZQuery; sCodNoCds:String; begin try Result:=true; //Pega os codigos que estão no Cliente para Selecionar o In Not no Banco de Dados sCodNoCds:= InNot(cds); //Retorna ao Estoque RetornarEstoque(sCodNoCds, aeeApagar); Qry:=TZQuery.Create(nil); Qry.Connection:=ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add(' DELETE '+ ' FROM VendasItens '+ ' WHERE VendaId=:VendaId '+ ' AND produtoId NOT IN ('+sCodNoCds+') '); Qry.ParamByName('vendaId').AsInteger :=Self.F_vendaId; Try ConexaoDB.StartTransaction; Qry.ExecSQL; ConexaoDB.Commit; Except ConexaoDB.Rollback; Result:=false; End; finally if Assigned(Qry) then FreeAndNil(Qry); end; end; function TVenda.InNot(cds:TClientDataSet):String; var sInNot:String; begin sInNot:=EmptyStr; cds.First; while not cds.Eof do begin if sInNot=EmptyStr then sInNot := cds.FieldByName('produtoId').AsString else sInNot := sInNot +','+cds.FieldByName('produtoId').AsString; cds.Next; end; Result:=sInNot; end; {$endRegion} {$Region 'Controle de Estoque '} procedure TVenda.RetornarEstoque(sCodigo:String; Acao:TAcaoExcluirEstoque); var Qry:TZQuery; oControleEstoque:TControleEstoque; begin Qry:=TZQuery.Create(nil); Qry.Connection:=ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add( ' SELECT produtoId, quantidade '+ ' FROM VendasItens '+ ' WHERE VendaId=:vendaId '); if Acao=aeeApagar then Qry.SQL.Add(' AND produtoId NOT IN ('+sCodigo+') ') else Qry.SQL.Add(' AND produtoId = ('+sCodigo+') '); Qry.ParamByName('vendaId').AsInteger :=Self.F_vendaId; Try oControleEstoque:=TControleEstoque.Create(ConexaoDB); Qry.Open; Qry.First; while not Qry.Eof do begin oControleEstoque.ProdutoId :=Qry.FieldByName('produtoId').AsInteger; oControleEstoque.Quantidade :=Qry.FieldByName('quantidade').AsFloat; oControleEstoque.RetornarEstoque; Qry.Next; end; Finally if Assigned(oControleEstoque) then FreeAndNil(oControleEstoque); End; end; procedure TVenda.BaixarEstoque(produtoId:Integer ; Quantidade:Double); var oControleEstoque:TControleEstoque; begin try oControleEstoque:=TControleEstoque.Create(ConexaoDB); oControleEstoque.ProdutoId := produtoId; oControleEstoque.Quantidade := Quantidade; oControleEstoque.BaixarEstoque; finally if Assigned(oControleEstoque) then FreeAndNil(oControleEstoque); end; end; {'$endRegion'} end.
unit DIOTA.Utils.Checksum; interface type { * This class defines utility methods to add/remove the checksum to/from an address. } TChecksum = class private class function RemoveChecksumFromAddress(addressWithChecksum: String): String; class function CalculateChecksum(address: String): String; public { * Adds the checksum to the specified address. * * @param address The address without checksum. * @return The address with the appended checksum. * @throws ArgumentException is thrown when the specified address is not a valid address, or already has a checksum. } class function AddChecksum(address: String): String; { * Remove the checksum to the specified address. * * @param address The address with checksum. * @return The address without checksum. * @throws ArgumentException is thrown when the specified address is not an address with checksum. } class function RemoveChecksum(address: String): String; { * Determines whether the specified address with checksum has a valid checksum. * * @param addressWithChecksum The address with checksum. * @return <code>true</code> if the specified address with checksum has a valid checksum [the specified address with checksum]; otherwise, <code>false</code>. * @throws ArgumentException is thrown when the specified address is not an valid address. } class function IsValidChecksum(addressWithChecksum: String): Boolean; { * Check if specified address is an address with checksum. * * @param address The address to check. * @return <code>true</code> if the specified address is with checksum ; otherwise, <code>false</code>. * @throws ArgumentException is thrown when the specified address is not an valid address. } class function IsAddressWithChecksum(address: String): Boolean; { * Check if specified address is an address without checksum. * * @param address The address to check. * @return <code>true</code> if the specified address is without checksum ; otherwise, <code>false</code>. * @throws ArgumentException is thrown when the specified address is not an valid address. } class function IsAddressWithoutChecksum(address: String): Boolean; end; implementation uses System.SysUtils, DIOTA.Utils.Constants, DIOTA.Utils.InputValidator, DIOTA.Utils.Converter, DIOTA.Pow.ICurl, DIOTA.Pow.JCurl, DIOTA.Pow.SpongeFactory; { TChecksum } class function TChecksum.AddChecksum(address: String): String; begin TInputValidator.CheckAddressWithoutChecksum(address); Result := address + CalculateChecksum(address); end; class function TChecksum.RemoveChecksum(address: String): String; begin if IsAddressWithChecksum(address) then Result := RemoveChecksumFromAddress(address) else if IsAddressWithoutChecksum(address) then Result := address else raise Exception.Create(INVALID_ADDRESSES_INPUT_ERROR); end; class function TChecksum.RemoveChecksumFromAddress(addressWithChecksum: String): String; begin Result := Copy(addressWithChecksum, 1, ADDRESS_LENGTH_WITHOUT_CHECKSUM); end; class function TChecksum.IsValidChecksum(addressWithChecksum: String): Boolean; var addressWithoutChecksum: String; begin addressWithoutChecksum := RemoveChecksum(addressWithChecksum); Result := addressWithChecksum = (addressWithoutChecksum + CalculateChecksum(addressWithoutChecksum)); end; class function TChecksum.IsAddressWithChecksum(address: String): Boolean; begin Result := TInputValidator.CheckAddress(address); end; class function TChecksum.IsAddressWithoutChecksum(address: String): Boolean; begin Result := TInputValidator.CheckAddressWithoutChecksum(address); end; class function TChecksum.CalculateChecksum(address: String): String; var ACurl: ICurl; AChecksumTrits: TArray<Integer>; AAddressTrits: TArray<Integer>; AChecksumTrytes: String; begin ACurl := TSpongeFactory.Create(TSpongeFactory.Mode.KERL); ACurl.Reset; AAddressTrits := TConverter.trits(address); ACurl.Absorb(AAddressTrits); SetLength(AChecksumTrits, TJCurl.HASH_LENGTH); ACurl.Squeeze(AChecksumTrits); AChecksumTrytes := TConverter.Trytes(AChecksumTrits); Result := Copy(AChecksumTrytes, 73, 9); end; end.
{ High level managment of whole display lists. } module displ_list; define displ_list_new; define displ_list_del; define displ_list_draws; %include 'displ2.ins.pas'; { ******************************************************************************** * * Internal subroutine LIST_RESET (LIST) * * Reset all the fields of LIST to unused, benign, or default values, except * for the MEM_P field, which is not altered. } procedure list_reset ( {reset list fields to unused} out list: displ_t); {the list descriptor to reset} val_param; begin list.id := 0; list.first_p := nil; list.last_p := nil; displ_rend_init (list.rend); end; { ******************************************************************************** * * Subroutine DISPL_LIST_NEW (MEM, LIST) * * Create a new display list. MEM is the parent memory context to use. A * subordinate context will be created for the new list. } procedure displ_list_new ( {create a new display list} in out mem: util_mem_context_t; {parent mem context, subordinate created for list} out list: displ_t); {returned filled-in list descriptor} val_param; begin list_reset (list); {reset fields to unused} util_mem_context_get (mem, list.mem_p); {make mem context for the list} if list.mem_p = nil then begin sys_message_bomb ('sys', 'no_mem', nil, 0); end; end; { ******************************************************************************** * * Subroutine DISPL_LIST_DEL (LIST) * * Delete the indicated list and deallocate any system resources used by the * list. The list descriptor will be returned invalid. A new list must be * created to use the list descriptor again. } procedure displ_list_del ( {delete list, deallocate resources} in out list: displ_t); {the list to delete} val_param; begin if list.mem_p <> nil then begin {memory context is allocated ?} util_mem_context_del (list.mem_p); {deallocate it} end; list_reset (list); {reset all other fields to unused} end; { ******************************************************************************** * * Function DISPL_LIST_DRAWS (LIST) * * Determine whether a display list causes any actual drawing. } function displ_list_draws ( {check whether display list causes drawing} in list: displ_t) {the display list to check} :boolean; {causes drawing} val_param; var item_p: displ_item_p_t; {points to current item in the display list} label done_item; begin displ_list_draws := true; {init to list does cause drawing} item_p := list.first_p; {init to first item in the list} while item_p <> nil do begin {scan the items in the display list} case item_p^.item of {which type of item is this ?} displ_item_list_k: begin {subordinate display list} if item_p^.list_sub_p = nil then goto done_item; {no list here ?} if displ_list_draws(item_p^.list_sub_p^) then return; {sub-list draws} end; displ_item_vect_k: begin {chain of vectors} if item_p^.vect_first_p = nil {no points at all ?} then goto done_item; if item_p^.vect_first_p^.next_p = nil {no second point, so no vector ?} then goto done_item; return; {at least one vector, this list draws} end; displ_item_img_k: begin {overlay image} if item_p^.img_p = nil {no image referenced ?} then goto done_item; if {the overlay region has positive area ?} (item_p^.img_rit > item_p^.img_lft) and (item_p^.img_top > item_p^.img_bot) then return; end; end; {end of item type cases} done_item: {done with this item, on to next} item_p := item_p^.next_p; {to the next item in this list} end; {back to check this new item} displ_list_draws := false; {checked whole list, and no drawing} end;
unit Model.Employee; interface uses Model.Interfaces, Model.IMyConnection, System.Generics.Collections, Spring.Collections, Spring.Persistence.Criteria.Interfaces, Spring.Persistence.Criteria.Restrictions, Spring.Persistence.Criteria.OrderBy, Spring.Data.ObjectDataset, MainDM; function CreateEmployeeModelClass: IEmployeeModelInterface; implementation uses System.SysUtils, Model.Declarations, Model.FormDeclarations, Forms; type TEmployeeModel = class (TInterfacedObject, IEmployeeModelInterface) private fEmployee: TEmployee; public function GetAllEmployees(acompanyId : integer; const filter : string) : IObjectList; function GetAllEmployeesDS(acompanyId : integer; const filter : string) : TObjectDataset; procedure AddEmployee(const newEmployee: TEmployee); function GetEmployee(const EmployeeId : Integer) : TEmployee; procedure UpdateEmployee(const Employee: TEmployee); procedure DeleteEmployee(const Employee: TEmployee); end; function CreateEmployeeModelClass: IEmployeeModelInterface; begin result:=TEmployeeModel.Create; end; { TEmployeeModel } procedure TEmployeeModel.AddEmployee(const newEmployee: TEmployee); begin DMMain.Session.Insert(newEmployee); end; procedure TEmployeeModel.DeleteEmployee(const Employee: TEmployee); begin DMMain.Session.Delete(Employee); end; function TEmployeeModel.GetAllEmployees(acompanyId : integer; const filter: string): IObjectList; var FCriteria : ICriteria<TEmployee>; begin FCriteria := DMMain.Session.CreateCriteria<TEmployee>; Result := FCriteria .Add(Restrictions.Eq('CompanyId', acompanyId)) .Add(Restrictions.NotEq('IsDeleted', 1)) .OrderBy(TOrderBy.Asc('EmployeeId')).ToList as IObjectList; end; function TEmployeeModel.GetAllEmployeesDS(acompanyId: integer; const filter: string): TObjectDataset; begin Result := TObjectDataset.Create(Application); Result.DataList := GetAllEmployees(acompanyId, ''); end; function TEmployeeModel.GetEmployee(const EmployeeId : Integer) : TEmployee; begin Result := DMMain.Session.FindOne<TEmployee>(EmployeeId); end; procedure TEmployeeModel.UpdateEmployee(const Employee: TEmployee); begin DMMain.Session.Update(Employee); end; end.
{******************************************************************************* * * * TksTableView - High-Performance Mobile Scrolling List Component * * * * https://github.com/gmurt/KernowSoftwareFMX * * * * Copyright 2015 Graham Murt * * * * email: graham@kernow-software.co.uk * * * * 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 forthe specific language governing permissions and * * limitations under the License. * * * *******************************************************************************} // Contributors // ------------ // // Thank you to the following for their contribution to this project: // // Simon Farmer // Harry James // { *** HTML SUPPORT - PLEASE READ *** In order to use the HTML formatting within ksListView, you will need to have the TMS Pack for FireMonkey installed. You can get this from the following link... http://www.tmssoftware.com/site/tmsfmxpack.asp Once installed, simply uncomment the conditional define in ksComponents.inc } unit ksTableView; interface {$I ksComponents.inc} uses Classes, FMX.Controls, FMX.Layouts, FMX.Types, System.Types, System.Generics.Collections, FMX.Graphics, FMX.Objects, FMX.InertialMovement, System.UITypes, System.TypInfo, System.UIConsts, System.Rtti, FMX.DateTimeCtrls, FMX.StdCtrls, FMX.Utils, FMX.Styles, FMX.Styles.Objects, FMX.Edit, FMX.SearchBox, FMX.ListBox, FMX.Effects, ksTypes; const C_TABLEVIEW_DEFAULT_ITEM_HEIGHT = 44; C_TABLEVIEW_DEFAULT_HEADER_HEIGHT = 32; C_TABLEVIEW_DEFAULT_WIDTH = 200; C_TABLEVIEW_DEFAULT_HEIGHT = 300; C_TABLEVIEW_DEFAULT_SELECTED_COLOR = $FFD6EFF9; C_TABLEVIEW_DEFAULT_FONT_SIZE = 13; C_TABLEVIEW_DEFAULT_HEADER_COLOR = $FFF0F0F0; C_TABLEVIEW_DEFAULT_INDICATOR_WIDTH = 6; C_TABLEVIEW_DEFAULT_INDICATOR_HEIGHT = 0; // default which stretches to row height C_TABLEVIEW_DEFAULT_IMAGE_SIZE = 24; C_TABLEVIEW_DEFAULT_SELECT_DURATION = 200; C_TABlEVIEW_SCROLL_THRESHOLD = 10; C_TABLEVIEW_REMOVEITEM_SIZE = 20; C_TABLEVIEW_ACCESSORY_KEEPCOLOR = $20000000; {$IFDEF MSWINDOWS} C_SCROLL_BAR_WIDTH = 8; {$ELSE} C_SCROLL_BAR_WIDTH = 8; {$ENDIF} {$IFDEF ANDROID} C_TABLEVIEW_PAGE_SIZE = 50; {$ELSE} C_TABLEVIEW_PAGE_SIZE = 50; {$ENDIF} type TksTableViewItem = class; TksTableViewItemObject = class; TksTableView = class; TksTableViewItems = class; TksTableViewActionButtons = class; TksTableViewActionButton = class; TksTableViewItemSwitch = class; TksTableViewItemTable = class; TksTableViewItemEmbeddedBaseEdit = class; TksTableViewItemEmbeddedEdit = class; TksTableViewItemButton = class; TksTableViewSelectionOptions = class; TksTableViewItemEmbeddedDateEdit = class; // TksTableViewItemBadge = class; TksTableItemAlign = (Leading, Center, Trailing, Fit); TksSwipeDirection = (ksSwipeUnknown, ksSwipeLeftToRight, ksSwipeRightToLeft, ksSwipeTopToBottom, ksSwipeBottomToTop); TksTableViewShape = (ksRectangle, ksSquare, ksRoundRect, ksEllipse); TksTableViewItemPurpose = (None, Header); TksTableViewCheckMarks = (cmNone, cmSingleSelect, cmMultiSelect); TksTableViewCheckMarkPosition = (cmpLeft, cmpRight); TksTableViewChatBubblePosition = (ksCbpLeft, ksCbpRight); TksTableViewCheckMarkCheckArea = (caWholeRow, caCheckMarkRect); TksTableViewActionButtonAlignment = (abLeftActionButtons, abRightActionButtons); TksImageDrawMode = (ksDrawModeStretch, ksDrawModeFit); TksTableViewButtonStyle = (ksButtonDefault, ksButtonSegmentLeft, ksButtonSegmentMiddle, ksButtonSegmentRight); TksTableViewButtonState = (ksPressed, ksUnpressed); TksTableViewItemAppearance = ( iaNormal, iaTile_Image, iaTile_TitleImage, iaTile_ImageTitle, iaTile_TitleImageSubTitle, iaTile_SubTitleImageTitle ); TksTableItemSelector = (NoSelector, DateSelector, ItemPicker); TksTableViewOverlaySelectorPosition = (ksSelectorLeft, ksSelectorRight ); TksTableViewOverlaySelectorStyle = (ksBlankSpace, ksArrow, ksSemiCircle); TksTableViewHeaderButtonType = (hbtNone, hbtJumpToHeader); TksEmbeddedEditStyle = (ksEditNormal, ksEditClearing, ksEditCombo, ksEditTransparent); TksClearCacheType = (ksClearCacheAll, ksClearCacheNonVisible); TksTableViewRowSelectAnimation = (ksRowSelectAniNone, ksRowSelectAniFromLeft, ksRowSelectAniFromRight); TksTableViewRowIndicatorAlign = (ksRowIndicatorLeft, ksRowIndicatorRight); TksTableBeginRowCacheEvent = procedure(Sender: TObject; ARow:TksTableViewItem) of object; TksTableViewRowCacheEvent = procedure(Sender: TObject; ACanvas: TCanvas; ARow: TksTableViewItem; ARect: TRectF) of object; TksTableViewDeletingItemEvent = procedure(Sender: TObject; AItem: TksTableViewItem; var ACanDelete: Boolean) of object; TksTableViewDeleteItemEvent = procedure(Sender: TObject; AItem: TksTableViewItem) of object; TksTableViewItemClickEvent = procedure(Sender: TObject; x, y: single; AItem: TksTableViewItem; AId: string; ARowObj: TksTableViewItemObject) of object; TksItemSwipeEvent = procedure(Sender: TObject; ARow: TksTableViewItem; ASwipeDirection: TksSwipeDirection; AButtons: TksTableViewActionButtons) of object; TksItemActionButtonClickEvent = procedure(Sender: TObject; ARow: TksTableViewItem; AButton: TksTableViewActionButton) of object; TksTableViewItemSwitchEvent = procedure(Sender: TObject; AItem: TksTableViewItem; ASwitch: TksTableViewItemSwitch; ARowID: string) of object; TksTableViewItemButtonEvent = procedure(Sender: TObject; AItem: TksTableViewItem; AButton: TksTableViewItemButton; ARowID: string) of object; TksItemChecMarkChangedEvent = procedure(Sender: TObject; ARow: TksTableViewItem; AChecked: Boolean) of object; TksTableViewSelectDateEvent = procedure(Sender: TObject; AItem: TksTableViewItem; ASelectedDate: TDateTime; var AAllow: Boolean) of object; TksTableViewSelectPickerItem = procedure(Sender: TObject; AItem: TksTableViewItem; ASelected: string; var AAllow: Boolean) of object; TksTableViewSelectPickerItemExt = procedure(Sender: TObject; AItem: TksTableViewItem; ASelected: string; AIndex: integer; var AAllow: Boolean) of object; TksTableViewEmbeddedEditChange = procedure(Sender: TObject; ARow: TksTableViewItem; AEdit: TksTableViewItemEmbeddedBaseEdit; AText: string) of object; TksTableViewEmbeddedDateEditChange = procedure(Sender: TObject; ARow: TksTableViewItem; ADateEdit: TksTableViewItemEmbeddedDateEdit; ADate: TDateTime) of object; TksTableViewScrollChangeEvent = procedure(Sender: TObject; AScrollPos, AMaxScrollLimit: single) of object; TksTableViewCanDragItemEvent = procedure(Sender: TObject; ADragRow: TksTableViewItem; var AllowDrag: Boolean) of object; TksTableViewCanDropItemEvent = procedure(Sender: TObject; ADragRow, ADropRow: TksTableViewItem; var AllowDrop: Boolean) of object; TksTableViewDropItemEvent = procedure(Sender: TObject; ADragRow, ADropRow: TksTableViewItem; var AllowMove: Boolean) of object; TksTableViewSearchFilterChange = procedure(Sender: TObject; ASearchText: string) of object; TksTableViewStickyHeaderChange = procedure(Sender: TObject; AFromStickHeader, AToStickHeader: TksTableViewItem) of object; TksTableViewRowIndicatorExpandEvent = procedure(Sender: TObject; AItem: TksTableViewItem; ABackground: TAlphaColor; var AForeground: TAlphaColor) of object; //--------------------------------------------------------------------------------------- // TksTableViewActionButton TksTableViewActionButton = class strict private FWidth: integer; FIcon: TBitmap; FTextColor: TAlphaColor; FColor: TAlphaColor; FText: string; FIsDeleteButton: Boolean; FAccessory: TksAccessoryType; procedure SetAccessory(const Value: TksAccessoryType); public constructor Create(AIsDelete: Boolean); destructor Destroy; override; procedure Render(ACanvas: TCanvas; ARect: TRectF); property Accessory: TksAccessoryType read FAccessory write SetAccessory; property Text: string read FText write FText; property TextColor: TAlphaColor read FTextColor write FTextColor default claWhite; property Color: TAlphaColor read FColor write FColor; property Width: integer read FWidth write FWidth default 80; property IsDeleteButton: Boolean read FIsDeleteButton write FIsDeleteButton; end; //--------------------------------------------------------------------------------------- // TksTableViewActionButtons TksTableViewActionButtons = class(TObjectList<TksTableViewActionButton>) strict private [weak]FTableItem: TksTableviewItem; [weak]FTableView: TksTableView; FPercentWidth: integer; FAlignment: TksTableViewActionButtonAlignment; FAnimating: Boolean; private procedure SetPercentWidth(const Value: integer); function GetVisible: Boolean; procedure ShowButtons(AItem: TKsTableViewItem); procedure HideButtons; function TotalWidth: integer; property PercentWidth: integer read FPercentWidth write SetPercentWidth; property Visible: Boolean read GetVisible; procedure Render(ACanvas: TCanvas; ARect: TRectF); function ButtonFromXY(x, y: single): TksTableViewActionButton; function AddDeleteButton: TksTableViewActionButton; public constructor Create(AOwner: TksTableView); function AddButton(AText: string; AColor, ATextColor: TAlphaColor; const AIcon: TksAccessoryType = atNone; const AWidth: integer = 60): TksTableViewActionButton; property TableItem: TKsTableviewItem read FTableItem; property Alignment: TksTableViewActionButtonAlignment read FAlignment write FAlignment; end; //--------------------------------------------------------------------------------------- // TksTableViewActionButtons TksTableViewItemObject = class private [weak]FTableItem: TksTableViewItem; [weak]FPositionRelativeTo : TksTableViewItemObject; FAlign: TksTableItemAlign; FVertAlign: TksTableItemAlign; FID: string; FSelected: Boolean; FWidth: single; FHeight: single; FPlaceOffset: TPointF; FHitTest: Boolean; FOffsetX: single; FOffsetY: single; FShowSelection: Boolean; FMouseDown: Boolean; FMargins: TBounds; FHeightPercentange : Single; FWidthPercentange : Single; FVisible: Boolean; FItemRect: TRectF; procedure SetHeight(const Value: single); procedure SetWidth(const Value: single); procedure SetHeightPercentange(const Value: single); procedure SetWidthPercentange(const Value: single); procedure SetPositionRelativeTo(const Value: TksTableViewItemObject); procedure SetHitTest(const Value: Boolean); procedure SetOffsetX(const Value: single); procedure SetOffsetY(const Value: single); procedure SetShowSelection(const Value: Boolean); procedure SetSelected(const Value: Boolean); procedure SetVisible(const Value: Boolean); protected function ConsumesClick: Boolean; virtual; function GetItemRect: TRectF; function GetObjectRect: TRectF; virtual; procedure Changed; procedure Render(AItemRect: TRectF; ACanvas: TCanvas); virtual; procedure SetAlign(Value: TksTableItemAlign); procedure SetVertAlign(Value: TksTableItemAlign); procedure SetID(Value: string); property ObjectRect: TRectF read GetObjectRect; procedure Deselect; public constructor Create(ATableItem: TksTableViewItem); virtual; destructor Destroy; override; procedure MouseDown(x, y: single); virtual; procedure MouseUp(x, y: single); virtual; property Align: TksTableItemAlign read FAlign write SetAlign; property Height: single read FHeight write SetHeight; property HitTest: Boolean read FHitTest write SetHitTest default True; property ID: string read FID write SetID; property Margins: TBounds read FMargins write FMargins; property OffsetX: single read FOffsetX write SetOffsetX; property OffsetY: single read FOffsetY write SetOffsetY; property TableItem: TksTableViewItem read FTableItem; property VertAlign: TksTableItemAlign read FVertAlign write SetVertAlign; property Width: single read FWidth write SetWidth; property ShowSelection: Boolean read FShowSelection write SetShowSelection default False; property HeightPercentange: single read FHeightPercentange write SetHeightPercentange; property WidthPercentange: single read FWidthPercentange write SetWidthPercentange; property PositionRelativeTo: TksTableViewItemObject read FPositionRelativeTo write SetPositionRelativeTo; property Selected: Boolean read FSelected write SetSelected default False; property Visible: Boolean read FVisible write SetVisible default True; end; //--------------------------------------------------------------------------------------- { TksTableViewItemEmbeddedControl } TksTableViewItemEmbeddedControl = class(TksTableViewItemObject) private FFocused: Boolean; FCached: TBitmap; procedure DoExitControl(Sender: TObject); procedure ApplyStyle(AControl: TFmxObject); protected FControl: TStyledControl; function CanFocus: Boolean; virtual; function CreateControl: TStyledControl; virtual; abstract; function GetControlBitmap(AForceRecreate: Boolean): TBitmap; procedure InitializeControl; virtual; procedure FocusControl; virtual; procedure HideControl; virtual; function ConsumesClick: Boolean; override; procedure Render(AItemRect: TRectF; ACanvas: TCanvas); override; procedure EnableEvents; virtual; abstract; procedure DisableEvents; virtual; abstract; public constructor Create(ATableItem: TksTableViewItem); override; destructor Destroy; override; procedure MouseDown(x, y: single); override; end; //--------------------------------------------------------------------------------------- { TksTableViewItemEmbeddedBaseEdit } TksTableViewItemEmbeddedBaseEdit = class(TksTableViewItemEmbeddedControl) private FStyle: TksEmbeddedEditStyle; function GetCustomEdit: TCustomEdit; procedure DoEditChange(Sender: TObject); procedure SetStyle(const Value: TksEmbeddedEditStyle); protected function CanFocus: Boolean; override; function GetText: string; virtual; abstract; procedure SetText(const Value: string); virtual; abstract; property CustomEdit: TCustomEdit read GetCustomEdit; procedure FocusControl; override; procedure HideControl; override; procedure EnableEvents; override; procedure DisableEvents; override; property Text: string read GetText write SetText; property Style: TksEmbeddedEditStyle read FStyle write SetStyle; end; //--------------------------------------------------------------------------------------- { TksTableViewItemEmbeddedEdit } TksTableViewItemEmbeddedEdit = class(TksTableViewItemEmbeddedBaseEdit) private function GetEditControl: TEdit; protected function GetText: string; override; procedure SetText(const Value: string); override; function CreateControl: TStyledControl; override; public property Style; property Text; end; //--------------------------------------------------------------------------------------- // TksTableViewItemEmbeddedDateEdit TksTableViewItemEmbeddedDateEdit = class(TksTableViewItemEmbeddedControl) private function GetEditControl: TDateEdit; procedure DoDateChanged(Sender: TObject); protected function GetDate: TDateTime; procedure SetDate(const Value: TDateTime); function CreateControl: TStyledControl; override; procedure EnableEvents; override; procedure DisableEvents; override; public property Date: TDateTime read GetDate write SetDate; end; //--------------------------------------------------------------------------------------- { TksTableViewItemButton } TksTableViewItemButton = class(TksTableViewItemEmbeddedControl) private function GetButton: TSpeedButton; function GetTintColor: TAlphaColor; procedure SetTintColor(const Value: TAlphaColor); function GetText: string; procedure SetText(const Value: string); procedure DoButtonClicked(Sender: TObject); function GetStyleLookup: string; procedure SetStyleLookup(const Value: string); protected function CreateControl: TStyledControl; override; procedure EnableEvents; override; procedure DisableEvents; override; public property TintColor: TAlphaColor read GetTintColor write SetTintColor; property Text: string read GetText write SetText; property StyleLookup: string read GetStyleLookup write SetStyleLookup; end; //--------------------------------------------------------------------------------------- { TksTableViewItemSwitch } TksTableViewItemSwitch = class(TksTableViewItemEmbeddedControl) private FClickDelay: TFmxHandle; function GetSwitch: TSwitch; function GetChecked: Boolean; procedure SetChecked(const Value: Boolean); procedure DoSwitchClickedDelayed; procedure DoSwitchClicked(Sender: TObject); protected function CreateControl: TStyledControl; override; procedure EnableEvents; override; procedure DisableEvents; override; public property Checked: Boolean read GetChecked write SetChecked; end; //--------------------------------------------------------------------------------------- { TksTableViewItemText } TksTableViewItemText = class(TksTableViewItemObject) private FBackground: TAlphaColor; FText: string; FFont: TFont; FTextColor: TAlphaColor; FTextAlign: TTextAlign; FTextVertAlign: TTextAlign; FWordWrap: Boolean; FTrimming: TTextTrimming; FIsHtmlText: Boolean; procedure SetText(const Value: string); procedure SetFont(const Value: TFont); procedure SetTextColor(const Value: TAlphaColor); procedure SetTextAlign(const Value: TTextAlign); procedure SetTextVertAlign(const Value: TTextAlign); procedure SetWordWrap(const Value: Boolean); procedure SetTrimming(const Value: TTextTrimming); procedure SetBackground(const Value: TAlphaColor); procedure FontChanged(Sender: TObject); procedure SetIsHtmlText(const Value: Boolean); protected procedure Render(AItemRect: TRectF; ACanvas: TCanvas); override; public constructor Create(ATableItem: TksTableViewItem); override; destructor Destroy; override; function CalculateSize: TSizeF; procedure Assign(ASource: TksTableViewItemText); property Background: TAlphaColor read FBackground write SetBackground default claNull; property Font: TFont read FFont write SetFont; property Text: string read FText write SetText; property TextColor: TAlphaColor read FTextColor write SetTextColor default claBlack; property TextAlignment: TTextAlign read FTextAlign write SetTextAlign default TTextAlign.Leading; property TextVertAlign: TTextAlign read FTextVertAlign write SetTextVertAlign default TTextAlign.Leading; property Trimming: TTextTrimming read FTrimming write SetTrimming default TTextTrimming.Character; property WordWrap: Boolean read FWordWrap write SetWordWrap default False; property IsHtmlText: Boolean read FIsHtmlText write SetIsHtmlText; end; //--------------------------------------------------------------------------------------- { TksTableViewShadow } TksTableViewShadow = class(TPersistent) private FColor: TAlphaColor; FOffset: integer ; FVisible: Boolean; public constructor Create; virtual; procedure Assign(ASource: TPersistent); override; procedure SetVisible(const Value: Boolean); property Color: TAlphaColor read FColor write FColor default claSilver; property Offset: integer read FOffset write FOffset default 2; property Visible: Boolean read FVisible write SetVisible default True; end; //--------------------------------------------------------------------------------------- { TksListItemRowTableCell } TksListItemRowTableCell = class(TPersistent) private [weak]FTable: TksTableViewItemTable; FRow, FCol: integer; FTextSettings: TTextSettings; FFill: TBrush; FStroke: TStrokeBrush; FText: string; FWidth: single; FHeight: single; FPadding: TBounds; FVisible: Boolean; FSides: TSides; procedure SetText(const Value: string); procedure SetTextSettings(const Value: TTextSettings); procedure SetVisible(const Value: Boolean); procedure Changed; function GetShadow: TksTableViewShadow; public constructor Create(ATable: TksTableViewItemTable); virtual; destructor Destroy; override; function IsFixedCell: Boolean; procedure DrawToCanvas(x, y: single; ACanvas: TCanvas; ACol, ARow: integer; AShadow: TksTableViewShadow; AText: Boolean); property Fill: TBrush read FFill; property Stroke: TStrokeBrush read FStroke; property TextSettings: TTextSettings read FTextSettings write SetTextSettings; property Text: string read FText write SetText; property Width: single read FWidth write FWidth; property Height: single read FHeight write FHeight; property Padding: TBounds read FPadding write FPadding; property Shadow: TksTableViewShadow read GetShadow; property Sides: TSides read FSides write FSides; property Visible: Boolean read FVisible write SetVisible default True; end; TksListItemRowTableRow = array of TksListItemRowTableCell; //--------------------------------------------------------------------------------------- // TksListItemRowTableBanding TksListItemRowTableBanding = class(TPersistent) private FActive: Boolean; FColor2: TAlphaColor; FColor1: TAlphaColor; procedure SetActive(const Value: Boolean); public constructor Create; virtual; procedure Assign(ASource: TPersistent); override; property Color1: TAlphaColor read FColor1 write FColor1 default claNull; property Color2: TAlphaColor read FColor2 write FColor2 default claNull; property Active: Boolean read FActive write SetActive; end; //--------------------------------------------------------------------------------------- // TksTableViewItemTable TksTableViewItemTable = class(TksTableViewItemObject) private FBackground: TAlphaColor; FBorderColor: TAlphaColor; FRows: array of TksListItemRowTableRow; FRowCount: integer; FColCount: integer; FDefaultRowHeight: single; FDefaultColWidth: single; FShadow: TksTableViewShadow; FFixedCellColor: TAlphaColor; FFixedRows: integer; FFixedCols: integer; FBanding: TksListItemRowTableBanding; procedure SetColCount(const Value: integer); procedure SetRowCount(const Value: integer); procedure SetBackgroundColor(const Value: TAlphaColor); procedure SetBorderColor(const Value: TAlphaColor); procedure SetDefaultColWidth(const Value: single); procedure SetDefaultRowHeight(const Value: single); procedure ResizeTable; function GetColWidths(ACol: integer): single; procedure SetColWidths(ACol: integer; const Value: single); function GetCells(ACol, ARow: integer): TksListItemRowTableCell; function GetTableSize: TSizeF; procedure RenderTableContents(ACanvas: TCanvas; AText: Boolean); procedure SetFixedCellColor(const Value: TAlphaColor); procedure SetBanding(const Value: TksListItemRowTableBanding); protected procedure Render(AItemRect: TRectF; ACanvas: TCanvas); override; public constructor Create(ARow: TKsTableViewItem); override; destructor Destroy; override; procedure Clear; procedure MergeRowCells(x, y, AMergeCount: integer); procedure SetRowColor(ARow: integer; AColor: TAlphaColor); procedure SetColColor(ACol: integer; AColor: TAlphaColor); procedure SetRowFont(ARow: integer; AFontName: TFontName; AColor: TAlphaColor; ASize: integer; AStyle: TFontStyles); procedure SetColFont(ACol: integer; AFontName: TFontName; AColor: TAlphaColor; ASize: integer; AStyle: TFontStyles); property Background: TAlphaColor read FBackground write SetBackgroundColor default claWhite; property Banding: TksListItemRowTableBanding read FBanding write SetBanding; property BorderColor: TAlphaColor read FBorderColor write SetBorderColor default claBlack; property FixCellColor: TAlphaColor read FFixedCellColor write SetFixedCellColor default claGainsboro; property FixedRows: integer read FFixedRows write FFixedRows default 1; property FixedCols: integer read FFixedCols write FFixedCols default 1; property Cells[ACol, ARow: integer]: TksListItemRowTableCell read GetCells; property ColCount: integer read FColCount write SetColCount; property RowCount: integer read FRowCount write SetRowCount; property DefaultRowHeight: single read FDefaultRowHeight write SetDefaultRowHeight; property DefaultColWidth: single read FDefaultColWidth write SetDefaultColWidth; property ColWidths[ACol: integer]: single read GetColWidths write SetColWidths; property Shadow: TksTableViewShadow read FShadow; property TableSize: TSizeF read GetTableSize; end; //--------------------------------------------------------------------------------------- // TksTableViewItemBaseImage TksTableViewItemBaseImage = class(TksTableViewItemObject) strict private FBitmap: TBitmap; FDrawMode: TksImageDrawMode; FShadow: TksTableViewShadow; FHighQuality: Boolean; FBadgeValue: integer; FBadgeColor: TAlphaColor; FBadgeTextColor: TAlphaColor; [weak]FExternalBitmap: TBitmap; private FOwnsBitmap: Boolean; procedure SetBitmap(const Value: TBitmap); function GetBitmap: TBitmap; procedure SetOwnsBitmap(const Value: Boolean); procedure SetShadow(const Value: TksTableViewShadow); procedure SetDrawMode(const Value: TksImageDrawMode); procedure SetHighQuality(const Value: Boolean); procedure SetBadgeValue(const Value: integer); procedure SetBadgeColor(const Value: TAlphaColor); procedure SetBadgeTextColor(const Value: TAlphaColor); protected procedure Render(AItemRect: TRectF; ACanvas: TCanvas); override; procedure Clear; procedure DoBeforeRenderBitmap(ABmp: TBitmap); virtual; property Bitmap: TBitmap read GetBitmap write SetBitmap; property Shadow: TksTableViewShadow read FShadow write SetShadow; property OwnsBitmap: Boolean read FOwnsBitmap write SetOwnsBitmap default False; property DrawMode: TksImageDrawMode read FDrawMode write SetDrawMode default ksDrawModeStretch; property HighQuality: Boolean read FHighQuality write SetHighQuality default False; property BadgeValue: integer read FBadgeValue write SetBadgeValue; property BadgeColor: TAlphaColor read FBadgeColor write SetBadgeColor default claRed; property BadgeTextColor: TAlphaColor read FBadgeTextColor write SetBadgeTextColor default claWhite; public constructor Create(ATableItem: TksTableViewItem); override; destructor Destroy; override; procedure Assign(ASource: TksTableViewItemBaseImage); end; //--------------------------------------------------------------------------------------- // TksTableViewItemImage TksTableViewItemImage = class(TksTableViewItemBaseImage) public property Bitmap; property Shadow; property DrawMode; property OwnsBitmap; property HighQuality; property BadgeValue; property BadgeColor; property BadgeTextColor; end; //--------------------------------------------------------------------------------------- // TksTableViewItemShape TksTableViewBaseItemShape = class(TksTableViewItemObject) private FStroke: TStrokeBrush; FFill: TBrush; FShape: TksTableViewShape; FCornerRadius: single; procedure SetCornerRadius(const Value: single); procedure SetFill(const Value: TBrush); procedure SetShape(const Value: TksTableViewShape); procedure SetStroke(const Value: TStrokeBrush); protected procedure Render(AItemRect: TRectF; ACanvas: TCanvas); override; property Stroke: TStrokeBrush read FStroke write SetStroke; property Fill: TBrush read FFill write SetFill; property Shape: TksTableViewShape read FShape write SetShape; property CornerRadius: single read FCornerRadius write SetCornerRadius; public constructor Create(ATableItem: TksTableViewItem); override; destructor Destroy; override; end; TksTableViewItemShape = class(TksTableViewBaseItemShape) public property Stroke; property Fill; property Shape; property CornerRadius; end; TksTableViewChatBubble = class(TksTableViewItemShape) private FText: string; FFont: TFont; FTextColor: TAlphaColor; FPosition: TksTableViewChatBubblePosition; procedure SetFont(const Value: TFont); procedure SetText(const Value: string); procedure SetTextColor(const Value: TAlphaColor); protected procedure RecalculateSize; procedure Render(AItemRect: TRectF; ACanvas: TCanvas); override; public constructor Create(ATableItem: TksTableViewItem); override; destructor Destroy; override; property Text: string read FText write SetText; property Font: TFont read FFont write SetFont; property TextColor: TAlphaColor read FTextColor write SetTextColor; property Position: TksTableViewChatBubblePosition read FPosition write FPosition; end; //--------------------------------------------------------------------------------------- // TksTableViewItemTileBackground TksTableViewItemTileBackground = class(TksTableViewItemShape) private FPadding: TBounds; public constructor Create(ATableItem: TksTableViewItem); override; destructor Destroy; override; procedure Assign(ASource: TksTableViewItemTileBackground); property Padding: TBounds read FPadding write FPadding; end; //--------------------------------------------------------------------------------------- // TksTableViewItemAccessory TksTableViewItemAccessory = class(TksTableViewItemImage) strict private FColor: TAlphaColor; private FAccessory: TksAccessoryType; procedure RedrawAccessory; protected procedure DoBeforeRenderBitmap(ABmp: TBitmap); override; procedure SetAccessory(const Value: TksAccessoryType); procedure SetColor(const Value: TAlphaColor); procedure Render(AItemRect: TRectF; ACanvas: TCanvas); override; public constructor Create(ATableItem: TksTableViewItem); override; property Accessory: TksAccessoryType read FAccessory write SetAccessory; property Color: TAlphaColor read FColor write SetColor default claNull; end; //--------------------------------------------------------------------------------------- // TksTableViewItemObjects TksTableViewItemObjects = class(TObjectList<TksTableViewItemObject>) private [weak]FTableView: TksTableView; function GetObjectByID(AId: string): TksTableViewItemObject; function GetImageByID(AId: string): TksTableViewItemImage; function GetTextByID(AId: string): TksTableViewItemText; public constructor Create(ATableView: TksTableView); virtual; property ObjectByID[AId: string]: TksTableViewItemObject read GetObjectByID; property ImageByID[AId: string]: TksTableViewItemImage read GetImageByID; property TextByID[AId: string]: TksTableViewItemText read GetTextByID; end; //--------------------------------------------------------------------------------------- // TksTableViewItem TksTableViewItem = class private [weak]FTableView: TksTableView; [weak]FCheckMarkAccessory: TksTableViewItemAccessory; [weak]FTagObject: TObject; [weak]FOwner: TksTableViewItems; FData: TDictionary<string, TValue>; FID: string; FAbsoluteIndex: integer; FIndicator: TksTableViewItemShape; FTileBackground: TksTableViewItemTileBackground; FImage: TksTableViewItemImage; FTitle: TksTableViewItemText; FSubTitle: TksTableViewItemText; FDetail: TksTableViewItemText; FAccessory: TksTableViewItemAccessory; FHeight: single; FHeightPercentage: single; FHeaderHeight: single; FIsStickyHeader: boolean; FItemRect: TRectF; FCached: Boolean; FCaching: Boolean; _FBitmap: TBitmap; FIndex: integer; FSearchIndex: string; FSearchFilter: string; FChecked: Boolean; FUpdating: Boolean; FPurpose: TksTableViewItemPurpose; FObjects: TksTableViewItemObjects; FSelectionValue: Variant; FFont: TFont; FTextColor: TAlphaColor; FCanSelect: Boolean; FTagString: string; FTagInteger: integer; FSelector: TksTableItemSelector; FPickerItems: TStrings; FColCount: integer; FIsFirstCol : Boolean; FIsLastCol : Boolean; FIsFirstRow : Boolean; FIsLastRow : Boolean; FIsFixedHeader : Boolean; FIsFixedFooter : Boolean; FAppearance : TksTableViewItemAppearance; FDragging: Boolean; FFill : TBrush; FCheckmarkAllowed: Boolean; FHidden: Boolean; FDeleting: Boolean; FForegroundColor: TAlphaColor; function MatchesSearch(AFilter: string): Boolean; function IsVisible(AViewport: TRectF): Boolean; function GetInternalRect: TRectF; //procedure SetSearchIndex(const Value: string); procedure SetItemRect(const Value: TRectF); procedure SetIndex(const Value: integer); procedure SetAppearance(const Value: TksTableViewItemAppearance); procedure SetHidden(const Value: Boolean); procedure Changed; procedure RealignStandardObjects; procedure SetHeight(const Value: single); procedure SetHeightPercentage(const Value: single); procedure SetCached(const Value: Boolean); procedure SetPurpose(const Value: TksTableViewItemPurpose); procedure SetColCount(const Value: Integer); procedure SetFont(const Value: TFont); procedure SetTextColor(const Value: TAlphaColor); procedure SetChecked(const Value: Boolean); function CheckMarkClicked(x, y: single) : Boolean; procedure DoClick(x, y: single); function GetIndicatorColor: TAlphaColor; procedure SetIndicatorColor(const Value: TAlphaColor); procedure DoSwipe(ADirecton: TksSwipeDirection); procedure SetPickerItems(const Value: TStrings); procedure PickerItemsChanged(Sender: TObject); function GetItemData(const AIndex: string): TValue; procedure SetItemData(const AIndex: string; const Value: TValue); function GetHasData(const AIndex: string): Boolean; procedure DeselectObjects; procedure SetFill(const Value: TBrush); procedure SelectFirstEmbeddedEdit; function IsHeader: Boolean; procedure Invalidate; function GetImageByID(AID: string): TksTableViewItemImage; function GetTextByID(AID: string): TksTableViewItemText; procedure SetSearchFilter(const Value: string); protected function Render(ACanvas: TCanvas; AScrollPos: single): TRectF; procedure CacheItem(const AForceCache: Boolean = False); procedure UpdateSearchIndex; public constructor Create(ATableView: TksTableView); reintroduce; virtual; destructor Destroy; override; function TimeToCacheItem: integer; function ObjectAtPos(x, y: single): TksTableViewItemObject; function IsLastItem: Boolean; //procedure RecreateCache; procedure ClearCache; procedure ExpandIndicatorToWidth; // image functions... function DrawBitmap(ABmp: TBitmap; ARect: TRectF; const AVertAlign: TksTableItemAlign = Center): TksTableViewItemImage; overload; function DrawBitmap(ABmp: TBitmap; x, AWidth, AHeight: single; const AVertAlign: TksTableItemAlign = Center): TksTableViewItemImage; overload; function DrawBitmap(ABmp: TBitmap; x, y, AWidth, AHeight: single; const AVertAlign: TksTableItemAlign = Center): TksTableViewItemImage overload; // text functions... function TextWidth(AText: string; AIsHtml: Boolean): single; function TextHeight(AText: string; AWordWrap, AIsHtml: Boolean; ATrimming: TTextTrimming; const AMaxWidth: single): single; procedure SetItemFontStyle(AFontStyle: TFontStyles); procedure SetItemTextColor(AColor: TAlphaColor); function TextOut(AText: string; x: single; const AVertAlign: TksTableItemAlign = TksTableItemAlign.Center; const AWordWrap: Boolean = False): TksTableViewItemText; overload; function TextOut(AText: string; x, AWidth: single; const AVertAlign: TksTableItemAlign = TksTableItemAlign.Center; const AWordWrap: Boolean = False): TksTableViewItemText; overload; function TextOut(AText: string; x, y, AWidth: single; const AVertAlign: TksTableItemAlign = TksTableItemAlign.Center; const AWordWrap: Boolean = False): TksTableViewItemText; overload; function TextBox(AText: string; ARect: TRectF; ATextAlign: TTextAlign; ATextLayout: TTextAlign; const ABackground: TAlphaColor = claNull): TksTableViewItemText; overload; function TextBoxHtml(AText: string; ARect: TRectF): TksTableViewItemText; function TextOutRight(AText: string; y, AWidth: single; AXOffset: single; const AVertAlign: TksTableItemAlign = TksTableItemAlign.Center): TksTableViewItemText; overload; // shape functions... function DrawChatBubble(AText: string; APosition: TksTableViewChatBubblePosition; AColor, ATextColor: TAlphaColor): TksTableViewChatBubble; function DrawRect(x, y, AWidth, AHeight: single; AStroke, AFill: TAlphaColor; const AVertAlign: TksTableItemAlign = TksTableItemAlign.Center): TksTableViewItemShape; overload; function DrawRect(ARect: TRectF; AStroke, AFill: TAlphaColor; const AVertAlign: TksTableItemAlign = TksTableItemAlign.Center): TksTableViewItemShape; overload; function AddButton(AWidth: integer; AText: string; const ATintColor: TAlphaColor = claNull; const AVertAlign: TksTableItemAlign = TksTableItemAlign.Center; const AYPos: integer = 0): TksTableViewItemButton; overload; function AddButton(AStyle: TksTableViewButtonStyle; const ATintColor: TAlphaColor = claNull): TksTableViewItemButton; overload; function AddEdit(AX, AY, AWidth: single; AText: string; const AStyle: TksEmbeddedEditStyle = TksEmbeddedEditStyle.ksEditNormal): TksTableViewItemEmbeddedEdit; function AddDateEdit(AX, AY, AWidth: single; ADate: TDateTime): TksTableViewItemEmbeddedDateEdit; function AddSwitch(x: single; AIsChecked: Boolean; const AAlign: TksTableItemAlign = TksTableItemAlign.Trailing): TksTableViewItemSwitch; function AddTable(AX, AY, AColWidth, ARowHeight: single; AColCount, ARowCount: integer): TksTableViewItemTable; property AbsoluteIndex: integer read FAbsoluteIndex; property Accessory: TksTableViewItemAccessory read FAccessory; property CheckMarkAccessory: TksTableViewItemAccessory read FCheckMarkAccessory; property CanSelect: Boolean read FCanSelect write FCanSelect default True; property Checked: Boolean read FChecked write SetChecked default False; property Data[const AIndex: string]: TValue read GetItemData write SetItemData; property Font: TFont read FFont write SetFont; property HasData[const AIndex: string]: Boolean read GetHasData; property Height: single read FHeight write SetHeight; property HeightPercentage: single read FHeightPercentage write SetHeightPercentage; property ItemRect: TRectF read FItemRect write SetItemRect; property IndicatorColor: TAlphaColor read GetIndicatorColor write SetIndicatorColor; property ID: string read FID write FID; property TileBackground : TksTableViewItemTileBackground read FTileBackground; property Image: TksTableViewItemImage read FImage; property Title: TksTableViewItemText read FTitle; property SubTitle: TksTableViewItemText read FSubTitle; property TextColor: TAlphaColor read FTextColor write SetTextColor default claBlack; property Detail: TksTableViewItemText read FDetail; property Index: integer read FIndex write SetIndex; //property SearchIndex: string read GetSearchIndex; property SearchFilter: string read FSearchFilter write SetSearchFilter; property Objects: TksTableViewItemObjects read FObjects; property ImageByID[AID: string]: TksTableViewItemImage read GetImageByID; property TextByID[AID: string]: TksTableViewItemText read GetTextByID; property Cached: Boolean read FCached write SetCached default False; property PickerItems: TStrings read FPickerItems write SetPickerItems; property Purpose: TksTableViewItemPurpose read FPurpose write SetPurpose default None; property Selector: TksTableItemSelector read FSelector write FSelector; property TableView: TksTableView read FTableView; property TagString: string read FTagString write FTagString; property TagInteger: integer read FTagInteger write FTagInteger default 0; property TagObject: TObject read FTagObject write FTagObject; property ColCount: integer read FColCount write SetColCount default 0; property IsFirstCol: Boolean read FIsFirstCol; property IsLastCol: Boolean read FIsLastCol; property IsFirstRow: Boolean read FIsFirstRow; property IsLastRow: Boolean read FIsLastRow; property Appearance: TksTableViewItemAppearance read FAppearance write SetAppearance default iaNormal; property Fill: TBrush read FFill write SetFill; property IsStickyHeader: Boolean read FIsStickyHeader; property Hidden: Boolean read FHidden write SetHidden default false; end; //--------------------------------------------------------------------------------------- // TksTableViewItems TksTableViewItems = class(TObjectList<TksTableViewItem>) private FCachedCount: integer; {$IFNDEF VER310} [weak]FTableView: TksTableView; procedure UpdateIndexes; {$ENDIF} function GetLastItem: TksTableViewItem; function GetFirstItem: TksTableViewItem; function GetItemByID(AID: string): TksTableViewItem; protected {$IFDEF VER310} [weak]FTableView: TksTableView; procedure UpdateIndexes; {$ENDIF} function GetTotalItemHeight: single; public constructor Create(ATableView: TksTableView; AOwnsObjects: Boolean); virtual; procedure Move(CurIndex, NewIndex: Integer); overload; function AddHeader(AText: string): TksTableViewItem; function AddItem(AText: string; const AAccessory: TksAccessoryType = atNone): TksTableViewItem; overload; function AddItem(AText, ADetail: string; const AAccessory: TksAccessoryType = atNone): TksTableViewItem; overload; function AddItem(AText, ASubTitle, ADetail: string; const AAccessory: TksAccessoryType = atNone): TksTableViewItem; overload; function AddChatBubble(AText: string; APosition: TksTableViewChatBubblePosition; AColor, ATextColor: TAlphaColor; const AUserImage: TBitmap): TksTableViewChatBubble; function AddDateSelector(AText: string; ADate: TDateTime): TksTableViewItem; function AddItemSelector(AText, ASelected: string; AItems: TStrings): TksTableViewItem; overload; function AddItemSelector(AText, ASelected: string; AItems: array of string): TksTableViewItem; overload; function AddItemWithSwitch(AText: string; AChecked: Boolean; AID: string): TksTableViewItem; property ItemByID[AID: string]: TksTableViewItem read GetItemByID; function GetCheckedCount: integer; procedure Delete(AIndex: integer; const AAnimate: Boolean = True); reintroduce; procedure DeleteItem(AItem: TksTableViewItem; const AAnimate: Boolean = True); property FirstItem: TksTableViewItem read GetFirstItem; property LastItem: TksTableViewItem read GetLastItem; property CachedCount: integer read FCachedCount; end; //--------------------------------------------------------------------------------------- // TksTableViewBackgroundText TksTableViewBackgroundText = class(TPersistent) private FFont: TFont; FTextColor: TAlphaColor; FText: string; FEnabled: Boolean; procedure SetFont(const Value: TFont); procedure SetText(const Value: string); procedure SetTextColor(const Value: TAlphaColor); procedure SetEnabled(const Value: Boolean); public constructor Create; virtual; destructor Destroy; override; procedure Assign(ASource: TPersistent); override; published property Font: TFont read FFont write SetFont; property TextColor: TAlphaColor read FTextColor write SetTextColor default claSilver; property Text: string read FText write SetText; property Enabled: Boolean read FEnabled write SetEnabled default True; end; //--------------------------------------------------------------------------------------- // TksTableViewAppearence TksTableViewAppearence = class(TPersistent) private [weak]FListView: TksTableView; FBackground: TBrush; FItemBackground: TBrush; FAlternatingItemBackground: TAlphaColor; FSeparatorColor: TAlphaColor; FHeaderColor: TAlphaColor; FSelectedColor: TAlphaColor; procedure SetBackground(const Value: TBrush); procedure SetItemBackground(const Value: TBrush); procedure SetAlternatingItemBackground(const Value: TAlphaColor); procedure SetSeparatorBackground(const Value: TAlphaColor); procedure SetHeaderColor(const Value: TAlphaColor); procedure SetSelectedColor(const Value: TAlphaColor); public constructor Create(AListView: TksTableView); destructor Destroy; override; procedure Assign(ASource: TPersistent); override; published property Background: TBrush read FBackground write SetBackground; property HeaderColor: TAlphaColor read FHeaderColor write SetHeaderColor default claNull; property SeparatorColor: TAlphaColor read FSeparatorColor write SetSeparatorBackground default $FFF0F0F0; property ItemBackground: TBrush read FItemBackground write SetItemBackground; property SelectedColor: TAlphaColor read FSelectedColor write SetSelectedColor default C_TABLEVIEW_DEFAULT_SELECTED_COLOR; property AlternatingItemBackground: TAlphaColor read FAlternatingItemBackground write SetAlternatingItemBackground default claNull; end; //--------------------------------------------------------------------------------------- // TksDeleteButton TksDeleteButton = class(TPersistent) private FEnabled: Boolean; FText: string; FColor: TAlphaColor; FTextColor: TAlphaColor; FWidth: integer; FShowImage: Boolean; FShowText: Boolean; public constructor Create; virtual; published property Color: TAlphaColor read FColor write FColor default claRed; property TextColor: TAlphaColor read FTextColor write FTextColor default claWhite; property Enabled: Boolean read FEnabled write FEnabled default False; property Text: string read FText write FText; property ShowImage: Boolean read FShowImage write FShowImage default True; property ShowText: Boolean read FShowText write FShowText default True; property Width: integer read FWidth write FWidth default 60; end; //--------------------------------------------------------------------------------------- // TksListViewRowIndicators TksListViewRowIndicators = class(TPersistent) strict private [weak]FTableView: TksTableView; FWidth: integer; FHeight: integer; FVisible: Boolean; FOutlined: Boolean; FShadow: Boolean; FShape: TksTableViewShape; FSelectRow: Boolean; FAlignment: TksTableViewRowIndicatorAlign; private procedure Changed; procedure SetShadow(const Value: Boolean); procedure SetShape(const Value: TksTableViewShape); procedure SetAlignment(const Value: TksTableViewRowIndicatorAlign); procedure SetSelectRow(const Value: Boolean); published constructor Create(ATableView: TksTableView); virtual; property Width: integer read FWidth write FWidth default C_TABLEVIEW_DEFAULT_INDICATOR_WIDTH; property Height: integer read FHeight write FHeight default C_TABLEVIEW_DEFAULT_INDICATOR_HEIGHT; property Visible: Boolean read FVisible write FVisible default False; property Outlined: Boolean read FOutlined write FOutlined default True; property Shadow: Boolean read FShadow write SetShadow default True; property Shape: TksTableViewShape read FShape write SetShape default ksRectangle; property SelectRow: Boolean read FSelectRow write SetSelectRow default False; property Alignment: TksTableViewRowIndicatorAlign read FAlignment write SetAlignment default ksRowIndicatorLeft; end; //--------------------------------------------------------------------------------------- // TksTableViewTextDefault TksTableViewTextDefault = class(TPersistent) private FFont: TFont; FTextColor: TAlphaColor; procedure SetFont(const Value: TFont); procedure SetTextColor(const Value: TAlphaColor); public constructor Create; destructor Destroy; override; procedure Assign(ASource: TPersistent); override; published property Font: TFont read FFont write SetFont; property TextColor: TAlphaColor read FTextColor write SetTextColor; end; //--------------------------------------------------------------------------------------- // TksTableViewTextDefaults TksTableViewTextDefaults = class(TPersistent) private FTitle: TksTableViewTextDefault; FSubtitle: TksTableViewTextDefault; FDetail: TksTableViewTextDefault; FHeader: TksTableViewTextDefault; procedure SetDetail(const Value: TksTableViewTextDefault); procedure SetSubTitle(const Value: TksTableViewTextDefault); procedure SetTitle(const Value: TksTableViewTextDefault); procedure SetHeader(const Value: TksTableViewTextDefault); public constructor Create; destructor Destroy; override; published property Title: TksTableViewTextDefault read FTitle write SetTitle; property SubTitle: TksTableViewTextDefault read FSubtitle write SetSubTitle; property Detail: TksTableViewTextDefault read FDetail write SetDetail; property Header: TksTableViewTextDefault read FHeader write SetHeader; end; //--------------------------------------------------------------------------------------- // TksTableViewPullToRefresh TksTableViewPullToRefresh = class(TPersistent) private [weak]FTableView: TksTableView; FEnabled: Boolean; FPullText: string; FReleaseText: string; FFont: TFont; FTextColor: TAlphaColor; procedure SetEnabled(const Value: Boolean); procedure SetFont(const Value: TFont); public constructor Create(ATableView: TksTableView); virtual; destructor Destroy; override; procedure Assign(ASource: TPersistent); override; published property Enabled: Boolean read FEnabled write SetEnabled default True; property Font: TFont read FFont write SetFont; property PullText: string read FPullText write FPullText; property ReleaseText: string read FReleaseText write FReleaseText; property TextColor: TAlphaColor read FTextColor write FTextColor default claSilver; end; //--------------------------------------------------------------------------------------- // TksDragImage TksDragImage = class(TRectangle) private FBorder: TRectangle; FShadow: TShadowEffect; FMouseDownOffset: TPointF; procedure SetAllowDropColor(const Value: TStrokeBrush); function GetAllowDropColor: TStrokeBrush; property MouseDownOffset: TPointF read FMouseDownOffset write FMouseDownOffset; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Shadow: TShadowEffect read FShadow; property AllowDropStroke: TStrokeBrush read GetAllowDropColor write SetAllowDropColor; end; //--------------------------------------------------------------------------------------- // TksDragHighlightOptions TksDragHighlightOptions = class(TPersistent) private FAllowDropStroke: TStrokeBrush; FDisallowDropStroke: TStrokeBrush; FEnabled: Boolean; procedure SetAllowDropStroke(const Value: TStrokeBrush); procedure SetDisallowDropStroke(const Value: TStrokeBrush); public constructor Create; virtual; destructor Destroy; override; published property AllowDropStroke: TStrokeBrush read FAllowDropStroke write SetAllowDropStroke; property DisallowDropStroke: TStrokeBrush read FDisallowDropStroke write SetDisallowDropStroke; property Enabled: Boolean read FEnabled write FEnabled default True; end; //--------------------------------------------------------------------------------------- // TksDragDropOptions TksDragDropOptions = class(TPersistent) private FEnabled: Boolean; FShadow: Boolean; FOpacity: single; FDragSpaceColor: TAlphaColor; FDragHighlightOptions: TksDragHighlightOptions; FLiveMoving : Boolean; procedure SetOpacity(const Value: single); procedure SetShadow(const Value: Boolean); procedure SetDragHighlightOptions(const Value: TksDragHighlightOptions); procedure SetLiveMoving(const Value: Boolean); public constructor Create; virtual; destructor Destroy; override; published property DragHighlight: TksDragHighlightOptions read FDragHighlightOptions write SetDragHighlightOptions; property DragSpaceColor: TAlphaColor read FDragSpaceColor write FDragSpaceColor default $FFECECEC; property Enabled: Boolean read FEnabled write FEnabled default False; property Shadow: Boolean read FShadow write SetShadow default True; property Opacity: single read FOpacity write SetOpacity; property LiveMoving: Boolean read FLiveMoving write SetLiveMoving default True; end; //--------------------------------------------------------------------------------------- // TksTableViewSelectionOverlayOptions TksTableViewSelectionOverlayOptions = class(TPersistent) private [weak]FParent: TksTableViewSelectionOptions; FPosition: TksTableViewOverlaySelectorPosition; FStyle: TksTableViewOverlaySelectorStyle; FEnabled: Boolean; FStroke: TStrokeBrush; FBackgroundColor: TAlphaColor; FBitmap: TBitmap; FSize: integer; FLastStickyHeaderOffset: Single; FLastFixedFooterOffset: Single; procedure SetPosition(const Value: TksTableViewOverlaySelectorPosition); procedure SetEnabled(const Value: Boolean); procedure SetStrokeBrush(const Value: TStrokeBrush); procedure RecreateIndicator(AWidth,AHeight, AStickyHeaderOffset,AFixedFooterOffset: single); procedure SetStyle(const Value: TksTableViewOverlaySelectorStyle); procedure SetSize(const Value: integer); procedure DoStrokeChanged(Sender: TObject); public constructor Create(AParent: TksTableViewSelectionOptions); destructor Destroy; override; procedure Assign(ASource: TPersistent); override; procedure DrawToCanvas(ACanvas: TCanvas; ARect: TRectF ; AStickyHeaderBottom,FixedFooterStart : Single); published property Enabled: Boolean read FEnabled write SetEnabled default False; property BackgroundColor: TAlphaColor read FBackgroundColor write FBackgroundColor default claWhite; property Position: TksTableViewOverlaySelectorPosition read FPosition write SetPosition default ksSelectorRight; property Stroke: TStrokeBrush read FStroke write SetStrokeBrush; property Style: TksTableViewOverlaySelectorStyle read FStyle write SetStyle default ksArrow; property Size: integer read FSize write SetSize default 1; end; //--------------------------------------------------------------------------------------- // TksTableViewSelectionOptions TksTableViewSelectionOptions = class(TPersistent) private [weak]FTableView: TksTableView; FSelectionOverlay: TksTableViewSelectionOverlayOptions; FShowSelection: Boolean; FKeepSelection: Boolean; FSelectDuration: integer; FKeepSelectedInView: Boolean; FLongTapSelects: Boolean; procedure SetKeepSelection(const Value: Boolean); procedure SetShowSelection(const Value: Boolean); procedure SetSelectionOverlay(const Value: TksTableViewSelectionOverlayOptions); procedure SetKeepSelectedInView(const Value: Boolean); procedure SetLongTapSelects(const Value: Boolean); public constructor Create(ATableView: TKsTableView); destructor Destroy; override; procedure Assign(ASource: TPersistent); override; published property ShowSelection: Boolean read FShowSelection write SetShowSelection default True; property KeepSelection: Boolean read FKeepSelection write SetKeepSelection default False; property SelectionOverlay: TksTableViewSelectionOverlayOptions read FSelectionOverlay write SetSelectionOverlay; property SelectDuration: integer read FSelectDuration write FSelectDuration default C_TABLEVIEW_DEFAULT_SELECT_DURATION; property KeepSelectedInView: Boolean read FKeepSelectedInView write SetKeepSelectedInView default True; property LongTapSelects: Boolean read FLongTapSelects write SetLongTapSelects default True; end; //--------------------------------------------------------------------------------------- // TksTableViewJumpToHeaderOptions TksTableViewJumpToHeaderOptions = class(TPersistent) private FHeaderFill: TBrush; FHeaderFont: TFont; FHeaderTextColor: TAlphaColor; FHeaderHeight: Single; FHeaderText: String; FItemFill: TBrush; FItemFont: TFont; FItemTextColor: TAlphaColor; FItemHeight: Single; public constructor Create; destructor Destroy; override; procedure Assign(ASource: TPersistent); override; published property HeaderFill: TBrush read FHeaderFill write FHeaderFill; property HeaderFont: TFont read FHeaderFont write FHeaderFont; property HeaderTextColor: TAlphaColor read FHeaderTextColor write FHeaderTextColor default claBlack; property HeaderHeight : Single read FHeaderHeight write FHeaderHeight; property HeaderText: String read FHeaderText write FHeaderText; property ItemFill: TBrush read FItemFill write FItemFill; property ItemFont: TFont read FItemFont write FItemFont; property ItemTextColor: TAlphaColor read FItemTextColor write FItemTextColor default claBlack; property ItemHeight : Single read FItemHeight write FItemHeight; end; //--------------------------------------------------------------------------------------- // TksTableViewStickyHeaderButton TksTableViewStickyHeaderButton = class(TPersistent) private [weak]FTableView: TksTableView; FVisible: Boolean; FHeaderTableViewBackground : TRectangle; FHeaderTableView: TksTableView; FHeaderTableViewShadowEffect: TShadowEffect; FButtonType : TksTableViewHeaderButtonType; FJumpToHeaderOptions: TksTableViewJumpToHeaderOptions; FSelected: Boolean; FRemovePopupTimer : TFmxHandle; procedure Changed; procedure SetVisible(const Value: Boolean); procedure SetButtonType(const Value: TksTableViewHeaderButtonType); procedure SetJumpToHeaderOptions(const Value: TksTableViewJumpToHeaderOptions); public constructor Create(ATableView: TksTableView); destructor Destroy; override; procedure Assign(ASource: TPersistent); override; procedure DoButtonClicked(Sender: TObject ; AItem: TksTableViewItem); procedure CancelPopup(Sender: TObject); procedure RemovePopup; procedure JumpToHeaderClick(Sender: TObject; x, y: Single; AItem: TksTableViewItem; AId: string; ARowObj: TksTableViewItemObject); published property Visible: Boolean read FVisible write SetVisible default False; property ButtonType: TksTableViewHeaderButtonType read FButtonType write SetButtonType default TksTableViewHeaderButtonType.hbtJumpToHeader; property JumpToHeaderOptions: TksTableViewJumpToHeaderOptions read FJumpToHeaderOptions write SetJumpToHeaderOptions; property Selected: Boolean read FSelected write FSelected default False; end; //--------------------------------------------------------------------------------------- // TksTableViewStickyHeaderOptions TksTableViewStickyHeaderOptions = class(TPersistent) private [weak]FTableView: TksTableView; FEnabled: Boolean; FStickyHeight: single; FButton: TksTableViewStickyHeaderButton; FExtendScrollHeight: Boolean; procedure Changed; procedure SetEnabled(const Value: Boolean); procedure SetStickyHeight(const Value: single); procedure SetButton(const Value: TksTableViewStickyHeaderButton); procedure SetExtendScrollHeight(const Value: Boolean); public constructor Create(ATableView: TksTableView); destructor Destroy; override; procedure Assign(ASource: TPersistent); override; published property Button: TksTableViewStickyHeaderButton read FButton write SetButton; property Enabled: Boolean read FEnabled write SetEnabled default True; property StickyHeight: single read FStickyHeight write SetStickyHeight; property ExtendScrollHeight: Boolean read FExtendScrollHeight write SetExtendScrollHeight default false; end; //--------------------------------------------------------------------------------------- // TksTableViewItemHeaderOptions TksTableViewItemHeaderOptions = class(TPersistent) private [weak]FTableView: TksTableView; FHeight: integer; FStickyHeaders: TksTableViewStickyHeaderOptions; procedure Changed; function GetHeaderColor: TAlphaColor; procedure SetHeaderColor(const Value: TAlphaColor); procedure SetHeaderHeight(const Value: integer); procedure SetStickyHeaders(const Value: TksTableViewStickyHeaderOptions); procedure LegacyGetStickyHeadersHeight(Reader: TReader); protected procedure DefineProperties(Filer: TFiler); override; public constructor Create(ATableView: TksTableView); destructor Destroy; override; procedure Assign(ASource: TPersistent); override; published property Color: TAlphaColor read GetHeaderColor write SetHeaderColor; property Height: integer read FHeight write SetHeaderHeight default C_TABLEVIEW_DEFAULT_HEADER_HEIGHT; property StickyHeaders: TksTableViewStickyHeaderOptions read FStickyHeaders write SetStickyHeaders; end; //--------------------------------------------------------------------------------------- // TksTableViewAccessoryOptions TksTableViewAccessoryOptions = class(TPersistent) private [weak]FTableView: TksTableView; FShowAccessory: Boolean; FColor: TAlphaColor; procedure Changed; procedure SetShowAccessory(const Value: Boolean); procedure SetColor(const Value: TAlphaColor); public constructor Create(ATableView: TksTableView); procedure Assign(ASource: TPersistent); override; published property ShowAccessory: Boolean read FShowAccessory write SetShowAccessory default True; property Color: TAlphaColor read FColor write SetColor default claNull; end; //--------------------------------------------------------------------------------------- // TksTableViewBorderOptions TksTableViewBorderOptions = class(TPersistent) private [weak]FTableView: TksTableView; FVisible: Boolean; FSides: TSides; FStroke: TStrokeBrush; function Showing: Boolean; procedure Changed; procedure SetVisible(const Value: Boolean); function IsSidesStored: Boolean; procedure SetSides(const Value: TSides); procedure SetStroke(const Value: TStrokeBrush); public constructor Create(ATableView: TksTableView); destructor Destroy; override; procedure Assign(ASource: TPersistent); override; published property Sides: TSides read FSides write SetSides stored IsSidesStored; property Stroke: TStrokeBrush read FStroke write SetStroke; property Visible: Boolean read FVisible write SetVisible default False; end; //--------------------------------------------------------------------------------------- // TksTableViewFixedRowsOptions TksTableViewFixedRowsOptions = class(TPersistent) private [weak]FTableView: TksTableView; FHeaderCount: Integer; FFooterCount: Integer; FMinimumWorkHeight: Integer; procedure Changed; procedure SetHeaderCount(const Value: Integer); procedure SetFooterCount(const Value: Integer); procedure SetMinimumWorkHeight(const Value: Integer); public constructor Create(ATableView: TksTableView); procedure Assign(ASource: TPersistent); override; published property HeaderCount: Integer read FHeaderCount write SetHeaderCount default 0; property FooterCount: Integer read FFooterCount write SetFooterCount default 0; property MinimumWorkHeight: Integer read FMinimumWorkHeight write SetMinimumWorkHeight default 0; end; //--------------------------------------------------------------------------------------- // TksTableViewCheckMarkOptions TksTableViewCheckMarkOptions = class(TPersistent) private [weak]FTableView: TksTableView; FCheckMarks: TksTableViewCheckMarks; FPosition: TksTableViewCheckMarkPosition; FShowInHeader: Boolean; FCheckArea: TksTableViewCheckMarkCheckArea; FCheckSelects: Boolean; FHeaderCheckSelectsAll: Boolean; FCheckMarkChecked: TksTableViewItemAccessory; FCheckMarkUnchecked: TksTableViewItemAccessory; procedure Changed; procedure SetCheckMarks(const Value: TksTableViewCheckMarks); procedure SetPosition(const Value: TksTableViewCheckMarkPosition); procedure SetShowInHeader(const Value: Boolean); procedure SetCheckArea(const Value: TksTableViewCheckMarkCheckArea); procedure SetCheckSelects(const Value: Boolean); procedure SetHeaderCheckSelectsAll(const Value: Boolean); public constructor Create(ATableView: TksTableView); destructor Destroy; override; procedure Assign(ASource: TPersistent); override; published property CheckMarks: TksTableViewCheckMarks read FCheckMarks write SetCheckMarks default TksTableViewCheckMarks.cmNone; property Position: TksTableViewCheckMarkPosition read FPosition write SetPosition default TksTableViewCheckMarkPosition.cmpRight; property ShowInHeader: Boolean read FShowInHeader write SetShowInHeader default true; property CheckArea: TksTableViewCheckMarkCheckArea read FCheckArea write SetCheckArea default TksTableViewCheckMarkCheckArea.caWholeRow; property CheckSelects: Boolean read FCheckSelects write SetCheckSelects default true; property HeaderCheckSelectsAll: Boolean read FHeaderCheckSelectsAll write SetHeaderCheckSelectsAll default true; end; //--------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------- // TksTableView [ComponentPlatformsAttribute(pidWin32 or pidWin64 or {$IFDEF XE8_OR_NEWER} pidiOSDevice32 or pidiOSDevice64 {$ELSE} pidiOSDevice {$ENDIF} or pidiOSSimulator or pidAndroid)] TksTableView = class(TksControl) strict private FFullWidthSeparator: Boolean; FClearCacheTimer: TFmxHandle; //procedure DoClearCacheTimer; private FCombo: TComboBox; FDateSelector: TDateEdit; FSearchBox: TSearchBox; FItems: TksTableViewItems; FFilteredItems: TksTableViewItems; FTimerService: IFMXTimerService; FAniCalc: TksAniCalc; FScrollPos: single; FPainting: Boolean; FScrolling: Boolean; FAppearence: TksTableViewAppearence; FItemHeight: integer; FItemImageSize: integer; FSearchVisible: Boolean; FItemIndex: integer; FMouseDownPoint: TPointF; FMouseCurrentPos: TPointF; FUpdateCount: integer; FSelectTimer: TFmxHandle; FDeselectTimer: TFmxHandle; FSwipeDirection: TksSwipeDirection; FMouseDownItem: TksTableViewItem; FMouseDown: Boolean; FBackgroundText: TksTableViewBackgroundText; FRowIndicators: TksListViewRowIndicators; FDeleteButton: TksDeleteButton; FTextDefaults: TksTableViewTextDefaults; FMouseDownObject: TksTableViewItemObject; [weak]FFocusedControl: TksTableViewItemEmbeddedControl; FColCount: integer; FMaxScrollPos: single; FDragDropImage : TksDragImage; FDragDropScrollTimer: TFmxHandle; FDragging: Boolean; FDragOverItem: TksTableViewItem; FSelectionOptions: TksTableViewSelectionOptions; FAccessoryOptions: TksTableViewAccessoryOptions; FHeaderOptions: TksTableViewItemHeaderOptions; FBorder: TksTableViewBorderOptions; FStickyHeader: TksTableViewItem; FStickyButtonRect: TRectF; FFixedRowOptions: TksTableViewFixedRowsOptions; FCascadeHeaderCheck: Boolean; FActionButtons: TksTableViewActionButtons; //FCachedCount: integer; // events... FItemClickEvent: TksTableViewItemClickEvent; FOnPullRefresh: TNotifyEvent; FPullToRefresh: TksTableViewPullToRefresh; FNeedsRefresh: Boolean; FCheckMarkOptions: TksTableViewCheckMarkOptions; FOnItemSwipe: TksItemSwipeEvent; FOnItemActionButtonClick: TksItemActionButtonClickEvent; FOnDeleteItem: TksTableViewDeleteItemEvent; FOnDeletingItem: TksTableViewDeletingItemEvent; FBeforeRowCache: TksTableViewRowCacheEvent; FAfterRowCache: TksTableViewRowCacheEvent; FOnEmbeddedEditChange: TksTableViewEmbeddedEditChange; FOnEmbeddedDateEditChange: TksTableViewEmbeddedDateEditChange; FOnItemChecMarkChanged: TksItemChecMarkChangedEvent; FOnSelectDate: TksTableViewSelectDateEvent; FOnSelectPickerItem: TksTableViewSelectPickerItem; FOnSelectPickerItemExt: TksTableViewSelectPickerItemExt; FOnSwitchClicked: TksTableViewItemSwitchEvent; FOnButtonClicked: TksTableViewItemButtonEvent; FOnScrollViewChange: TksTableViewScrollChangeEvent; FOnCanDragItem : TksTableViewCanDragItemEvent; FOnCanDropItem : TksTableViewCanDropItemEvent; FOnDropItem : TksTableViewDropItemEvent; FDragDropOptions: TksDragDropOptions; FOnSearchFilterChanged: TksTableViewSearchFilterChange; FOnStickyHeaderChange: TksTableViewStickyHeaderChange; FOnIndicatorExpand: TksTableViewRowIndicatorExpandEvent; FOnBeforePaint : TPaintEvent; FOnAfterPaint : TPaintEvent; FOnBeginRowCacheEvent: TksTableBeginRowCacheEvent; FItemObjectMouseUpEvent: TksTableViewItemClickEvent; FMouseEventsEnabledCounter: integer; FLastCacheClear: TDateTime; function GetViewPort: TRectF; procedure UpdateStickyHeaders; procedure SetScrollViewPos(const Value: single; const AAnimate: Boolean = False); procedure AniCalcStart(Sender: TObject); procedure AniCalcChange(Sender: TObject); procedure AniCalcStop(Sender: TObject); //procedure CacheItems(AForceRedraw: Boolean); function GetTopItem: TksTableViewItem; function GetVisibleItems: TList<TksTableViewItem>; procedure SetItemImageSize(const Value: integer); procedure SetColCount(const Value: integer); procedure SetKsItemHeight(const Value: integer); procedure SetSearchVisible(const Value: Boolean); procedure SetItemIndex(const Value: integer); procedure DoFilterChanged(Sender: TObject); procedure DoFilterEnter(Sender: TObject); //function GetScrollViewPos: single; function GetSearchHeight: single; function GetFixedHeaderHeight: single; function GetFixedFooterHeight: single; function GetStartOffsetY: single; function GetSelectedItem: TksTableViewItem; //function GetItemIndex: integer; procedure DeselectItem(const ADelay: integer = 0); procedure DoDeselectItem; procedure DoPullToRefresh; procedure UpdateFilteredItems; procedure DoSelectTimer; procedure UpdateDropImage(x, y: single); procedure DoDropScroll; procedure DoSelectItem; procedure SetCheckMarkOptions(const Value: TksTableViewCheckMarkOptions); procedure SetTextDefaults(const Value: TksTableViewTextDefaults); function CreateTimer(AInterval: integer; AProc: TTimerProc): TFmxHandle; procedure KillTimer(var ATimer: TFmxHandle); procedure KillAllTimers; procedure SetFullWidthSeparator(const Value: Boolean); procedure ComboClosePopup(Sender: TObject); procedure DoSwitchClicked(AItem: TksTableViewItem; ASwitch: TksTableViewItemSwitch); procedure DoButtonClicked(AItem: TksTableViewItem; AButton: TksTableViewItemButton); procedure SetPullToRefresh(const Value: TksTableViewPullToRefresh); procedure DoEmbeddedEditChange(AItem: TksTableViewItem; AEmbeddedEdit: TksTableViewItemEmbeddedBaseEdit); procedure SetSelectionOptions(const Value: TksTableViewSelectionOptions); procedure DoEmbeddedDateEditChange(AItem: TksTableViewItem; AEmbeddedDateEdit: TksTableViewItemEmbeddedDateEdit); procedure SetAccessoryOptions(const Value: TksTableViewAccessoryOptions); procedure SetAppearence(const Value: TksTableViewAppearence); procedure SetBackgroundText(const Value: TksTableViewBackgroundText); procedure LegacyGetShowAccessory(Reader: TReader); procedure LegacyGetStickyHeaders(Reader: TReader); procedure SetHeaderOptions(const Value: TksTableViewItemHeaderOptions); procedure LegacyGetHeaderHeight(Reader: TReader); procedure LegacyGetCheckMarks(Reader: TReader); procedure SetBorder(const Value: TksTableViewBorderOptions); procedure SetFixedRowOptions(const Value: TksTableViewFixedRowsOptions); procedure DoItemsChanged(Sender: TObject; const Item: TksTableViewItem; Action: TCollectionNotification); function GetSearchText: string; procedure SetSearchText(const Value: string); procedure CreateAniCalculator(AUpdateScrollLimit: Boolean); function GetCachedCount: integer; protected function GetTotalItemHeight: single; function IsHeader(AItem: TksTableViewItem): Boolean; procedure DefineProperties(Filer: TFiler); override; procedure Paint; override; procedure KeyDown(var Key: Word; var KeyChar: WideChar; Shift: TShiftState); override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; x, y: single); override; procedure MouseMove(Shift: TShiftState; x, y: single); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; x, y: single); override; procedure DoMouseLeave; override; procedure MouseWheel(Shift: TShiftState; WheelDelta: Integer; var Handled: Boolean); override; procedure Resize; override; {$IFDEF XE10_OR_NEWER} procedure VisibleChanged; override; {$ENDIF} function GetMouseDownBox: TRectF; procedure SelectDate(ARow: TksTableViewItem; ASelected: TDateTime; AOnSelectDate: TNotifyEvent); procedure SelectItem(ARow: TksTableViewItem; AItems: TStrings; ASelected: string; AOnSelectItem: TNotifyEvent); procedure DoSelectDate(Sender: TObject); procedure DoSelectPickerItem(Sender: TObject); procedure DoItemObjectMouseUp(AObject: TksTableViewItemObject; x, y: single); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function GetItemFromPos(AXPos,AYPos: single): TksTableViewItem; procedure EnableMouseEvents; procedure DisableMouseEvents; procedure ClearItems; procedure HideFocusedControl; procedure BeginUpdate; {$IFDEF XE8_OR_NEWER} override; {$ENDIF} procedure EndUpdate; {$IFDEF XE8_OR_NEWER} override; {$ENDIF} procedure Invalidate; procedure UpdateAll(AUpdateFiltered: Boolean); procedure UpdateItemRects(AUpdateFiltered: Boolean); procedure UncheckAll; procedure UpdateScrollingLimits; procedure ResetIndicatorWidths; procedure RedrawAllVisibleItems; procedure ClearCache(AClearType: TksClearCacheType); procedure ScrollTo(const Value: single); procedure ScrollToItem(AItem: TksTableViewItem; const AAnimate: Boolean = False); overload; procedure ScrollToItem(AItemIndex: integer); overload; procedure BringSelectedIntoView; procedure CheckChildren(AHeader: TksTableViewItem ; Value : Boolean); procedure UncheckHeader(AChild: TksTableViewItem); procedure SearchSetFocus; property UpdateCount: integer read FUpdateCount; property TopItem: TksTableViewItem read GetTopItem; property VisibleItems: TList<TksTableViewItem> read GetVisibleItems; property ViewPort: TRectF read GetViewPort; property ScrollViewPos: single read FScrollPos; property Items: TksTableViewItems read FItems; property FilteredItems: TksTableViewItems read FFilteredItems; property ItemIndex: integer read FItemIndex write SetItemIndex; property SelectedItem: TksTableViewItem read GetSelectedItem; property SearchText: string read GetSearchText write SetSearchText; property TotalItemHeight: single read GetTotalItemHeight; property CachedCount: integer read GetCachedCount; published property AccessoryOptions: TksTableViewAccessoryOptions read FAccessoryOptions write SetAccessoryOptions; property Align; property Anchors; property Appearence: TksTableViewAppearence read FAppearence write SetAppearence; property BackgroundText: TksTableViewBackgroundText read FBackgroundText write SetBackgroundText; property BorderOptions: TksTableViewBorderOptions read FBorder write SetBorder; property CanFocus default True; property CanParentFocus; property CheckMarkOptions: TksTableViewCheckMarkOptions read FCheckMarkOptions write SetCheckMarkOptions; property ClipChildren default True; property ClipParent default False; property Cursor default crDefault; property DeleteButton: TksDeleteButton read FDeleteButton write FDeleteButton; property DragDropOptions: TksDragDropOptions read FDragDropOptions write FDragDropOptions; property FullWidthSeparator: Boolean read FFullWidthSeparator write SetFullWidthSeparator default True; property ColCount: integer read FColCount write SetColCount default 0; property FixedRowOptions: TksTableViewFixedRowsOptions read FFixedRowOptions write SetFixedRowOptions; property HeaderOptions: TksTableViewItemHeaderOptions read FHeaderOptions write SetHeaderOptions; property ItemHeight: integer read FItemHeight write SetKsItemHeight default C_TABLEVIEW_DEFAULT_ITEM_HEIGHT; property ItemImageSize: integer read FItemImageSize write SetItemImageSize default C_TABLEVIEW_DEFAULT_IMAGE_SIZE; property Locked default False; property Height; property HitTest default True; property Margins; property Opacity; property Padding; property PopupMenu; property Position; property PullToRefresh: TksTableViewPullToRefresh read FPullToRefresh write SetPullToRefresh; property RotationAngle; property RotationCenter; property RowIndicators: TksListViewRowIndicators read FRowIndicators write FRowIndicators; property Scale; property SearchVisible: Boolean read FSearchVisible write SetSearchVisible default False; property SelectionOptions: TksTableViewSelectionOptions read FSelectionOptions write SetSelectionOptions; property Size; property TabOrder; property TabStop; property TextDefaults: TksTableViewTextDefaults read FTextDefaults write SetTextDefaults; property Visible default True; property Width; // events... property AfterRowCache: TksTableViewRowCacheEvent read FAfterRowCache write FAfterRowCache; property BeforeRowCache: TksTableViewRowCacheEvent read FBeforeRowCache write FBeforeRowCache; property OnButtonClick: TksTableViewItemButtonEvent read FOnButtonClicked write FOnButtonClicked; property OnDblClick; property OnDeletingItem: TKsTableViewDeletingItemEvent read FOnDeletingItem write FOnDeletingItem; property OnDeleteItem: TKsTableViewDeleteItemEvent read FOnDeleteItem write FOnDeleteItem; property OnEmbeddedEditChange: TksTableViewEmbeddedEditChange read FOnEmbeddedEditChange write FOnEmbeddedEditChange; property OnEmbeddedDateEditChange: TksTableViewEmbeddedDateEditChange read FOnEmbeddedDateEditChange write FOnEmbeddedDateEditChange; property OnIndicatorExpand: TksTableViewRowIndicatorExpandEvent read FOnIndicatorExpand write FOnIndicatorExpand; property OnItemActionButtonClick: TksItemActionButtonClickEvent read FOnItemActionButtonClick write FOnItemActionButtonClick; property OnItemCheckmarkChanged: TksItemChecMarkChangedEvent read FOnItemChecMarkChanged write FOnItemChecMarkChanged; property OnItemClick: TksTableViewItemClickEvent read FItemClickEvent write FItemClickEvent; property OnItemObjectMouseUp: TksTableViewItemClickEvent read FItemObjectMouseUpEvent write FItemObjectMouseUpEvent; property OnPainting; property OnPaint; property OnResize; property OnPullRefresh: TNotifyEvent read FOnPullRefresh write FOnPullRefresh; property OnDragEnter; property OnDragLeave; property OnDragOver; property OnDragDrop; property OnDragEnd; { Keyboard events } property OnKeyDown; property OnKeyUp; { Mouse events } property OnCanFocus; property OnEnter; property OnExit; property OnItemSwipe: TksItemSwipeEvent read FOnItemSwipe write FOnItemSwipe; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnMouseWheel; property OnMouseEnter; property OnMouseLeave; property OnBeginRowCache: TksTableBeginRowCacheEvent read FOnBeginRowCacheEvent write FOnBeginRowCacheEvent; property OnScrollViewChange: TksTableViewScrollChangeEvent read FOnScrollViewChange write FOnScrollViewChange; property OnSelectDate: TksTableViewSelectDateEvent read FOnSelectDate write FOnSelectDate; property OnSelectPickerItem: TksTableViewSelectPickerItem read FOnSelectPickerItem write FOnSelectPickerItem; property OnSelectPickerItemExt: TksTableViewSelectPickerItemExt read FOnSelectPickerItemExt write FOnSelectPickerItemExt; property OnSearchFilterChanged: TksTableViewSearchFilterChange read FOnSearchFilterChanged write FOnSearchFilterChanged; property OnSwitchClick: TksTableViewItemSwitchEvent read FOnSwitchClicked write FOnSwitchClicked; property OnCanDragItem: TksTableViewCanDragItemEvent read FOnCanDragItem write FOnCanDragItem; property OnCanDropItem: TksTableViewCanDropItemEvent read FOnCanDropItem write FOnCanDropItem; property OnDropItem: TksTableViewDropItemEvent read FOnDropItem write FOnDropItem; property OnBeforePaint: TPaintEvent read FOnBeforePaint write FOnBeforePaint; property OnAfterPaint: TPaintEvent read FOnAfterPaint write FOnAfterPaint; property OnStickyHeaderChange: TksTableViewStickyHeaderChange read FOnStickyHeaderChange write FOnStickyHeaderChange; end; {$R *.dcr} procedure Register; var AccessoryImages: TksTableViewAccessoryImageList; implementation uses SysUtils, FMX.Platform, Math, FMX.TextLayout, System.Math.Vectors, ksCommon, FMX.Ani, FMX.Forms, DateUtils; var AIsSwiping: Boolean; procedure Register; begin RegisterComponents('Kernow Software FMX', [TksTableView]); end; // TksTableViewItemObject procedure TksTableViewItemObject.Changed; begin if FTableItem = nil then Exit; FTableItem.Cached := False; FTableItem.CacheItem(True); FTableItem.FTableView.Invalidate; end; constructor TksTableViewItemObject.Create(ATableItem: TksTableViewItem); begin inherited Create; FMargins := TBounds.Create(TRectF.Empty); FTableItem := ATableItem; FHitTest := True; FOffsetX := 0; FOffsetY := 0; FShowSelection := False; FMouseDown := False; FPositionRelativeTo := nil; FSelected := False; FVisible := True; end; destructor TksTableViewItemObject.Destroy; begin FreeAndNil(FMargins); inherited; end; procedure TksTableViewItemObject.Deselect; begin if FMouseDown then begin FMouseDown := False; Changed; end; end; procedure TksTableViewItemObject.MouseDown(x, y: single); begin if (FHitTest) then begin FMouseDown := True; if FShowSelection then FSelected := True; Changed; end; end; procedure TksTableViewItemObject.MouseUp(x, y: single); begin FTableItem.TableView.DoItemObjectMouseUp(Self, x, y); //if (Assigned(FOnClick)) then // FOnClick(Self); end; procedure TksTableViewItemObject.Render(AItemRect: TRectF; ACanvas: TCanvas); var AObjRect: TRectF; AState: TCanvasSaveState; begin if FVisible = False then Exit; FItemRect := AItemRect; if (FSelected) and (FShowSelection) then begin AObjRect := GetObjectRect; AObjRect.Inflate(8, 8); AState := ACanvas.SaveState; try ACanvas.IntersectClipRect(AObjRect); ACanvas.Fill.Color := FTableItem.FTableView.Appearence.SelectedColor; ACanvas.Stroke.Color := claDimgray; ACanvas.FillRect(AObjRect, 0, 0, AllCorners, 1); finally ACanvas.RestoreState(AState); end; end; end; function TksTableViewItemObject.ConsumesClick: Boolean; begin Result := False; end; function TksTableViewItemObject.GetItemRect: TRectF; begin if (FPositionRelativeTo <> nil) then Result := FPositionRelativeTo.GetObjectRect else Result := FTableItem.ItemRect; end; function TksTableViewItemObject.GetObjectRect: TRectF; var ARowRect: TRectF; RelativeOffset : TPointF; begin if (FTableItem.Appearance <> iaNormal) then begin Result := RectF(FPlaceOffset.X, FPlaceOffset.Y, FPlaceOffset.X +FWidth, FPlaceOffset.Y + FHeight); Exit; end; ARowRect := GetItemRect; if (Self <> FTableItem.Accessory) and (Self <> FTableItem.FCheckMarkAccessory) then begin if (FTableItem.Accessory.Accessory <> atNone) then ARowRect.Right := ARowRect.Right - (FTableItem.Accessory.Width+8); end; RelativeOffset := PointF(0, 0); if (FPositionRelativeTo <> nil) then begin RelativeOffset.X := FPositionRelativeTo.GetObjectRect.Left; RelativeOffset.Y := FPositionRelativeTo.GetObjectRect.Top; end; if (WidthPercentange > 0) then FWidth := ARowRect.Width * WidthPercentange / 100; if (HeightPercentange > 0) then FHeight := ARowRect.Height * HeightPercentange / 100; Result := RectF(ARowRect.Left + FMargins.Left, FMargins.Top, FWidth, FHeight); Result := RectF(RelativeOffset.X + FMargins.Left, RelativeOffset.Y + FMargins.Top, RelativeOffset.X + FMargins.Left + FWidth, RelativeOffset.Y + FMargins.Top + FHeight); case FAlign of TksTableItemAlign.Center: OffsetRect(Result, ((ARowRect.Width - Result.Width) / 2), 0); TksTableItemAlign.Trailing: OffsetRect(Result, ((ARowRect.Width - Result.Width) - C_SCROLL_BAR_WIDTH) - FMargins.Right, 0); TksTableItemAlign.Fit: Result.Width := ARowRect.Width - FMargins.Left - FMargins.Right; end; case FVertAlign of TksTableItemAlign.Center: OffsetRect(Result, 0, (ARowRect.Height - Result.Height) / 2); TksTableItemAlign.Trailing: OffsetRect(Result, 0, (ARowRect.Height - Result.Height) - FMargins.Bottom); TksTableItemAlign.Fit: Result.Height := ARowRect.Height - FMargins.Top - FMargins.Bottom; end; OffsetRect(Result, FItemRect.Left + FPlaceOffset.x + FOffsetX, FItemRect.Top + FPlaceOffset.y + FOffsetY); end; procedure TksTableViewItemObject.SetAlign(Value: TksTableItemAlign); begin FAlign := Value; end; procedure TksTableViewItemObject.SetHeight(const Value: single); begin if FHeight <> Value then begin FHeight := Value; Changed; end; end; procedure TksTableViewItemObject.SetHeightPercentange(const Value: single); begin if FHeightPercentange <> Value then begin FHeightPercentange := Value; Changed; end; end; procedure TksTableViewItemObject.SetWidthPercentange(const Value: single); begin if FWidthPercentange <> Value then begin FWidthPercentange := Value; Changed; end; end; procedure TksTableViewItemObject.SetPositionRelativeTo(const Value: TksTableViewItemObject); begin if FPositionRelativeTo <> Value then begin FPositionRelativeTo := Value; Changed; end; end; procedure TksTableViewItemObject.SetHitTest(const Value: Boolean); begin FHitTest := Value; end; procedure TksTableViewItemObject.SetID(Value: string); begin FID := Value; end; procedure TksTableViewItemObject.SetOffsetX(const Value: single); begin if FOffsetX <> Value then begin FOffsetX := Value; Changed; end; end; procedure TksTableViewItemObject.SetOffsetY(const Value: single); begin if FOffsetY <> Value then begin FOffsetY := Value; Changed; end; end; procedure TksTableViewItemObject.SetSelected(const Value: Boolean); begin if FSelected <> Value then begin FSelected := Value; Changed end; end; procedure TksTableViewItemObject.SetShowSelection(const Value: Boolean); begin FShowSelection := Value; end; procedure TksTableViewItemObject.SetVertAlign(Value: TksTableItemAlign); begin FVertAlign := Value; end; procedure TksTableViewItemObject.SetVisible(const Value: Boolean); begin if FVisible <> Value then begin FVisible := Value; Changed; end; end; procedure TksTableViewItemObject.SetWidth(const Value: single); begin if FWidth <> Value then begin FWidth := Value; Changed; end; end; // ------------------------------------------------------------------------------ { TksTableViewItemText } function TksTableViewItemText.CalculateSize: TSizeF; begin Result.cx := CalculateTextWidth(FText, FFont, FWordWrap, FWidth); Result.cy := CalculateTextHeight(FText, FFont, FWordWrap, FTrimming, FWidth); end; constructor TksTableViewItemText.Create(ATableItem: TksTableViewItem); begin inherited; FFont := TFont.Create; FFont.Size := C_TABLEVIEW_DEFAULT_FONT_SIZE; FFont.OnChanged := FontChanged; FText := ''; FTextColor := claBlack; FVertAlign := TksTableItemAlign.Center; FTextAlign := TTextAlign.Leading; FTextVertAlign := TTextAlign.Leading; FWordWrap := False; FTrimming := TTextTrimming.Character; FBackground := claNull; FIsHtmlText := False; end; destructor TksTableViewItemText.Destroy; begin FreeAndNil(FFont); inherited; end; procedure TksTableViewItemText.Assign(ASource: TksTableViewItemText); begin FBackground := ASource.FBackground; FText := ASource.FText; FFont.Assign(ASource.FFont); FTextColor := ASource.FTextColor; FTextAlign := ASource.FTextAlign; FTextVertAlign := ASource.FTextVertAlign; FWordWrap := ASource.FWordWrap; FTrimming := ASource.FTrimming; FIsHtmlText := ASource.FIsHtmlText; end; procedure TksTableViewItemText.FontChanged(Sender: TObject); begin Height := CalculateTextHeight(FText, FFont, FWordWrap, FTrimming, FWidth) end; procedure TksTableViewItemText.Render(AItemRect: TRectF; ACanvas: TCanvas); var r: TRectF; ATextColor: TAlphaColor; begin inherited Render(AItemRect, ACanvas); r := GetObjectRect; if FBackground <> claNull then begin ACanvas.Fill.Color := FBackground; ACanvas.FillRect(r, 0, 0, AllCorners, 1); end; ATextColor := FTextColor; if FTableItem.FForegroundColor <> claNull then ATextColor := FTableItem.FForegroundColor; if FText <> '' then begin case FIsHtmlText of False: RenderText(ACanvas, r.Left, r.Top, r.Width, r.Height, FText, FFont, ATextColor, FWordWrap, FTextAlign, FTextVertAlign, FTrimming); True: RenderHhmlText(ACanvas, r.Left, r.Top, r.Width, r.Height, FText, FFont, ATextColor, FWordWrap, FTextAlign, FTextVertAlign, FTrimming); end; end; end; procedure TksTableViewItemText.SetBackground(const Value: TAlphaColor); begin if FBackground <> Value then begin FBackground := Value; Changed; end; end; procedure TksTableViewItemText.SetFont(const Value: TFont); begin FFont.Assign(Value); end; procedure TksTableViewItemText.SetIsHtmlText(const Value: Boolean); begin FIsHtmlText := Value; Changed; end; procedure TksTableViewItemText.SetText(const Value: string); begin if FText <> Value then begin FText := Value; Changed; end; end; procedure TksTableViewItemText.SetTextAlign(const Value: TTextAlign); begin if FTextAlign <> Value then begin FTextAlign := Value; Changed; end; end; procedure TksTableViewItemText.SetTextColor(const Value: TAlphaColor); begin if FTextColor <> Value then begin FTextColor := Value; Changed; end; end; procedure TksTableViewItemText.SetTextVertAlign(const Value: TTextAlign); begin if FTextVertAlign <> Value then begin FTextVertAlign := Value; Changed; end; end; procedure TksTableViewItemText.SetTrimming(const Value: TTextTrimming); begin if FTrimming <> Value then begin FTrimming := Value; Changed; end; end; procedure TksTableViewItemText.SetWordWrap(const Value: Boolean); begin if FWordWrap <> Value then begin FWordWrap := Value; Changed; end; end; // ------------------------------------------------------------------------------ { TksTableViewItemObjects } constructor TksTableViewItemObjects.Create(ATableView: TksTableView); begin inherited Create(True); FTableView := ATableView; end; // ------------------------------------------------------------------------------ function TksTableViewItemObjects.GetImageByID(AId: string): TksTableViewItemImage; var AObj: TksTableViewItemObject; begin Result := nil; AObj := ObjectByID[AId]; if AObj is TksTableViewItemImage then Result := (AObj as TksTableViewItemImage); end; function TksTableViewItemObjects.GetObjectByID(AId: string): TksTableViewItemObject; var ICount: integer; begin Result := nil; for ICount := 0 to Count-1 do begin if Items[ICount].ID = AId then begin Result := Items[ICount]; Exit; end; end; end; function TksTableViewItemObjects.GetTextByID(AId: string): TksTableViewItemText; var AObj: TksTableViewItemObject; begin Result := nil; AObj := ObjectByID[AId]; if AObj is TksTableViewItemText then Result := (AObj as TksTableViewItemText); end; //--------------------------------------------------------------------------------------- // TksTableViewItemBaseImage procedure TksTableViewItemBaseImage.Clear; begin FreeAndNil(FBitmap); end; constructor TksTableViewItemBaseImage.Create(ATableItem: TksTableViewItem); begin inherited; FShadow := TksTableViewShadow.Create; FBadgeValue := 0; FBadgeColor := claRed; FBadgeTextColor := claWhite; FShadow.Visible := False; FOwnsBitmap := True; FHighQuality := False; FDrawMode := TksImageDrawMode.ksDrawModeStretch; end; destructor TksTableViewItemBaseImage.Destroy; begin FreeAndNil(FShadow); if (FBitmap <> nil) and (FOwnsBitmap) then FreeAndNil(FBitmap); inherited; end; procedure TksTableViewItemBaseImage.Assign(ASource: TksTableViewItemBaseImage); begin Bitmap := ASource.Bitmap; FDrawMode := ASource.FDrawMode; FShadow.Assign(ASource.FShadow); FHighQuality := ASource.FHighQuality; end; procedure TksTableViewItemBaseImage.DoBeforeRenderBitmap(ABmp: TBitmap); begin // overridden to make changes before painting. end; function TksTableViewItemBaseImage.GetBitmap: TBitmap; begin if FOwnsBitmap then begin if (FBitmap=Nil) then begin FBitmap := TBitmap.Create; end; Result := FBitmap end else Result := FExternalBitmap; end; procedure TksTableViewItemBaseImage.Render(AItemRect: TRectF; ACanvas: TCanvas); var AShadowRect: TRectF; AShadowBmp: TBitmap; ARect: TRectF; AScaleX, AScaleY: single; AOriginalRect: TRectF; ABmp: TBitmap; begin inherited; if Bitmap <> nil then begin ARect := GetObjectRect; AOriginalRect := ARect; if FDrawMode = ksDrawModeFit then begin ARect := RectF(ARect.Left, ARect.Top, ARect.Left+Bitmap.Width, ARect.Top+Bitmap.Height); AScaleX := GetObjectRect.Width / ARect.Width; AScaleY := GetObjectRect.Height / ARect.Height; ARect.Height := ARect.Height * Min(AScaleX, AScaleY); ARect.Width := ARect.Width * Min(AScaleX, AScaleY); OffsetRect(ARect, (AOriginalRect.Width - ARect.Width)/2, (AOriginalRect.Height - ARect.Height)/2) ; end; if FShadow.Visible then begin AShadowBmp := TBitmap.Create; try AShadowRect := ARect; OffsetRect(AShadowRect, FShadow.Offset, FShadow.Offset); AShadowBmp.Assign(Bitmap); AShadowBmp.ReplaceOpaqueColor(FShadow.Color); ACanvas.DrawBitmap(AShadowBmp, RectF(0, 0, AShadowBmp.Width, AShadowBmp.Height), AShadowRect, 1, True); finally AShadowBmp.Free; end; end; ABmp := TBitmap.Create; try ABmp.Assign(Bitmap); DoBeforeRenderBitmap(ABmp); ACanvas.DrawBitmap(ABmp, RectF(0, 0, ABmp.Width, ABmp.Height), ARect, 1, not FHighQuality); finally ABmp.Free; end; end; if FBadgeValue > 0 then begin GenerateBadge(ACanvas, PointF(ARect.Right-12, ARect.Top-4), FBadgeValue, FBadgeColor, claWhite, FBadgeTextColor); end; end; procedure TksTableViewItemBaseImage.SetBadgeColor(const Value: TAlphaColor); begin if FBadgeColor <> Value then begin FBadgeColor := Value; Changed; end; end; procedure TksTableViewItemBaseImage.SetBadgeTextColor(const Value: TAlphaColor); begin if FBadgeTextColor <> Value then begin FBadgeTextColor := Value; Changed; end; end; procedure TksTableViewItemBaseImage.SetBadgeValue(const Value: integer); begin if FBadgeValue <> Value then begin FBadgeValue := Value; Changed; end; end; procedure TksTableViewItemBaseImage.SetBitmap(const Value: TBitmap); begin if FOwnsBitmap then begin if FBitmap = nil then FBitmap := TBitmap.Create; FBitmap.Assign(Value); end else begin FreeAndNil(FBitmap); FExternalBitmap := Value; end; Changed; end; procedure TksTableViewItemBaseImage.SetDrawMode(const Value: TksImageDrawMode); begin if FDrawMode <> Value then begin FDrawMode := Value; Changed; end; end; procedure TksTableViewItemBaseImage.SetHighQuality(const Value: Boolean); begin if FHighQuality <> Value then begin FHighQuality := Value; Changed; end; end; procedure TksTableViewItemBaseImage.SetOwnsBitmap(const Value: Boolean); begin if FOwnsBitmap <> Value then begin FOwnsBitmap := Value; if (FOwnsBitmap) and (FExternalBitmap <> nil) then Bitmap.Assign(FExternalBitmap) else FreeAndNil(FBitmap); end; end; procedure TksTableViewItemBaseImage.SetShadow(const Value: TksTableViewShadow); begin FShadow.Assign(Value); end; procedure TksDragDropOptions.SetLiveMoving(const Value: Boolean); begin FLiveMoving := Value; end; // ------------------------------------------------------------------------------ { TksTableViewItemAccessory } constructor TksTableViewItemAccessory.Create(ATableItem: TksTableViewItem); begin inherited; FAccessory := atNone; FAlign := TksTableItemAlign.Trailing; FVertAlign := TksTableItemAlign.Center; FColor := claNull; end; procedure TksTableViewItemAccessory.DoBeforeRenderBitmap(ABmp: TBitmap); begin inherited; if FTableItem.FForegroundColor <> claNull then ReplaceOpaqueColor(ABmp, FTableItem.FForegroundColor); end; procedure TksTableViewItemAccessory.RedrawAccessory; begin Bitmap := AccessoryImages.Images[FAccessory]; if FColor = claNull then OwnsBitmap := False; FWidth := Bitmap.Width / AccessoryImages.ImageScale; FHeight := Bitmap.Height / AccessoryImages.ImageScale; Changed; end; procedure TksTableViewItemAccessory.Render(AItemRect: TRectF; ACanvas: TCanvas); begin if (Bitmap = nil) and (FAccessory <> atNone) then RedrawAccessory; if FColor <> C_TABLEVIEW_ACCESSORY_KEEPCOLOR then begin if FColor <> claNull then ReplaceOpaqueColor(Bitmap, FColor) else begin if FTableItem.TableView.AccessoryOptions.Color <> claNull then ReplaceOpaqueColor(Bitmap, FTableItem.TableView.AccessoryOptions.Color) end; end; inherited; end; procedure TksTableViewItemAccessory.SetAccessory(const Value: TksAccessoryType); begin if FAccessory <> Value then begin FAccessory := Value; Clear; RedrawAccessory; end; end; procedure TksTableViewItemAccessory.SetColor(const Value: TAlphaColor); begin if FColor <> Value then begin FColor := Value; RedrawAccessory; end; end; // ------------------------------------------------------------------------------ { TksTableViewItems } function TksTableViewItems.AddItem(AText: string; const AAccessory: TksAccessoryType = atNone): TksTableViewItem; begin Result := AddItem(AText, '', AAccessory); end; function TksTableViewItems.AddItem(AText, ADetail: string; const AAccessory: TksAccessoryType): TksTableViewItem; begin Result := AddItem(AText, '', ADetail, AAccessory); end; function TksTableViewItems.AddChatBubble(AText: string; APosition: TksTableViewChatBubblePosition; AColor, ATextColor: TAlphaColor; const AUserImage: TBitmap): TksTableViewChatBubble; var //ABubble: TksTableViewChatBubble; AItem: TksTableViewItem; r: TRectF; begin Result := nil; if Trim(AText) = '' then Exit; AItem := AddItem(''); Result := AItem.DrawChatBubble(AText, APosition, AColor, ATextColor); Result.Position := APosition; if AUserImage <> nil then begin r := RectF(0, 0, 32, 32); case APosition of ksCbpLeft: Result.OffsetX := 44; ksCbpRight: Result.OffsetX := -44; end; with AItem.DrawBitmap(AUserImage, r) do begin if APosition = ksCbpLeft then begin Align := TksTableItemAlign.Leading; OffsetX := 4; end else begin Align := TksTableItemAlign.Trailing; OffsetX := -4; end; VertAlign := TksTableItemAlign.Trailing; OffsetY := -4; end; end; AItem.Height := Result.Height + 16; end; function TksTableViewItems.AddDateSelector(AText: string; ADate: TDateTime): TksTableViewItem; begin Result := Additem(AText, '', FormatDateTime('ddd, dd mmmm, yyyy', ADate), atMore); Result.Selector := DateSelector; Result.FSelectionValue := ADate; end; function TksTableViewItems.AddHeader(AText: string): TksTableViewItem; begin Result := TksTableViewItem.Create(FTableView); Result.Title.Text := AText; Result.Title.Font.Assign(FTableView.TextDefaults.Header.Font); Result.Title.TextColor := FTableView.TextDefaults.Header.TextColor; //Result.FSearchIndex := ''; Result.Height := FTableView.HeaderOptions.Height; Result.Purpose := TksTableViewItemPurpose.Header; Add(Result); //UpdateIndexes; FTableView.UpdateAll(True); end; function TksTableViewItems.AddItem(AText, ASubTitle, ADetail: string; const AAccessory: TksAccessoryType): TksTableViewItem; begin Result := TksTableViewItem.Create(FTableView); Result.Title.Text := AText; Result.SubTitle.Text := ASubTitle; Result.Detail.Text := ADetail; Result.Accessory.Accessory := AAccessory; Result.Accessory.OwnsBitmap := True; Result.Height := FTableView.ItemHeight; Add(Result); UpdateIndexes; Result.UpdateSearchIndex; FTableView.UpdateAll(True); end; function TksTableViewItems.AddItemSelector(AText, ASelected: string; AItems: TStrings): TksTableViewItem; begin Result := AddItem(AText, '', ASelected, atMore); Result.Selector := ItemPicker; Result.PickerItems.Assign(AItems); Result.FSelectionValue := ASelected; end; function TksTableViewItems.AddItemWithSwitch(AText: string; AChecked: Boolean; AID: string): TksTableViewItem; var ASwitch: TksTableViewItemSwitch; begin Result := AddItem(AText); Result.CanSelect := False; ASwitch := Result.AddSwitch(0, AChecked, TksTableItemAlign.Trailing); ASwitch.ID := AID; Result.CanSelect := False; end; function TksTableViewItems.AddItemSelector(AText, ASelected: string; AItems: array of string): TksTableViewItem; var AStrings: TStrings; ICount: integer; begin AStrings := TStringList.Create; try for ICount := Low(AItems) to High(AItems) do AStrings.Add(AItems[ICount]); Result := AddItemSelector(AText, ASelected, AStrings); finally FreeAndNil(AStrings); end; end; constructor TksTableViewItems.Create(ATableView: TksTableView; AOwnsObjects: Boolean); begin inherited Create(AOwnsObjects); FTableView := ATableView; FCachedCount := 0; end; procedure TksTableViewItems.Delete(AIndex: integer; const AAnimate: Boolean = True); begin DeleteItem(Items[AIndex], AAnimate); end; procedure TksTableViewItems.DeleteItem(AItem: TksTableViewItem; const AAnimate: Boolean = True); var ICount: integer; ACanDelete: Boolean; AIndex: integer; begin ACanDelete := True; if Assigned(FTableView.OnDeletingItem) then begin ACanDelete := False; FTableView.OnDeletingItem(FTableView, AItem, ACanDelete); if ACanDelete = False then Exit; end; AIndex := IndexOf(AItem); if AIndex = -1 then Exit; AItem.FDeleting := True; if FTableView.UpdateCount > 0 then begin inherited Delete(AIndex); FTableView.UpdateItemRects(False); if Assigned(FTableView.OnDeleteItem) then FTableView.OnDeleteItem(FTableView, AItem); Exit; end; FTableView.DisableMouseEvents; try if AAnimate then begin for ICount := Trunc(AItem.Height) downto 0 do begin AItem.Height := ICount; //FTableView.Repaint; {$IFDEF NEXTGEN} if ICount mod 5 = 0 then ProcessMessages; {$ELSE} ProcessMessages; {$ENDIF} end; end; inherited Delete(AIndex); FTableView.UpdateItemRects(False); //FTableView.UpdateAll(True); FTableView.Invalidate; if Assigned(FTableView.OnDeleteItem) then FTableView.OnDeleteItem(FTableView, AItem); finally FTableView.EnableMouseEvents; end; end; function TksTableViewItems.GetCheckedCount: integer; var ICount: integer; begin Result := 0; for ICount := 0 to Count-1 do begin if Items[ICount].Checked then Result := Result + 1; end; end; function TksTableViewItems.GetFirstItem: TksTableViewItem; begin Result := nil; if Count > 0 then Result := Items[0]; end; function TksTableViewItems.GetItemByID(AID: string): TksTableViewItem; var ICount: integer; begin Result := nil; for ICount := 0 to Count-1 do begin if Items[ICount].ID = AID then begin Result := Items[ICount]; Exit; end; end; end; function TksTableViewItems.GetLastItem: TksTableViewItem; begin Result := nil; if Count > 0 then Result := Items[Count - 1]; end; function TksTableViewItems.GetTotalItemHeight: single; var ICount: integer; AItem: TksTableViewItem; ALastHeaderItem: TksTableViewItem; begin Result := 0; ALastHeaderItem := nil; for ICount := 0 to Count - 1 do begin AItem := Items[ICount]; if (AItem.FIsFirstCol) then begin if (AItem.Purpose=TksTableViewItemPurpose.Header) then ALastHeaderItem := AItem; if (AItem.FHeaderHeight>0) then Result := Result + AItem.FHeaderHeight else Result := Result + AItem.Height; end; end; if (FTableView.FHeaderOptions.FStickyHeaders.Enabled) and (FTableView.FHeaderOptions.FStickyHeaders.FExtendScrollHeight) and (ALastHeaderItem<>Nil) then Result := ALastHeaderItem.ItemRect.Top + FTableView.Height - FTableView.GetStartOffsetY - FTableView.GetFixedFooterHeight; end; procedure TksTableViewItems.Move(CurIndex, NewIndex: Integer); begin inherited; Items[CurIndex].CacheItem(True); Items[NewIndex].CacheItem(True); //FTableView.UpdateAll(True); FTableView.UpdateItemRects(True); FTableView.Invalidate; end; procedure TksTableViewItems.UpdateIndexes; var ICount: integer; begin for ICount := 0 to Count - 1 do Items[ICount].FAbsoluteIndex := ICount; end; // ------------------------------------------------------------------------------ { TksTableItem } function TksTableViewItem.AddButton(AWidth: integer; AText: string; const ATintColor: TAlphaColor = claNull; const AVertAlign: TksTableItemAlign = TksTableItemAlign.Center; const AYPos: integer = 0): TksTableViewItemButton; begin Result := TksTableViewItemButton.Create(Self); Result.Width := AWidth; Result.FPlaceOffset := PointF(0, AYPos); Result.VertAlign := TksTableItemAlign.Center; Result.Align := TksTableItemAlign.Trailing; Result.TintColor := ATintColor; Result.Text := AText; FObjects.Add(Result); Changed; end; function TksTableViewItem.AddButton(AStyle: TksTableViewButtonStyle; const ATintColor: TAlphaColor): TksTableViewItemButton; begin Result := AddButton(44, '', ATintColor); Result.Width := 44; Result.Height := 44; Changed; end; function TksTableViewItem.AddDateEdit(AX, AY, AWidth: single; ADate: TDateTime): TksTableViewItemEmbeddedDateEdit; begin Result := TksTableViewItemEmbeddedDateEdit.Create(Self); Result.Width := AWidth; Result.FPlaceOffset := PointF(AX, AY); Result.VertAlign := TksTableItemAlign.Center; Result.Date := ADate; FObjects.Add(Result); Changed; end; function TksTableViewItem.AddEdit(AX, AY, AWidth: single; AText: string; const AStyle: TksEmbeddedEditStyle = TksEmbeddedEditStyle.ksEditNormal): TksTableViewItemEmbeddedEdit; begin Result := TksTableViewItemEmbeddedEdit.Create(Self); Result.Width := AWidth; Result.FPlaceOffset := PointF(AX, AY); Result.VertAlign := TksTableItemAlign.Center; Result.Style := AStyle; Result.Text := AText; FObjects.Add(Result); Changed; end; function TksTableViewItem.AddSwitch(x: single; AIsChecked: Boolean; const AAlign: TksTableItemAlign = TksTableItemAlign.Trailing): TksTableViewItemSwitch; begin Result := TksTableViewItemSwitch.Create(Self); Result.FPlaceOffset := PointF(x, 0); Result.Checked := AIsChecked; Result.Align := AAlign; Result.VertAlign := TksTableItemAlign.Center; FObjects.Add(Result); Changed; end; function TksTableViewItem.AddTable(AX, AY, AColWidth, ARowHeight: single; AColCount, ARowCount: integer): TksTableViewItemTable; begin Result := TksTableViewItemTable.Create(Self); Result.DefaultRowHeight := ARowHeight; Result.DefaultColWidth := AColWidth; Result.ColCount := AColCount; Result.RowCount := ARowCount; Result.FPlaceOffset := PointF(AX, AY); Result.ResizeTable; FObjects.Add(Result); Changed; end; procedure TksTableViewItem.CacheItem(const AForceCache: Boolean = False); var ARect: TRectF; ICount: integer; ColumnOffset : Single; w,h: integer; AScreenScale: Single; begin if (FUpdating) or (FTableView.UpdateCount > 0) then Exit; if (FItemRect.Height = 0) or (FItemRect.Width = 0) then Exit; if AForceCache then ClearCache; if (FCached = True) or (FCaching) then Exit; FCaching := True; if Assigned(FTableView.OnBeginRowCache) then FTableView.OnBeginRowCache(FTableView, Self); ColumnOffset := ItemRect.Left; OffsetRect(FItemRect,-ColumnOffset,0); RealignStandardObjects; AScreenScale := GetScreenScale; w := Round(FItemRect.Width * AScreenScale); h := Round(FItemRect.Height * AScreenScale); Inc(FOwner.FCachedCount); _FBitmap.SetSize(w, h); ARect := RectF(0, 0, _FBitmap.Width, _FBitmap.Height); _FBitmap.Canvas.BeginScene; try if (Purpose=None) and ((FTableView.FSelectionOptions.ShowSelection) and (FCanSelect)) and ((FIndex = FTableView.ItemIndex) or ((Checked) and (FTableView.FCheckMarkOptions.FCheckSelects))) then begin _FBitmap.Canvas.Fill.Kind := TBrushKind.Solid; if FTableView.FSelectionOptions.FSelectionOverlay.Enabled then begin if (FTableView.FSelectionOptions.FSelectionOverlay.FStyle=ksBlankSpace) then _FBitmap.Canvas.Fill.Color := GetColorOrDefault(FTableView.FSelectionOptions.FSelectionOverlay.BackgroundColor,C_TABLEVIEW_DEFAULT_SELECTED_COLOR) end else _FBitmap.Canvas.Fill.Color := GetColorOrDefault(FTableView.Appearence.SelectedColor,C_TABLEVIEW_DEFAULT_SELECTED_COLOR); end else if (FFill.Kind<>TBrushKind.None) then _FBitmap.Canvas.Fill.Assign(FFill) else if (FPurpose<>None) then begin _FBitmap.Canvas.Fill.Kind := TBrushKind.Solid; _FBitmap.Canvas.Fill.Color := GetColorOrDefault(FTableView.Appearence.HeaderColor, C_TABLEVIEW_DEFAULT_HEADER_COLOR) end else if (FTableView.Appearence.AlternatingItemBackground <> claNull) and (FIndex mod 2 = 0) then begin _FBitmap.Canvas.Fill.Kind := TBrushKind.Solid; _FBitmap.Canvas.Fill.Color := FTableView.Appearence.AlternatingItemBackground; end else _FBitmap.Canvas.Fill.Assign(FTableView.Appearence.ItemBackground); _FBitmap.Canvas.FillRect(ARect, 0, 0, AllCorners, 1); if Assigned(FTableView.BeforeRowCache) then FTableView.BeforeRowCache(FTableView, _FBitmap.Canvas, Self, ARect); // indicator... if FTableView.RowIndicators.Visible then begin case FTableView.RowIndicators.Outlined of False: FIndicator.Stroke.Kind := TBrushKind.None; True: FIndicator.Stroke.Kind := TBrushKind.Solid; end; if FIndicator.Width = 0 then FIndicator.Width := FTableView.RowIndicators.Width; if Trunc(FTableView.RowIndicators.Height) <> 0 then FIndicator.Height := FTableView.RowIndicators.Height else FIndicator.Height := Height; FIndicator.Shape := FTableView.RowIndicators.Shape; FIndicator.Render(RectF(0, 0, 0, 0), _FBitmap.Canvas); end; FTileBackground.Render(RectF(0, 0, 0, 0), _FBitmap.Canvas); FImage.Render(RectF(0, 0, 0, 0), _FBitmap.Canvas); FTitle.Render(RectF(0, 0, 0, 0), _FBitmap.Canvas); FSubTitle.Render(RectF(0, 0, 0, 0), _FBitmap.Canvas); FDetail.Render(RectF(0, 0, 0, 0), _FBitmap.Canvas); if FTableView.AccessoryOptions.ShowAccessory then FAccessory.Render(RectF(0, 0, 0, 0), _FBitmap.Canvas); if FTableView.FCheckMarkOptions.FCheckMarks <> TksTableViewCheckMarks.cmNone then begin if (FCheckmarkAllowed) then begin FCheckMarkAccessory.FTableItem := Self; FCheckMarkAccessory.Render(RectF(0, 0, 0, 0), _FBitmap.Canvas); end; end; for ICount := 0 to FObjects.Count - 1 do begin if FObjects[ICount].Visible then begin FObjects[ICount].Render(RectF(0, 0, 0, 0), _FBitmap.Canvas); end; end; if Assigned(FTableView.AfterRowCache) then FTableView.AfterRowCache(FTableView, _FBitmap.Canvas, Self, ARect); finally _FBitmap.Canvas.EndScene; FCached := True; end; OffsetRect(FItemRect,ColumnOffset,0); FCaching := False; //Inc(FOwner.FCachedCount); end; procedure TksTableViewItem.Changed; begin FCached := False; if FUpdating then Exit; if (FTableView.FUpdateCount = 0) then FTableView.Invalidate; UpdateSearchIndex; end; procedure TksTableViewItem.PickerItemsChanged(Sender: TObject); begin FSelector := TksTableItemSelector.NoSelector; if FPickerItems.Count > 0 then FSelector := TksTableItemSelector.ItemPicker; end; constructor TksTableViewItem.Create(ATableView: TksTableView); begin inherited Create; FUpdating := True; try FTableView := ATableView; FOwner := ATableView.Items; _FBitmap := TBitmap.Create; _FBitmap.BitmapScale := GetScreenScale; FObjects := TksTableViewItemObjects.Create(FTableView); FFont := TFont.Create; FFont.Size := C_TABLEVIEW_DEFAULT_FONT_SIZE; FFill := TBrush.Create(TBrushKind.None, claNull); FIndicator := TksTableViewItemShape.Create(Self); FIndicator.VertAlign := TksTableItemAlign.Center; FTileBackground := TksTableViewItemTileBackground.Create(Self); FPickerItems := TStringList.Create; (FPickerItems as TStringList).OnChange := PickerItemsChanged; FImage := TksTableViewItemImage.Create(Self); FImage.VertAlign := TksTableItemAlign.Center; FAccessory := TksTableViewItemAccessory.Create(Self); FAccessory.OwnsBitmap := False; FCheckMarkAccessory := TableView.CheckMarkOptions.FCheckMarkUnchecked; FTitle := TksTableViewItemText.Create(Self); FTitle.Font.Assign(FTableView.TextDefaults.Title.Font); FTitle.TextColor := FTableView.TextDefaults.Title.TextColor; FSubTitle := TksTableViewItemText.Create(Self); FSubTitle.Font.Assign(FTableView.TextDefaults.SubTitle.Font); FSubTitle.TextColor := FTableView.TextDefaults.SubTitle.TextColor; FDetail := TksTableViewItemText.Create(Self); FDetail.TextAlignment := TTextAlign.Trailing; FDetail.Font.Assign(FTableView.TextDefaults.Detail.Font); FDetail.TextColor := FTableView.TextDefaults.Detail.TextColor; FPurpose := None; FTextColor := claBlack; FChecked := False; Height := C_TABLEVIEW_DEFAULT_ITEM_HEIGHT; FHeightPercentage := 0; FCaching := False; FUpdating := False; FCanSelect := True; FTagString := ''; FTagInteger := 0; FColCount := 0; FSearchIndex := ''; FAppearance := iaNormal; FDragging := False; FDeleting := False; FForegroundColor := claNull; finally FUpdating := False; end; end; procedure TksTableViewItem.DeselectObjects; var ICount: integer; begin for ICount := 0 to FObjects.Count-1 do begin FObjects[ICount].Deselect; end; end; destructor TksTableViewItem.Destroy; begin FreeAndNil(FTitle); FreeAndNil(FSubTitle); FreeAndNil(FDetail); FreeAndNil(FIndicator); FreeAndNil(FTileBackground); FreeAndNil(FAccessory); FreeAndNil(FObjects); FreeAndNil(_FBitmap); FreeAndNil(FFont); FreeAndNil(FImage); FreeAndNil(FPickerItems); FreeAndNil(FFill); FreeAndNil(FData); inherited; end; function TksTableViewItem.CheckMarkClicked(x, y: single) : Boolean; var ACheckMarkRect: TRectF; begin if (FCheckmarkAllowed) then begin if (FTableView.FCheckMarkOptions.FCheckArea=TksTableViewCheckMarkCheckArea.caCheckMarkRect) then begin ACheckMarkRect.Left := FCheckMarkAccessory.FPlaceOffset.X; ACheckMarkRect.Top := FCheckMarkAccessory.FPlaceOffset.Y + (FCheckMarkAccessory.Height / 2); ACheckMarkRect.Width := FCheckMarkAccessory.Width; ACheckMarkRect.Height := FCheckMarkAccessory.Height; InflateRect(ACheckMarkRect,8,8); Result := PtInRect(ACheckMarkRect, PointF(x,y)); end else Result := true; end else Result := false; end; procedure TksTableViewItem.DoClick(x, y: single); var ABtn: TksTableViewActionButton; AObj: TksTableViewItemObject; AActBtns: TksTableViewActionButtons; begin DeselectObjects; try AActBtns := TableView.FActionButtons; if (AActBtns.Visible) and (AActBtns.TableItem = Self) then begin // check for actionbutton click... ABtn := TableView.FActionButtons.ButtonFromXY(x, y); if ABtn <> nil then begin if ABtn.IsDeleteButton then begin FTableView.Items.DeleteItem(Self); Exit; end; // custom button... FTableView.FActionButtons.HideButtons; if Assigned(FTableView.OnItemActionButtonClick) then FTableView.OnItemActionButtonClick(FTableView, Self, ABtn); end; end; AObj := ObjectAtPos(x, y + ItemRect.Top); if AObj <> nil then begin if AObj.HitTest then AObj.MouseDown(x-AObj.ObjectRect.Left, y-AObj.ObjectRect.Top); if AObj.ConsumesClick then Exit; end; if FSelector = DateSelector then begin FTableView.SelectDate(Self, FSelectionValue, FTableView.DoSelectDate); Exit; end; if FSelector = ItemPicker then begin FTableView.SelectItem(Self, FPickerItems, FSelectionValue, FTableView.DoSelectPickerItem); Exit; end; if (FTableView.FCheckMarkOptions.FCheckMarks <> cmNone) and (CheckMarkClicked(x,y)) then Checked := not Checked; finally TableView.FActionButtons.HideButtons; end; end; procedure TksTableViewItem.DoSwipe(ADirecton: TksSwipeDirection); begin if AIsSwiping then Exit; if FTableView.FActionButtons.Visible then begin FTableView.FActionButtons.HideButtons; Exit; end; AIsSwiping := True; try if TableView.FActionButtons.Visible then begin if (TableView.FActionButtons.Alignment = abLeftActionButtons) and (ADirecton = ksSwipeRightToLeft) then TableView.fActionButtons.HideButtons; if (TableView.FActionButtons.Alignment = abRightActionButtons) and (ADirecton = ksSwipeLeftToRight) then TableView.fActionButtons.HideButtons; Exit; end; FTableView.FActionButtons.HideButtons; TableView.FActionButtons.Clear; if Assigned(FTableView.FOnItemSwipe) then FTableView.FOnItemSwipe(FTableView, Self, ADirecton, TableView.fActionButtons); if (ADirecton = TksSwipeDirection.ksSwipeRightToLeft) then TableView.FActionButtons.AddDeleteButton; if TableView.FActionButtons.Count = 0 then Exit; if ADirecton = ksSwipeRightToLeft then TableView.FActionButtons.Alignment := TksTableViewActionButtonAlignment.abRightActionButtons; if ADirecton = ksSwipeLeftToRight then TableView.FActionButtons.Alignment := TksTableViewActionButtonAlignment.abLeftActionButtons; TableView.fActionButtons.ShowButtons(Self); finally AIsSwiping := False; end; end; function TksTableViewItem.DrawBitmap(ABmp: TBitmap; ARect: TRectF; const AVertAlign: TksTableItemAlign = Center): TksTableViewItemImage; begin Result := DrawBitmap(ABmp, ARect.Left, ARect.Top, ARect.Width, ARect.Height, AVertAlign); end; function TksTableViewItem.DrawBitmap(ABmp: TBitmap; x, AWidth, AHeight: single; const AVertAlign: TksTableItemAlign = Center): TksTableViewItemImage; begin Result := DrawBitmap(ABmp, x, 0, AWidth, AHeight, AVertAlign); end; function TksTableViewItem.DrawBitmap(ABmp: TBitmap; x, y, AWidth, AHeight: single; const AVertAlign: TksTableItemAlign = Center): TksTableViewItemImage; begin Result := TksTableViewItemImage.Create(Self); Result.Width := AWidth; Result.Height := AHeight; Result.FPlaceOffset := PointF(x, y); Result.VertAlign := AVertAlign; Result.Bitmap := ABmp; FObjects.Add(Result); Changed; end; function TksTableViewItem.DrawChatBubble(AText: string; APosition: TksTableViewChatBubblePosition; AColor, ATextColor: TAlphaColor): TksTableViewChatBubble; begin FUpdating := True; try Result := TksTableViewChatBubble.Create(Self); Result.FText := AText; case APosition of ksCbpLeft: Result.Align := TksTableItemAlign.Leading; ksCbpRight: Result.Align := TksTableItemAlign.Trailing; end; Result.OffsetX := 16; if APosition = ksCbpRight then Result.OffsetX := -16; Result.RecalculateSize; Result.CornerRadius := 16; Result.Fill.Color := AColor; Result.FTextColor := ATextColor; CanSelect := False; Objects.Add(Result); finally FUpdating := False; end; Changed; end; function TksTableViewItem.DrawRect(x, y, AWidth, AHeight: single; AStroke, AFill: TAlphaColor; const AVertAlign: TksTableItemAlign = TksTableItemAlign.Center): TksTableViewItemShape; begin Result := TksTableViewItemShape.Create(Self); Result.Width := AWidth; Result.Height := AHeight; Result.FPlaceOffset := PointF(x, y); Result.Stroke.Color := AStroke; Result.Fill.Color := AFill; Result.VertAlign := AVertAlign; FObjects.Add(Result); Changed; end; function TksTableViewItem.DrawRect(ARect: TRectF; AStroke, AFill: TAlphaColor; const AVertAlign: TksTableItemAlign = TksTableItemAlign.Center): TksTableViewItemShape; begin Result := DrawRect(ARect.Left, ARect.Top, ARect.Width, ARect.Height, AStroke, AFill, AVertAlign); end; function TksTableViewItem.GetItemData(const AIndex: string): TValue; begin if (FData <> nil) and not FData.TryGetValue(AIndex, Result) then Result := TValue.Empty; end; function TksTableViewItem.GetTextByID(AID: string): TksTableViewItemText; begin Result := Objects.TextByID[AId]; end; function TksTableViewItem.GetHasData(const AIndex: string): Boolean; begin Result := (FData <> nil) and FData.ContainsKey(AIndex); end; function TksTableViewItem.GetImageByID(AID: string): TksTableViewItemImage; begin Result := Objects.ImageByID[AId]; end; function TksTableViewItem.GetIndicatorColor: TAlphaColor; begin Result := FIndicator.Fill.Color; end; function TksTableViewItem.GetInternalRect: TRectF; begin Result := FItemRect; Result.Left := Result.Left + 8; Result.Right := Result.Right - C_SCROLL_BAR_WIDTH; end; procedure TksTableViewItem.Invalidate; begin TableView.Invalidate; end; function TksTableViewItem.IsHeader: Boolean; begin Result := FPurpose = TksTableViewItemPurpose.Header; end; function TksTableViewItem.IsLastItem: Boolean; begin Result := Self = FTableView.FilteredItems.LastItem; end; function TksTableViewItem.IsVisible(AViewport: TRectF): Boolean; begin Result := (FItemRect.Bottom >= (AViewport.Top)) and (FItemRect.Top <= (AViewport.Bottom)); end; function TksTableViewItem.MatchesSearch(AFilter: string): Boolean; begin Result := True; if AFilter <> '' then Result := Pos(LowerCase(AFilter), LowerCase(FSearchIndex)) > 0; end; function TksTableViewItem.ObjectAtPos(x, y: single): TksTableViewItemObject; var ICount: integer; AObj: TksTableViewItemObject; begin Result := nil; for ICount := FObjects.Count-1 downto 0 do begin AObj := FObjects[ICount]; if PtInRect(AObj.ObjectRect, PointF(x, (y-ItemRect.Top))) then begin Result := AObj; Exit; end; end; end; procedure TksTableViewItem.RealignStandardObjects; var ARect: TRectF; TileImageOffsetT : Single; TileImageOffsetB : Single; Margins : TRectF; ARightOffset : Single; begin FUpdating := True; try if (FAppearance=TksTableViewItemAppearance.iaNormal) then begin ARect := GetInternalRect; if (FTableView.SelectionOptions.FSelectionOverlay.FEnabled) then begin ARightOffset := Round(FTableView.SelectionOptions.FSelectionOverlay.Stroke.Thickness/2); ARect.Right := ARect.Right - ARightOffset; end else ARightOffset := 0; if (FTableView.FCheckMarkOptions.FCheckMarks <> cmNone) and (FCheckmarkAllowed) then begin if FCheckMarkAccessory.Bitmap = nil then FCheckMarkAccessory.RedrawAccessory; if (FTableView.FCheckMarkOptions.FPosition = cmpLeft) then begin FCheckMarkAccessory.FPlaceOffset := PointF(ARect.Left, 0); ARect.Left := ARect.Left + (8 + FCheckMarkAccessory.Width); ARect.Right := ARect.Right - (8 + FCheckMarkAccessory.Width); end else begin ARightOffset := ARightOffset + (8 + FCheckMarkAccessory.Width); ARect.Right := ARect.Right - (8 + FCheckMarkAccessory.Width); FCheckMarkAccessory.FPlaceOffset := PointF(ARect.Right + 8, 0); end; end; if (FAccessory.Accessory<>atNone) then begin if (FAccessory.Align=TksTableItemAlign.Leading) then begin FAccessory.FPlaceOffset := PointF(0, 0); ARect.Left := ARect.Left + 24; ARect.Right := ARect.Right - 24; end else begin ARect.Right := ARect.Right - 24; FAccessory.FPlaceOffset := PointF(-((24-FAccessory.Width)/2)-ARightOffset, 0); end; end; if (FPurpose = None) and (FTableView.RowIndicators.Visible) then begin if (Trunc(FIndicator.Height) <> 0) and (Trunc(FIndicator.Height) <> Height) then FIndicator.FPlaceOffset := PointF(ARect.Left, 0); if FIndicator.Width = 0 then FIndicator.Width := FTableView.RowIndicators.Width; FIndicator.Height := FTableView.RowIndicators.Height; if FIndicator.Height = 0 then FIndicator.Height := ItemRect.Height - 16; ARect.Left := ARect.Left + FTableView.RowIndicators.Width+4; FIndicator.OffsetX := 0; case FTableView.RowIndicators.Alignment of ksRowIndicatorLeft: FIndicator.Align := TksTableItemAlign.Leading; ksRowIndicatorRight: begin //FIndicator.Align := TksTableItemAlign.Trailing; FIndicator.OffsetX := ItemRect.Right - FIndicator.Width;; end; end; end; FTileBackground.Width:=0; FTileBackground.Height:=0; if FImage.Bitmap <> nil then begin if FImage.Bitmap.Width > 0 then begin FImage.Width := FTableView.ItemImageSize; FImage.Height := FTableView.ItemImageSize; FImage.FPlaceOffset := PointF(ARect.Left, 0); ARect.Left := ARect.Left + FTableView.ItemImageSize + 4; end; end; FTitle.FPlaceOffset := PointF(ARect.Left, 0); FTitle.Width := ARect.Width; FTitle.Height := CalculateTextHeight(FTitle.Text, FTitle.Font, FTitle.WordWrap, FTitle.FTrimming, FTitle.Width); FSubTitle.FPlaceOffset := PointF(ARect.Left, 0); FSubTitle.Width := ARect.Width; FSubTitle.Height := CalculateTextHeight(FSubTitle.Text, FSubTitle.Font, FSubTitle.WordWrap, FSubTitle.FTrimming, FSubTitle.Width); if FSubTitle.Text <> '' then begin FTitle.FPlaceOffset := PointF(FTitle.FPlaceOffset.x, -9); FSubTitle.FPlaceOffset := PointF(FSubTitle.FPlaceOffset.x, 9); end; FDetail.Width := ARect.Width; FDetail.FPlaceOffset := PointF(ARect.Right-(FDetail.Width), 0); FDetail.Height := CalculateTextHeight(FDetail.Text, FDetail.Font, FDetail.WordWrap, FDetail.FTrimming); end else if (FAppearance>=iaTile_Image) and (FAppearance<=iaTile_SubTitleImageTitle) then begin FIndicator.Width := 0; FTitle.Width := 0; FSubTitle.Width := 0; FDetail.Width := 0; FAccessory.Width := 0; FCheckMarkAccessory.Width := 0; TileImageOffsetT := 0; TileImageOffsetB := 0; Margins.Left := FTileBackground.Margins.Left; Margins.Top := FTileBackground.Margins.Top; Margins.Right := FTileBackground.Margins.Right; Margins.Bottom := FTileBackground.Margins.Bottom; if (not FIsFirstCol) then Margins.Left := Round(Margins.Left / 2); if (not FIsFirstRow) then Margins.Top := Round(Margins.Top / 2); if (not FIsLastCol ) then Margins.Right := Round(Margins.Right / 2); if (not FIsLastRow ) then Margins.Bottom := Round(Margins.Bottom / 2); ARect.Left := FItemRect.Left + Margins.Left; ARect.Top := Margins.Top; ARect.Width := FItemRect.Width - Margins.Left - Margins.Right; ARect.Height := FItemRect.Height - Margins.Top - Margins.Bottom; FTileBackground.FPlaceOffset := PointF(ARect.Left, ARect.Top); FTileBackground.Width := ARect.Width; FTileBackground.Height := ARect.Height; ARect.Left := ARect.Left + FTileBackground.Padding.Left; ARect.Top := ARect.Top + FTileBackground.Padding.Top; ARect.Right := ARect.Right - FTileBackground.Padding.Right; ARect.Bottom := ARect.Bottom - FTileBackground.Padding.Bottom; if (FAppearance=iaTile_TitleImage) or (FAppearance=iaTile_TitleImageSubTitle) then begin FTitle.Width := CalculateTextWidth(FTitle.Text, FTitle.Font, False); FTitle.Height := CalculateTextHeight(FTitle.Text, FTitle.Font, FTitle.WordWrap, FTitle.FTrimming, FTitle.Width); FTitle.FPlaceOffset := PointF(ARect.Left + ((ARect.Width - FTitle.Width) / 2), ARect.Top); TileImageOffsetT := FTitle.Height; end else if (FAppearance=iaTile_SubTitleImageTitle) then begin FSubTitle.Width := CalculateTextWidth(FSubTitle.Text, FSubTitle.Font, False); FSubTitle.Height := CalculateTextHeight(FSubTitle.Text, FSubTitle.Font, FSubTitle.WordWrap, FSubTitle.FTrimming, FSubTitle.Width); FSubTitle.FPlaceOffset := PointF(ARect.Left + ((ARect.Width - FSubTitle.Width) / 2), ARect.Top); TileImageOffsetT := FSubTitle.Height; end; if (FAppearance=iaTile_ImageTitle) or (FAppearance=iaTile_SubTitleImageTitle) then begin FTitle.Width := CalculateTextWidth(FTitle.Text, FTitle.Font, False); FTitle.Height := CalculateTextHeight(FTitle.Text, FTitle.Font, FTitle.WordWrap, FTitle.FTrimming, FTitle.Width); FTitle.FPlaceOffset := PointF(ARect.Left + ((ARect.Width - FTitle.Width) / 2), ARect.Bottom - FTitle.Height); TileImageOffsetB := FTitle.Height; end else if (FAppearance=iaTile_TitleImageSubTitle) then begin FSubTitle.Width := CalculateTextWidth(FSubTitle.Text, FSubTitle.Font, False); FSubTitle.Height := CalculateTextHeight(FSubTitle.Text, FSubTitle.Font, FSubTitle.WordWrap, FSubTitle.FTrimming, FSubTitle.Width); FSubTitle.FPlaceOffset := PointF(ARect.Left + ((ARect.Width - FSubTitle.Width) / 2), ARect.Bottom - FSubTitle.Height); TileImageOffsetB := FSubTitle.Height; end; if FImage.Bitmap <> nil then begin FImage.Width := ARect.Width; FImage.Height := ARect.Height - TileImageOffsetT - TileImageOffsetB; FImage.FPlaceOffset := PointF(ARect.Left, ARect.Top + TileImageOffsetT); ARect.Left := ARect.Left + FTableView.ItemImageSize + 4; end; end; finally FUpdating := False; end; end; {procedure TksTableViewItem.RecreateCache; begin CacheItem(True); end;} procedure TksTableViewItem.ClearCache; begin if FCached then begin FCached := false; _FBitmap.SetSize(0,0); Dec(FOwner.FCachedCount); end; end; function TksTableViewItem.Render(ACanvas: TCanvas; AScrollPos: single): TRectF; var ARect: TRectF; AButtonRect: TRectF; AWidth: single; ASeperatorMargin: single; ASrcRect: TRectF; begin if _FBitmap = nil then Exit; ARect := FItemRect; OffsetRect(ARect, 0, (0 - AScrollPos) + FTableView.GetStartOffsetY); if (FDragging) and (FTableView.DragDropOptions.DragSpaceColor <> claNull) then begin ACanvas.Fill.Color := FTableView.DragDropOptions.DragSpaceColor; ACanvas.FillRect(ARect, 0, 0, AllCorners, 1); Exit; end; CacheItem; if (TableView.FActionButtons.Visible = False) or (TableView.FActionButtons.TableItem <> Self) then begin ACanvas.DrawBitmap(_FBitmap, RectF(0, 0, _FBitmap.Width, _FBitmap.Height), ARect, 1, True); end else begin AWidth := (TableView.FActionButtons.TotalWidth / 100) * TableView.FActionButtons.PercentWidth; ASrcRect := RectF(0, 0, _FBitmap.Width, _FBitmap.Height); case TableView.FActionButtons.Alignment of abLeftActionButtons: begin ARect.Left := ARect.Left + AWidth; ASrcRect.Right := ASrcRect.Right - (AWidth * GetScreenScale); AButtonRect := RectF(FItemRect.Left, ARect.Top, ARect.Left, ARect.Bottom); TableView.FActionButtons.Render(ACanvas, AButtonRect); end; abRightActionButtons: begin ARect.Right := ARect.Right - AWidth; ASrcRect.Left := ASrcRect.Left + (AWidth * GetScreenScale); AButtonRect := RectF(ARect.Right, ARect.Top, FItemRect.Right, ARect.Bottom); TableView.FActionButtons.Render(ACanvas, AButtonRect); end; end; ACanvas.DrawBitmap(_FBitmap, ASrcRect, ARect, 1, True); end; if (FPurpose = TksTableViewItemPurpose.Header) or (FAppearance=iaNormal) then begin // seperator... ACanvas.Stroke.Color := FTableView.Appearence.SeparatorColor; ACanvas.StrokeThickness := 1; ACanvas.Stroke.Kind := TBrushKind.Solid; ACanvas.Stroke.Dash := TStrokeDash.Solid; if FPurpose = Header then begin ACanvas.Stroke.Color := $FFD2D2D2; ACanvas.StrokeThickness := 0.5; end; ASeperatorMargin := 0; if (FTableView.FullWidthSeparator = False) and (FPurpose = TksTableViewItemPurpose.None) then ASeperatorMargin := FTitle.FPlaceOffset.X; if (ARect.Left = 0) or (FColCount < 2) then begin ACanvas.DrawLine(PointF(ARect.Left + ASeperatorMargin, Round(ARect.Top) - 0.5), PointF(FTableView.Width , Round(ARect.Top) - 0.5), 1); if (IsLastItem) or (FPurpose = TksTableViewItemPurpose.Header) then ACanvas.DrawLine(PointF(0 , Round(ARect.Bottom) - 0.5), PointF(FTableView.Width, Round(ARect.Bottom) - 0.5), 1); end; if (FPurpose <> Header) and not (FIsLastCol) then ACanvas.DrawLine(PointF(Round(ARect.Right) - 0.5, ARect.Top), PointF(Round(ARect.Right) - 0.5, ARect.Bottom), 1); Result := ARect; end; {finally ACanvas.EndScene; // ACanvas.RestoreState(AState); end; } end; procedure TksTableViewItem.SetCached(const Value: Boolean); begin FCached := Value; end; procedure TksTableViewItem.SetChecked(const Value: Boolean); begin if FChecked <> Value then begin FChecked := Value; case FChecked of True: FCheckMarkAccessory := TableView.CheckMarkOptions.FCheckMarkChecked; False: FCheckMarkAccessory := TableView.CheckMarkOptions.FCheckMarkUnchecked; end; Changed; if Assigned(FTableView.OnItemCheckmarkChanged) then FTableView.OnItemCheckmarkChanged(Self, Self, FChecked); if (Purpose=Header) and (FTableView.CheckMarkOptions.FHeaderCheckSelectsAll) and (FTableView.FCascadeHeaderCheck) then FTableView.CheckChildren(Self,Value); if (Purpose <> Header) and (FTableView.CheckMarkOptions.FHeaderCheckSelectsAll) and (Value = False) then begin FTableView.FCascadeHeaderCheck := False; FTableView.UncheckHeader(Self); FTableView.FCascadeHeaderCheck := True; end; end; end; procedure TksTableViewItem.SetItemData(const AIndex: string; const Value: TValue); begin if FData = nil then FData := TDictionary<string, TValue>.Create; FData.AddOrSetValue(AIndex, Value); end; procedure TksTableViewItem.SetFill(const Value: TBrush); begin if Value <> nil then FFill.Assign(Value) end; procedure TksTableViewItem.SetFont(const Value: TFont); begin FFont.Assign(Value); end; procedure TksTableViewItem.SetHeight(const Value: single); begin if Value <> FHeight then begin FHeight := Value; FTableView.UpdateItemRects(True); //FTableView.UpdateAll(False); if not FDeleting then CacheItem(True); end; end; procedure TksTableViewItem.SetHeightPercentage(const Value: single); begin if Value <> FHeight then begin FHeightPercentage := Value; FTableView.UpdateAll(False); Invalidate; end; end; procedure TksTableViewItem.SetIndex(const Value: integer); begin FIndex := Value; end; procedure TksTableViewItem.SelectFirstEmbeddedEdit; var ICount: integer; begin for ICount := 0 to FObjects.Count-1 do begin if (FObjects[ICount] is TksTableViewItemEmbeddedBaseEdit) then begin (FObjects[ICount] as TksTableViewItemEmbeddedBaseEdit).FocusControl; Exit; end; end; end; procedure TksTableViewItem.SetAppearance(const Value: TksTableViewItemAppearance); begin if (FAppearance<>Value) then begin FAppearance := Value; FCached := False; Invalidate; end; end; procedure TksTableViewItem.SetHidden(const Value: Boolean); begin if (FHidden<>Value) then begin FHidden := Value; FTableView.ClearCache(ksClearCacheAll); FTableView.UpdateAll(true); Invalidate; end; end; procedure TksTableViewItem.SetIndicatorColor(const Value: TAlphaColor); begin FIndicator.Fill.Color := Value; FCached := False; Invalidate; end; procedure TksTableViewItem.SetItemFontStyle(AFontStyle: TFontStyles); var ICount: integer; begin FFont.Style := AFontStyle; for ICount := 0 to FObjects.Count - 1 do begin if (FObjects[ICount] is TksTableViewItemText) then (FObjects[ICount] as TksTableViewItemText).Font.Style := AFontStyle; end; FTitle.Font.Style := AFontStyle; FSubTitle.Font.Style := AFontStyle; FDetail.Font.Style := AFontStyle; end; procedure TksTableViewItem.SetItemRect(const Value: TRectF); var ALastHeight: single; begin ALastHeight := FItemRect.Height; FItemRect := Value; if FItemRect.Height <> ALastHeight then Changed; end; procedure TksTableViewItem.SetItemTextColor(AColor: TAlphaColor); var ICount: integer; begin FTextColor := AColor; for ICount := 0 to FObjects.Count - 1 do begin if (FObjects[ICount] is TksTableViewItemText) then (FObjects[ICount] as TksTableViewItemText).TextColor := AColor; end; FTitle.TextColor := AColor; FSubTitle.TextColor := AColor; FDetail.TextColor := AColor; Changed; end; procedure TksTableViewItem.SetPickerItems(const Value: TStrings); begin FPickerItems.Assign(Value); end; procedure TksTableViewItem.SetPurpose(const Value: TksTableViewItemPurpose); begin if FPurpose <> Value then begin FPurpose := Value; Changed; end; end; procedure TksTableViewItem.ExpandIndicatorToWidth; var ICount: integer; ACurrentlyExpanded: TksTableViewItem; ASteps: integer; AStepValue: single; begin ACurrentlyExpanded := nil; FTableView.DisableMouseEvents; try if Trunc(FIndicator.Width) = (ItemRect.Right) then Exit; for ICount := 0 to FTableView.Items.Count-1 do begin if FTableView.Items[ICount].FIndicator.Width > FTableView.RowIndicators.Width then begin ACurrentlyExpanded := FTableView.Items[ICount]; ACurrentlyExpanded.FForegroundColor := claNull; Break; end; end; FForegroundColor := claNull; if Assigned(FTableView.OnIndicatorExpand) then FTableView.OnIndicatorExpand(Self, Self, FIndicator.Fill.Color, FForegroundColor); ASteps := 10; AStepValue := (ItemRect.Width / ASteps); for ICount := 1 to ASteps do begin if ACurrentlyExpanded <> nil then ACurrentlyExpanded.FIndicator.Width := (ItemRect.Right - (ICount * AStepValue)); FIndicator.Width := (ICount * AStepValue); ProcessMessages; {$IFDEF MSWINDOWS} Sleep(10); {$ENDIF} end; finally FTableView.EnableMouseEvents; end; end; procedure TksTableViewItem.SetColCount(const Value: Integer); begin if FColCount <> Value then begin FColCount := Value; FTableView.ClearCache(ksClearCacheAll); FTableView.UpdateAll(True); Changed; end; end; procedure TksTableViewItem.SetSearchFilter(const Value: string); begin FSearchFilter := Value; UpdateSearchIndex; end; { procedure TksTableViewItem.SetSearchIndex(const Value: string); begin FSearchIndex := Value; end; } procedure TksTableViewItem.SetTextColor(const Value: TAlphaColor); begin FTextColor := Value; end; function TksTableViewItem.TextBox(AText: string; ARect: TRectF; ATextAlign, ATextLayout: TTextAlign; const ABackground: TAlphaColor) : TksTableViewItemText; begin FUpdating := True; try Result := TextOut(AText, ARect.Left, ARect.Top, ARect.Width, TksTableItemAlign.Leading, True); Result.Background := ABackground; Result.Height := ARect.Height; Result.TextAlignment := ATextAlign; Result.TextVertAlign := ATextLayout; finally FUpdating := False; end; Changed; end; function TksTableViewItem.TextBoxHtml(AText: string; ARect: TRectF) : TksTableViewItemText; begin FUpdating := True; try Result := TextOut(AText, ARect.Left, ARect.Top, ARect.Width, TksTableItemAlign.Leading, True); Result.FIsHtmlText := True; Result.Height := ARect.Height; finally FUpdating := False; end; Changed; end; function TksTableViewItem.TextHeight(AText: string; AWordWrap, AIsHtml: Boolean; ATrimming: TTextTrimming; const AMaxWidth: single): single; begin if AIsHtml then Result := GetTextSizeHtml(AText, FFont, AMaxWidth).y else Result := CalculateTextHeight(AText, FFont, AWordWrap, ATrimming, AMaxWidth); end; function TksTableViewItem.TextOut(AText: string; x: single; const AVertAlign: TksTableItemAlign; const AWordWrap: Boolean) : TksTableViewItemText; var AWidth: single; begin AWidth := TextWidth(AText, False); Result := TextOut(AText, x, AWidth, AVertAlign, AWordWrap); end; function TksTableViewItem.TextOut(AText: string; x, y, AWidth: single; const AVertAlign: TksTableItemAlign; const AWordWrap: Boolean) : TksTableViewItemText; var AHeight: single; begin Result := TksTableViewItemText.Create(Self); Result.Font.Assign(Font); Result.FPlaceOffset := PointF(x, y); AHeight := CalculateTextHeight(AText, FFont, AWordWrap, Result.Trimming, AWidth); if AWidth = 0 then AWidth := CalculateTextWidth(AText, Font, AWordWrap); Result.Width := AWidth; Result.Height := AHeight; Result.VertAlign := AVertAlign; Result.TextAlignment := TTextAlign.Leading; Result.TextColor := FTextColor; Result.Text := AText; Result.WordWrap := AWordWrap; //if SearchIndex = '' then // SearchIndex := AText; UpdateSearchIndex; FObjects.Add(Result); Changed; end; function TksTableViewItem.TextOut(AText: string; x, AWidth: single; const AVertAlign: TksTableItemAlign; const AWordWrap: Boolean) : TksTableViewItemText; begin Result := TextOut(AText, x, 0, AWidth, AVertAlign, AWordWrap); end; function TksTableViewItem.TextOutRight(AText: string; y, AWidth, AXOffset: single; const AVertAlign: TksTableItemAlign) : TksTableViewItemText; begin FUpdating := True; try Result := TextOut(AText, AXOffset, y, AWidth, AVertAlign); Result.Align := TksTableItemAlign.Trailing; Result.TextAlignment := TTextAlign.Trailing; finally FUpdating := False; end; Changed; end; function TksTableViewItem.TextWidth(AText: string; AIsHtml: Boolean): single; begin if AIsHtml then Result := GetTextSizeHtml(AText, FFont, 0).x else Result := CalculateTextWidth(AText, FFont, False); end; function TksTableViewItem.TimeToCacheItem: integer; var AStart: TDateTime; begin AStart := Now; CacheItem(True); Invalidate; ProcessMessages; Result := MilliSecondsBetween(Now, AStart); end; procedure TksTableViewItem.UpdateSearchIndex; var ICount: integer; begin FSearchIndex := ''; FSearchIndex := FTitle.Text+'|'+FSubTitle.Text+'|'+FDetail.Text+'|'; for ICount := 0 to FObjects.Count-1 do begin if FObjects[ICount] is TksTableViewItemText then FSearchIndex := FSearchIndex + LowerCase((FObjects[ICount] as TksTableViewItemText).Text)+#13; end; FSearchIndex := Trim(FSearchIndex); if FSearchFilter <> '' then FSearchIndex := FSearchIndex + '|'+FSearchFilter; end; // ------------------------------------------------------------------------------ { TksTableViewAppearence } constructor TksTableViewAppearence.Create(AListView: TksTableView); begin inherited Create; FListView := AListView; FItemBackground := TBrush.Create(TBrushKind.Solid, claWhite); FBackground := TBrush.Create(TBrushKind.Solid, claWhite); FSeparatorColor := $FFF0F0F0; FSelectedColor := C_TABLEVIEW_DEFAULT_SELECTED_COLOR; FAlternatingItemBackground := claNull; end; destructor TksTableViewAppearence.Destroy; begin FreeAndNil(FItemBackground); FreeAndNil(FBackground); inherited; end; procedure TksTableViewAppearence.Assign(ASource: TPersistent); var Src : TksTableViewAppearence; begin if (ASource is TksTableViewAppearence) then begin Src := TksTableViewAppearence(ASource); FBackground.Assign(Src.FBackground); FItemBackground.Assign(Src.FItemBackground); FAlternatingItemBackground := Src.FAlternatingItemBackground; FSeparatorColor := Src.FSeparatorColor; FHeaderColor := Src.FHeaderColor; FSelectedColor := Src.FSelectedColor; end else inherited; end; procedure TksTableViewAppearence.SetAlternatingItemBackground (const Value: TAlphaColor); begin FAlternatingItemBackground := Value; end; procedure TksTableViewAppearence.SetBackground(const Value: TBrush); begin if Value <> nil then FBackground.Assign(Value); end; procedure TksTableViewAppearence.SetHeaderColor(const Value: TAlphaColor); begin FHeaderColor := Value; end; procedure TksTableViewAppearence.SetItemBackground(const Value: TBrush); begin if Value <> nil then FItemBackground.Assign(Value); end; procedure TksTableViewAppearence.SetSelectedColor(const Value: TAlphaColor); begin FSelectedColor := Value; end; procedure TksTableViewAppearence.SetSeparatorBackground (const Value: TAlphaColor); begin FSeparatorColor := Value; end; // ------------------------------------------------------------------------------ { TksTableView } procedure TksTableView.BeginUpdate; begin KillAllTimers; FUpdateCount := FUpdateCount + 1; end; procedure TksTableView.AniCalcStart(Sender: TObject); begin if Scene <> nil then Scene.ChangeScrollingState(Self, True); //FScrolling := True; end; procedure TksTableView.UpdateAll(AUpdateFiltered: Boolean); begin if FUpdateCount > 0 then Exit; FItems.UpdateIndexes; // <- here UpdateItemRects(AUpdateFiltered); UpdateStickyHeaders; UpdateScrollingLimits; {if (FItems.Count > 0) and (TopItem <> nil) then begin AStartIndex := Max(TopItem.Index - (C_TABLEVIEW_PAGE_SIZE div 2), 0); AEndIndex := Min(FItems.Count-1, AStartIndex + C_TABLEVIEW_PAGE_SIZE); for ICount := AStartIndex to AEndIndex do FItems[ICount].CacheItem(False); end;} end; procedure TksTableView.UpdateItemRects(AUpdateFiltered: Boolean); var ICount: integer; AYPos: single; AXPos: single; ANoCols: integer; ACol: Integer; ARow: Integer; AHeight: single; AClientHeight: single; AWidth: single; AItem: TksTableViewItem; AIsLastRow: Boolean; AFixedHeaderEnd : Integer; AFixedFooterStart : Integer; AFixedHeaderHeight: Single; AFixedFooterHeight: Single; ASearchHeight: Single; begin if FUpdateCount > 0 then Exit; if AUpdateFiltered then UpdateFilteredItems; AClientHeight := Height; if (FFixedRowOptions.FHeaderCount>0) or (FFixedRowOptions.FFooterCount>0) then begin AFixedHeaderEnd := Min(FFixedRowOptions.FHeaderCount,Items.Count)-1; AFixedFooterStart := Max(0,Items.Count-FFixedRowOptions.FFooterCount); AFixedHeaderHeight := 0; AFixedFooterHeight := 0; ASearchHeight := GetSearchHeight; AYPos := ASearchHeight; for ICount := 0 to AFixedHeaderEnd do begin AItem := Items[ICount]; if (AItem.HeightPercentage>0) then AItem.FHeight := AClientHeight * AItem.HeightPercentage / 100.0; AItem.ItemRect := RectF(0, AYPos, Width, AYPos + AItem.Height); AYPos := AYPos + AItem.Height; AFixedHeaderHeight := AFixedHeaderHeight + AItem.Height; AItem.FCheckmarkAllowed := false; AItem.FIsFixedHeader := true; end; AYPos := Height; for ICount := AFixedFooterStart to Items.Count-1 do AYPos := AYPos - Items[ICount].Height; for ICount := AFixedFooterStart to Items.Count-1 do begin AItem := Items[ICount]; if (AItem.HeightPercentage>0) then AItem.FHeight := AClientHeight * AItem.HeightPercentage / 100.0; AItem.ItemRect := RectF(0, AYPos, Width, AYPos + AItem.Height); AYPos := AYPos + AItem.Height; AFixedFooterHeight := AFixedFooterHeight + AItem.Height; AItem.FCheckmarkAllowed := false; AItem.FIsFixedFooter := true; end; AHeight := Height - ASearchHeight - AFixedHeaderHeight - AFixedFooterHeight; if (AHeight<FFixedRowOptions.FMinimumWorkHeight) then begin AYPos := Min(AFixedFooterHeight,FFixedRowOptions.FMinimumWorkHeight-AHeight); AHeight := AHeight + AYPos; for ICount := AFixedFooterStart to Items.Count-1 do OffsetRect(Items[ICount].FItemRect,0,AYPos); end; if (AHeight<FFixedRowOptions.FMinimumWorkHeight) then begin AYPos := Min(AFixedHeaderHeight,FFixedRowOptions.FMinimumWorkHeight-AHeight); for ICount := 0 to AFixedHeaderEnd do OffsetRect(Items[ICount].FItemRect,0,-AYPos); end; end; AHeight := 0; ANoCols := Max(1,ColCount); AWidth := Width / ANoCols; AXPos := 0; AYPos := 0; ACol := 0; ARow := 0; AClientHeight := Height - GetStartOffsetY; for ICount := 0 to FFilteredItems.Count - 1 do begin AItem := FFilteredItems[ICount]; if (AItem.HeightPercentage>0) then AItem.FHeight := AClientHeight * AItem.HeightPercentage / 100; if (AItem.Purpose=TksTableViewItemPurpose.Header) then begin ARow := 0; if (ACol>0) then begin ACol := 0; AYPos := AYPos + AHeight; end; if (AItem.FHeaderHeight>0) then AHeight := AItem.FHeaderHeight else AHeight := AItem.Height; AItem.ItemRect := RectF(0, AYPos, Width, AYPos + AHeight); if (AItem.ColCount>0) then ANoCols := AItem.ColCount else ANoCols := Max(1,AItem.ColCount); AWidth := Width / ANoCols; AItem.FCheckmarkAllowed := FCheckMarkOptions.ShowInHeader; end else begin AItem.ItemRect := RectF(AXPos, AYPos, AXPos + AWidth, AYPos + AItem.Height); // First column item sets row height if (ACol=0) then AHeight := AItem.Height; AItem.FCheckmarkAllowed := true; end; AItem.FIsFirstCol := (ACol=0); AItem.FIsLastCol := (ACol=ANoCols-1); AItem.FIsFirstRow := (ARow=0); AItem.FIsLastRow := false; AItem.FIsFixedHeader := false; AItem.FIsFixedFooter := false; AItem.Index := ICount; if (AItem.Purpose<>TksTableViewItemPurpose.Header) and (ACol<ANoCols-1) then begin Inc(ACol); AXPos := AXPos + AWidth; end else begin AYPos := AYPos + AHeight; ACol := 0; AXPos := 0; if (AItem.Purpose<>TksTableViewItemPurpose.Header) then Inc(ARow); end; end; AIsLastRow := true; for ICount := FFilteredItems.Count - 1 downto 0 do begin AItem := FFilteredItems[ICount]; if (FFilteredItems[ICount].Purpose=TksTableViewItemPurpose.Header) then AIsLastRow := true else begin AItem.FIsLastRow := AIsLastRow; if (AItem.FIsFirstCol) then AIsLastRow := false; end; end; end; procedure TksTableView.UpdateScrollingLimits; var Targets: array of TAniCalculations.TTarget; begin if FUpdateCount > 0 then Exit; if FAniCalc <> nil then begin SetLength(Targets, 2); Targets[0].TargetType := TAniCalculations.TTargetType.Min; Targets[0].Point := TPointD.Create(0, 0); Targets[1].TargetType := TAniCalculations.TTargetType.Max; FMaxScrollPos := Max((GetTotalItemHeight - Height) + GetStartOffsetY + GetFixedFooterHeight, 0); if FMaxScrollPos < FScrollPos then FScrollPos := FMaxScrollPos; Targets[1].Point := TPointD.Create(0,FMaxScrollPos); FAniCalc.SetTargets(Targets); FAniCalc.ViewportPosition := PointF(0, FScrollPos); end; end; procedure TksTableView.AniCalcStop(Sender: TObject); begin FScrolling := False; FSwipeDirection := ksSwipeUnknown; //ClearCache(ksClearCacheNonVisible); if Scene <> nil then Scene.ChangeScrollingState(nil, False); end; procedure TksTableView.AniCalcChange(Sender: TObject); var NewViewPos: single; begin {$IFDEF MSWINDOWS} NewViewPos := Trunc(FAniCalc.ViewportPosition.y); {$ELSE} NewViewPos := FAniCalc.ViewportPosition.y; {$ENDIF} if FScrolling then begin SetScrollViewPos(NewViewPos); end; end; (* procedure TksTableView.CacheItems(AForceRedraw: Boolean); var ICount: integer; ATopItem: TksTableViewItem; AItems: TksTableViewItems; AStartPos: integer; begin {ATopItem := TopItem; if ATopItem = nil then Exit; AItems := FFilteredItems; AStartPos := Max(ATopItem.Index, 0); if Items.Count < C_TABLEVIEW_PAGE_SIZE then AStartPos := 0; for ICount := AStartPos to (AStartPos + C_TABLEVIEW_PAGE_SIZE) do begin if ICount > AItems.Count - 1 then Exit; AItems[ICount].CacheItem(AForceRedraw); end; } end; *) procedure TksTableView.ClearItems; begin FItemIndex := -1; FScrollPos := 0; FFilteredItems.Clear; FItems.Clear; if FUpdateCount = 0 then Invalidate; end; procedure TksTableView.ComboClosePopup(Sender: TObject); begin (Sender as TStyledControl).Width := 0; (Sender as TStyledControl).Visible := False; end; constructor TksTableView.Create(AOwner: TComponent); begin inherited; AUnitTesting := AOwner = nil; TPlatformServices.Current.SupportsPlatformService(IFMXTimerService, FTimerService); FItems := TksTableViewItems.Create(Self, True); FFilteredItems := TksTableViewItems.Create(Self, False); FBackgroundText := TksTableViewBackgroundText.Create; FRowIndicators := TksListViewRowIndicators.Create(Self); FDeleteButton := TksDeleteButton.Create; FAppearence := TksTableViewAppearence.Create(Self); FDragDropOptions := TksDragDropOptions.Create; FSelectionOptions := TksTableViewSelectionOptions.Create(Self); FAccessoryOptions := TksTableViewAccessoryOptions.Create(Self); FHeaderOptions := TksTableViewItemHeaderOptions.Create(Self); FBorder := TksTableViewBorderOptions.Create(Self); FFixedRowOptions := TksTableViewFixedRowsOptions.Create(Self); FCheckMarkOptions:= TksTableViewCheckMarkOptions.Create(Self); FActionButtons := TksTableViewActionButtons.Create(Self); FSearchBox := TSearchBox.Create(Self); FSearchBox.Stored := False; FSearchBox.Locked := True; FSearchBox.Visible := False; FSearchBox.Align := TAlignLayout.Top; FSearchBox.OnTyping := DoFilterChanged; FSearchBox.OnChange := DoFilterChanged; FSearchBox.OnEnter := DoFilterEnter; FSearchBox.Parent := Self; FTextDefaults := TksTableViewTextDefaults.Create; FPullToRefresh := TksTableViewPullToRefresh.Create(Self); Size.Width := C_TABLEVIEW_DEFAULT_WIDTH; Size.Height := C_TABLEVIEW_DEFAULT_HEIGHT; ClipChildren := True; FAniCalc := nil; CreateAniCalculator(True); FSearchVisible := False; FItemIndex := -1; FItemHeight := C_TABLEVIEW_DEFAULT_ITEM_HEIGHT; FItemImageSize := C_TABLEVIEW_DEFAULT_IMAGE_SIZE; FNeedsRefresh := False; FMouseDown := False; FFullWidthSeparator := True; FStickyHeader := Nil; FLastCacheClear := Now; FUpdateCount := 0; FDragging := False; AddObject(FSearchBox); SetAcceptsControls(False); FItems.OnNotify := DoItemsChanged; FCascadeHeaderCheck := True; CanFocus := True; AutoCapture := True; FMouseEventsEnabledCounter := 0; //FClearCacheTimer := CreateTimer(1000, DoClearCacheTimer) end; procedure TksTableView.CreateAniCalculator(AUpdateScrollLimit: Boolean); begin if FAniCalc <> nil then FreeAndNil(FAniCalc); FAniCalc := TksAniCalc.Create(nil); FAniCalc.Animation := True; FAniCalc.Averaging := True; FAniCalc.Interval := 8; FAniCalc.BoundsAnimation := True; FAniCalc.TouchTracking := [ttVertical]; if AUpdateScrollLimit then UpdateScrollingLimits; // set events... FAniCalc.OnChanged := AniCalcChange; FAniCalc.OnStart := AniCalcStart; FAniCalc.OnStop := AniCalcStop; end; destructor TksTableView.Destroy; begin KillTimer(FClearCacheTimer); if FSearchBox <> nil then begin FSearchBox.Parent := nil; FreeAndNil(FSearchBox); end; FreeAndNil(FCheckMarkOptions); FreeAndNil(FFixedRowOptions); FreeAndNil(FBorder); FreeAndNil(FHeaderOptions); FreeAndNil(FAccessoryOptions); FreeAndNil(FRowIndicators); FreeAndNil(FBackgroundText); FreeAndNil(FFilteredItems); FreeAndNil(FItems); FreeAndNil(FAniCalc); FreeAndNil(FAppearence); FreeAndNil(FDragDropOptions); FreeAndNil(FDeleteButton); FreeAndNil(FTextDefaults); FreeAndNil(FPullToRefresh); FreeAndNil(FSelectionOptions); FreeAndNil(FActionButtons); inherited; end; procedure TksTableView.DisableMouseEvents; begin Inc(FMouseEventsEnabledCounter); end; function TksTableView.CreateTimer(AInterval: integer; AProc: TTimerProc): TFmxHandle; begin Result := 0; if FTimerService <> nil then Result := FTimerService.CreateTimer(AInterval, AProc); end; procedure TksTableView.DoButtonClicked(AItem: TksTableViewItem; AButton: TksTableViewItemButton); begin if Assigned(FOnButtonClicked) then FOnButtonClicked(Self, AItem, AButton, AItem.ID); end; { procedure TksTableView.DoClearCacheTimer; var AViewPort: TRectF; ICount: integer; AItem: TksTableViewItem; begin if MilliSecondsBetween(FLastCacheClear, Now) > 1000 then begin FLastCacheClear := Now; AViewport := ViewPort; AViewPort.Top := AViewPort.Top - 1000; AViewPort.Bottom := AViewPort.Bottom + 1000; for ICount := 0 to FItems.Count-1 do begin AItem := FItems[ICount]; if (AItem.Cached) and (AItem.IsVisible(AViewPort) = False) then AItem.ClearCache; end; end; end; } procedure TksTableView.DoDeselectItem; var ASelected: TksTableViewItem; begin if FTimerService = nil then Exit; KillTimer(FDeselectTimer); ASelected := SelectedItem; if ASelected <> nil then begin ASelected.DeselectObjects; FItemIndex := -1; ASelected.CacheItem(True); Invalidate; if FFocusedControl <> nil then FFocusedControl.FocusControl; end end; procedure TksTableView.DoEmbeddedEditChange(AItem: TksTableViewItem; AEmbeddedEdit: TksTableViewItemEmbeddedBaseEdit); begin if Assigned(FOnEmbeddedEditChange) then FOnEmbeddedEditChange(Self, AItem, AEmbeddedEdit, AEmbeddedEdit.Text); end; procedure TksTableView.DoEmbeddedDateEditChange(AItem: TksTableViewItem; AEmbeddedDateEdit: TksTableViewItemEmbeddedDateEdit); begin if Assigned(FOnEmbeddedDateEditChange) then FOnEmbeddedDateEditChange(Self, AItem, AEmbeddedDateEdit, AEmbeddedDateEdit.Date); end; procedure TksTableView.LegacyGetShowAccessory(Reader: TReader); begin FAccessoryOptions.ShowAccessory := Reader.ReadBoolean; end; procedure TksTableView.LegacyGetStickyHeaders(Reader: TReader); begin FHeaderOptions.StickyHeaders.Enabled := Reader.ReadBoolean; end; procedure TksTableView.LegacyGetHeaderHeight(Reader: TReader); begin FHeaderOptions.Height := Reader.ReadInteger; end; procedure TksTableView.LegacyGetCheckMarks(Reader: TReader); begin FCheckMarkOptions.CheckMarks := TksTableViewCheckMarks(GetEnumValue(TypeInfo(TksTableViewCheckMarks),Reader.ReadIdent)); end; procedure TksTableView.DefineProperties(Filer: TFiler); begin inherited; // deleted properties... Filer.DefineProperty('ShowAccessory', LegacyGetShowAccessory, nil, False); Filer.DefineProperty('StickyHeaders', LegacyGetStickyHeaders, nil, False); Filer.DefineProperty('HeaderHeight', LegacyGetHeaderHeight, nil, False); Filer.DefineProperty('CheckMarks', LegacyGetCheckMarks, nil, False); end; //------------------------------------------------------------------------------ procedure TksTableView.DeselectItem(const ADelay: integer); begin if ADelay > 0 then begin KillTimer(FDeselectTimer); FDeselectTimer := CreateTimer(ADelay, DoDeselectItem) end else DoDeselectItem; end; procedure TksTableView.DoFilterChanged(Sender: TObject); begin SetScrollViewPos(0); UpdateAll(True); Repaint; if Assigned(FOnSearchFilterChanged) then FOnSearchFilterChanged(Self, FSearchBox.Text); end; procedure TksTableView.DoFilterEnter(Sender: TObject); begin HideFocusedControl; end; procedure TksTableView.DoItemObjectMouseUp(AObject: TksTableViewItemObject; x, y: single); begin if Assigned(FItemObjectMouseUpEvent) then FItemObjectMouseUpEvent(Self, x, y, AObject.TableItem, AObject.ID, AObject); end; procedure TksTableView.DoItemsChanged(Sender: TObject; const Item: TksTableViewItem; Action: TCollectionNotification); begin if (FUpdateCount > 0) then Exit; UpdateFilteredItems; end; procedure TksTableView.DoMouseLeave; begin inherited; if (FAniCalc <> nil) then FAniCalc.MouseLeave; FMouseDown := False; end; procedure TksTableView.DoPullToRefresh; begin if Assigned(FOnPullRefresh) then begin KillAllTimers; DisableMouseEvents; FOnPullRefresh(Self); EnableMouseEvents; end; end; procedure TksTableView.DoSelectDate(Sender: TObject); var AAllow: Boolean; ARow: TksTableViewItem; begin AAllow := True; ARow := TksTableViewItem(FDateSelector.TagObject); if AAllow then begin ARow.FSelectionValue := FDateSelector.Date; ARow.Detail.Text := FormatDateTime('ddd, dd mmmm, yyyy', FDateSelector.Date); ARow.Cached := False; end; if Assigned(FOnSelectDate) then FOnSelectDate(Self, ARow, FDateSelector.Date, AAllow); end; procedure TksTableView.DoSelectItem; begin KillTimer(FSelectTimer); if FMouseDownItem = nil then Exit; if FMouseDownItem.TableView.FActionButtons.Visible then begin FMouseDownItem.DoClick(FMouseDownPoint.x, (FMouseDownPoint.y - FMouseDownItem.ItemRect.Top) + ScrollViewPos); Exit; end; if (CheckMarkOptions.FCheckMarks <> TksTableViewCheckMarks.cmMultiSelect) and (FActionButtons.Visible = False) then begin UncheckAll; ItemIndex := FMouseDownItem.Index; end; FMouseDownItem.DoClick(FMouseDownPoint.x, (FMouseDownPoint.y - FMouseDownItem.ItemRect.Top) + ScrollViewPos); // select the first embedded edit if no OnClick event handler exists for the table item FMouseDownItem.SelectFirstEmbeddedEdit; if FRowIndicators.SelectRow then //begin FMouseDownItem.ExpandIndicatorToWidth; //end; if Assigned(FItemClickEvent) then FItemClickEvent(Self, FMouseDownPoint.x, FMouseDownPoint.y, FMouseDownItem, FMouseDownItem.ID, FMouseDownObject); FActionButtons.HideButtons; end; procedure TksTableView.DoSelectPickerItem(Sender: TObject); var AAllow: Boolean; ASelected: string; AItem: TksTableViewItem; begin ASelected := ''; AItem := TksTableViewItem(FCombo.TagObject); if FCombo.ItemIndex > -1 then ASelected := FCombo.Items[FCombo.ItemIndex]; AAllow := True; if Assigned(FOnSelectPickerItem) then FOnSelectPickerItem(Self, AItem, ASelected, AAllow); if Assigned(FOnSelectPickerItemExt) then FOnSelectPickerItemExt(Self, AItem, ASelected, FCombo.Items.IndexOf(ASelected), AAllow); if AAllow then begin AItem.FSelectionValue := ASelected; AItem.Detail.Text := ASelected; AItem.CacheItem(True); end; end; procedure TksTableView.DoSwitchClicked(AItem: TksTableViewItem; ASwitch: TksTableViewItemSwitch); begin if Assigned(FOnSwitchClicked) then FOnSwitchClicked(Self, AItem, ASwitch, AItem.ID); end; procedure TksTableView.EnableMouseEvents; begin // process any pending mouse events before re-enabling... ProcessMessages; Dec(FMouseEventsEnabledCounter); end; procedure TksTableView.EndUpdate; begin if FUpdateCount = 0 then Exit; FUpdateCount := FUpdateCount - 1; if FUpdateCount = 0 then begin ClearCache(ksClearCacheAll); UpdateAll(True); Invalidate; end; end; procedure TksTableView.UncheckAll; var ICount: integer; begin for ICount := 0 to FItems.Count - 1 do begin Items[ICount].Checked := False; end; end; procedure TksTableView.UpdateFilteredItems; var ICount: integer; ASearchText: string; ALastSelected: TksTableViewItem; AItem: TksTableViewItem; begin if (FFilteredItems = nil) then Exit; ALastSelected := SelectedItem; FFilteredItems.Clear; ASearchText := Trim(FSearchBox.Text); for ICount := FFixedRowOptions.FHeaderCount to (FItems.Count-FFixedRowOptions.FFooterCount-1) do begin AItem := FItems[ICount]; if (AItem.MatchesSearch(ASearchText)) and not (AItem.Hidden) then begin AItem.Index := FFilteredItems.Count; FFilteredItems.Add(AItem); end; end; FItemIndex := FFilteredItems.IndexOf(ALastSelected); end; procedure TksTableView.DoSelectTimer; var Form : TCustomForm; AAllowDrag: Boolean; begin if FMouseDownItem = nil then Exit; AAllowDrag := (FDragDropOptions.Enabled); if (AAllowDrag) and (Assigned(FOnCanDragItem)) then FOnCanDragItem(Self, FMouseDownItem, AAllowDrag); if (AAllowDrag) and (FActionButtons.Visible = False) then begin KillTimer(FSelectTimer); //FActionButtons.HideButtons(True); if (Root.GetObject is TCustomForm) then begin Form := TCustomForm(Root.GetObject); FDragDropImage := TksDragImage.Create(Form); FDragDropImage.FShadow.Enabled := FDragDropOptions.Shadow; FDragDropImage.Parent := Form; FDragDropImage.HitTest := False; FDragDropImage.Width := FMouseDownItem._FBitmap.Width / GetScreenScale; FDragDropImage.Height := FMouseDownItem._FBitmap.Height / GetScreenScale; FDragDropImage.Fill.Bitmap.Bitmap := FMouseDownItem._FBitmap; FDragDropImage.Fill.Kind := TBrushKind.Bitmap; FDragDropImage.Fill.Bitmap.WrapMode := TWrapMode.TileStretch; FDragDropImage.Opacity := FDragDropOptions.Opacity; FDragDropScrollTimer := CreateTimer(100,DoDropScroll); Capture; FDragDropImage.MouseDownOffset := PointF(FMouseDownPoint.X - FMouseDownItem.ItemRect.Left, FMouseDownPoint.Y - FMouseDownItem.ItemRect.Top + FScrollPos); if FDragDropImage.MouseDownOffset.Y < 8 then FDragDropImage.MouseDownOffset := PointF(FDragDropImage.MouseDownOffset.X, FDragDropImage.MouseDownOffset.y + 8); UpdateDropImage(FMouseDownPoint.X+8, FMouseDownPoint.Y+8); FDragging := True; FMouseDownItem.FDragging := True; FDragOverItem := nil; end; end else if (FSelectionOptions.FLongTapSelects) and (FActionButtons.Visible = False) then DoSelectItem; end; procedure TksTableView.UpdateDropImage(x, y: single); var ScreenMousePos : TPointF; FormMousePos : TPointF; AAllowDrop: Boolean; ADragOverItem: TksTableViewItem; begin if FDragDropImage = nil then Exit; AAllowDrop := True; ADragOverItem := GetItemFromPos(x, y); if (Assigned(FOnCanDropItem)) and (ADragOverItem <> nil) then FOnCanDropItem(Self, FMouseDownItem, ADragOverItem, AAllowDrop); if FDragDropOptions.DragHighlight.Enabled then begin case AAllowDrop of True: FDragDropImage.AllowDropStroke := FDragDropOptions.DragHighlight.AllowDropStroke; False: FDragDropImage.AllowDropStroke := FDragDropOptions.DragHighlight.DisallowDropStroke; end; // add 1 to the thickness so it shows inside the existing dark gray border... FDragDropImage.Stroke.Thickness := FDragDropImage.Stroke.Thickness + 1; end else FDragDropImage.Stroke.Color := claNull; FDragDropImage.Fill.Bitmap.Bitmap := FMouseDownItem._FBitmap; FDragDropImage.Width := FMouseDownItem._FBitmap.Width / GetScreenScale; FDragDropImage.Height := FMouseDownItem._FBitmap.Height / GetScreenScale; if (FDragDropImage.MouseDownOffset.X>FDragDropImage.Width) then FDragDropImage.MouseDownOffset := PointF((FDragDropImage.Width / 2)+8,FDragDropImage.MouseDownOffset.Y); if (FDragDropImage.MouseDownOffset.Y>FDragDropImage.Height) then FDragDropImage.MouseDownOffset := PointF(FDragDropImage.MouseDownOffset.X,(FDragDropImage.Height / 2)+8); ScreenMousePos := LocalToScreen(PointF(x, y)); FormMousePos := TForm(FDragDropImage.Parent).ScreenToClient(ScreenMousePos); FDragDropImage.SetBounds(FormMousePos.X - FDragDropImage.MouseDownOffset.X, FormMousePos.Y - FDragDropImage.MouseDownOffset.Y + GetStartOffsetY, FDragDropImage.Width, FDragDropImage.Height); Invalidate; end; procedure TksTableView.DoDropScroll; var MinHeight : Single; MaxHeight : Single; begin if (FMouseCurrentPos.Y<0) then begin FScrolling := false; FScrollPos := FScrollPos - (GetScreenScale * (0-FMouseCurrentPos.Y)); MinHeight := GetStartOffsetY; if (FScrollPos<MinHeight) then FScrollPos := MinHeight; Repaint; end else if (FMouseCurrentPos.Y>Height) then begin FScrolling := false; FScrollPos := FScrollPos + (GetScreenScale * (FMouseCurrentPos.Y-Height)); MaxHeight := Max((GetTotalItemHeight - Height) + GetStartOffsetY, 0); if (FScrollPos>MaxHeight) then FScrollPos := MaxHeight; Repaint; end; end; function TksTableView.GetItemFromPos(AXPos,AYPos: single): TksTableViewItem; var ICount: integer; JCount: integer; AFiltered: TksTableViewItems; AItem: TksTableViewItem; begin Result := nil; AFiltered := FFilteredItems; for ICount := 0 to AFiltered.Count - 1 do begin AItem := AFiltered[ICount]; if (AItem.IsStickyHeader) then begin if PtInRect(RectF(0,0,AItem.ItemRect.Width,AItem.ItemRect.Height), PointF(AXPos,AYPos)) then begin Result := AItem; // Check for clicking on Header over Sticky Header for JCount := ICount+1 to AFiltered.Count - 1 do begin AItem := AFiltered[JCount]; if (AItem.Purpose=Header) then begin if PtInRect(AItem.ItemRect, PointF(AXPos, (AYPos + FScrollPos))) then begin Result := AItem; Exit; end; end; end; Exit; end; end else begin if PtInRect(AItem.ItemRect, PointF(AXPos, (AYPos + FScrollPos))) then begin Result := AItem; Exit; end; end; end; end; function TksTableView.GetMouseDownBox: TRectF; var pt: TPointF; v: single; begin v := C_TABlEVIEW_SCROLL_THRESHOLD; pt := FMouseDownPoint; Result := RectF(pt.x - v, pt.y - v, pt.x + v, pt.y + v); end; function TksTableView.GetSearchHeight: single; begin Result := 0; if FSearchVisible then Result := FSearchBox.Height; end; function TksTableView.GetSearchText: string; begin Result := FSearchBox.Text; end; function TksTableView.GetFixedHeaderHeight: single; var I : Integer; begin if (Items.Count>0) then begin Result := 0; //Items[0].FItemRect.Top {- GetSearchHeight}; for I:=0 to Min(FFixedRowOptions.FHeaderCount,Items.Count)-1 do Result := Result + Items[I].FItemRect.Height; end else Result := 0; end; function TksTableView.GetCachedCount: integer; //var // ICount: integer; begin {Result := 0; for ICount := 0 to FItems.Count-1 do if FItems[ICount].Cached then Result := Result + 1; } Result := FItems.CachedCount; end; function TksTableView.GetFixedFooterHeight: single; var ICount : Integer; begin ICount := Max(0,Items.Count-FFixedRowOptions.FFooterCount); if (ICount<Items.Count) then Result := Height - Items[ICount].FItemRect.Top else Result := 0; end; function TksTableView.GetStartOffsetY: single; begin Result := GetSearchHeight + GetFixedHeaderHeight; end; function TksTableView.GetSelectedItem: TksTableViewItem; begin Result := nil; if FItemIndex > -1 then Result := FilteredItems[FItemIndex]; end; function TksTableView.GetTopItem: TksTableViewItem; var ICount: integer; AViewport: TRectF; AItems: TksTableViewItems; begin Result := nil; AViewport := ViewPort; AItems := FFilteredItems; for ICount := 0 to AItems.Count - 1 do begin if AItems[ICount].IsVisible(AViewport) then begin Result := AItems[ICount]; Exit; end; end; end; function TksTableView.GetTotalItemHeight: single; begin Result := FFilteredItems.GetTotalItemHeight; end; function TksTableView.GetViewPort: TRectF; begin Result := RectF(0, 0, Width, Height); OffsetRect(Result, 0, FScrollPos); end; function TksTableView.GetVisibleItems: TList<TksTableViewItem>; var ICount: integer; ATopItem: TksTableViewItem; AViewport: TRectF; begin Result := TList<TksTableViewItem>.Create; ATopItem := TopItem; if ATopItem = nil then Exit; AViewport := ViewPort; for ICount := ATopItem.Index to FItems.Count - 1 do begin if Items[ICount].IsVisible(AViewport) then Result.Add(Items[ICount]) else Break; end; end; procedure TksTableView.HideFocusedControl; var AParent: TFmxObject; begin if FFocusedControl <> nil then begin FFocusedControl.HideControl; FFocusedControl := nil; AParent := Parent; while AParent <> nil do begin if (AParent is TForm) then begin (AParent as TForm).Focused := nil; Break; end; AParent := AParent.Parent; end; end; end; procedure TksTableView.Invalidate; begin InvalidateRect(LocalRect); end; function TksTableView.IsHeader(AItem: TksTableViewItem): Boolean; begin Result := False; if AItem <> nil then Result := AItem.Purpose = TksTableViewItemPurpose.Header; end; procedure TksTableView.KeyDown(var Key: Word; var KeyChar: WideChar; Shift: TShiftState); begin inherited; if Key = vkUp then ScrollTo(ScrollViewPos-ItemHeight); if Key = vkDown then ScrollTo(ScrollViewPos+ItemHeight); if Key = vkHome then ScrollTo(0); if Key = vkEnd then ScrollTo(FMaxScrollPos); if Key = vkPrior then ScrollTo(ScrollViewPos-Height); if Key = vkNext then ScrollTo(ScrollViewPos+Height); end; procedure TksTableView.KillAllTimers; begin KillTimer(FSelectTimer); KillTimer(FDeselectTimer); end; procedure TksTableView.KillTimer(var ATimer: TFmxHandle); begin if FTimerService <> nil then begin if (ATimer<>0) then begin FTimerService.DestroyTimer(ATimer); ATimer := 0; end; end; end; procedure TksTableView.MouseDown(Button: TMouseButton; Shift: TShiftState; x, y: single); //var // AConsumesClick: Boolean; begin if (UpdateCount > 0) or (FMouseEventsEnabledCounter > 0) then Exit; y := y - GetStartOffsetY; inherited; if (FUpdateCount > 0) or (AIsSwiping) then Exit; //if (Root is TCommonCustomForm) then // (Root as TCommonCustomForm).Focused := nil; //Capture; FMouseDownObject := nil; FMouseDown := True; FSwipeDirection := ksSwipeUnknown; FMouseDownPoint := PointF(x, y); FMouseCurrentPos := FMouseDownPoint; FAniCalc.MouseDown(x, y); FMouseDownItem := GetItemFromPos(x,y); if FMouseDownItem <> nil then begin FMouseDownObject := FMouseDownItem.ObjectAtPos(x, y + FScrollPos); if (FMouseDownObject <> FFocusedControl) and (FFocusedControl <> nil) then HideFocusedControl; if (FMouseDownObject <> nil) then begin //AConsumesClick := FMouseDownObject.ConsumesClick; FMouseDownItem.DoClick(FMouseDownPoint.x, (FMouseDownPoint.y - FMouseDownItem.ItemRect.Top) + ScrollViewPos); if (Assigned(FItemClickEvent)) and (FMouseDownObject.ConsumesClick = False) then FItemClickEvent(Self, FMouseDownPoint.X, FMouseDownPoint.Y, FMouseDownItem, FMouseDownItem.ID, FMouseDownObject); Exit; //if FMouseDownObject.ConsumesClick then // Exit; end; if FMouseDownItem = nil then Exit; if (FMouseDownItem.Purpose=Header) then begin if (FMouseDownItem.IsStickyHeader) and ((FHeaderOptions.StickyHeaders.Button.Visible)) then begin if (PtInRect(FStickyButtonRect, PointF(FMouseDownPoint.x,FMouseDownPoint.y + GetStartOffsetY))) then begin FHeaderOptions.StickyHeaders.Button.DoButtonClicked(Self, FMouseDownItem); exit; end; end; if (FCheckMarkOptions.FCheckMarks <> cmNone) then begin if (FMouseDownItem.CheckMarkClicked(FMouseDownPoint.x,FMouseDownPoint.y - FMouseDownItem.ItemRect.Top + ScrollViewPos)) then begin FMouseDownItem.Checked := not FMouseDownItem.Checked; exit; end; end; end; if (FMouseDownItem.Purpose = None) then begin KillTimer(FSelectTimer); FSelectTimer := CreateTimer(200, DoSelectTimer); end; end; end; procedure TksTableView.MouseMove(Shift: TShiftState; x, y: single); var AMouseDownRect: TRectF; ADragOverItem : TksTableViewItem; //AAllowDrop : Boolean; //I : Integer; begin if (UpdateCount > 0) or (FMouseEventsEnabledCounter > 0) then Exit; y := y - GetStartOffsetY; FMouseCurrentPos := PointF(x, y); inherited; if FDragging then begin ADragOverItem := GetItemFromPos(x, y); if ADragOverItem <> FMouseDownItem then FDragOverItem := ADragOverItem; // live moving is causing index problems... need to re-work this code. {if (FDragDropOptions.FLiveMoving) and (ADragOverItem<>Nil) and (ADragOverItem<>FMouseDownItem) then begin for I:=FItems.IndexOf(ADragOverItem) downto 1 do begin if (Items[I].Purpose<>TksTableViewItemPurpose.Header) then break; ADragOverItem := Items[I-1]; end; AAllowDrop := (ADragOverItem=Nil) or (ADragOverItem.Purpose<>TksTableViewItemPurpose.Header); if (Assigned(FOnCanDropItem)) then FOnCanDropItem(Self, FMouseDownItem, ADragOverItem, AAllowDrop); if (AAllowDrop) and (ADragOverItem<>Nil) then begin FMouseDownItem.Appearance := ADragOverItem.Appearance; FMouseDownItem.Height := ADragOverItem.Height; FItems.Move(FItems.IndexOf(FMouseDownItem), FItems.IndexOf(ADragOverItem)); UpdateAll(true); RedrawAllVisibleItems; end; end; } UpdateDropImage(FMouseCurrentPos.X+8, FMouseCurrentPos.Y+8); Exit; end; AMouseDownRect := GetMouseDownBox; if (ssLeft in Shift) and (PtInRect(AMouseDownRect, PointF(x, y)) = False) and (FSwipeDirection = ksSwipeUnknown) then begin FScrolling := True; if FSwipeDirection = ksSwipeUnknown then begin KillTimer(FSelectTimer); FSelectTimer := 0; if x < AMouseDownRect.Left then FSwipeDirection := ksSwipeRightToLeft; if x > AMouseDownRect.Right then FSwipeDirection := ksSwipeLeftToRight; if y < AMouseDownRect.Top then FSwipeDirection := ksSwipeBottomToTop; if y > AMouseDownRect.Bottom then FSwipeDirection := ksSwipeTopToBottom; FAniCalc.MouseDown(x, y); end; end; if FSwipeDirection = ksSwipeUnknown then Exit; if (FSwipeDirection in [ksSwipeLeftToRight, ksSwipeRightToLeft]) and (FMouseDownItem <> nil) then begin if (FSwipeDirection <> TksSwipeDirection.ksSwipeUnknown) and (not FMouseDownItem.IsHeader) then FMouseDownItem.DoSwipe(FSwipeDirection); Exit; end; if FSwipeDirection in [ksSwipeTopToBottom, ksSwipeBottomToTop] then x := FMouseDownPoint.x; if (FScrolling) and (ssLeft in Shift) then FAniCalc.MouseMove(x, y); end; procedure TksTableView.MouseUp(Button: TMouseButton; Shift: TShiftState; x, y: single); var ACanDrop: Boolean; AAllowMove: Boolean; Form: TCustomForm; begin y := y - GetStartOffsetY; AAllowMove := True; if (UpdateCount > 0) or (FMouseEventsEnabledCounter > 0) then Exit; inherited; if (FDragging) then begin Form := TCustomForm(Root.GetObject); Form.RemoveObject(FDragDropImage); FreeAndNil(FDragDropImage); FDragDropImage := nil; KillTimer(FDragDropScrollTimer); ReleaseCapture; //ADragOverItem := GetItemFromPos(x, y); if (Assigned(FOnDropItem)) and (FDragOverItem <> nil) then begin ACanDrop := True; if Assigned(FOnCanDropItem) then FOnCanDropItem(Self, FMouseDownItem, FDragOverItem, ACanDrop); if ACanDrop then begin FOnDropItem(Self,FMouseDownItem, FDragOverItem, AAllowMove); if AAllowMove then begin // move the drag row to the new position... FItems.Move(FMouseDownItem.Index, FDragOverItem.Index); UpdateAll(True); RedrawAllVisibleItems; end; end; end; FDragging := False; if FMouseDownItem <> nil then FMouseDownItem.FDragging := False; Invalidate; Exit; end; if PtInRect(GetMouseDownBox, PointF(x,y)) then begin if FSelectTimer <> 0 then begin if (FMouseDownObject = nil) or (FMouseDownObject.ConsumesClick = False) then DoSelectItem; end; end; if FScrolling then FAniCalc.MouseUp(x, y); FAniCalc.BoundsAnimation := True; FMouseDown := False; if (FItemIndex > -1) and (FSelectionOptions.FKeepSelection = False) then DeselectItem(FSelectionOptions.SelectDuration); if (FMouseDownObject <> nil) and (FScrolling = False) then FMouseDownObject.MouseUp(x, y); end; procedure TksTableView.MouseWheel(Shift: TShiftState; WheelDelta: Integer; var Handled: Boolean); var Offset: Single; ANewPos: single; begin inherited; if (csDesigning in ComponentState) then Exit; if (not Handled) then begin if not (ssHorizontal in Shift) then begin HideFocusedControl; // <------ ADD THIS LINE FAniCalc.UpdatePosImmediately; Offset := Height / 14; Offset := Offset * -1 * (WheelDelta / 120); ANewPos := Max(ScrollViewPos + Offset, 0); ANewPos := Min(ANewPos, (FMaxScrollPos)); ScrollTo(Floor(ANewPos)); Handled := True; end end; end; procedure TksTableView.Paint; var ICount: integer; AItems: TksTableViewItems; AViewport: TRectF; AItem: TksTableViewItem; ARect: TRectF; ASelectedRect: TRectF; ATop: single; sh: single; SaveState : TCanvasSaveState; SaveState2 : TCanvasSaveState; SaveStatePullRefresh: TCanvasSaveState; AStickyHeaderBottom: Single; begin inherited; if not FPainting then begin SaveState := nil; SaveState2 := nil; AStickyHeaderBottom := 0; FPainting := True; try sh := GetSearchHeight; if (sh > 0) then begin SaveState := Canvas.SaveState; Canvas.IntersectClipRect (RectF(0, sh, Width, Height)); end; if (Assigned(OnBeforePaint)) then OnBeforePaint(Self,Canvas); if FAppearence.Background <> nil then Canvas.Fill.Assign(FAppearence.Background); Canvas.FillRect(RectF(0, 0, Width, Height), 0, 0, AllCorners, 1); if (csDesigning in ComponentState) and (FBorder.Showing = False) then begin DrawDesignBorder(claDimgray, claDimgray); end; if (FPullToRefresh.Enabled) and (Trunc(ScrollViewPos) < 0) then begin SaveStatePullRefresh := Canvas.SaveState; try Canvas.Stroke.Thickness := 1/(GetScreenScale*2); Canvas.Stroke.Color := claDimgray; if IsHeader(Items.FirstItem) = False then Canvas.DrawLine(PointF(0, (0-ScrollViewPos)+sh), PointF(Width, (0-ScrollViewPos)+sh), 1); Canvas.IntersectClipRect (RectF(0, 0, Width, (0-ScrollViewPos)+sh)); // pull to refresh... if (FMouseDown) then FNeedsRefresh := (ScrollViewPos <= -50); Canvas.Fill.Color := FPullToRefresh.TextColor; Canvas.Font.Size := 16; if (FNeedsRefresh) and (ScrollViewPos <= -25) then begin Canvas.FillText(RectF(0, sh, Width, sh+50), FPullToRefresh.FReleaseText, False, 1, [], TTextAlign.Center); FNeedsRefresh := True; end else Canvas.FillText(RectF(0, sh+0, Width, sh+50), FPullToRefresh.FPullText, False, 1, [], TTextAlign.Center); finally Canvas.RestoreState(SaveStatePullRefresh); end; end; AItems := FilteredItems; AViewport := ViewPort; for ICount := 0 to Min(FFixedRowOptions.FHeaderCount,Items.Count) - 1 do if (Items[ICount].ItemRect.Height>0) then Items[ICount].Render(Canvas, GetFixedHeaderHeight); if (FFixedRowOptions.FHeaderCount>0) or (FFixedRowOptions.FFooterCount>0) then begin SaveState2 := Canvas.SaveState; Canvas.IntersectClipRect (RectF(0, GetStartOffsetY, Width, Height - GetFixedFooterHeight)); end; for ICount := 0 to AItems.Count - 1 do begin AItem := AItems[ICount]; if (AItem.IsVisible(AViewport)) then AItem.Render(Canvas, AViewport.Top); end; if (FHeaderOptions.StickyHeaders.Enabled) then begin for ICount := 0 to AItems.Count -1 do begin AItem := AItems[ICount]; if (AItem.Purpose = Header) then begin if AItem.ItemRect.Top < (AViewport.Top) then ATop := Round(AItem.ItemRect.Top) else ATop := AViewport.Top; ARect := AItem.Render(Canvas, ATop); if (AItem.IsStickyHeader) then begin AStickyHeaderBottom := ARect.Bottom; if ((FHeaderOptions.StickyHeaders.Button.Visible)) then begin FStickyButtonRect := RectF(ARect.Right - ARect.Height - 4, ARect.Top, ARect.Right -4, ARect.Bottom); InflateRect(FStickyButtonRect, -1, -1); if (AItem.Accessory.Visible) and (AItem.Accessory.Accessory <> atNone) then OffsetRect(FStickyButtonRect, -32, 0); if (FCheckMarkOptions.FCheckMarks <> cmNone) and (FCheckMarkOptions.FPosition = cmpRight) and (AItem.FCheckmarkAllowed) then OffsetRect(FStickyButtonRect, -(AItem.FCheckMarkAccessory.Width + 8) , 0); if (SelectionOptions.FSelectionOverlay.FEnabled) then OffsetRect(FStickyButtonRect,-(SelectionOptions.FSelectionOverlay.Stroke.Thickness/2),0); // draw the sticky button... case FHeaderOptions.StickyHeaders.Button.Selected of True: AccessoryImages.DrawAccessory(Canvas, FStickyButtonRect, TksAccessoryType.atArrowDown, claBlack, FAppearence.SelectedColor); False: AccessoryImages.DrawAccessory(Canvas, FStickyButtonRect, TksAccessoryType.atArrowDown, claNull, claNull); end; end; end; end; end; end; if (FFixedRowOptions.FHeaderCount>0) or (FFixedRowOptions.FFooterCount>0) then Canvas.RestoreState(SaveState2); for ICount := Max(0,Items.Count-FFixedRowOptions.FooterCount) to Items.Count - 1 do if (Items[ICount].ItemRect.Height>0) then Items[ICount].Render(Canvas, GetFixedHeaderHeight); if (FSelectionOptions.SelectionOverlay.Enabled) then begin Canvas.Stroke.Assign(FSelectionOptions.SelectionOverlay.Stroke); case FSelectionOptions.SelectionOverlay.Position of ksSelectorLeft: Canvas.DrawLine(PointF(0, 0), PointF(0, Height), 1); ksSelectorRight: Canvas.DrawLine(PointF(Width, 0), PointF(Width, Height), 1); end; if SelectedItem <> nil then begin ASelectedRect := SelectedItem.ItemRect; OffsetRect(ASelectedRect, 0, (0-ScrollViewPos)+GetStartOffsetY); FSelectionOptions.SelectionOverlay.DrawToCanvas(Canvas, ASelectedRect, AStickyHeaderBottom, Height-GetFixedFooterHeight); end; end; if (FBackgroundText.Enabled) and (AItems.Count = 0) then begin if FBackgroundText.Text <> '' then begin Canvas.Font.Assign(FBackgroundText.Font); Canvas.Fill.Color := FBackgroundText.TextColor; Canvas.Fill.Kind := TBrushKind.Solid; ARect := LocalRect; if ScrollViewPos < 0 then OffsetRect(ARect, 0, 0-ScrollViewPos); Canvas.FillText(ARect, FBackgroundText.Text, False, 1, [], TTextAlign.Center); end; end; if (Assigned(OnAfterPaint)) then OnAfterPaint(Self,Canvas); if (sh>0) then Canvas.RestoreState(SaveState); if FBorder.Showing then begin Canvas.Stroke.Assign(FBorder.Stroke); Canvas.DrawRectSides(RectF(0, 0, Width, Height), 0, 0, AllCorners, 1, FBorder.Sides); end; finally FPainting := False; end; end; end; procedure TksTableView.RedrawAllVisibleItems; var AList: TList<TksTableViewItem>; ICount: integer; begin AList := GetVisibleItems; try for ICount := 0 to Items.Count-1 do Items[ICount].FCached := False; for ICount := 0 to AList.Count-1 do AList[ICount].CacheItem(True); Invalidate; finally AList.Free; end; end; procedure TksTableView.ClearCache(AClearType: TksClearCacheType); var ICount: integer; AVisible: TList<TksTableViewItem>; begin if AClearType = ksClearCacheAll then begin for ICount := 0 to Items.Count-1 do Items[ICount].ClearCache; end else begin if FItems.Count <= C_TABLEVIEW_PAGE_SIZE then Exit; AVisible := VisibleItems; try for ICount := 0 to Items.Count-1 do if AVisible.IndexOf(Items[ICount]) = -1 then Items[ICount].ClearCache; finally AVisible.Free; end; end; end; procedure TksTableView.CheckChildren(AHeader: TksTableViewItem ; Value : Boolean); var I,J : Integer; AItem: TksTableViewItem; begin for I := 0 to FilteredItems.Count-1 do begin AItem := FilteredItems[I]; if (AItem=AHeader) then begin for J:=I+1 to FilteredItems.Count-1 do begin AItem := FilteredItems[J]; if (AItem.Purpose=Header) then break; AItem.Checked := Value; end; break; end; end; end; procedure TksTableView.UncheckHeader(AChild: TksTableViewItem); var AIndex: integer; ICount: integer; begin AIndex := FilteredItems.IndexOf(AChild); for ICount := AIndex downto 0 do begin if FilteredItems[ICount].Purpose = Header then begin FilteredItems[ICount].Checked := False; FilteredItems[ICount].CacheItem(True); Invalidate; Exit; end; end; end; procedure TksTableView.BringSelectedIntoView; begin ScrollToItem(SelectedItem); end; procedure TksTableView.ScrollToItem(AItem: TksTableViewItem; const AAnimate: Boolean = False); var AMinHeight : Single; AMaxHeight : Single; ANewScrollViewPos : Single; begin if AItem = nil then Exit; FAniCalc.UpdatePosImmediately; //CreateAniCalculator(False); ANewScrollViewPos := FScrollPos; AMinHeight := 0; if (FStickyHeader <> nil) then AMinHeight := FStickyHeader.FHeaderHeight; if (AItem.ItemRect.Top - ANewScrollViewPos < AMinHeight) then ANewScrollViewPos := AItem.ItemRect.Top - AMinHeight; AMaxHeight := Height - GetFixedFooterHeight - GetFixedHeaderHeight; if (AItem.ItemRect.Bottom - ANewScrollViewPos > AMaxHeight) then ANewScrollViewPos := AItem.ItemRect.Bottom - AMaxHeight; if (ANewScrollViewPos <> FScrollPos) then SetScrollViewPos(ANewScrollViewPos, AAnimate); UpdateScrollingLimits; end; procedure TksTableView.ResetIndicatorWidths; var ICount: integer; begin BeginUpdate; try for Icount := 0 to Items.Count-1 do begin if Items[ICount].FIndicator.Width <> RowIndicators.Width then begin Items[ICount].FIndicator.Width := RowIndicators.Width; Items[ICount].FForegroundColor := claNull; Items[ICount].FCached := False; end; end; finally EndUpdate; end; end; procedure TksTableView.Resize; begin inherited; if FItems.Count = 0 then Exit; if FUpdateCount > 0 then Exit; HideFocusedControl; UpdateItemRects(False); UpdateScrollingLimits; ClearCache(ksClearCacheAll); if (FSelectionOptions.FKeepSelectedInView) then BringSelectedIntoView; end; {$IFDEF XE10_OR_NEWER} procedure TksTableView.VisibleChanged; begin inherited; ClearCache(ksClearCacheAll); end; {$ENDIF} procedure TksTableView.SearchSetFocus; begin if FSearchVisible then FSearchBox.SetFocus; end; procedure TksTableView.SelectDate(ARow: TksTableViewItem; ASelected: TDateTime; AOnSelectDate: TNotifyEvent); begin if FDateSelector = nil then begin FDateSelector := TDateEdit.Create(nil); FDateSelector.OnClosePicker := ComboClosePopup; end; FDateSelector.Position.X := ARow.ItemRect.Right - 100; FDateSelector.Position.Y := ARow.ItemRect.Top; FDateSelector.OnChange := nil; FDateSelector.TagObject := ARow; FDateSelector.Width := 0; {$IFDEF MSWINDOWS} FDateSelector.Width := 200; {$ENDIF} AddObject(FDateSelector); FDateSelector.Date := ASelected; FDateSelector.OnChange := AOnSelectDate; FDateSelector.OpenPicker; end; procedure TksTableView.SelectItem(ARow: TksTableViewItem; AItems: TStrings; ASelected: string; AOnSelectItem: TNotifyEvent); begin //if FCombo <> nil then // FCombo.DisposeOf; if FCombo = nil then begin FCombo := TComboBox.Create(nil); FCombo.OnClosePopup := ComboClosePopup; FCombo.Visible := False; AddObject(FCombo); end; FCombo.OnChange := nil; //FCombo.Position.X := ARow.ItemRect.Right - 100; FCombo.Position.Y := ARow.ItemRect.Top; FCombo.TagObject := ARow; FCombo.Items.Assign(AItems); FCombo.ItemIndex := AItems.IndexOf(ASelected); FCombo.Width := 0; {$IFDEF MSWINDOWS} FCombo.Width := 200; {$ENDIF} FCombo.OnChange := AOnSelectItem; FCombo.DropDown; end; procedure TksTableView.SetAccessoryOptions(const Value: TksTableViewAccessoryOptions); begin FAccessoryOptions.Assign(Value); end; procedure TksTableView.SetAppearence(const Value: TksTableViewAppearence); begin FAppearence.Assign(Value); end; procedure TksTableView.SetBackgroundText(const Value: TksTableViewBackgroundText); begin BackgroundText.Assign(Value); end; procedure TksTableView.SetBorder(const Value: TksTableViewBorderOptions); begin FBorder.Assign(Value); end; procedure TksTableView.SetFixedRowOptions(const Value: TksTableViewFixedRowsOptions); begin FFixedRowOptions.Assign(Value); end; procedure TksTableView.SetCheckMarkOptions(const Value: TksTableViewCheckMarkOptions); begin FCheckMarkOptions.Assign(Value); end; procedure TksTableView.SetFullWidthSeparator(const Value: Boolean); begin FFullWidthSeparator := Value; Invalidate; end; procedure TksTableView.SetHeaderOptions(const Value: TksTableViewItemHeaderOptions); begin FHeaderOptions.Assign(Value); end; procedure TksTableView.SetItemImageSize(const Value: integer); begin FItemImageSize := Value; end; procedure TksTableView.SetItemIndex(const Value: integer); var ASelected: TksTableViewItem; ANewSelected: TksTableViewItem; begin if (Value < 0) or (Value > Items.Count-1) then Exit; if Value <> FItemIndex then begin ASelected := SelectedItem; FItemIndex := Value; ANewSelected := SelectedItem; if (FSelectionOptions.KeepSelectedInView) then BringSelectedIntoView; if FSelectionOptions.ShowSelection then begin if ASelected <> nil then begin ASelected.CacheItem(True); end; if ANewSelected <> nil then ANewSelected.CacheItem(True); end; Invalidate; ProcessMessages; if FMouseDown = False then begin if (FSelectionOptions.KeepSelection = False) and (FItemIndex > -1) then DeselectItem(250); end; end; end; procedure TksTableView.SetColCount(const Value: integer); begin if FColCount <> Value then begin FColCount := Value; ClearCache(ksClearCacheAll); UpdateAll(False); Invalidate; end; end; procedure TksTableView.SetKsItemHeight(const Value: integer); begin FItemHeight := Value; end; procedure TksTableView.SetPullToRefresh(const Value: TksTableViewPullToRefresh); begin if Value <> nil then FPullToRefresh.Assign(Value); end; procedure TksTableView.UpdateStickyHeaders; var ICount: integer; AItem: TksTableViewItem; ANextStickyHeaderHeight: single; ANeedsRecalc: Boolean; AViewportTop: single; ALastStickyHeader: TksTableViewItem; begin if FUpdateCount > 0 then Exit; if (FHeaderOptions.StickyHeaders.Enabled) and (FHeaderOptions.StickyHeaders.StickyHeight > 0) and (FilteredItems.Count > 0) then begin ANeedsRecalc := false; AViewportTop := Viewport.Top; ALastStickyHeader := FStickyHeader; FStickyHeader := Nil; if (AViewportTop<0) then AViewportTop := 0; for ICount := 0 to FilteredItems.Count-1 do begin AItem := FilteredItems[ICount]; if (AItem.Purpose = Header) then begin AItem.FIsStickyHeader := AItem.ItemRect.Top <= AViewportTop; if (AItem.FIsStickyHeader) then begin // is sticky header... FStickyHeader := AItem; if (AItem.FHeaderHeight <> FHeaderOptions.StickyHeaders.StickyHeight) then begin AItem.FHeaderHeight := FHeaderOptions.StickyHeaders.StickyHeight; ANeedsRecalc := true; end; end else if (AItem.ItemRect.Top <= (AViewportTop+FHeaderOptions.StickyHeaders.StickyHeight)) then begin ANextStickyHeaderHeight := Max(AItem.Height,(AViewportTop+FHeaderOptions.StickyHeaders.StickyHeight) - AItem.ItemRect.Top); if (AItem.FHeaderHeight <> ANextStickyHeaderHeight) then begin AItem.FHeaderHeight := ANextStickyHeaderHeight; ANeedsRecalc := true; end; end else begin if (AItem.FHeaderHeight<>0) then begin AItem.FHeaderHeight := 0; ANeedsRecalc := true; end; end; end; end; if (ANeedsRecalc) then begin UpdateItemRects(False); UpdateScrollingLimits; end; if (Assigned(FOnStickyHeaderChange)) and (ALastStickyHeader<>FStickyHeader) then FOnStickyHeaderChange(Self,ALastStickyHeader,FStickyHeader); end; end; procedure TksTableView.SetScrollViewPos(const Value: single; const AAnimate: Boolean = False); var ICount: integer; AStep: single; begin if not SameValue(FScrollPos, Value, TEpsilon.Vector) then begin HideFocusedControl; FActionButtons.HideButtons; if CachedCount > C_TABLEVIEW_PAGE_SIZE then ClearCache(ksClearCacheNonVisible); AStep := (Value - FScrollPos) / 20; if AAnimate then begin for ICount := 1 to 20 do begin FScrollPos := FScrollPos + AStep; UpdateStickyHeaders; Invalidate; {$IFDEF MSWINDOWS} Sleep(5); {$ENDIF} ProcessMessages; end; end else begin FScrollPos := Value; UpdateStickyHeaders; //IRepaint; Invalidate; end; if (Round(FScrollPos) = 0) and (FNeedsRefresh) then begin ProcessMessages; FNeedsRefresh := False; DisableMouseEvents; DoPullToRefresh; FAniCalc.UpdatePosImmediately; EnableMouseEvents; end; if Assigned(FOnScrollViewChange) then FOnScrollViewChange(Self, FScrollPos, FMaxScrollPos); end; end; procedure TksTableView.ScrollTo(const Value: single); var ANewValue: single; begin ANewValue := Value; if ANewValue < 0 then ANewValue := 0; if ANewValue > FMaxScrollPos then ANewValue := FMaxScrollPos; if ((ANewValue-Height) < FMaxScrollPos) and (ANewValue >= 0) then begin FScrollPos := ANewValue; SetScrollViewPos(ANewValue); UpdateScrollingLimits; Invalidate; end; end; procedure TksTableView.ScrollToItem(AItemIndex: integer); begin if (AItemIndex > -1) and (AItemIndex < FFilteredItems.Count) then ScrollToItem(FFilteredItems.Items[AItemIndex]); end; procedure TksTableView.SetSearchText(const Value: string); begin FSearchBox.Text := Value; end; procedure TksTableView.SetSearchVisible(const Value: Boolean); var AScrollPos: single; begin if Value <> FSearchVisible then begin AScrollPos := ScrollViewPos; FSearchVisible := Value; FSearchBox.Visible := FSearchVisible; UpdateScrollingLimits; TAnimator.AnimateFloatWait(Self, 'ScrollPos', AScrollPos); UpdateItemRects(True); Invalidate; end; end; procedure TksTableView.SetSelectionOptions(const Value: TksTableViewSelectionOptions); begin FSelectionOptions.Assign(Value); end; procedure TksTableView.SetTextDefaults(const Value: TksTableViewTextDefaults); begin FTextDefaults.Assign(Value); end; // ------------------------------------------------------------------------------ { TksTableViewBackgroundText } constructor TksTableViewBackgroundText.Create; begin inherited Create; FFont := TFont.Create; FFont.Size := 18; FTextColor := claSilver; FText := ''; FEnabled := True; end; destructor TksTableViewBackgroundText.Destroy; begin FreeAndNil(FFont); inherited; end; procedure TksTableViewBackgroundText.Assign(ASource: TPersistent); var Src : TksTableViewBackgroundText; begin if (ASource is TksTableViewBackgroundText) then begin Src := TksTableViewBackgroundText(ASource); FFont.Assign(Src.FFont); FTextColor := Src.FTextColor; FText := Src.FText; FEnabled := Src.FEnabled; end else inherited; end; procedure TksTableViewBackgroundText.SetFont(const Value: TFont); begin FFont.Assign(FFont); end; procedure TksTableViewBackgroundText.SetText(const Value: string); begin FText := Value; end; procedure TksTableViewBackgroundText.SetTextColor(const Value: TAlphaColor); begin FTextColor := Value; end; procedure TksTableViewBackgroundText.SetEnabled(const Value: Boolean); begin FEnabled := Value; end; // ------------------------------------------------------------------------------ { TksTableViewBaseItemShape } constructor TksTableViewBaseItemShape.Create(ATableItem: TksTableViewItem); begin inherited; FFill := TBrush.Create(TBrushKind.Solid, claWhite); FStroke := TStrokeBrush.Create(TBrushKind.Solid, claBlack); FCornerRadius := 0; FShape := ksRectangle; end; destructor TksTableViewBaseItemShape.Destroy; begin FreeAndNil(FFill); FreeAndNil(FStroke); inherited; end; procedure TksTableViewBaseItemShape.Render(AItemRect: TRectF; ACanvas: TCanvas); var ARect: TRectF; AShadowWidth: single; ABmp: TBitmap; begin inherited; if (Width = 0) or (Height = 0) then Exit; ABmp := TBitmap.Create; try AShadowWidth := 0; if (FTableItem.FTableView.RowIndicators.Shadow) and (Self = FTableItem.FIndicator) then AShadowWidth := 2; ABmp.SetSize(Round(Width * GetScreenScale), Round(Height * GetScreenScale)); //ABmp.BitmapScale := GetScreenScale; ABmp.Clear(claNull); ABmp.Canvas.BeginScene; try ARect := RectF(0, 0, (ABmp.Width {/ GetScreenScale}) - AShadowWidth, (ABmp.Height {/ GetScreenScale}) - AShadowWidth); if AShadowWidth > 0 then begin OffsetRect(ARect, AShadowWidth, AShadowWidth); ABmp.Canvas.Fill.Color := claDimgray; if FShape = ksEllipse then ABmp.Canvas.FillEllipse(ARect, 1) else ABmp.Canvas.FillRect(ARect, FCornerRadius, FCornerRadius, AllCorners, 1); OffsetRect(ARect, 0-AShadowWidth, 0-AShadowWidth); end; ABmp.Canvas.Fill.Assign(FFill); ABmp.Canvas.Stroke.Assign(FStroke); ABmp.Canvas.StrokeThickness := 1; FFill.Color := FFill.Color; if FShape in [ksRectangle, ksRoundRect, ksSquare] then begin if FFill.Color <> claNull then ABmp.Canvas.FillRect(ARect, FCornerRadius, FCornerRadius, AllCorners, 1); ABmp.Canvas.DrawRect(ARect, FCornerRadius, FCornerRadius, AllCorners, 1); end; if FShape = ksEllipse then begin if FFill.Color <> claNull then ABmp.Canvas.FillEllipse(ARect, 1); ABmp.Canvas.DrawEllipse(ARect, 1); end; finally ABmp.Canvas.EndScene; end; ACanvas.DrawBitmap(ABmp, RectF(0, 0, ABmp.Width, ABmp.Height), ObjectRect, 1, False); ACanvas.Stroke.Color := clablack; finally ABmp.Free; end; inherited; end; procedure TksTableViewBaseItemShape.SetCornerRadius(const Value: single); begin FCornerRadius := Value; end; procedure TksTableViewBaseItemShape.SetFill(const Value: TBrush); begin FFill.Assign(Value); end; procedure TksTableViewBaseItemShape.SetShape(const Value: TksTableViewShape); begin FShape := Value; if FShape = ksSquare then begin if FWidth <> FHeight then FHeight := FWidth; end; end; procedure TksTableViewBaseItemShape.SetStroke(const Value: TStrokeBrush); begin FStroke.Assign(Value); end; // ------------------------------------------------------------------------------ { TksTableViewItemTileBackground } constructor TksTableViewItemTileBackground.Create(ATableItem: TksTableViewItem); begin inherited; FPadding := TBounds.Create(RectF(5,5,5,5)); CornerRadius := 5; Width := 0; Height := 0; Margins.Left := 5; Margins.Top := 5; Margins.Right := 5; Margins.Bottom := 5; end; destructor TksTableViewItemTileBackground.Destroy; begin FreeAndNil(FPadding); inherited; end; procedure TksTableViewItemTileBackground.Assign(ASource: TksTableViewItemTileBackground); begin FPadding.Assign(ASource.FPadding); end; // ------------------------------------------------------------------------------ { TksListViewRowIndicators } procedure TksListViewRowIndicators.Changed; begin FTableView.ClearCache(ksClearCacheAll); FTableView.Invalidate; end; constructor TksListViewRowIndicators.Create(ATableView: TksTableView); begin FTableView := ATableView; FWidth := C_TABLEVIEW_DEFAULT_INDICATOR_WIDTH; FHeight := C_TABLEVIEW_DEFAULT_INDICATOR_HEIGHT; FVisible := False; FShape := TksTableViewShape.ksRectangle; FOutlined := True; FShadow := True; FSelectRow := False; FAlignment := ksRowIndicatorLeft; end; // ------------------------------------------------------------------------------ procedure TksListViewRowIndicators.SetAlignment(const Value: TksTableViewRowIndicatorAlign); begin if FAlignment <> Value then begin FAlignment := Value; FTableView.ClearCache(ksClearCacheAll); FTableView.Invalidate; end; end; procedure TksListViewRowIndicators.SetSelectRow(const Value: Boolean); begin if FSelectRow <> Value then begin FSelectRow := Value; if Value = False then FTableView.ResetIndicatorWidths; Changed; end; end; procedure TksListViewRowIndicators.SetShadow(const Value: Boolean); begin if FShadow <> Value then begin FShadow := Value; FTableView.ClearCache(ksClearCacheAll); FTableView.Invalidate; end; end; procedure TksListViewRowIndicators.SetShape(const Value: TksTableViewShape); begin if FShape <> Value then begin FShape := Value; if FShape = ksRectangle then begin FHeight := 0; FWidth := 8; end; if (FShape = ksSquare) or (FShape = ksEllipse) then begin FWidth := 16; FHeight := 16; end; Changed; end; end; { TksTableViewActionButtons } function TksTableViewActionButtons.AddButton(AText: string; AColor, ATextColor: TAlphaColor; const AIcon: TksAccessoryType = atNone; const AWidth: integer = 60): TksTableViewActionButton; begin Result := TksTableViewActionButton.Create(False); Result.Text := AText; Result.Color := AColor; Result.Width := AWidth; Result.Accessory := AIcon; Result.TextColor := ATextColor; Add(Result); end; function TksTableViewActionButtons.AddDeleteButton: TksTableViewActionButton; var ADelBtn: TksDeleteButton; AAcc: TksAccessoryType; begin Result := nil; AAcc := atNone; ADelBtn := FTableView.DeleteButton; if ADelBtn.Enabled = False then Exit; if ADelBtn.ShowImage then AAcc := atTrash; if FTableView.DeleteButton.ShowText = False then ADelBtn.Text := ''; Result := AddButton(ADelBtn.Text, ADelBtn.Color, ADelBtn.TextColor, AAcc); Result.IsDeleteButton := True; end; function TksTableViewActionButtons.ButtonFromXY(x, y: single): TksTableViewActionButton; var ARect: TRectF; ICount: integer; XPos: single; begin Result := nil; ARect := RectF(0, 0, TotalWidth, FTableItem.Height); if FAlignment = TksTableViewActionButtonAlignment.abRightActionButtons then x := x - (FTableItem.ItemRect.Width - TotalWidth); XPos := 0; for ICount := 0 to Count-1 do begin if (x >= XPos) and (x <= XPos+Items[ICount].Width) then begin Result := Items[ICount]; Exit; end; XPos := XPos + Items[Icount].Width; end; end; constructor TksTableViewActionButtons.Create(AOwner: TksTableView); begin inherited Create(True); FTableView := AOwner; FAlignment := abRightActionButtons; FPercentWidth := 0; FAnimating := False; end; function TksTableViewActionButtons.GetVisible: Boolean; begin Result := FPercentWidth > 0; end; procedure TksTableViewActionButtons.HideButtons; var ICount: integer; begin //Exit; if (Visible = False) or (Count = 0) then Exit; if FAnimating then Exit; FAnimating := True; try for ICount := 100 downto 0 do begin FPercentWidth := ICount; FTableView.Invalidate; {$IFDEF NEXTGEN} if ICount mod 10 = 0 then ProcessMessages; {$ELSE} if ICount mod 2 = 0 then ProcessMessages; {$ENDIF} end; finally FAnimating := False; FTableItem := nil; end; end; procedure TksTableViewActionButtons.Render(ACanvas: TCanvas; ARect: TRectF); var ICount: integer; AXPos: single; ABtnRect: TRectF; AScale: single; begin AXPos := ARect.Left; AScale := ARect.Width / TotalWidth; for ICount := 0 to Count-1 do begin ABtnRect := RectF(AXPos, ARect.Top, AXPos+(Items[ICount].Width * AScale), ARect.Bottom); Items[ICount].Render(ACanvas, ABtnRect);// AXPos, ARect.); AXPos := AXPos + (Items[ICount].Width * AScale); end; end; procedure TksTableViewActionButtons.SetPercentWidth(const Value: integer); begin if PercentWidth <> Value then begin FPercentWidth := Value; FTableItem.FTableView.Invalidate; ProcessMessages; end; end; procedure TksTableViewActionButtons.ShowButtons(AItem: TksTableViewItem); var ICount: integer; begin if (FAnimating) or (Count = 0) then Exit; FTableItem := AItem; FTableView.DisableMouseEvents; FTableView.HideFocusedControl; FAnimating := True; try for ICount := 1 to 100 do begin FPercentWidth := ICount; FTableView.Invalidate; {$IFDEF NEXTGEN} if ICount mod 7 = 0 then ProcessMessages; {$ELSE} ProcessMessages; {$ENDIF} end; ProcessMessages; finally FAnimating := False; FTableView.FMouseDownItem := nil; FTableView.EnableMouseEvents; end; end; function TksTableViewActionButtons.TotalWidth: integer; var ICount: integer; begin Result := 0; for ICount := 0 to Count-1 do Result := Result + Items[Icount].Width; end; // ------------------------------------------------------------------------------ { TksTableViewActionButton } constructor TksTableViewActionButton.Create(AIsDelete: Boolean); begin FWidth := 80; FTextColor := claWhite; FIsDeleteButton := AIsDelete; end; // ------------------------------------------------------------------------------ destructor TksTableViewActionButton.Destroy; begin FreeAndNil(FIcon); inherited; end; procedure TksTableViewActionButton.Render(ACanvas: TCanvas; ARect: TRectF); var ATextRect: TRectF; AIconRect: TRectF; AClipRect: TRectF; AState: TCanvasSaveState; begin AState := ACanvas.SaveState; try ATextRect := ARect; AIconRect := ARect; ARect.Right := ARect.Right +1; ACanvas.Fill.Color := Color; ACanvas.FillRect(ARect, 0, 0, AllCorners, 1); ACanvas.Font.Size := 14; ACanvas.Fill.Color := TextColor; AClipRect := ARect; InflateRect(AClipRect, -2, -2); ACanvas.IntersectClipRect(AClipRect); if FAccessory <> atNone then begin if FIcon = nil then begin FIcon := TksTableViewAccessoryImage.Create; FIcon.Assign(AccessoryImages.GetAccessoryImage(FAccessory)); (FIcon as TksTableViewAccessoryImage).Color := FTextColor; end; if (Text <> '')then begin AIconRect.Bottom := AIconRect.CenterPoint.Y; AIconRect.Top := AIconRect.Bottom - 28; end; ATextRect.Top := ATextRect.CenterPoint.Y; ATextRect.Bottom := ATextRect.CenterPoint.Y; OffsetRect(ATextRect, 0, 4); (FIcon as TksTableViewAccessoryImage).DrawToCanvas(ACanvas, AIconRect, False); end; ACanvas.FillText(ATextRect, Text, False, 1, [], TTextAlign.Center); if Trunc(ARect.Width) = 0 then FreeAndNil(FIcon); finally ACanvas.RestoreState(AState); end; end; procedure TksTableViewActionButton.SetAccessory(const Value: TksAccessoryType); begin if FAccessory <> Value then FAccessory := Value; end; { TksDeleteButton } constructor TksDeleteButton.Create; begin inherited; FEnabled := False; FText := 'Delete'; FColor := claRed; FTextColor := claWhite; FWidth := 60; FShowImage := True; FShowText := True; end; // ------------------------------------------------------------------------------ { TksTableViewTextDefaults } constructor TksTableViewTextDefaults.Create; begin FTitle := TksTableViewTextDefault.Create; FSubtitle := TksTableViewTextDefault.Create; FDetail := TksTableViewTextDefault.Create; FHeader := TksTableViewTextDefault.Create; FSubtitle.TextColor := claDimgray; FDetail.TextColor := claDodgerblue; end; destructor TksTableViewTextDefaults.Destroy; begin FreeAndNil(FTitle); FreeAndNil(FSubtitle); FreeAndNil(FDetail); FreeAndNil(FHeader); inherited; end; procedure TksTableViewTextDefaults.SetDetail(const Value: TksTableViewTextDefault); begin FDetail.Assign(Value); end; procedure TksTableViewTextDefaults.SetHeader(const Value: TksTableViewTextDefault); begin FHeader.Assign(Value); end; procedure TksTableViewTextDefaults.SetSubTitle(const Value: TksTableViewTextDefault); begin FSubtitle.Assign(Value); end; procedure TksTableViewTextDefaults.SetTitle(const Value: TksTableViewTextDefault); begin FTitle.Assign(Value); end; // ------------------------------------------------------------------------------ { TksTableViewTextDefault } procedure TksTableViewTextDefault.Assign(ASource: TPersistent); var Src : TksTableViewTextDefault; begin if (ASource is TksTableViewTextDefault) then begin Src := TksTableViewTextDefault(ASource); FFont.Assign(Src.Font); FTextColor := Src.TextColor; end else inherited; end; constructor TksTableViewTextDefault.Create; begin inherited Create; FFont := TFont.Create; FFont.Size := C_TABLEVIEW_DEFAULT_FONT_SIZE; FTextColor := claBlack; end; destructor TksTableViewTextDefault.Destroy; begin FreeAndNil(FFont); inherited; end; procedure TksTableViewTextDefault.SetFont(const Value: TFont); begin FFont.Assign(Value); end; procedure TksTableViewTextDefault.SetTextColor(const Value: TAlphaColor); begin FTextColor := Value; end; // ------------------------------------------------------------------------------ { TksTableViewShadow } procedure TksTableViewShadow.Assign(ASource: TPersistent); var ASrc: TksTableViewShadow; begin if (ASource is TksTableViewShadow) then begin ASrc := (ASource as TksTableViewShadow); Visible := ASrc.Visible; Color := ASrc.Color; Offset := ASrc.Offset; end else inherited; end; constructor TksTableViewShadow.Create; begin FOffset := 2; FColor := claSilver; FVisible := True; end; procedure TksTableViewShadow.SetVisible(const Value: Boolean); begin FVisible := Value; end; // ------------------------------------------------------------------------------ { TksListItemRowTableCell } procedure TksListItemRowTableCell.Changed; begin // need to implement. end; constructor TksListItemRowTableCell.Create(ATable: TksTableViewItemTable); begin inherited Create; FTable := ATable; FTextSettings := TTextSettings.Create(nil); FFill := TBrush.Create(TBrushKind.Solid, claWhite); FStroke := TStrokeBrush.Create(TBrushKind.Solid, claBlack); FPadding := TBounds.Create(RectF(0, 0, 0, 0)); FTextSettings.FontColor := claBlack; FTextSettings.Font.Family := 'Arial'; FTextSettings.HorzAlign := TTextAlign.Center; FTextSettings.VertAlign := TTextAlign.Center; FTextSettings.Font.Size := 12; FSides := AllSides; FVisible := True; {$IFDEF DEBUG} FText := 'CELL'; {$ENDIF} end; destructor TksListItemRowTableCell.Destroy; begin FreeAndNil(FTextSettings); FreeAndNil(FFill); FreeAndNil(FStroke); FreeAndNil(FPadding); inherited; end; procedure TksListItemRowTableCell.DrawToCanvas(x, y: single; ACanvas: TCanvas; ACol, ARow: integer; AShadow: TksTableViewShadow; AText: Boolean); var s: single; ARect: TRectF; ATextRect: TRectF; AXShift: single; AYShift: single; AShadowRect: TRectF; ASide: TSide; begin if not FVisible then Exit; s := GetScreenScale; if s < 2 then s := 2; with ACanvas do begin Stroke.Color := claBlack; Stroke.Thickness := (FStroke.Thickness * s)/2; AXShift := 0; AYShift := 0; if ACol = 0 then AXShift := 1*s; if ARow = 0 then AYShift := 1*s; ARect := RectF(x*s, y*s, (x+FWidth)*s, (y+FHeight)*s); if AText = False then begin if AShadow.Visible then begin // bottom shadow... AShadowRect := RectF(ARect.Left, ARect.Bottom, ARect.Right, ARect.Bottom+(AShadow.Offset*s)); ACanvas.Fill.Color := AShadow.Color; OffsetRect(AShadowRect, AShadow.Offset*s, 0); ACanvas.FillRect(AShadowRect, 0, 0, AllCorners, 1); // right shadow... AShadowRect := RectF(ARect.Right, ARect.Top, ARect.Right+(AShadow.Offset*s), ARect.Bottom); ACanvas.Fill.Color := AShadow.Color; OffsetRect(AShadowRect, 0, AShadow.Offset*s); ACanvas.FillRect(AShadowRect, 0, 0, AllCorners, 1); end; if IsFixedCell then ACanvas.Fill.Color := GetColorOrDefault(FFill.Color, FTable.FixCellColor) else begin ACanvas.Fill.Color := GetColorOrDefault(FFill.Color, claWhite); if FTable.Banding.Active then begin case FRow mod 2 of 0: ACanvas.Fill.Color := GetColorOrDefault(FTable.Banding.Color1, claWhite); 1: ACanvas.Fill.Color := GetColorOrDefault(FTable.Banding.Color2, claWhite); end; end; end; ACanvas.Fill.Kind := FFill.Kind; ACanvas.FillRect(RectF(ARect.Left+AXShift, ARect.Top+AYShift, ARect.Right, ARect.Bottom), 0, 0, AllCorners, 1); ACanvas.Stroke.Color := GetColorOrDefault(FStroke.Color, claDimgray); ACanvas.StrokeCap := TStrokeCap.Flat; ACanvas.StrokeJoin := TStrokeJoin.Miter; DrawRect(RectF(ARect.Left+AXShift, ARect.Top+AYShift, ARect.Right, ARect.Bottom), 0, 0, AllCorners, 1); ACanvas.Stroke.Color := ACanvas.Fill.Color; for ASide := Low(TSide) to High(TSide) do if not (ASide in FSides) then DrawRectSides(RectF(ARect.Left+AXShift, ARect.Top+AYShift, ARect.Right, ARect.Bottom), 0, 0, AllCorners, 1, [ASide]); end else begin ARect := RectF(x, y, x+FWidth, y+FHeight); ATextRect := ARect; ATextRect.Left := ATextRect.Left + (FPadding.Left); ATextRect.Top := ATextRect.Top + (FPadding.Top * s); ATextRect.Right := ATextRect.Right - (FPadding.Right * s); ATextRect.Bottom := ATextRect.Bottom - (FPadding.Bottom * s); ACanvas.Font.Assign(FTextSettings.Font); ACanvas.Font.Size := FTextSettings.Font.Size; RenderText(ACanvas, ATextRect.Left, ATextRect.Top, ATextRect.Width, ATextRect.Height, FText, ACanvas.Font, FTextSettings.FontColor, True, FTextSettings.HorzAlign, FTextSettings.VertAlign, TTextTrimming.Character); end; end; end; function TksListItemRowTableCell.GetShadow: TksTableViewShadow; begin Result := FTable.Shadow; end; function TksListItemRowTableCell.IsFixedCell: Boolean; begin Result := (FRow <= (FTable.FixedRows-1)) or (FCol <= (FTable.FixedCols-1)); end; procedure TksListItemRowTableCell.SetText(const Value: string); begin FText := Value; end; procedure TksListItemRowTableCell.SetTextSettings(const Value: TTextSettings); begin FTextSettings.Assign(Value); end; procedure TksListItemRowTableCell.SetVisible(const Value: Boolean); begin FVisible := Value; Changed; end; // ------------------------------------------------------------------------------ { TksListItemRowTableBanding } procedure TksListItemRowTableBanding.Assign(ASource: TPersistent); var Src : TksListItemRowTableBanding; begin if (ASource is TksListItemRowTableBanding) then begin Src := TksListItemRowTableBanding(ASource); FActive := Src.Active; FColor1 := Src.FColor1; FColor2 := Src.FColor2; end; end; constructor TksListItemRowTableBanding.Create; begin inherited Create; FActive :=False; FColor1 := claNull; FColor2 := claNull; end; procedure TksListItemRowTableBanding.SetActive(const Value: Boolean); begin FActive := Value; end; // ------------------------------------------------------------------------------ { TksTableViewItemTable } procedure TksTableViewItemTable.Clear; var X, Y: integer; ARow: TksListItemRowTableRow; begin for y := Low(FRows) to High(FRows) do begin ARow := FRows[y]; for x := Low(ARow) to High(ARow) do FreeAndNil(ARow[x]); end; end; constructor TksTableViewItemTable.Create(ARow: TKsTableViewItem); begin inherited; FShadow := TksTableViewShadow.Create; FBanding := TksListItemRowTableBanding.Create; SetLength(FRows, 5, 5); FBackground := claWhite; FBorderColor := claBlack; FColCount := 5; FRowCount := 5; FFixedCellColor := claGainsboro; FFixedRows := 1; FFixedCols := 1; end; destructor TksTableViewItemTable.Destroy; begin Clear; FreeAndNil(FShadow); FreeAndNil(FBanding); inherited; end; function TksTableViewItemTable.GetCells(ACol, ARow: integer): TksListItemRowTableCell; begin Result := FRows[ARow, ACol]; end; function TksTableViewItemTable.GetColWidths(ACol: integer): single; begin Result := FRows[0, ACol].Width; end; function TksTableViewItemTable.GetTableSize: TSizeF; var ICount: integer; begin Result.cx := 0; Result.cy := 0; if FRowCount > 0 then begin for ICount := Low(FRows) to High(FRows) do begin Result.cy := Result.cy + Frows[ICount, 0].Height; end; end; if (FColCount > 0) and (FColCount > 0) then begin for ICount := Low(FRows[0]) to High(FRows[0]) do begin Result.cx := Result.cx + Frows[0, ICount].Width; end; end; end; procedure TksTableViewItemTable.MergeRowCells(x, y, AMergeCount: integer); var ICount: integer; ACell: TksListItemRowTableCell; begin ACell := Cells[x, y]; for ICount := x to x+(AMergeCount-1) do begin if ICount > x then begin Cells[ICount, y].Visible := False; ACell.Width := ACell.Width + Cells[ICount, y].Width; end; end; end; procedure TksTableViewItemTable.Render(AItemRect: TRectF; ACanvas: TCanvas); begin inherited; RenderTableContents(ACanvas, False); // render the grid. RenderTableContents(ACanvas, True); // render the cell text end; procedure TksTableViewItemTable.RenderTableContents(ACanvas: TCanvas; AText: Boolean); var IRowCount, ICellCount: integer; AXPos, AYPos: single; ARow: TksListItemRowTableRow; ACell: TksListItemRowTableCell; ASides: TSides; ABmp: TBitmap; ASize: TSizeF; AScale: single; begin AScale := GetScreenScale; if AScale < 2 then AScale := 2; if AText then begin AXPos := ObjectRect.Left; AYPos := ObjectRect.Top; ACell := nil; for IRowCount := Low(FRows) to High(FRows) do begin ARow := FRows[IRowCount]; for ICellCount := Low(ARow) to High(ARow) do begin ACell := ARow[ICellCount]; begin ASides := [TSide.Right, TSide.Bottom]; if ICellCount = 0 then ASides := ASides + [TSide.Left]; if IRowCount = 0 then ASides := ASides + [TSide.Top]; ACell.DrawToCanvas(AXpos, AYPos, ACanvas, ICellCount, IRowCount, FShadow, True); end; AXPos := AXPos + (ColWidths[ICellCount]); end; AYpos := AYpos + (ACell.Height); AXpos := ObjectRect.Left; end; Exit; end; ABmp := TBitmap.Create; try ASize := GetTableSize; FWidth := ASize.cx; FHeight := ASize.cy; ABmp.SetSize(Round((ASize.cx+FShadow.Offset+2) * (AScale)), Round((ASize.cy+FShadow.Offset+2) * (AScale))); ABmp.Clear(claNull); ABmp.Canvas.BeginScene; with ABmp.Canvas.Fill do begin Kind := TBrushKind.Solid; Color := FBackground; end; with ABmp.Canvas.Stroke do begin Kind := TBrushKind.Solid; Color := FBorderColor; end; AXPos := 0; AYPos := 0; ACell := nil; for IRowCount := Low(FRows) to High(FRows) do begin ARow := FRows[IRowCount]; for ICellCount := Low(ARow) to High(ARow) do begin ACell := ARow[ICellCount]; begin ASides := [TSide.Right, TSide.Bottom]; if ICellCount = 0 then ASides := ASides + [TSide.Left]; if IRowCount = 0 then ASides := ASides + [TSide.Top]; ACell.DrawToCanvas(AXpos, AYPos, ABmp.Canvas, ICellCount, IRowCount, FShadow, False); end; AXPos := AXPos + (ColWidths[ICellCount]); end; AYpos := AYpos + (ACell.Height); AXpos := 0; end; ABmp.Canvas.EndScene; ACanvas.DrawBitmap(ABmp, RectF(0, 0, ABmp.Width, ABmp.Height), RectF(ObjectRect.Left, ObjectRect.Top, ObjectRect.Left+FWidth+FShadow.Offset+1, ObjectRect.Top+FHeight+FShadow.Offset+1), 1, True); finally FreeAndNil(ABmp); end; end; procedure TksTableViewItemTable.ResizeTable; var AShadowWidth: integer; x,y: integer; ARow: TksListItemRowTableRow; ACell: TksListItemRowTableCell; begin SetLength(FRows, FRowCount, FColCount); for y := Low(FRows) to High(FRows) do begin ARow := FRows[y]; for x := Low(ARow) to High(ARow) do begin ACell := ARow[x]; if ACell = nil then begin ACell := TksListItemRowTableCell.Create(Self); ACell.Width := FDefaultColWidth; ACell.Height := FDefaultRowHeight; ACell.FRow := y; ACell.FCol := x; FRows[y, x] := ACell; end; end; end; AShadowWidth := 0; if FShadow.Visible then AShadowWidth := FShadow.Offset; FWidth := GetTableSize.cx + AShadowWidth + (4*GetScreenScale); FHeight := GetTableSize.cy + AShadowWidth + (4*GetScreenScale); end; procedure TksTableViewItemTable.SetBackgroundColor(const Value: TAlphaColor); begin FBackground := Value; end; procedure TksTableViewItemTable.SetBanding(const Value: TksListItemRowTableBanding); begin FBanding.Assign(Value); end; procedure TksTableViewItemTable.SetBorderColor(const Value: TAlphaColor); begin FBorderColor := Value; end; procedure TksTableViewItemTable.SetColColor(ACol: integer; AColor: TAlphaColor); var ICount: integer; begin for ICount := Low(FRows) to High(FRows) do FRows[ICount, ACol].Fill.Color := AColor; end; procedure TksTableViewItemTable.SetColCount(const Value: integer); begin FColCount := Value; ResizeTable; end; procedure TksTableViewItemTable.SetColFont(ACol: integer; AFontName: TFontName; AColor: TAlphaColor; ASize: integer; AStyle: TFontStyles); var ICount: integer; ACell: TksListItemRowTableCell; begin for ICount := Low(FRows) to High(FRows) do begin ACell := FRows[ICount, ACol]; with ACell.TextSettings do begin if AFontName <> '' then Font.Family := AFontName; Font.Size := ASize; FontColor := AColor; Font.Style := AStyle; end; end; end; procedure TksTableViewItemTable.SetColWidths(ACol: integer; const Value: single); var ICount: integer; begin for ICount := Low(FRows) to High(FRows) do FRows[ICount, ACol].Width := Value; ResizeTable; end; procedure TksTableViewItemTable.SetDefaultColWidth(const Value: single); begin FDefaultColWidth := Value; end; procedure TksTableViewItemTable.SetDefaultRowHeight(const Value: single); begin FDefaultRowHeight := Value; end; procedure TksTableViewItemTable.SetFixedCellColor(const Value: TAlphaColor); begin FFixedCellColor := Value; end; procedure TksTableViewItemTable.SetRowColor(ARow: integer; AColor: TAlphaColor); var ICount: integer; begin for ICount := Low(FRows[ARow]) to High(FRows[ARow]) do FRows[ARow, ICount].Fill.Color := AColor; end; procedure TksTableViewItemTable.SetRowCount(const Value: integer); begin FRowCount := Value; ResizeTable; end; procedure TksTableViewItemTable.SetRowFont(ARow: integer; AFontName: TFontName; AColor: TAlphaColor; ASize: integer; AStyle: TFontStyles); var ICount: integer; ACell: TksListItemRowTableCell; begin for ICount := Low(FRows[ARow]) to High(FRows[ARow]) do begin ACell := FRows[ARow, ICount]; with ACell.TextSettings do begin if AFontName <> '' then Font.Family := AFontName; Font.Size := ASize; FontColor := AColor; Font.Style := AStyle; end; end; end; // ------------------------------------------------------------------------------ { TksTableViewPullToRefresh } procedure TksTableViewPullToRefresh.Assign(ASource: TPersistent); var Src: TksTableViewPullToRefresh; begin if (ASource is TksTableViewPullToRefresh) then begin Src := (ASource as TksTableViewPullToRefresh); FEnabled := Src.Enabled; FPullText := Src.PullText; FReleaseText := Src.ReleaseText; FFont.Assign(Src.Font); FTextColor := Src.TextColor; end else inherited; end; constructor TksTableViewPullToRefresh.Create(ATableView: TksTableView); begin FTableView := ATableView; FFont := TFont.Create; FEnabled := True; FPullText := 'pull to refresh'; FReleaseText := 'release to refresh'; FFont.Size := 16; FTextColor := claSilver; end; destructor TksTableViewPullToRefresh.Destroy; begin FreeAndNil(FFont); inherited; end; procedure TksTableViewPullToRefresh.SetEnabled(const Value: Boolean); begin FEnabled := Value; FTableView.FAniCalc.BoundsAnimation := FEnabled; end; procedure TksTableViewPullToRefresh.SetFont(const Value: TFont); begin FFont.Assign(Value); end; // ------------------------------------------------------------------------------ { TksTableViewItemEmbeddedControl } function TksTableViewItemEmbeddedControl.CanFocus: Boolean; begin Result := False; end; function TksTableViewItemEmbeddedControl.ConsumesClick: Boolean; begin Result := True; end; constructor TksTableViewItemEmbeddedControl.Create(ATableItem: TksTableViewItem); begin inherited; FControl := CreateControl; //FControl.OnExit := DoLoseFocus; FWidth := FControl.Width; FHeight := FControl.Height; InitializeControl; FFocused := False; FControl.Cursor := crHandPoint; FControl.OnExit := DoExitControl; end; destructor TksTableViewItemEmbeddedControl.Destroy; begin FreeAndNil(FCached); {$IFDEF MSWINDOWS} FControl.Free; {$ELSE} FControl.DisposeOf; {$ENDIF} inherited; end; procedure TksTableViewItemEmbeddedControl.DoExitControl(Sender: TObject); begin FTableItem.TableView.HideFocusedControl; end; function TksTableViewItemEmbeddedControl.GetControlBitmap(AForceRecreate: Boolean): TBitmap; var ARect: TRectF; begin if FControl.IsFocused then begin Result := FCached; FCached.Clear(claNull); Exit; end; ARect := GetObjectRect; if (FCached = nil) or (IsBlankBitmap(FCached)) or (AForceRecreate) then begin FControl.Width := ARect.Width; FControl.Height := ARect.Height; // first free the cached bitmap if it exists... if FCached <> nil then FreeAndNil(FCached); FCached := FControl.MakeScreenshot; end; Result := FCached; if FControl.IsFocused then FCached.Clear(claNull); end; procedure TksTableViewItemEmbeddedControl.HideControl; begin DisableEvents; FControl.Root.SetFocused(nil); GetControlBitmap(True); FFocused := False; FTableItem.CacheItem(True); FTableItem.FTableView.Invalidate; FControl.Visible := False; end; procedure TksTableViewItemEmbeddedControl.ApplyStyle(AControl: TFmxObject); var ICount: integer; begin if (AControl is TControl) then begin (AControl as TControl).RecalcSize; (AControl as TControl).UpdateEffects; (AControl as TControl).Repaint; end; if (AControl is TStyledControl) then (AControl as TStyledControl).ApplyStyleLookup; for ICount := 0 to AControl.ChildrenCount-1 do ApplyStyle(AControl.Children[ICount]); end; procedure TksTableViewItemEmbeddedControl.InitializeControl; begin FTableItem.FTableView.AddObject(FControl); FControl.RecalcSize; ApplyStyle(FControl); FControl.UpdateEffects; FControl.Visible := False; end; { procedure TksTableViewItemEmbeddedControl.SimulateClick(x, y: single); var AParent : TFmxObject; AForm : TCommonCustomForm; AFormPoint: TPointF; begin AParent := FControl.Parent; if AParent = nil then Exit; while not (AParent is TCommonCustomForm) do AParent := AParent.Parent; if (AParent is TCommonCustomForm) then begin AForm := TCommonCustomForm(AParent); AFormPoint := FControl.LocalToAbsolute(PointF(X,Y)); AForm.MouseDown(TMouseButton.mbLeft, [], AFormPoint.X, AFormPoint.Y); AForm.MouseUp(TMouseButton.mbLeft, [], AFormPoint.X, AFormPoint.Y); end; end; } procedure TksTableViewItemEmbeddedControl.MouseDown(x, y: single); begin if (FControl.IsFocused) or (FVisible = False) or (FTableItem.TableView.FScrolling) then Exit; GetControlBitmap(True); FocusControl; SimulateClick(FControl, x, y); end; procedure TksTableViewItemEmbeddedControl.Render(AItemRect: TRectF; ACanvas: TCanvas); var ABmp: TBitmap; r: TRectF; begin if FFocused then Exit; r := ObjectRect; ABmp := GetControlBitmap(False); if ABmp = nil then Exit; ACanvas.DrawBitmap(ABmp, RectF(0, 0, ABmp.Width, ABmp.Height), r, 1, False); end; procedure TksTableViewItemEmbeddedControl.FocusControl; var r: TRectF; begin inherited; if FControl.IsFocused then Exit; if FTableItem.FTableView.FFocusedControl <> Self then FTableItem.FTableView.HideFocusedControl; r := GetObjectRect; OffsetRect(r, 0, FTableItem.TableView.GetStartOffsetY); FControl.SetBounds(r.Left, (FTableItem.ItemRect.Top - FTableItem.FTableView.ScrollViewPos) + r.Top, r.width, r.height); FControl.Visible := True; FFocused := True; FTableItem.FTableView.FFocusedControl := Self; FCached.Canvas.Clear(claNull); FTableItem.CacheItem(True); if (FTableItem.TableView.SelectionOptions.KeepSelection) and (FTableItem.CanSelect) then begin if FTableItem.Purpose <> TksTableViewItemPurpose.Header then FTableItem.TableView.ItemIndex := FTableItem.Index; end; FControl.CanFocus := True; FControl.SetFocus; FTableItem.CacheItem(True); FTableItem.FTableView.Invalidate; FTableItem.FTableView.FSearchBox.BringToFront; EnableEvents; end; function TksTableViewItemEmbeddedBaseEdit.CanFocus: Boolean; begin Result := True; end; procedure TksTableViewItemEmbeddedBaseEdit.DisableEvents; begin CustomEdit.OnChange := nil; CustomEdit.OnTyping := nil; end; procedure TksTableViewItemEmbeddedBaseEdit.DoEditChange(Sender: TObject); begin FTableItem.TableView.DoEmbeddedEditChange(FTableItem, Self); end; procedure TksTableViewItemEmbeddedBaseEdit.EnableEvents; begin CustomEdit.OnChange := DoEditChange; CustomEdit.OnTyping := DoEditChange; end; procedure TksTableViewItemEmbeddedBaseEdit.FocusControl; begin if GetCustomEdit.IsFocused then Exit; inherited; GetCustomEdit.SelStart := Length(GetCustomEdit.Text); end; function TksTableViewItemEmbeddedBaseEdit.GetCustomEdit: TCustomEdit; begin Result := (FControl as TCustomEdit); end; procedure TksTableViewItemEmbeddedBaseEdit.HideControl; begin GetCustomEdit.SelStart := 0; inherited; end; procedure TksTableViewItemEmbeddedBaseEdit.SetStyle( const Value: TksEmbeddedEditStyle); begin FStyle := Value; case FStyle of ksEditNormal: CustomEdit.StyleLookup := 'editstyle'; ksEditClearing: CustomEdit.StyleLookup := 'clearingeditstyle'; ksEditCombo: CustomEdit.StyleLookup := 'comboeditstyle'; ksEditTransparent: CustomEdit.StyleLookup := 'transparentedit'; end; end; // ------------------------------------------------------------------------------ { TksTableViewItemEmbeddedEdit } function TksTableViewItemEmbeddedEdit.CreateControl: TStyledControl; begin Result := TEdit.Create(FTableItem.FTableView); end; function TksTableViewItemEmbeddedEdit.GetEditControl: TEdit; begin Result := (FControl as TEdit); end; function TksTableViewItemEmbeddedEdit.GetText: string; begin Result := GetEditControl.Text; end; procedure TksTableViewItemEmbeddedEdit.SetText(const Value: string); begin GetEditControl.Text := Value; end; // ------------------------------------------------------------------------------ { TksDragDropOptions } constructor TksDragDropOptions.Create; begin inherited Create; FDragHighlightOptions := TksDragHighlightOptions.Create; FShadow := True; FOpacity := 1; FEnabled := False; FLiveMoving := True; FDragSpaceColor := $FFECECEC; end; destructor TksDragDropOptions.Destroy; begin FreeAndNil(FDragHighlightOptions); inherited; end; procedure TksDragDropOptions.SetDragHighlightOptions(const Value: TksDragHighlightOptions); begin FDragHighlightOptions := Value; end; procedure TksDragDropOptions.SetOpacity(const Value: single); begin FOpacity := Value; if FOpacity < 1 then FShadow := False; end; procedure TksDragDropOptions.SetShadow(const Value: Boolean); begin FShadow := Value; if FShadow then FOpacity := 1; end; // ------------------------------------------------------------------------------ { TksDragImage } constructor TksDragImage.Create(AOwner: TComponent); begin inherited Create(AOwner); FBorder := TRectangle.Create(Self); FBorder.Stroke.Color := claDimgray; FBorder.Fill.Color := claNull; FBorder.Align := TAlignLayout.Client; Stroke.Thickness := 3; FShadow := TShadowEffect.Create(Self); FShadow.Direction := 45; FShadow.Distance := 5; FShadow.Softness := 0.2; Stroke.Color := claBlack; AddObject(FShadow); AddObject(FBorder); end; destructor TksDragImage.Destroy; begin FreeAndNil(FShadow); inherited; end; function TksDragImage.GetAllowDropColor: TStrokeBrush; begin Result := Stroke; end; procedure TksDragImage.SetAllowDropColor(const Value: TStrokeBrush); begin Stroke.Assign(Value); end; // ------------------------------------------------------------------------------ { TksDragHighlightOptions } constructor TksDragHighlightOptions.Create; begin FAllowDropStroke := TStrokeBrush.Create(TBrushKind.Solid, claLimegreen); FDisallowDropStroke := TStrokeBrush.Create(TBrushKind.Solid, claRed); FEnabled := True; end; destructor TksDragHighlightOptions.Destroy; begin FreeAndNil(FAllowDropStroke); FreeAndNil(FDisallowDropStroke); inherited; end; procedure TksDragHighlightOptions.SetAllowDropStroke(const Value: TStrokeBrush); begin FAllowDropStroke.Assign(Value); end; procedure TksDragHighlightOptions.SetDisallowDropStroke(const Value: TStrokeBrush); begin FDisallowDropStroke.Assign(Value); end; // ------------------------------------------------------------------------------ { TksTableViewSelectionOptions } constructor TksTableViewSelectionOptions.Create(ATableView: TKsTableView); begin inherited Create; FTableView := ATableView; FSelectionOverlay := TksTableViewSelectionOverlayOptions.Create(Self); FShowSelection := True; FKeepSelection := False; FSelectDuration := C_TABLEVIEW_DEFAULT_SELECT_DURATION; FKeepSelectedInView := True; FLongTapSelects := True; end; destructor TksTableViewSelectionOptions.Destroy; begin FreeAndNil(FSelectionOverlay); inherited; end; procedure TksTableViewSelectionOptions.Assign(ASource: TPersistent); var Src : TksTableViewSelectionOptions; begin if (ASource is TksTableViewSelectionOptions) then begin Src := TksTableViewSelectionOptions(ASource); FSelectionOverlay.Assign(Src.FSelectionOverlay); FShowSelection := Src.FShowSelection; FKeepSelection := Src.FKeepSelection; FSelectDuration := Src.FSelectDuration; FKeepSelectedInView := Src.FKeepSelectedInView; FLongTapSelects := Src.FLongTapSelects; end else inherited; end; procedure TksTableViewSelectionOptions.SetKeepSelection(const Value: Boolean); begin if FKeepSelection <> Value then begin FKeepSelection := Value; FTableView.ClearCache(ksClearCacheAll); FTableView.Invalidate; end; end; procedure TksTableViewSelectionOptions.SetShowSelection(const Value: Boolean); begin if FShowSelection <> Value then begin FShowSelection := Value; FTableView.ClearCache(ksClearCacheAll); FTableView.Invalidate; end; end; procedure TksTableViewSelectionOptions.SetSelectionOverlay(const Value: TksTableViewSelectionOverlayOptions); begin FSelectionOverlay.Assign(Value); FTableView.ClearCache(ksClearCacheAll); FTableView.Invalidate; end; procedure TksTableViewSelectionOptions.SetKeepSelectedInView(const Value: Boolean); begin FKeepSelectedInView := Value; end; procedure TksTableViewSelectionOptions.SetLongTapSelects(const Value: Boolean); begin FLongTapSelects := Value; end; // ------------------------------------------------------------------------------ { TksTableViewSelectionOverlayOptions } constructor TksTableViewSelectionOverlayOptions.Create(AParent: TksTableViewSelectionOptions); begin inherited Create; FParent := AParent; FBitmap := TBitmap.Create; FStroke := TStrokeBrush.Create(TBrushKind.Solid, claBlack); FPosition := ksSelectorRight; FBackgroundColor := claWhite; FStyle := ksArrow; FStroke.OnChanged := DoStrokeChanged; FLastStickyHeaderOffset := 0; FLastFixedFooterOffset := 0; end; destructor TksTableViewSelectionOverlayOptions.Destroy; begin FreeAndNil(FStroke); FreeAndNil(FBitmap); inherited; end; procedure TksTableViewSelectionOverlayOptions.Assign(ASource: TPersistent); var Src : TksTableViewSelectionOverlayOptions; begin if (ASource is TksTableViewSelectionOverlayOptions) then begin Src := TksTableViewSelectionOverlayOptions(ASource); FPosition := Src.FPosition; FStyle := Src.FStyle; FEnabled := Src.FEnabled; FStroke.Assign(Src.FStroke); FBackgroundColor := Src.FBackgroundColor; if (FBitmap=Nil) then FBitmap := TBitmap.Create; FBitmap.Assign(Src.FBitmap); FSize := Src.FSize; FLastStickyHeaderOffset := Src.FLastStickyHeaderOffset; FLastFixedFooterOffset := Src.FLastFixedFooterOffset; end else inherited; end; procedure TksTableViewSelectionOverlayOptions.DrawToCanvas(ACanvas: TCanvas; ARect: TRectF ; AStickyHeaderBottom,FixedFooterStart : Single); var StickyHeaderOffset : Single; FixedFooterOffset : Single; ScreenScale: Single; ANewBitmapWidth : Integer; ANewBitmapHeight : Integer; ANewStickyHeaderOffset: Single; ANewFixedFooterOffset: Single; begin if (ARect.Bottom>AStickyHeaderBottom) and (ARect.Top<FixedFooterStart) then begin ScreenScale := GetScreenScale; if FStyle = ksBlankSpace then begin ARect.Top := ARect.Top - 1; AStickyHeaderBottom := AStickyHeaderBottom - 1; end; if (ARect.Top<AStickyHeaderBottom) then StickyHeaderOffset := AStickyHeaderBottom - ARect.Top else StickyHeaderOffset := 0; if (ARect.Bottom>FixedFooterStart) then FixedFooterOffset := ARect.Bottom - FixedFooterStart else FixedFooterOffset := 0; ANewBitmapWidth := Round(ARect.Width * ScreenScale * 2); ANewBitmapHeight := Round(ARect.Height * ScreenScale); ANewStickyHeaderOffset := StickyHeaderOffset * ScreenScale; ANewFixedFooterOffset := (ARect.Height-FixedFooterOffset) * ScreenScale; if (FBitmap.Width <> ANewBitmapWidth) or (FBitmap.Height <> ANewBitmapHeight) or (ANewStickyHeaderOffset<>FLastStickyHeaderOffset) or (ANewFixedFooterOffset<>FLastFixedFooterOffset) then begin RecreateIndicator(ANewBitmapWidth,ANewBitmapHeight,ANewStickyHeaderOffset,ANewFixedFooterOffset); FLastStickyHeaderOffset := ANewStickyHeaderOffset; FLastFixedFooterOffset := ANewFixedFooterOffset; end; case FPosition of ksSelectorLeft: ACanvas.DrawBitmap(FBitmap, RectF(0, StickyHeaderOffset * ScreenScale, FBitmap.Width, FBitmap.Height - (FixedFooterOffset * ScreenScale)), RectF(ARect.Left - ARect.Width, ARect.Top + StickyHeaderOffset, ARect.Left + ARect.Width, ARect.Bottom-FixedFooterOffset), 1, false); ksSelectorRight: ACanvas.DrawBitmap(FBitmap, RectF(0, StickyHeaderOffset * ScreenScale, FBitmap.Width, FBitmap.Height - (FixedFooterOffset * ScreenScale)), RectF(ARect.Right - ARect.Width, ARect.Top + StickyHeaderOffset, ARect.Right + ARect.Width, ARect.Bottom-FixedFooterOffset), 1, false); end; end; end; procedure TksTableViewSelectionOverlayOptions.RecreateIndicator(AWidth,AHeight,AStickyHeaderOffset,AFixedFooterOffset: single); var APath: TPathData; ASize: single; AMaxSize: single; AOffsetX: single; AOffsetY: single; AIndicatorRect: TRectF; AHypot: single; StrokeThickness : Single; ScreenScale: Single; ALineSize: single; ATop: single; ABottom: single; begin ScreenScale := GetScreenScale; StrokeThickness := (FStroke.Thickness /2) * ScreenScale; FBitmap.SetSize(Round(AWidth), Round(AHeight)); FBitmap.Canvas.BeginScene; FBitmap.Canvas.Fill.Color := claNull; FBitmap.Canvas.FillRect(RectF(0,0,FBitmap.Width,FBitmap.Height),0,0,AllCorners,1); try FBitmap.Canvas.Stroke.Assign(FStroke); FBitmap.Canvas.Fill.Color := FBackgroundColor; ASize := (2*FSize*ScreenScale); AMaxSize := AHeight - StrokeThickness; if (ASize>AMaxSize) then ASize := AMaxSize; AOffsetX := (AWidth - ASize) / 2; AOffsetY := (AHeight - ASize) / 2; AIndicatorRect := RectF(AOffsetX, AOffsetY, FBitmap.Width-AOffsetX, FBitmap.Height-AOffsetY); FBitmap.Canvas.Stroke.Thickness := StrokeThickness; if FStyle = ksBlankSpace then begin FBitmap.Canvas.Fill.Color := FStroke.Color; FBitmap.Canvas.FillRect(RectF(0,0,FBitmap.Width,FBitmap.Height),0,0,AllCorners,1); ATop := AStickyHeaderOffset+Round(StrokeThickness); ABottom := Floor(FBitmap.Height-StrokeThickness)-(AHeight-AFixedFooterOffset); if (ATop<ABottom-1) then begin FBitmap.Canvas.ClearRect(RectF(0,ATop,FBitmap.Width,ABottom)); FBitmap.Canvas.Fill.Color := FBackgroundColor; FBitmap.Canvas.FillRect(RectF((FBitmap.Width/2)-StrokeThickness-1,ATop, (FBitmap.Width/2)+StrokeThickness+1,ABottom), 0,0,AllCorners,1); end; end else if FStyle = ksSemiCircle then begin FBitmap.Canvas.FillEllipse(AIndicatorRect, 1); FBitmap.Canvas.DrawEllipse(AIndicatorRect, 1); if (AStickyHeaderOffset>AIndicatorRect.Top) and (AStickyHeaderOffset<AIndicatorRect.Bottom) then begin AHypot := (ASize/2); AOffsetY := Abs(AIndicatorRect.CenterPoint.Y - AStickyHeaderOffset); if (AHypot>AOffsetY) then begin ALineSize := Sqrt((AHypot*AHypot) - (AOffsetY*AOffsetY)); AStickyHeaderOffset := Floor(AStickyHeaderOffset + (StrokeThickness/2)); FBitmap.Canvas.DrawLine(PointF(AIndicatorRect.CenterPoint.X-ALineSize,AStickyHeaderOffset), PointF(AIndicatorRect.CenterPoint.X+ALineSize,AStickyHeaderOffset), 1); end; end; if (AFixedFooterOffset>AIndicatorRect.Top) and (AFixedFooterOffset<AIndicatorRect.Bottom) then begin AHypot := (ASize/2); AOffsetY := Abs(AIndicatorRect.CenterPoint.Y - AFixedFooterOffset); if (AHypot>AOffsetY) then begin ALineSize := Sqrt((AHypot*AHypot) - (AOffsetY*AOffsetY)); AFixedFooterOffset := AFixedFooterOffset - (StrokeThickness/2) + 0.5; FBitmap.Canvas.DrawLine(PointF(AIndicatorRect.CenterPoint.X-ALineSize,AFixedFooterOffset), PointF(AIndicatorRect.CenterPoint.X+ALineSize,AFixedFooterOffset), 1); end; end; end else if FStyle = ksArrow then begin APath := TPathData.Create; try APath.MoveTo(PointF(AIndicatorRect.Left, AIndicatorRect.CenterPoint.Y)); APath.LineTo(PointF(AIndicatorRect.CenterPoint.X, AIndicatorRect.Top)); APath.LineTo(PointF(AIndicatorRect.Right, AIndicatorRect.CenterPoint.Y)); APath.LineTo(PointF(AIndicatorRect.CenterPoint.X, AIndicatorRect.Bottom)); APath.LineTo(PointF(AIndicatorRect.Left, AIndicatorRect.CenterPoint.Y)); APath.ClosePath; FBitmap.Canvas.FillPath(APath, 1); FBitmap.Canvas.DrawPath(APath, 1); if (AStickyHeaderOffset>AIndicatorRect.Top) and (AStickyHeaderOffset<AIndicatorRect.Bottom) then begin ALineSize := (ASize/2) - Abs(AIndicatorRect.CenterPoint.Y - AStickyHeaderOffset); AStickyHeaderOffset := Floor(AStickyHeaderOffset + (StrokeThickness/2)); FBitmap.Canvas.DrawLine(PointF(AIndicatorRect.CenterPoint.X-ALineSize,AStickyHeaderOffset), PointF(AIndicatorRect.CenterPoint.X+ALineSize,AStickyHeaderOffset), 1); end; if (AFixedFooterOffset>AIndicatorRect.Top) and (AFixedFooterOffset<AIndicatorRect.Bottom) then begin ALineSize := (ASize/2) - Abs(AIndicatorRect.CenterPoint.Y - AFixedFooterOffset); AFixedFooterOffset := AFixedFooterOffset - (StrokeThickness/2) + 0.5; FBitmap.Canvas.DrawLine(PointF(AIndicatorRect.CenterPoint.X-ALineSize,AFixedFooterOffset), PointF(AIndicatorRect.CenterPoint.X+ALineSize,AFixedFooterOffset), 1); end; finally FreeAndNil(APath); end; end; finally FBitmap.Canvas.EndScene; end; end; procedure TksTableViewSelectionOverlayOptions.SetEnabled(const Value: Boolean); begin if FEnabled <> Value then begin FEnabled := Value; FParent.FTableView.Invalidate; end; end; procedure TksTableViewSelectionOverlayOptions.SetPosition(const Value: TksTableViewOverlaySelectorPosition); begin if FPosition <> Value then begin FPosition := Value; FParent.FTableView.Invalidate; end; end; procedure TksTableViewSelectionOverlayOptions.SetSize(const Value: integer); begin if FSize <> Value then begin FSize := Value; FParent.FTableView.Invalidate; end; end; procedure TksTableViewSelectionOverlayOptions.SetStrokeBrush(const Value: TStrokeBrush); begin if Value <> nil then begin FStroke.Assign(Value); FParent.FTableView.Invalidate; end; end; procedure TksTableViewSelectionOverlayOptions.SetStyle(const Value: TksTableViewOverlaySelectorStyle); begin if FStyle <> Value then begin FStyle := Value; FBitmap.SetSize(0, 0); FParent.FTableView.Invalidate; end; end; procedure TksTableViewSelectionOverlayOptions.DoStrokeChanged(Sender: TObject); begin FParent.FTableView.Invalidate; end; // ------------------------------------------------------------------------------ { TksTableViewItemEmbeddedDateEdit } function TksTableViewItemEmbeddedDateEdit.CreateControl: TStyledControl; begin Result := TDateEdit.Create(FTableItem.FTableView); end; procedure TksTableViewItemEmbeddedDateEdit.DisableEvents; begin (FControl as TDateEdit).OnChange := nil; end; procedure TksTableViewItemEmbeddedDateEdit.DoDateChanged(Sender: TObject); begin FTableItem.TableView.DoEmbeddedDateEditChange(FTableItem, Self); end; procedure TksTableViewItemEmbeddedDateEdit.EnableEvents; begin (FControl as TDateEdit).OnChange := DoDateChanged; end; function TksTableViewItemEmbeddedDateEdit.GetDate: TDateTime; begin Result := GetEditControl.Date; end; function TksTableViewItemEmbeddedDateEdit.GetEditControl: TDateEdit; begin Result := (FControl as TDateEdit); end; procedure TksTableViewItemEmbeddedDateEdit.SetDate(const Value: TDateTime); begin GetEditControl.Date := Value; end; // ------------------------------------------------------------------------------ { TksTableViewItemEmbeddedButton } function TksTableViewItemButton.CreateControl: TStyledControl; begin Result := TSpeedButton.Create(FTableItem.TableView); (Result as TSpeedButton).CanFocus := False; (Result as TSpeedButton).DisableFocusEffect := True; (Result as TSpeedButton).StyleLookup := 'listitembutton'; end; procedure TksTableViewItemButton.DisableEvents; begin GetButton.OnClick := nil; end; procedure TksTableViewItemButton.DoButtonClicked(Sender: TObject); begin FTableItem.TableView.DoButtonClicked(FTableItem, Self); end; procedure TksTableViewItemButton.EnableEvents; begin GetButton.OnClick := DoButtonClicked; end; function TksTableViewItemButton.GetButton: TSpeedButton; begin Result := (FControl as TSpeedButton); end; function TksTableViewItemButton.GetStyleLookup: string; begin Result := GetButton.StyleLookup; end; function TksTableViewItemButton.GetText: string; begin Result := GetButton.Text; end; function TksTableViewItemButton.GetTintColor: TAlphaColor; begin Result := GetButton.TintColor; end; procedure TksTableViewItemButton.SetStyleLookup(const Value: string); begin if StyleLookup <> Value then begin InitializeControl; GetButton.StyleLookup := Value; {$IFDEF ANDROID} GetButton.Size.Size := GetButton.DefaultSize; fheight := GetButton.Size.height; FWidth := GetButton.Size.Width; {$ENDIF} Changed; end; end; procedure TksTableViewItemButton.SetText(const Value: string); begin GetButton.Text := Value; end; procedure TksTableViewItemButton.SetTintColor(const Value: TAlphaColor); begin GetButton.TintColor := Value; end; // ------------------------------------------------------------------------------ { TksTableViewAccessoryOptions } procedure TksTableViewAccessoryOptions.Changed; begin FTableView.RedrawAllVisibleItems; end; constructor TksTableViewAccessoryOptions.Create(ATableView: TksTableView); begin inherited Create; FTableView := ATableView; FShowAccessory := True; FColor := claNull; end; procedure TksTableViewAccessoryOptions.Assign(ASource: TPersistent); var Src : TksTableViewAccessoryOptions; begin if (ASource is TksTableViewAccessoryOptions) then begin Src := TksTableViewAccessoryOptions(ASource); FShowAccessory := Src.FShowAccessory; FColor := Src.FColor; end else inherited; end; procedure TksTableViewAccessoryOptions.SetColor(const Value: TAlphaColor); begin if FColor <> Value then begin FColor := Value; Changed; end; end; procedure TksTableViewAccessoryOptions.SetShowAccessory(const Value: Boolean); begin if FShowAccessory <> Value then begin FShowAccessory := Value; Changed; end; end; // ------------------------------------------------------------------------------ { TksTableViewItemHeaderOptions } procedure TksTableViewItemHeaderOptions.Changed; begin FTableView.UpdateFilteredItems; FTableView.Invalidate; end; constructor TksTableViewItemHeaderOptions.Create(ATableView: TksTableView); begin inherited Create; FTableView := ATableView; FStickyHeaders := TksTableViewStickyHeaderOptions.Create(FTableView); FHeight := C_TABLEVIEW_DEFAULT_HEADER_HEIGHT; end; procedure TksTableViewItemHeaderOptions.LegacyGetStickyHeadersHeight(Reader: TReader); begin FStickyHeaders.StickyHeight := Reader.ReadInteger; end; procedure TksTableViewItemHeaderOptions.DefineProperties(Filer: TFiler); begin inherited; Filer.DefineProperty('StickyHeaderHeight', LegacyGetStickyHeadersHeight, nil, False); end; destructor TksTableViewItemHeaderOptions.Destroy; begin FreeAndNil(FStickyHeaders); inherited; end; procedure TksTableViewItemHeaderOptions.Assign(ASource: TPersistent); var Src : TksTableViewItemHeaderOptions; begin if (ASource is TksTableViewItemHeaderOptions) then begin Src := TksTableViewItemHeaderOptions(ASource); FHeight := Src.FHeight; FStickyHeaders.Assign(Src.FStickyHeaders); end else inherited; end; function TksTableViewItemHeaderOptions.GetHeaderColor: TAlphaColor; begin Result := FTableView.Appearence.HeaderColor; end; procedure TksTableViewItemHeaderOptions.SetHeaderColor(const Value: TAlphaColor); begin FTableView.Appearence.HeaderColor := Value; end; procedure TksTableViewItemHeaderOptions.SetHeaderHeight(const Value: integer); begin if FHeight <> Value then begin FHeight := Value; Changed; end; end; procedure TksTableViewItemHeaderOptions.SetStickyHeaders(const Value: TksTableViewStickyHeaderOptions); begin FStickyHeaders.Assign(Value); end; // ------------------------------------------------------------------------------ { TksTableViewBorderOptions } function TksTableViewBorderOptions.Showing: Boolean; begin Result := (Visible) and (FStroke.Color <> claNull) and (FStroke.Kind <> TBrushKind.None); end; procedure TksTableViewBorderOptions.Changed; begin FTableView.Invalidate; end; constructor TksTableViewBorderOptions.Create(ATableView: TksTableView); begin inherited Create; FTableView := ATableView; FStroke := TStrokeBrush.Create(TBrushKind.Solid, claBlack); FSides := AllSides; FVisible := False; end; destructor TksTableViewBorderOptions.Destroy; begin FreeAndNil(FStroke); inherited; end; procedure TksTableViewBorderOptions.Assign(ASource: TPersistent); var Src : TksTableViewBorderOptions; begin if (ASource is TksTableViewBorderOptions) then begin Src := TksTableViewBorderOptions(ASource); FVisible := Src.FVisible; FSides := Src.FSides; FStroke.Assign(Src.FStroke); end else inherited; end; function TksTableViewBorderOptions.IsSidesStored: Boolean; begin Result := FSides * AllSides <> AllSides end; procedure TksTableViewBorderOptions.SetSides(const Value: TSides); begin if FSides <> Value then begin FSides := Value; Changed; end; end; procedure TksTableViewBorderOptions.SetStroke(const Value: TStrokeBrush); begin FStroke.Assign(Value); Changed; end; procedure TksTableViewBorderOptions.SetVisible(const Value: Boolean); begin if FVisible <> Value then begin FVisible := Value; Changed; end; end; // ------------------------------------------------------------------------------ { TksTableViewFixedRowsOptions } constructor TksTableViewFixedRowsOptions.Create(ATableView: TksTableView); begin inherited Create; FTableView := ATableView; FHeaderCount := 0; FFooterCount := 0; FMinimumWorkHeight := 0; end; procedure TksTableViewFixedRowsOptions.Assign(ASource: TPersistent); var Src : TksTableViewFixedRowsOptions; begin if (ASource is TksTableViewFixedRowsOptions) then begin Src := TksTableViewFixedRowsOptions(ASource); FHeaderCount := Src.FHeaderCount; FFooterCount := Src.FFooterCount; FMinimumWorkHeight := Src.FMinimumWorkHeight; end else inherited; end; procedure TksTableViewFixedRowsOptions.Changed; begin FTableView.UpdateItemRects(false); FTableView.Invalidate; end; procedure TksTableViewFixedRowsOptions.SetHeaderCount(const Value: Integer); begin if (FHeaderCount <> Value) then begin FHeaderCount := Value; Changed; end; end; procedure TksTableViewFixedRowsOptions.SetFooterCount(const Value: Integer); begin if (FFooterCount <> Value) then begin FFooterCount := Value; Changed; end; end; procedure TksTableViewFixedRowsOptions.SetMinimumWorkHeight(const Value: Integer); begin if (FMinimumWorkHeight <> Value) then begin FMinimumWorkHeight := Value; Changed; end; end; // ------------------------------------------------------------------------------ { TksTableViewCheckMarkOptions } constructor TksTableViewCheckMarkOptions.Create(ATableView: TksTableView); begin inherited Create; FTableView := ATableView; FCheckMarks := TksTableViewCheckMarks.cmNone; FPosition := TksTableViewCheckMarkPosition.cmpRight; FCheckMarkChecked := TksTableViewItemAccessory.Create(nil); FCheckMarkUnchecked := TksTableViewItemAccessory.Create(nil); FCheckMarkChecked.FAccessory := atCheckBoxChecked; FCheckMarkChecked.FAlign := TksTableItemAlign.Leading; FCheckMarkChecked.Color := C_TABLEVIEW_ACCESSORY_KEEPCOLOR; FCheckMarkChecked.OwnsBitmap := False; FCheckMarkUnchecked.FAccessory := atCheckBox; FCheckMarkUnchecked.FAlign := TksTableItemAlign.Leading; FCheckMarkUnchecked.Color := C_TABLEVIEW_ACCESSORY_KEEPCOLOR; FCheckMarkUnchecked.OwnsBitmap := False; FShowInHeader := true; FCheckArea := caWholeRow; FCheckSelects := true; FHeaderCheckSelectsAll := true; end; destructor TksTableViewCheckMarkOptions.Destroy; begin FreeAndNil(FCheckMarkChecked); FreeAndNil(FCheckMarkUnchecked); inherited; end; procedure TksTableViewCheckMarkOptions.Changed; begin FTableView.ClearCache(ksClearCacheAll); FTableView.Invalidate; end; procedure TksTableViewCheckMarkOptions.SetCheckMarks(const Value: TksTableViewCheckMarks); begin if FCheckMarks <> Value then begin FCheckMarks := Value; if FCheckMarks <> TksTableViewCheckMarks.cmMultiSelect then FTableView.UncheckAll; Changed; end; end; procedure TksTableViewCheckMarkOptions.SetPosition(const Value: TksTableViewCheckMarkPosition); begin if FPosition <> Value then begin FPosition := Value; Changed; end; end; procedure TksTableViewCheckMarkOptions.SetShowInHeader(const Value: Boolean); begin if FShowInHeader <> Value then begin FShowInHeader := Value; Changed; end; end; procedure TksTableViewCheckMarkOptions.SetCheckArea(const Value: TksTableViewCheckMarkCheckArea); begin if FCheckArea <> Value then FCheckArea := Value; end; procedure TksTableViewCheckMarkOptions.SetCheckSelects(const Value: Boolean); begin if FCheckSelects <> Value then begin FCheckSelects := Value; Changed; end; end; procedure TksTableViewCheckMarkOptions.SetHeaderCheckSelectsAll(const Value: Boolean); begin if FHeaderCheckSelectsAll <> Value then FHeaderCheckSelectsAll := Value; end; procedure TksTableViewCheckMarkOptions.Assign(ASource: TPersistent); var Src : TksTableViewCheckMarkOptions; begin if (ASource is TksTableViewCheckMarkOptions) then begin Src := TksTableViewCheckMarkOptions(ASource); FCheckMarks := Src.FCheckMarks; FPosition := Src.FPosition; FShowInHeader := Src.FShowInHeader; FCheckArea := Src.FCheckArea; FCheckSelects := Src.FCheckSelects; FHeaderCheckSelectsAll := Src.FHeaderCheckSelectsAll; end else inherited; end; // ------------------------------------------------------------------------------ { TksTableViewStickyHeaderOptions } procedure TksTableViewStickyHeaderOptions.Changed; begin FTableView.Invalidate; end; constructor TksTableViewStickyHeaderOptions.Create(ATableView: TksTableView); begin inherited Create; FTableView := ATableView; FButton := TksTableViewStickyHeaderButton.Create(FTableView); FEnabled := True; FStickyHeight := 0; end; destructor TksTableViewStickyHeaderOptions.Destroy; begin FreeAndNil(FButton); inherited; end; procedure TksTableViewStickyHeaderOptions.Assign(ASource: TPersistent); var Src : TksTableViewStickyHeaderOptions; begin if (ASource is TksTableViewStickyHeaderOptions) then begin Src := TksTableViewStickyHeaderOptions(ASource); FEnabled := Src.FEnabled; FStickyHeight := Src.FStickyHeight; FButton.Assign(Src.FButton); FExtendScrollHeight := Src.FExtendScrollHeight; end else inherited; end; procedure TksTableViewStickyHeaderOptions.SetButton(const Value: TksTableViewStickyHeaderButton); begin FButton.Assign(Value); end; procedure TksTableViewStickyHeaderOptions.SetEnabled(const Value: Boolean); begin if FEnabled <> Value then begin FEnabled := Value; Changed; end; end; procedure TksTableViewStickyHeaderOptions.SetStickyHeight(const Value: single); begin if FStickyHeight <> Value then begin FStickyHeight := Value; Changed; end; end; procedure TksTableViewStickyHeaderOptions.SetExtendScrollHeight(const Value: Boolean); begin if FExtendScrollHeight <> Value then begin FExtendScrollHeight := Value; Changed; end; end; // ------------------------------------------------------------------------------ { TksTableViewJumpToHeaderOptions } constructor TksTableViewJumpToHeaderOptions.Create; begin FHeaderFill := TBrush.Create(TBrushKind.Solid, claWhite); FHeaderFont := TFont.Create; FHeaderTextColor := claBlack; FHeaderHeight := 32; FHeaderText := ''; FItemFill := TBrush.Create(TBrushKind.Solid, claWhite); FItemFont := TFont.Create; FItemTextColor := claBlack; FItemHeight := 32; end; destructor TksTableViewJumpToHeaderOptions.Destroy; begin FreeAndNil(FHeaderFill); FreeAndNil(FHeaderFont); FreeAndNil(FItemFill); FreeAndNil(FItemFont); inherited; end; procedure TksTableViewJumpToHeaderOptions.Assign(ASource: TPersistent); var Src : TksTableViewJumpToHeaderOptions; begin if (ASource is TksTableViewJumpToHeaderOptions) then begin Src := TksTableViewJumpToHeaderOptions(ASource); FHeaderFill.Assign(Src.HeaderFill); FHeaderFont.Assign(Src.HeaderFont); FHeaderTextColor := Src.HeaderTextColor; FHeaderHeight := Src.FHeaderHeight; FHeaderText := Src.HeaderText; FItemFill.Assign(Src.ItemFill); FItemFont.Assign(Src.ItemFont); FItemTextColor := Src.ItemTextColor; FItemHeight := Src.ItemHeight; end else inherited; end; // ------------------------------------------------------------------------------ { TksTableViewStickyHeaderButton } procedure TksTableViewStickyHeaderButton.Changed; begin FTableView.Invalidate; end; constructor TksTableViewStickyHeaderButton.Create(ATableView: TksTableView); begin inherited Create; FTableView := ATableView; FVisible := False; FButtonType := hbtJumpToHeader; FJumpToHeaderOptions := TksTableViewJumpToHeaderOptions.Create; FSelected := False; end; destructor TksTableViewStickyHeaderButton.Destroy; begin FreeAndNil(FJumpToHeaderOptions); inherited; end; procedure TksTableViewStickyHeaderButton.Assign(ASource: TPersistent); var Src : TksTableViewStickyHeaderButton; begin if (ASource is TksTableViewStickyHeaderButton) then begin Src := TksTableViewStickyHeaderButton(ASource); FVisible := Src.FVisible; FHeaderTableViewBackground.Assign(Src.FHeaderTableViewBackground); FHeaderTableViewShadowEffect.Assign(Src.FHeaderTableViewShadowEffect); FButtonType := Src.FButtonType; FJumpToHeaderOptions.Assign(Src.FJumpToHeaderOptions); FSelected := Src.FSelected; end else inherited; end; procedure TksTableViewStickyHeaderButton.SetVisible(const Value: Boolean); begin if FVisible <> Value then begin FVisible := Value; Changed; end; end; procedure TksTableViewStickyHeaderButton.SetButtonType(const Value: TksTableViewHeaderButtonType); begin if FButtonType <> Value then begin FButtonType := Value; Changed; end; end; procedure TksTableViewStickyHeaderButton.SetJumpToHeaderOptions(const Value: TksTableViewJumpToHeaderOptions); begin JumpToHeaderOptions.Assign(Value); end; procedure TksTableViewStickyHeaderButton.DoButtonClicked(Sender: TObject ; AItem: TksTableViewItem); var I : Integer; Form : TCustomForm; ScreenPos : TPointF; ButtonFormPos : TPointF; BottomFormPos : TPointF; AHeaderItem : TksTableViewItem; TableViewHeight : Single; begin FTableView.Invalidate; if FTableView.Root = nil then Exit; FSelected := true; if (FButtonType=hbtJumpToHeader) then begin if (FTableView.Root.GetObject is TCustomForm) then begin Form := TCustomForm(FTableView.Root.GetObject); ScreenPos := FTableView.LocalToScreen(PointF(0, FTableView.FStickyButtonRect.Bottom)); ButtonFormPos := Form.ScreenToClient(ScreenPos); ScreenPos := FTableView.LocalToScreen(PointF(0, FTableView.Height)); BottomFormPos := Form.ScreenToClient(ScreenPos); if FHeaderTableViewBackground = nil then FHeaderTableViewBackground := TRectangle.Create(Form); FHeaderTableViewBackground.Parent := Form; FHeaderTableViewBackground.Opacity := 0; FHeaderTableViewBackground.OnClick := CancelPopup; FHeaderTableViewBackground.SetBounds(0,0,Form.Width,Form.Height); if FHeaderTableView = nil then FHeaderTableView := TksTableView.Create(Form); FHeaderTableView.ClearItems; FHeaderTableView.Parent := Form; FHeaderTableView.BorderOptions.Visible := true; FHeaderTableView.ItemHeight := 32; FHeaderTableView.PullToRefresh.Enabled := false; FHeaderTableView.OnItemClick := JumpToHeaderClick; if FHeaderTableViewShadowEffect = nil then FHeaderTableViewShadowEffect := TShadowEffect.Create(Form); FHeaderTableViewShadowEffect.Parent := FHeaderTableView; FHeaderTableViewShadowEffect.Distance := 4; FHeaderTableView.BeginUpdate; if (FJumpToHeaderOptions.FHeaderText<>'') then begin with (FHeaderTableView.Items.AddHeader(FJumpToHeaderOptions.FHeaderText)) do begin Height := JumpToHeaderOptions.HeaderHeight; Fill.Assign(JumpToHeaderOptions.HeaderFill); Title.Font.Assign(JumpToHeaderOptions.HeaderFont); Title.TextColor := JumpToHeaderOptions.HeaderTextColor; end; end; for I:=0 to FTableView.FilteredItems.Count-1 do begin AHeaderItem := FTableView.FilteredItems[I]; if (AHeaderItem.Purpose=Header) then begin with (FHeaderTableView.Items.AddItem(AHeaderItem.Title.Text)) do begin Height := JumpToHeaderOptions.ItemHeight; Fill.Assign(JumpToHeaderOptions.ItemFill); Title.Font.Assign(JumpToHeaderOptions.ItemFont); Title.TextColor := JumpToHeaderOptions.ItemTextColor; end; end; end; FHeaderTableView.EndUpdate; TableViewHeight := FHeaderTableView.GetTotalItemHeight; if (ButtonFormPos.Y + TableViewHeight > BottomFormPos.Y - 6) then TableViewHeight := BottomFormPos.Y - ButtonFormPos.Y - 6; FHeaderTableView.SetBounds(4,ButtonFormPos.Y,FTableView.Width-10,TableViewHeight); end; end; end; procedure TksTableViewStickyHeaderButton.CancelPopup(Sender: TObject); begin FRemovePopupTimer := FTableView.CreateTimer(50,RemovePopup); end; procedure TksTableViewStickyHeaderButton.RemovePopup; var Form : TCustomForm; begin FTableView.KillTimer(FRemovePopupTimer); FSelected := False; FTableView.Invalidate; if (FTableView.Root.GetObject is TCustomForm) then begin Form := TCustomForm(FTableView.Root.GetObject); Form.RemoveObject(FHeaderTableViewShadowEffect); Form.RemoveObject(FHeaderTableView); Form.RemoveObject(FHeaderTableViewBackground); FreeAndNil(FHeaderTableViewShadowEffect); FreeAndNil(FHeaderTableView); FreeAndNil(FHeaderTableViewBackground); end; end; procedure TksTableViewStickyHeaderButton.JumpToHeaderClick(Sender: TObject; x, y: Single; AItem: TksTableViewItem; AId: string; ARowObj: TksTableViewItemObject); var I : Integer; AHeaderItem : TksTableViewItem; NeedsUpdate : Boolean; begin Sleep(100); NeedsUpdate := false; for I:=0 to FTableView.FilteredItems.Count-1 do begin AHeaderItem := FTableView.FilteredItems[I]; if (AHeaderItem.Purpose=Header) then begin if (FTableView.HeaderOptions.StickyHeaders.StickyHeight>0) then begin if (AHeaderItem.FHeaderHeight<>FTableView.HeaderOptions.StickyHeaders.StickyHeight) then begin AHeaderItem.FHeaderHeight := FTableView.HeaderOptions.StickyHeaders.StickyHeight; NeedsUpdate := true; end; end; if (AHeaderItem.Title.Text=AItem.Title.Text) then begin if (NeedsUpdate) then begin FTableView.UpdateItemRects(false); FTableView.UpdateScrollingLimits; end; FTableView.ScrollTo(AHeaderItem.ItemRect.Top); break; end; end; end; CancelPopup(Nil); end; // ------------------------------------------------------------------------------ { TksTableViewItemSwitch } function TksTableViewItemSwitch.CreateControl: TStyledControl; begin Result := TSwitch.Create(FTableItem.TableView); (Result as TSwitch).CanFocus := True; (Result as TSwitch).DisableFocusEffect := True; Fheight := (Result as TSwitch).DefaultSize.height; FWidth := (Result as TSwitch).DefaultSize.Width; {$IFDEF MSWINDOWS} Result.Width := 50; Result.Height := 30; {$ENDIF} FClickDelay := 0; end; procedure TksTableViewItemSwitch.DisableEvents; begin GetSwitch.OnSwitch := nil; end; procedure TksTableViewItemSwitch.DoSwitchClicked(Sender: TObject); begin if FClickDelay > 0 then Exit; FClickDelay := FTableItem.TableView.CreateTimer(250, DoSwitchClickedDelayed); end; procedure TksTableViewItemSwitch.DoSwitchClickedDelayed; begin FTableItem.TableView.KillTimer(FClickDelay); FTableItem.TableView.DoSwitchClicked(FTableItem, Self); end; procedure TksTableViewItemSwitch.EnableEvents; begin GetSwitch.OnSwitch := DoSwitchClicked; end; function TksTableViewItemSwitch.GetChecked: Boolean; begin Result := GetSwitch.IsChecked; end; function TksTableViewItemSwitch.GetSwitch: TSwitch; begin Result := (FControl as TSwitch); end; procedure TksTableViewItemSwitch.SetChecked(const Value: Boolean); begin GetSwitch.IsChecked := Value; end; // ------------------------------------------------------------------------------ { TksTableViewChatBubble } constructor TksTableViewChatBubble.Create(ATableItem: TksTableViewItem); begin inherited; FFont := TFont.Create; FShape := ksRoundRect; FFill.Color := claGray; FStroke.Kind := TBrushKind.None; FVertAlign := TksTableItemAlign.Center; FTextColor := claWhite; FPosition := ksCbpLeft; end; destructor TksTableViewChatBubble.Destroy; begin FreeAndNil(FFont); inherited; end; procedure TksTableViewChatBubble.RecalculateSize; begin FWidth := CalculateTextWidth(FText, FFont, False, FTableItem.TableView.Width * 0.60, 8)+24; FHeight := CalculateTextHeight(FText, FFont, True, TTextTrimming.None, FWidth, 8)+16; end; procedure TksTableViewChatBubble.Render(AItemRect: TRectF; ACanvas: TCanvas); var ARect: TRectF; APath: TPathData; begin inherited; ARect := ObjectRect; APath := TPathData.Create; try if FAlign = TksTableItemAlign.Leading then begin APath.MoveTo(PointF(ARect.Left-4, ARect.Bottom-2)); APath.LineTo(PointF(ARect.Left+10, ARect.Bottom-6)); APath.LineTo(PointF(ARect.Left+10, ARect.Bottom-18)); APath.LineTo(PointF(ARect.Left-4, ARect.Bottom-2)); end; if FAlign = TksTableItemAlign.Trailing then begin APath.MoveTo(PointF(ARect.Right+4, ARect.Bottom-2)); APath.LineTo(PointF(ARect.Right-10, ARect.Bottom-6)); APath.LineTo(PointF(ARect.Right-10, ARect.Bottom-18)); APath.LineTo(PointF(ARect.Right+4, ARect.Bottom-2)); end; ACanvas.Stroke.Color := claBlack; ACanvas.Fill.Color := FFill.Color; ACanvas.FillPath(APath, 1); finally FreeAndNil(APath); end; {$IFNDEF MSWINDOWS} OffsetRect(ARect, 8, 8); {$ENDIF} RenderText(ACanvas, ARect, FText, FFont, FTextColor, True, TTextAlign.Leading, TTextAlign.Center, TTextTrimming.None, 8); end; procedure TksTableViewChatBubble.SetFont(const Value: TFont); begin FFont.Assign(Value); RecalculateSize; Changed; end; procedure TksTableViewChatBubble.SetText(const Value: string); begin if FText <> Value then begin FText := Value; RecalculateSize; Changed; end; end; procedure TksTableViewChatBubble.SetTextColor(const Value: TAlphaColor); begin if FTextColor <> Value then begin FTextColor := Value; Changed; end; end; initialization AIsSwiping := False; AccessoryImages := TksTableViewAccessoryImageList.Create; finalization FreeAndNil(AccessoryImages); end.
unit ExchangeCurrencyTest; interface uses dbTest, dbMovementTest; type TExchangeCurrencyTest = class (TdbMovementTestNew) published procedure ProcedureLoad; override; procedure Test; override; end; TExchangeCurrency = class(TMovementTest) private function InsertDefault: integer; override; public function InsertUpdateExchangeCurrency(const Id: integer; InvNumber: String; OperDate: TDateTime; AmountFrom, AmountTo: Double; FromId, ToId, InfoMoneyId: integer): integer; constructor Create; override; end; implementation uses UtilConst, JuridicalTest, dbObjectTest, SysUtils, Db, TestFramework; { TExchangeCurrency } constructor TExchangeCurrency.Create; begin inherited; spInsertUpdate := 'gpInsertUpdate_Movement_ExchangeCurrency'; spSelect := 'gpSelect_Movement_ExchangeCurrency'; spGet := 'gpGet_Movement_ExchangeCurrency'; end; function TExchangeCurrency.InsertDefault: integer; var Id: Integer; InvNumber: String; OperDate: TDateTime; AmountFrom, AmountTo: Double; FromId, ToId, InfoMoneyId: Integer; begin Id:=0; InvNumber:='1'; OperDate:= Date; FromId := TPersonalTest.Create.GetDefault; ToId := TJuridical.Create.GetDefault; InfoMoneyId := 0; AmountFrom := 265.68; AmountTo := 432.10; result := InsertUpdateExchangeCurrency(Id, InvNumber, OperDate, AmountFrom, AmountTo, FromId, ToId, InfoMoneyId); end; function TExchangeCurrency.InsertUpdateExchangeCurrency(const Id: integer; InvNumber: String; OperDate: TDateTime; AmountFrom, AmountTo: Double; FromId, ToId, InfoMoneyId: integer): integer; begin FParams.Clear; FParams.AddParam('ioId', ftInteger, ptInputOutput, Id); FParams.AddParam('inInvNumber', ftString, ptInput, InvNumber); FParams.AddParam('inOperDate', ftDateTime, ptInput, OperDate); FParams.AddParam('inAmountFrom', ftFloat, ptInput, AmountFrom); FParams.AddParam('inAmountTo', ftFloat, ptInput, AmountTo); FParams.AddParam('inFromId', ftInteger, ptInput, FromId); FParams.AddParam('inToId', ftInteger, ptInput, ToId); FParams.AddParam('inInfoMoneyId', ftInteger, ptInput, InfoMoneyId); result := InsertUpdate(FParams); end; { TExchangeCurrencyTest } procedure TExchangeCurrencyTest.ProcedureLoad; begin ScriptDirectory := ProcedurePath + 'Movement\ExchangeCurrency\'; inherited; end; procedure TExchangeCurrencyTest.Test; var MovementExchangeCurrency: TExchangeCurrency; Id: Integer; begin inherited; // Создаем документ MovementExchangeCurrency := TExchangeCurrency.Create; Id := MovementExchangeCurrency.InsertDefault; // создание документа try // редактирование finally end; end; initialization TestFramework.RegisterTest('Документы', TExchangeCurrencyTest.Suite); end.
{$I ..\Definition.Inc} unit WrapVclSamplesSpin; interface uses Classes, Vcl.Samples.Spin, WrapDelphi, WrapVclControls, WrapVclStdCtrls; type TPyDelphiSpinButton = class (TPyDelphiWinControl) private function GetDelphiObject: TSpinButton; procedure SetDelphiObject(const Value: TSpinButton); public class function DelphiObjectClass : TClass; override; // Properties property DelphiObject: TSpinButton read GetDelphiObject write SetDelphiObject; end; TPyDelphiSpinEdit = class (TPyDelphiCustomEdit) private function GetDelphiObject: TSpinEdit; procedure SetDelphiObject(const Value: TSpinEdit); public class function DelphiObjectClass : TClass; override; // Properties property DelphiObject: TSpinEdit read GetDelphiObject write SetDelphiObject; end; implementation { Register the wrappers, the globals and the constants } type TSamplesSpinRegistration = class(TRegisteredUnit) public function Name: string; override; procedure RegisterWrappers(APyDelphiWrapper: TPyDelphiWrapper); override; procedure DefineVars(APyDelphiWrapper: TPyDelphiWrapper); override; end; { TStdCtrlsRegistration } procedure TSamplesSpinRegistration.DefineVars(APyDelphiWrapper: TPyDelphiWrapper); begin inherited; end; function TSamplesSpinRegistration.Name: string; begin Result := 'Samples.Spin'; end; procedure TSamplesSpinRegistration.RegisterWrappers(APyDelphiWrapper: TPyDelphiWrapper); begin inherited; APyDelphiWrapper.RegisterDelphiWrapper(TPyDelphiSpinButton); APyDelphiWrapper.RegisterDelphiWrapper(TPyDelphiSpinEdit); end; { TPyDelphiSpinButton } class function TPyDelphiSpinButton.DelphiObjectClass: TClass; begin Result := TSpinButton; end; function TPyDelphiSpinButton.GetDelphiObject: TSpinButton; begin Result := TSpinButton(inherited DelphiObject); end; procedure TPyDelphiSpinButton.SetDelphiObject(const Value: TSpinButton); begin inherited DelphiObject := Value; end; { TPyDelphiSpinEdit } class function TPyDelphiSpinEdit.DelphiObjectClass: TClass; begin Result := TSpinEdit; end; function TPyDelphiSpinEdit.GetDelphiObject: TSpinEdit; begin Result := TSpinEdit(inherited DelphiObject); end; procedure TPyDelphiSpinEdit.SetDelphiObject(const Value: TSpinEdit); begin inherited DelphiObject := Value; end; initialization RegisteredUnits.Add( TSamplesSpinRegistration.Create ); Classes.RegisterClasses([TSpinButton, TSpinEdit]); end.
(* Problema: TRENO, selezioni territoriali 2009 *) (* Autore: William Di Luigi <williamdiluigi[at]gmail[dot]com> *) (* Questa e' un'implementazione iterativa in linguaggio Pascal della *) (* soluzione al problema "TRENO", per una versione ricorsiva e in *) (* linguaggio C++ si veda il seguente link: *) (* http://www.imparando.net/elearning/INF0002/document/Territoriali_2009/soluzione_treno.html *) (* L'osservazione chiave della soluzione e' che posso ridurre un *) (* input di "dimensione" N in un'altro di dimensione (N-1) con tre *) (* spostamenti di coppie di vagoni, ad esempio supponiamo che N=5: *) (* Treno iniziale : AAAAABBBBB** *) (* Sposto in fondo i due vagoni "AB" adiacenti: AAAA**BBBBAB *) (* [corrisponde allo spostamento: (5, 11) ovvero (N, 2*N+1)] *) (* Sposto i primi due vagoni nel buco: **AAAABBBBAB *) (* [corrisponde allo spostamento: (1, 5) ovvero (1, N)] *) (* Sposto i vagoni "AB" di prima all'inizio: ABAAAABBBB** *) (* [corrisponde allo spostamento: (11, 1) ovvero (2*N+1, 1)] *) (* Notare che ora ho due vagoni "AB" seguiti da: "AAAABBBB**", quindi *) (* mi rimane da risolvere un problema con N=4 (prima era N=5). *) (* NOTA BENE: Adesso non e' mai piu' necessario toccare i primi due *) (* vagoni!, dobbiamo semplicemente "risolvere" il treno con N=4, in *) (* cui ogni operazione sara' "traslata" di +2 dato che ignoriamo le *) (* prime due posizioni! *) (* Dal momento che per ridurre dalla grandezza N alla grandezza N-1 *) (* faccio una trasformazione composta da TRE spostamenti, per andare *) (* da N a 1 impiego 3*N spostamenti, che MOLTO PROBABILMENTE NON E' *) (* IL NUMERO MINIMO ASSOLUTO di spostamenti necessari per effettuare *) (* la trasformazione, ma il testo non richiede il minimo assoluto! *) (* Inoltre, quando arrivo a N=3 (che e' il minimo valore possibile, *) (* guardare la sezione "Assunzioni" nel testo), so gia' fare la *) (* trasformazione in soli 4 passi (invece che 3*N = 9), quindi quando *) (* dovro' risolvere un treno di "dimensione" N, mi fermero' al *) (* "sottotreno" di "dimensione" 3 dato che lo so risolvere (guardare *) (* il primo caso di esempio illustrato nel testo del problema). *) (* Quindi impieghero' leggermente meno di 3*N spostamenti. *) var N, risposta, traslazione, copia_di_N, i : longint; spostamento : array[1..3*1000, 1..2] of longint; (* Al massimo 3*N spostamenti! *) begin (* Redireziona l'input/output da tastiera sui relativi files txt *) assign(input, 'input.txt'); assign(output, 'output.txt'); reset(input); rewrite(output); (* Leggi N *) read(N); (* Salva il valore di N perche' dopo devo stamparlo (Ma chissa' perche' poi???) *) copia_di_N := N; (* Inizializza la risposta a zero *) risposta := 0; (* All'inizio, sto considerando il treno intero, quindi: *) traslazione := 0; (* Finche' il treno ha "dimensione" troppo grande, riducila di uno! *) while N > 3 do begin (* Ricorda che in ogni spostamento, dobbiamo tener conto della traslazione accumulata! *) (* Sposta "AB" in fondo: *) inc(risposta); spostamento[risposta][1] := (N) + traslazione; (* Da: N *) spostamento[risposta][2] := (2*N+1) + traslazione; (* A: 2*N+1 *) (* Sposta "AA" iniziale nel buco: *) inc(risposta); spostamento[risposta][1] := (1) + traslazione; (* Da: 1 *) spostamento[risposta][2] := (N) + traslazione; (* A: N *) (* Sposta "AB" di prima all'inizio: *) inc(risposta); spostamento[risposta][1] := (2*N+1) + traslazione; (* Da: 2*N+1 *) spostamento[risposta][2] := (1) + traslazione; (* A: 1 *) (* Adesso ho "risolto" i primi due vagoni, devo "tagliarli via" *) (* Mi basta aumentare di 2 la traslazione! *) inc(traslazione, 2); (* Inoltre, adesso N e' diminuito di uno! *) dec(N); end; (* Quando arrivo qui, N e' diventato uguale a 3, oppure l'input aveva N=3 *) (* in ogni caso, ho ancora la variabile "traslazione" che mi fa capire se *) (* l'input era proprio N=3 (traslazione=0) oppure no. *) (* Non ci rimane che eseguire "A MANO" gli ultimi 4 spostamenti! *) (* Gli ultimi spostamenti sono: (2, 7), (6, 2), (4, 6), (7, 4). *) (* Nell'eseguirli, dobbiamo di nuovo tenere conto della traslazione! *) (* Spostamento (2, 7) *) inc(risposta); spostamento[risposta][1] := (2) + traslazione; spostamento[risposta][2] := (7) + traslazione; (* Spostamento (6, 2) *) inc(risposta); spostamento[risposta][1] := (6) + traslazione; spostamento[risposta][2] := (2) + traslazione; (* Spostamento (4, 6) *) inc(risposta); spostamento[risposta][1] := (4) + traslazione; spostamento[risposta][2] := (6) + traslazione; (* Spostamento (7, 4) *) inc(risposta); spostamento[risposta][1] := (7) + traslazione; spostamento[risposta][2] := (4) + traslazione; (* Ho finito! Ora devo solo stampare tutto! *) writeln(risposta, ' ', copia_di_N); for i:=1 to risposta do writeln(spostamento[i][1], ' ', spostamento[i][2]); end.
{ Invokable implementation File for TCalibrationWS which implements ICalibrationWS } unit CalibrationCH1WSImpl; interface uses InvokeRegistry, Types, XSBuiltIns, CalibrationCH1WSIntf, ActiveX, CommunicationObj, Constants; type { TCalibrationWS } TCalibrationCH1WS = class(TCommObj, ICalibrationCH1WS) public // ICalibration function Get_Potencia: Integer; safecall; function Get_CRadarPL: Single; safecall; function Get_CRadarPC: Single; safecall; function Get_PotMetPL: Single; safecall; function Get_PotMetPC: Single; safecall; function Get_MPS_Voltage: Double; safecall; function Get_Tx_Pulse_SP: Integer; safecall; function Get_Tx_Pulse_LP: Integer; safecall; function Get_Start_Sample_SP: Integer; safecall; function Get_Final_Sample_SP: Integer; safecall; function Get_Start_Sample_LP: Integer; safecall; function Get_Final_Sample_LP: Integer; safecall; function Get_Tx_Factor: Double; safecall; function Get_Stalo_Delay: Integer; safecall; function Get_Stalo_Step: Integer; safecall; function Get_Stalo_Width: Integer; safecall; function Get_Valid_tx_power: Double; safecall; function Get_Loop_Gain: Double; safecall; // ICalibrationControl procedure Set_Potencia(Value: Integer); safecall; procedure Set_CRadarPL(Value: Single); safecall; procedure Set_CRadarPC(Value: Single); safecall; procedure Set_MPS_Voltage(Value: Double); safecall; procedure Set_Tx_Pulse_SP(Value: Integer); safecall; procedure Set_Tx_Pulse_LP(Value: Integer); safecall; procedure Set_Start_Sample_SP(Value: Integer); safecall; procedure Set_Final_Sample_SP(Value: Integer); safecall; procedure Set_Start_Sample_LP(Value: Integer); safecall; procedure Set_Final_Sample_LP(Value: Integer); safecall; procedure Set_Tx_Factor(Value: Double); safecall; procedure Set_Stalo_Delay(Value: Integer); safecall; procedure Set_Stalo_Step(Value: Integer); safecall; procedure Set_Stalo_Width(Value: Integer); safecall; procedure Set_Valid_tx_power(Value: Double); safecall; procedure Set_Loop_Gain(Value: Double); safecall; procedure SaveDRX; safecall; function CheckCredentials : boolean; override; end; implementation uses Users, Calib, ElbrusTypes, ManagerDRX; { TCalibrationCH1WS } function TCalibrationCH1WS.CheckCredentials: boolean; begin result := CheckAuthHeader >= ul_Service; end; function TCalibrationCH1WS.Get_CRadarPC: Single; begin Result := theCalibration.CRadarPC1; end; function TCalibrationCH1WS.Get_CRadarPL: Single; begin Result := theCalibration.CRadarPL1; end; function TCalibrationCH1WS.Get_Final_Sample_LP: Integer; begin try if DRX1.Ready then result := DRX1.AFC_WS.Get_Final_Sample_LP else result := 0; except result := 0; DRX1.Validate; end; end; function TCalibrationCH1WS.Get_Final_Sample_SP: Integer; begin try if DRX1.Ready then result := DRX1.AFC_WS.Get_Final_Sample_SP else result := 0; except result := 0; DRX1.Validate; end; end; function TCalibrationCH1WS.Get_Loop_Gain: Double; begin try if DRX1.Ready then result := DRX1.AFC_WS.Get_Loop_Gain else result := 0; except result := 0; DRX1.Validate; end; end; function TCalibrationCH1WS.Get_MPS_Voltage: Double; begin Result := theCalibration.MPS_Voltage1; end; function TCalibrationCH1WS.Get_Potencia: Integer; begin Result := theCalibration.Potencia1; end; function TCalibrationCH1WS.Get_PotMetPC: Single; begin Result := theCalibration.PotMetPC1; end; function TCalibrationCH1WS.Get_PotMetPL: Single; begin Result := theCalibration.PotMetPC1; end; function TCalibrationCH1WS.Get_Stalo_Delay: Integer; begin try if DRX1.Ready then result := DRX1.AFC_WS.Get_Stalo_Delay else result := 0; except result := 0; DRX1.Validate; end; end; function TCalibrationCH1WS.Get_Stalo_Step: Integer; begin try if DRX1.Ready then result := DRX1.AFC_WS.Get_Stalo_Step else result := 0; except result := 0; DRX1.Validate; end; end; function TCalibrationCH1WS.Get_Stalo_Width: Integer; begin try if DRX1.Ready then result := DRX1.AFC_WS.Get_Stalo_Width else result := 0; except result := 0; DRX1.Validate; end; end; function TCalibrationCH1WS.Get_Start_Sample_LP: Integer; begin try if DRX1.Ready then result := DRX1.AFC_WS.Get_Start_Sample_LP else result := 0; except result := 0; DRX1.Validate; end; end; function TCalibrationCH1WS.Get_Start_Sample_SP: Integer; begin try if DRX1.Ready then result := DRX1.AFC_WS.Get_Start_Sample_SP else result := 0; except result := 0; DRX1.Validate; end; end; function TCalibrationCH1WS.Get_Tx_Factor: Double; begin try if DRX1.Ready then result := DRX1.AFC_WS.Get_Tx_Factor else result := 0; except result := 0; DRX1.Validate; end; end; function TCalibrationCH1WS.Get_Tx_Pulse_LP: Integer; begin try if DRX1.Ready then result := DRX1.AFC_WS.Get_Tx_Pulse_LP else result := 0; except result := 0; DRX1.Validate; end; end; function TCalibrationCH1WS.Get_Tx_Pulse_SP: Integer; begin try if DRX1.Ready then result := DRX1.AFC_WS.Get_Tx_Pulse_SP else result := 0; except result := 0; DRX1.Validate; end; end; function TCalibrationCH1WS.Get_Valid_tx_power: Double; begin try if DRX1.Ready then result := DRX1.AFC_WS.Get_Valid_Tx_Power else result := 0; except result := 0; DRX1.Validate; end; end; procedure TCalibrationCH1WS.SaveDRX; begin if InControl and DRX1.Ready then DRX1.AFC_WS.Save_Calibration; end; procedure TCalibrationCH1WS.Set_CRadarPC(Value: Single); begin if InControl then theCalibration.CRadarPC1 := Value; end; procedure TCalibrationCH1WS.Set_CRadarPL(Value: Single); begin if InControl then theCalibration.CRadarPL1 := Value; end; procedure TCalibrationCH1WS.Set_Final_Sample_LP(Value: Integer); begin try if InControl and DRX1.Ready then DRX1.AFC_WS.Set_Final_Sample_LP(Value); except DRX1.Validate; end; end; procedure TCalibrationCH1WS.Set_Final_Sample_SP(Value: Integer); begin try if InControl and DRX1.Ready then DRX1.AFC_WS.Set_Final_Sample_SP(Value); except DRX1.Validate; end; end; procedure TCalibrationCH1WS.Set_Loop_Gain(Value: Double); begin try if InControl and DRX1.Ready then DRX1.AFC_WS.Set_Loop_Gain(Value); except DRX1.Validate; end; end; procedure TCalibrationCH1WS.Set_MPS_Voltage(Value: Double); begin if InControl then theCalibration.MPS_Voltage1 := Value; end; procedure TCalibrationCH1WS.Set_Potencia(Value: Integer); begin if InControl then theCalibration.Potencia1 := Value; end; procedure TCalibrationCH1WS.Set_Stalo_Delay(Value: Integer); begin try if InControl and DRX1.Ready then DRX1.AFC_WS.Set_Stalo_Delay(Value); except DRX1.Validate; end; end; procedure TCalibrationCH1WS.Set_Stalo_Step(Value: Integer); begin try if InControl and DRX1.Ready then DRX1.AFC_WS.Set_Stalo_Step(Value); except DRX1.Validate; end; end; procedure TCalibrationCH1WS.Set_Stalo_Width(Value: Integer); begin try if InControl and DRX1.Ready then DRX1.AFC_WS.Set_Stalo_Width(Value); except DRX1.Validate; end; end; procedure TCalibrationCH1WS.Set_Start_Sample_LP(Value: Integer); begin try if InControl and DRX1.Ready then DRX1.AFC_WS.Set_Start_Sample_LP(Value); except DRX1.Validate; end; end; procedure TCalibrationCH1WS.Set_Start_Sample_SP(Value: Integer); begin try if InControl and DRX1.Ready then DRX1.AFC_WS.Set_Start_Sample_SP(Value); except DRX1.Validate; end; end; procedure TCalibrationCH1WS.Set_Tx_Factor(Value: Double); begin try if InControl and DRX1.Ready then DRX1.AFC_WS.Set_Tx_Factor(Value); except DRX1.Validate; end; end; procedure TCalibrationCH1WS.Set_Tx_Pulse_LP(Value: Integer); begin try if InControl and DRX1.Ready then DRX1.AFC_WS.Set_Tx_Pulse_LP(Value); except DRX1.Validate; end; end; procedure TCalibrationCH1WS.Set_Tx_Pulse_SP(Value: Integer); begin try if InControl and DRX1.Ready then DRX1.AFC_WS.Set_Tx_Pulse_SP(Value); except DRX1.Validate; end; end; procedure TCalibrationCH1WS.Set_Valid_tx_power(Value: Double); begin try if InControl and DRX1.Ready then DRX1.AFC_WS.Set_Valid_tx_power(Value); except DRX1.Validate; end; end; initialization { Invokable classes must be registered } InvRegistry.RegisterInvokableClass(TCalibrationCH1WS); end.
unit LDB.VCL.Clientes; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.Imaging.pngimage, Vcl.ExtCtrls, Data.DB, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Vcl.Mask, LDB.Cliente, Vcl.Buttons, System.ImageList, Vcl.ImgList; type TFrmClientes = class(TForm) imgBkg: TImage; pgcClientes: TPageControl; pgPesquisar: TTabSheet; pgNovo: TTabSheet; dbgClientes: TDBGrid; lblPesquisar: TLabel; txtPesquisar: TEdit; cbxCategoria: TComboBox; lblID: TLabel; txtID: TEdit; cbxTitulo: TComboBox; lblTitulo: TLabel; lblNome: TLabel; txtNome: TEdit; lblSobrenome: TLabel; txtSobrenome: TEdit; lblEndereco: TLabel; txtEndereco: TEdit; lblNumero: TLabel; txtNumero: TEdit; txtComplemento: TEdit; lblComplemento: TLabel; txtCidade: TEdit; lblCidade: TLabel; cbxEstado: TComboBox; lblEstado: TLabel; lblCEP: TLabel; txtCEP: TMaskEdit; txtTelefone: TMaskEdit; txtCelular: TMaskEdit; lblTelefone: TLabel; lblCelular: TLabel; btnSalvar: TSpeedButton; btnEditar: TSpeedButton; btnCancelar: TSpeedButton; btnNovo: TSpeedButton; btnExcluir: TSpeedButton; procedure txtPesquisarKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormCreate(Sender: TObject); procedure dbgClientesDblClick(Sender: TObject); procedure btnEditarClick(Sender: TObject); procedure btnCancelarClick(Sender: TObject); procedure btnSalvarClick(Sender: TObject); procedure pgPesquisarShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnNovoClick(Sender: TObject); procedure btnExcluirClick(Sender: TObject); private procedure mostrarCliente; procedure desativarCampos; procedure ativarCampos; procedure limparCampos; public procedure novoCliente; { Public declarations } end; var FrmClientes: TFrmClientes; c : TCliente; clienteId : integer; implementation {$R *.dfm} uses LDB.SQL.DataModule; procedure TFrmClientes.ativarCampos; begin cbxTitulo.Enabled := True; txtNome.Enabled := True; txtSobrenome.Enabled := True; txtTelefone.Enabled := True; txtCelular.Enabled := True; txtEndereco.Enabled := True; txtNumero.Enabled := True; txtComplemento.Enabled := True; txtCidade.Enabled := True; cbxEstado.Enabled := True; txtCEP.Enabled := True; end; procedure TFrmClientes.btnCancelarClick(Sender: TObject); begin if Assigned(c) then begin mostrarCliente; desativarCampos; btnCancelar.Enabled := False; btnSalvar.Enabled := False; btnEditar.Enabled := True; btnNovo.Enabled := True; btnExcluir.Enabled := True; end else begin pgcClientes.TabIndex := 0; //Close; //ModalResult := mrCancel; end; end; procedure TFrmClientes.btnEditarClick(Sender: TObject); begin ativarCampos; btnCancelar.Enabled := True; btnSalvar.Enabled := True; btnEditar.Enabled := False; btnNovo.Enabled := False; btnExcluir.Enabled := False; end; procedure TFrmClientes.btnExcluirClick(Sender: TObject); var res : Integer; Cliente : String; begin //res := messageDlg('Deseja realmente excluir o cliente: ' + '[' + txtID.Text + '] ' + txtNome.Text + ' ' + txtSobrenome.Text, mtError, mbOkCancel, 0); Cliente := PChar('Deseja realmente excluir o cliente: ' + '[' + txtID.Text + '] ' + txtNome.Text + ' ' + txtSobrenome.Text) + '?'; res := Application.MessageBox(PChar(Cliente), 'Atenção!', mb_OKCANCEL + mb_iconquestion + MB_SYSTEMMODAL); if res = mrOk then begin if TCliente.Create.deletar(strToInt(txtId.Text)) then begin Application.MessageBox('Cliente excluído com sucesso!', 'Confirmação', MB_ICONINFORMATION); novoCliente; limparCampos; FreeAndNil(c); end else begin Application.MessageBox('Falha ao excluir cliente!', 'Erro!', MB_ICONERROR); end; end; end; procedure TFrmClientes.btnNovoClick(Sender: TObject); begin ativarCampos; novoCliente; limparCampos; FreeAndNil(c); end; procedure TFrmClientes.btnSalvarClick(Sender: TObject); var Cli : TCliente; s : string; begin Cli := TCliente.Create; if txtId.Text <> '' then begin Cli.IdCliente := strToInt(txtID.Text); end; Cli.Titulo := cbxTitulo.Items[cbxTitulo.ItemIndex]; Cli.Nome := txtNome.Text; Cli.Sobrenome := txtSobrenome.Text; Cli.Telefone := txtTelefone.Text; Cli.Celular := txtCelular.Text; Cli.Endereco := txtEndereco.Text; Cli.Numero := txtNumero.Text; Cli.Complemento := txtComplemento.Text; Cli.Cidade := txtCidade.Text; Cli.Estado := cbxEstado.Items[cbxEstado.ItemIndex]; Cli.CEP := txtCEP.Text; if txtId.Text <> '' then begin if TCliente.Create.atualizar(Cli) then begin messageDlg('Cliente atualizado com sucesso!', mtInformation, [mbOk], 0); desativarCampos; btnSalvar.Enabled := False; btnEditar.Enabled := True; btnCancelar.Enabled := False; btnNovo.Enabled := True; btnExcluir.Enabled := True; //pgcClientes.TabIndex := 0; end else begin messageDlg('Falha ao atualizar o cliente!', mtError, [mbOk], 0); end; end else begin clienteId := TCliente.Create.inserir(Cli); if clienteId <> -1 then begin messageDlg('Cliente registrado com sucesso!', mtInformation, [mbOk], 0); mostrarCliente; desativarCampos; btnSalvar.Enabled := False; btnEditar.Enabled := True; btnCancelar.Enabled := False; btnNovo.Enabled := True; btnExcluir.Enabled := True; //pgcClientes.TabIndex := 0; end else begin messageDlg('Falha ao salvar o cliente!', mtError, [mbOk], 0); end; end; end; procedure TFrmClientes.dbgClientesDblClick(Sender: TObject); begin clienteId := strToInt(dbgClientes.Columns.Items[0].Field.Text); mostrarCliente; desativarCampos; btnCancelar.Enabled := False; btnSalvar.Enabled := False; btnEditar.Enabled := True; btnNovo.Enabled := True; btnExcluir.Enabled := True; end; procedure TFrmClientes.desativarCampos; begin cbxTitulo.Enabled := False; txtNome.Enabled := False; txtSobrenome.Enabled := False; txtTelefone.Enabled := False; txtCelular.Enabled := False; txtEndereco.Enabled := False; txtNumero.Enabled := False; txtComplemento.Enabled := False; txtCidade.Enabled := False; cbxEstado.Enabled := False; txtCEP.Enabled := False; end; procedure TFrmClientes.FormClose(Sender: TObject; var Action: TCloseAction); begin if Assigned(c) then begin FreeAndNil(c); end; end; procedure TFrmClientes.FormCreate(Sender: TObject); var bmp: TBitmap; begin pgcClientes.TabIndex := 0; dbgClientes.EditorMode := False; end; procedure TFrmClientes.limparCampos; begin txtID.Text := ''; cbxTitulo.ItemIndex := 0; txtNome.Text := ''; txtSobrenome.Text := ''; txtTelefone.Text := ''; txtCelular.Text := ''; txtEndereco.Text := ''; txtNumero.Text := ''; txtComplemento.Text := ''; txtCidade.Text := ''; cbxEstado.ItemIndex := 0; txtCEP.Text := ''; txtNome.SetFocus; end; procedure TFrmClientes.mostrarCliente; var i : Integer; begin c := TCliente.Create.pesquisar(clienteId); txtID.Text := intToStr(c.IdCliente); cbxTitulo.ItemIndex := cbxTitulo.Items.IndexOf(c.Titulo); txtNome.Text := c.Nome; txtSobrenome.Text := c.Sobrenome; txtTelefone.Text := c.Telefone; txtCelular.Text := c.Celular; txtEndereco.Text := c.Endereco; txtNumero.Text := c.Numero; txtComplemento.Text := c.Complemento; txtCidade.Text := c.Cidade; cbxEstado.ItemIndex := cbxEstado.Items.IndexOf(c.Estado); txtCEP.Text := c.CEP; pgcClientes.TabIndex := 1; end; procedure TFrmClientes.novoCliente; begin pgcClientes.TabIndex := 1; btnNovo.Enabled := False; btnSalvar.Enabled := True; btnEditar.Enabled := False; btnCancelar.Enabled := True; btnExcluir.Enabled := False; ativarCampos; end; procedure TFrmClientes.pgPesquisarShow(Sender: TObject); begin with LDB.SQL.DataModule.dm.Query do begin Close; SQL.Clear; SQL.Add('SELECT id_cliente AS ID, CONCAT(nome, " ", sobrenome) AS Cliente, endereco AS Endereço, fone_fixo AS Telefone FROM tb_cliente WHERE fg_ativo = 1'); Open; end; end; procedure TFrmClientes.txtPesquisarKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin with LDB.SQL.DataModule.dm.Query do begin Close; SQL.Clear; case cbxCategoria.ItemIndex of 0://Nome begin SQL.Add('SELECT id_cliente AS ID, CONCAT(nome, " ", sobrenome) AS Cliente, endereco AS Endereço, fone_fixo AS Telefone FROM tb_cliente WHERE nome LIKE "' + txtPesquisar.Text + '%" AND fg_ativo = 1'); end; 1://Endereço begin SQL.Add('SELECT id_cliente AS ID, CONCAT(nome, " ", sobrenome) AS Cliente, endereco AS Endereço, fone_fixo AS Telefone FROM tb_cliente WHERE endereco LIKE "' + txtPesquisar.Text + '%" AND fg_ativo = 1'); end; 2://Telefone begin SQL.Add('SELECT id_cliente AS ID, CONCAT(nome, " ", sobrenome) AS Cliente, endereco AS Endereço, fone_fixo AS Telefone FROM tb_cliente WHERE fone_fixo LIKE "' + txtPesquisar.Text + '%" AND fg_ativo = 1'); end; end; Open; end; end; end.
unit RegImgLibObjs; interface uses Windows, Messages, SysUtils, Classes, Graphics,Controls; procedure Register; implementation uses ImageLibX,ImgLibObjs,DLGImgObjPropEd,DsgnIntf; type TImgLibObjProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; end; TILImageEditor = class(TComponentEditor) private procedure LoadImage; public function GetVerbCount: Integer; override; function GetVerb(Index: Integer): string;override; procedure ExecuteVerb(Index: Integer); override; end; procedure Register; begin //RegisterFileExt; RegisterComponents('users',[TILImage]); RegisterPropertyEditor(TImgLibObj.ClassInfo,nil,'',TImgLibObjProperty); RegisterComponentEditor(TILImage,TILImageEditor); end; { TImgLibObjProperty } procedure TImgLibObjProperty.Edit; var OpenDialog : TdlgImgObjpropEditor; image : TImgLibObj; begin image := TImgLibObj.Create; image.Assign(TImgLibObj(getOrdValue)); OpenDialog := TdlgImgObjpropEditor.Create(nil); try if OpenDialog.execute(image) then begin SetOrdValue(integer(image)); end; finally OpenDialog.free; image.free; end; end; function TImgLibObjProperty.GetAttributes: TPropertyAttributes; begin Result := [paMultiSelect, paSubProperties, paDialog, paReadOnly]; end; { TILImageEditor } procedure TILImageEditor.ExecuteVerb(Index: Integer); begin with Component as TILImage do case index of 0 : LoadImage; 1 : ImageObj.Clear; end; end; function TILImageEditor.GetVerb(Index: Integer): string; begin case index of 0 : result := 'Load Image...'; 1 : result := 'Clear Image'; end; end; function TILImageEditor.GetVerbCount: Integer; begin result := 2; end; procedure TILImageEditor.LoadImage; var OpenDialog : TdlgImgObjpropEditor; begin OpenDialog := TdlgImgObjpropEditor.Create(nil); try OpenDialog.execute(TILImage(Component).ImageObj); finally OpenDialog.free; end; end; end.
unit udrawtim; interface uses utim, Grids, Graphics, types, BGRABitmap; type PCanvas = ^TCanvas; PDrawSurf = ^TBGRABitmap; PDrawGrid = ^TDrawGrid; procedure Tim2Png(TIM: PTIM; CLUT_NUM: Integer; Image: PDrawSurf; TranspMode: Byte; ForExport: Boolean); procedure Png2Tim(Image: PDrawSurf; Dest: PTIM); procedure DrawClutCell(TIM: PTIM; CLUT_NUM: Integer; Grid: PDrawGrid; X, Y: Integer); procedure DrawClut(TIM: PTIM; CLUT_NUM: Integer; Grid: PDrawGrid); procedure ClearCanvas(ACanvas: PCanvas; Rect: TRect); procedure ClearGrid(Grid: PDrawGrid); implementation uses BGRABitmapTypes, Math, FPimage; type PFPPalette = ^TFPPalette; procedure AlphaForMode(C: PFPColor; TranspMode: Integer); var BT, CT: Boolean; begin BT := TranspMode in [0, 1]; CT := TranspMode in [0, 2]; if not (BT or CT) then C^.alpha := $FFFF else begin if (C^.red + C^.green + C^.blue) = 0 then case (C^.alpha and 1) of 0: C^.alpha := Word(ifthen(BT, 0, $FFFF)); 1: C^.alpha := $FFFF; end else if CT then case (C^.alpha and 1) of 0: C^.alpha := $FFFF; 1: C^.alpha := Word(ifthen(CT, $8080, $FFFF)); end else C^.alpha := $FFFF; end; end; function StpFromAlpha(C: PFPColor): Byte; begin Result := 0; if (C^.red + C^.green + C^.blue) = 0 then case C^.alpha of $0000: Result := 0; $FFFF: Result := 1; end else case C^.alpha of $FFFF: Result := 0; $8080: Result := 1; end end; procedure PrepareClut(TIM: PTIM; CLUT_NUM: Integer; Pal: PFPPalette; TranspMode: Integer; ForExport: Boolean); var I, COUNT: Integer; CC: TCLUT_COLOR; R, G, B, A: Byte; FC: TFPColor; begin if (TIM^.OverBpp in [cTIM16NC, cTIM24NC]) then Exit; if (TIM^.OverBpp in [cTIM4NC, cTIM8NC]) then begin Randomize; COUNT := 256; end else COUNT := GetTimColorsCount(TIM); Pal^.Clear; for I := 1 to 256 do begin CC := GetCLUTColor(TIM, CLUT_NUM, I - 1); if I <= COUNT then begin R := CC.R; G := CC.G; B := CC.B; A := CC.STP; end else begin R := 0; G := 0; B := 0; A := 0; end; if ForExport then begin R := R + ((I - 1) and %00000011); G := G + ((I - 1) and %00011100) shr 2; B := B + ((I - 1) and %11100000) shr 5; end; FC := BGRAToFPColor(BGRA(R, G, B, A)); AlphaForMode(@FC, TranspMode); Pal^.Add(FC); end; end; function PrepareImage(TIM: PTIM): PIMAGE_INDEXES; var I, OFFSET: Integer; RW: Word; P24: Integer; WH: Integer; begin New(Result); OFFSET := SizeOf(TTIMHeader) + GetTIMCLUTSize(TIM) + SizeOf(TIMAGEHeader); RW := GetTimRealWidth(TIM); WH := TIM^.IMAGE^.wWidth * TIM^.IMAGE^.wHeight; case TIM^.OverBpp of cTIM4C, cTIM4NC: for I := 1 to WH * 2 do begin Result^[(I - 1) * 2] := TIM^.DATA^[OFFSET + I - 1] and $F; Result^[(I - 1) * 2 + 1] := (TIM^.DATA^[OFFSET + I - 1] and $F0) shr 4; end; cTIM8C, cTIM8NC: for I := 1 to WH * 2 do Result^[I - 1] := TIM^.DATA^[OFFSET + I - 1]; cTIM16C, cTIM16NC: for I := 1 to WH do Move(TIM^.DATA^[OFFSET + (I - 1) * 2], Result^[I - 1], 2); cTIM24C, cTIM24NC: begin I := 1; P24 := 0; while I <= (WH * 2) do begin Result^[P24] := 0; Move(TIM^.DATA^[OFFSET + (I - 1)], Result^[P24], 3); Inc(I, 3); if Odd(RW) and (((P24 + 1) mod RW) = 0) then Inc(OFFSET); Inc(P24); end; end; end; end; procedure ClearCanvas(ACanvas: PCanvas; Rect: TRect); begin ACanvas^.FillRect(Rect); end; procedure ClearGrid(Grid: PDrawGrid); var X, Y, W, H: Word; begin W := Grid^.ColCount; H := Grid^.RowCount; for Y := 1 to H do for X := 1 to W do ClearCanvas(@Grid^.Canvas, Grid^.CellRect(X - 1, Y - 1)); end; procedure Tim2Png(TIM: PTIM; CLUT_NUM: Integer; Image: PDrawSurf; TranspMode: Byte; ForExport: Boolean); var RW, RH, CW: Word; INDEXES: PIMAGE_INDEXES; X, Y, INDEX, IDX, COLORS: Integer; R, G, B: Byte; CC: TCLUT_COLOR; PAL: PFPPalette; FC: TFPColor; begin RW := GetTimRealWidth(TIM); RH := GetTimHeight(TIM); if (Image^ <> nil) then Image^.Free; Image^ := TBGRABitmap.Create(RW, RH); Image^.UsePalette := not(TIM^.OverBpp in [cTIM16NC, cTIM24NC]); PAL := @(Image^.Palette); PrepareClut(TIM, CLUT_NUM, PAL, TranspMode, ForExport); INDEXES := PrepareIMAGE(TIM); COLORS := GetTimColorsCount(TIM); COLORS := ifthen(COLORS = 0, 256, COLORS); IDX := 0; R := 0; G := 0; B := 0; for Y := 1 to RH do for X := 1 to RW do begin case TIM^.OverBpp of cTIM4C, cTIM4NC, cTIM8C, cTIM8NC: Image^.Pixels[X - 1, Y - 1] := INDEXES^[IDX] mod COLORS; cTIM16C, cTIM16NC, cTIMMixC, cTIMMixNC: begin CW := 0; Move(INDEXES^[IDX], CW, 2); CC := ConvertTIMColor(CW); FC := BGRAToFPColor(BGRA(CC.R, CC.G, CC.B, CC.STP)); AlphaForMode(@FC, TranspMode); Image^.Colors[X - 1, Y - 1] := FC; end; cTIM24C, cTIM24NC: begin INDEX := INDEXES^[IDX]; R := (INDEX and $FF); G := ((INDEX and $FF00) shr 8); B := ((INDEX and $FF0000) shr 16); Image^.Colors[X - 1, Y - 1] := BGRAToFPColor(BGRA(R, G, B, 255)); end; else Break; end; Inc(IDX); end; Dispose(INDEXES); end; procedure Png2Tim(Image: PDrawSurf; Dest: PTIM); var IW, IH, X, Y, CW: Word; TData: PTIMDataArray; POS: Integer; CC: TCLUT_COLOR; PC: TBGRAPixel; FC: TFPColor; CD: DWord; begin IW := Image^.Width; IH := Image^.Height; TData := @Dest^.DATA^[SizeOf(TTIMHeader) + GetTIMCLUTSize(Dest) + SizeOf(TIMAGEHeader)]; POS := 0; for Y := 0 to IH-1 do case Dest^.HEAD^.bBPP of cTIM4C, cTIM4NC: for X := 0 to (IW div 2)-1 do begin TData^[POS] := Byte(Image^.Pixels[X * 2, Y]); TData^[POS] := (Byte(Image^.Pixels[X * 2 + 1, Y]) shl 4) and $F0 + TData^[POS]; Inc(POS); end; cTIM8C, cTIM8NC: for X := 0 to IW-1 do begin TData^[POS] := Byte(Image^.Pixels[X, Y]); Inc(POS); end; cTIM16C, cTIM16NC: for X := 0 to IW-1 do begin FC := Image^.Colors[X, Y]; CC.STP := StpFromAlpha(@FC); PC := FPColorToBGRA(FC); CC.R := PC.red; CC.G := PC.green; CC.B := PC.blue; CW := ConvertCLUTColor(CC); Move(CW, TData^[POS], 2); Inc(POS, 2); end; cTIM24C, cTIM24NC: for X := 0 to IW-1 do begin FC := Image^.Colors[X, Y]; PC := FPColorToBGRA(FC); CD := (PC.blue shl 16) + (PC.green shl 8) + PC.red; Move(CD, TData^[POS], 3); Inc(POS, 3); if Odd(IW) and ((IW - X + 1) = 0) then begin TData^[POS] := 0; Inc(POS); end; end; end; end; procedure DrawClutCell(TIM: PTIM; CLUT_NUM: Integer; Grid: PDrawGrid; X, Y: Integer); var CLUT_COLOR: PCLUT_COLOR; R, G, B, STP: Byte; Rect: TRect; COLS, Colors: Integer; FC: TFPColor; begin Colors := GetTimColorsCount(TIM); COLS := Min(Colors, 32); Rect := Grid^.CellRect(X, Y); if (Y * COLS + X) >= Colors then begin ClearCanvas(@Grid^.Canvas, Rect); Exit; end; New(CLUT_COLOR); CLUT_COLOR^ := GetCLUTColor(TIM, CLUT_NUM, Y * COLS + X); R := CLUT_COLOR^.R; G := CLUT_COLOR^.G; B := CLUT_COLOR^.B; STP := CLUT_COLOR^.STP; Grid^.Canvas.Brush.COLOR := RGBToColor(R, G, B); Grid^.Canvas.FillRect(Rect); FC := BGRAToFPColor(BGRA(R, G, B, STP)); AlphaForMode(@FC, 0); if (FC.alpha = 0) or (FC.alpha = $8080) then begin if (R + G + B)/3 > 128 then Grid^.Canvas.Brush.COLOR := clBlack else Grid^.Canvas.Brush.COLOR := clWhite; if FC.ALPHA = 0 then Rect.Bottom := Rect.Top + ((Rect.Bottom - Rect.Top) div 2) else Rect.Right := Rect.Left + ((Rect.Right - Rect.Left) div 2); Grid^.Canvas.FillRect(Rect); end; Dispose(CLUT_COLOR); end; procedure DrawCLUT(TIM: PTIM; CLUT_NUM: Integer; Grid: PDrawGrid); var X, Y, ROWS, COLS, COLORS: Integer; begin COLORS := GetTimColorsCount(TIM); COLS := Min(COLORS, 32); Grid^.ColCount := COLS; ROWS := Ceil(COLORS / COLS); Grid^.RowCount := ROWS; for Y := 1 to ROWS do for X := 1 to COLS do begin //ClearCanvas(@Grid^.Canvas, Grid^.CellRect(X - 1, Y - 1)); DrawClutCell(TIM, CLUT_NUM, Grid, X - 1, Y - 1); end; end; end.
{----------------------------------------------------------------------------- Unit Name: DUStartup Author: Sebastian Hütter Date: 2006-08-01 Purpose: Check if a given program is set to run on startup an do this setting History: 2006-08-01 initial release -----------------------------------------------------------------------------} unit DUStartup; interface uses windows, Registry; type TStartType = (stRunCU,stRunOnce,stRunLM); function IsAutostart(Key:string; StartType:TStartType):boolean; function ReadAutostart(Key:string; StartType:TStartType):string; procedure WriteAutostart(Key:string; StartType:TStartType; FileName:String); procedure DeleteAutostart(Key:string; StartType:TStartType); implementation function GetReg(S:TStartType):TRegistry; begin Result:= TRegistry.Create; case s of stRunCU: begin Result.RootKey:=HKEY_CURRENT_USER; Result.OpenKey('\Software\Microsoft\Windows\CurrentVersion\Run',false); end; stRunLM: begin Result.RootKey:=HKEY_CURRENT_USER; Result.OpenKey('\Software\Microsoft\Windows\CurrentVersion\RunOnce',false); end; stRunOnce: begin Result.RootKey:=HKEY_LOCAL_MACHINE; Result.OpenKey('\Software\Microsoft\Windows\CurrentVersion\Run',false); end; end; end; function IsAutostart(Key:string; StartType:TStartType):boolean; begin Result:= ReadAutostart(Key,StartType)>''; end; function ReadAutostart(Key:string; StartType:TStartType):string; var r:TRegistry; begin r:= GetReg(StartType); try try result:= r.ReadString(Key); except Result:= ''; end; finally r.Free; end; end; procedure WriteAutostart(Key:string; StartType:TStartType; FileName:String); var r:TRegistry; begin r:= GetReg(StartType); try if FileName>'' then r.WriteString(Key,FileName) else r.DeleteValue(Key); finally r.Free; end; end; procedure DeleteAutostart(Key:string; StartType:TStartType); begin WriteAutostart(Key,StartType,''); end; end.
{*******************************************************} { } { Delphi Runtime Library } { } { Copyright(c) 1995-2014 Embarcadero Technologies, Inc. } { } { Message-digest algorithm based on C sample } { provided in Appendix section of } { Rivest-MD5.TXT available at: } { http://theory.lcs.mit.edu/~rivest/Rivest-MD5.txt } { } {*******************************************************} unit MessageDigest_5; interface uses Types; type IMD5 = interface ['{887C9EF0-15B9-41B4-A403-0431793B6E41}'] procedure Init; procedure Update(const Input: TByteDynArray; Len: Longword); overload; procedure Update(const Input: string); overload; function Final: TByteDynArray; function AsString: string; function AsGUID: string; end; function GetMD5: IMD5; implementation const S11 = 7; S12 = 12; S13 = 17; S14 = 22; S21 = 5; S22 = 9; S23 = 14; S24 = 20; S31 = 4; S32 = 11; S33 = 16; S34 = 23; S41 = 6; S42 = 10; S43 = 15; S44 = 21; var padding: TByteDynArray; type ArrayOfLWord= array of Longword; TMD5 = class(TInterfacedObject, IMD5) private FContextState: ArrayOfLWord; FContextCount: ArrayOfLWord; FContextBuffer: TByteDynArray; public constructor Create; procedure Init; virtual; procedure Update(const Input: TByteDynArray; Len: Longword); overload; virtual; procedure Update(const Input: string); overload; virtual; function Final: TByteDynArray; virtual; procedure Transform(const block: TByteDynArray; shift: Integer); procedure Decode(var Dst: ArrayOfLWord; const Src: TByteDynArray; Len: Integer; shift: Integer); procedure Encode(var Dst: TByteDynArray; const Src: ArrayOfLWord; Len: Integer); function AsString: string; function AsGUID: string; end; function GetMD5: IMD5; begin Result := TMD5.Create; end; constructor TMD5.Create; begin inherited Create; Init; end; procedure TMD5.Init; begin SetLength(FContextCount, 2); FContextCount[0] := 0; FContextCount[1] := 0; SetLength(FContextState, 4); FContextState[0] := $67452301; FContextState[1] := $efcdab89; FContextState[2] := $98badcfe; FContextState[3] := $10325476; SetLength(FContextBuffer, 64); end; procedure TMD5.Update(const Input: string); var {$IFDEF UNICODE} utf8Str: UTF8String; {$ENDIF} Bytes: TByteDynArray; Len: Integer; Str: PAnsiChar; begin {$IFDEF UNICODE} utf8Str := UTF8Encode(Input); Len := Length(utf8Str); {$ELSE} Len := Length(Input); {$ENDIF} if Len > 0 then begin SetLength(Bytes, Len); {$IFDEF UNICODE} Str := PAnsiChar(utf8Str); {$ELSE} Str := PAnsiChar(Input); {$ENDIF} Move(Str^, Pointer(Bytes)^, Len); Update(Bytes, Len); end; end; procedure TMD5.Update(const Input: TByteDynArray; Len: Longword); var index, partlen, I, start: Longword; begin { Compute number of bytes mod 64 } index := (FContextCount[0] shr 3) and $3f; { Update number of bits } Inc(FContextCount[0], Len shl 3); if (FContextCount[0] < (Len shl 3)) then Inc(FContextCount[1]); Inc(FContextCount[1], Len shr 29); partlen := 64 - index; { Transform (as many times as possible) } if Len >= partLen then begin for I := 0 to partLen-1 do FContextBuffer[I+index] := Input[I]; Transform(FContextBuffer, 0); I := partLen; while (I + 63) < Len do begin Transform(Input, I); Inc(I, 64); end; index := 0; end else I := 0; { Input remaining input } if (I < Len) then begin start := I; while (I < Len) do begin FContextBuffer[index+I-start] := Input[I]; Inc(I); end; end; end; function TMD5.Final: TByteDynArray; var bits: TByteDynArray; index, padlen: Integer; begin { Save number of bits } Encode(bits, FContextCount, 8); { Pad out to 56 mod 64 } index := (FContextCount[0] shr 3) and $3f; if index < 56 then padlen := 56 - index else padlen := 120- index; Update(padding, padLen); { Append length (before padding) } Update(bits, 8); { Store state in digest } Encode(Result, FContextState, 16); end; function TMD5.AsString: string; const XD: array[0..15] of char = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'); var digest: TByteDynArray; I: Integer; begin Result := ''; digest := Final; for I := 0 to Length(digest)-1 do Result := Result + XD[(digest[I] shr 4) and $0f] + XD[digest[I] and $0f]; end; function TMD5.AsGUID: string; const XD: array[0..15] of char = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'); var digest: TByteDynArray; I: Integer; begin Result := ''; digest := Final; for I := 0 to Length(digest)-1 do begin case I of 0: Result := Result + '{'; 4, 6, 8, 10: Result := Result + '-'; end; Result := Result + XD[(digest[I] shr 4) and $0f] + XD[digest[I] and $0f]; if I = 15 then Result := Result + '}'; end; end; procedure TMD5.Transform(const block: TByteDynArray; shift: Integer); function F(x, y, z: Longword): Longword; begin Result := (x and y) or ((not x) and z); end; function G(x, y, z: Longword): Longword; begin Result := (x and z) or (y and (not z)); end; function H(x, y, z: Longword): Longword; begin Result := x xor y xor z; end; function I(x, y, z: Longword): Longword; begin Result := y xor (x or (not z)); end; procedure RL(var x: Longword; n: Byte); begin x := (x shl n) or (x shr (32 - n)); end; procedure FF(var a: Longword; b, c, d, x: Longword; s: Byte; ac: Longword); begin Inc(a, F(b, c, d) + x + ac); RL(a, s); Inc(a, b); end; procedure GG(var a: Longword; b, c, d, x: Longword; s: Byte; ac: Longword); begin Inc(a, G(b, c, d) + x + ac); RL(a, s); Inc(a, b); end; procedure HH(var a: Longword; b, c, d, x: Longword; s: Byte; ac: Longword); begin Inc(a, H(b, c, d) + x + ac); RL(a, s); Inc(a, b); end; procedure II(var a: Longword; b, c, d, x: Longword; s: Byte; ac: Longword); begin Inc(a, I(b, c, d) + x + ac); RL(a, s); Inc(a, b); end; var a, b, c, d: Longword; x: ArrayOfLWord; begin a := FContextState[0]; b := FContextState[1]; c := FContextState[2]; d := FContextState[3]; Decode(x, block, 64, shift); { Round 1 } FF( a, b, c, d, x[ 0], S11, $d76aa478); { 1 } FF( d, a, b, c, x[ 1], S12, $e8c7b756); { 2 } FF( c, d, a, b, x[ 2], S13, $242070db); { 3 } FF( b, c, d, a, x[ 3], S14, $c1bdceee); { 4 } FF( a, b, c, d, x[ 4], S11, $f57c0faf); { 5 } FF( d, a, b, c, x[ 5], S12, $4787c62a); { 6 } FF( c, d, a, b, x[ 6], S13, $a8304613); { 7 } FF( b, c, d, a, x[ 7], S14, $fd469501); { 8 } FF( a, b, c, d, x[ 8], S11, $698098d8); { 9 } FF( d, a, b, c, x[ 9], S12, $8b44f7af); { 10 } FF( c, d, a, b, x[10], S13, $ffff5bb1); { 11 } FF( b, c, d, a, x[11], S14, $895cd7be); { 12 } FF( a, b, c, d, x[12], S11, $6b901122); { 13 } FF( d, a, b, c, x[13], S12, $fd987193); { 14 } FF( c, d, a, b, x[14], S13, $a679438e); { 15 } FF( b, c, d, a, x[15], S14, $49b40821); { 16 } { Round 2 } GG( a, b, c, d, x[ 1], S21, $f61e2562); { 17 } GG( d, a, b, c, x[ 6], S22, $c040b340); { 18 } GG( c, d, a, b, x[11], S23, $265e5a51); { 19 } GG( b, c, d, a, x[ 0], S24, $e9b6c7aa); { 20 } GG( a, b, c, d, x[ 5], S21, $d62f105d); { 21 } GG( d, a, b, c, x[10], S22, $2441453); { 22 } GG( c, d, a, b, x[15], S23, $d8a1e681); { 23 } GG( b, c, d, a, x[ 4], S24, $e7d3fbc8); { 24 } GG( a, b, c, d, x[ 9], S21, $21e1cde6); { 25 } GG( d, a, b, c, x[14], S22, $c33707d6); { 26 } GG( c, d, a, b, x[ 3], S23, $f4d50d87); { 27 } GG( b, c, d, a, x[ 8], S24, $455a14ed); { 28 } GG( a, b, c, d, x[13], S21, $a9e3e905); { 29 } GG( d, a, b, c, x[ 2], S22, $fcefa3f8); { 30 } GG( c, d, a, b, x[ 7], S23, $676f02d9); { 31 } GG( b, c, d, a, x[12], S24, $8d2a4c8a); { 32 } { Round 3 } HH( a, b, c, d, x[ 5], S31, $fffa3942); { 33 } HH( d, a, b, c, x[ 8], S32, $8771f681); { 34 } HH( c, d, a, b, x[11], S33, $6d9d6122); { 35 } HH( b, c, d, a, x[14], S34, $fde5380c); { 36 } HH( a, b, c, d, x[ 1], S31, $a4beea44); { 37 } HH( d, a, b, c, x[ 4], S32, $4bdecfa9); { 38 } HH( c, d, a, b, x[ 7], S33, $f6bb4b60); { 39 } HH( b, c, d, a, x[10], S34, $bebfbc70); { 40 } HH( a, b, c, d, x[13], S31, $289b7ec6); { 41 } HH( d, a, b, c, x[ 0], S32, $eaa127fa); { 42 } HH( c, d, a, b, x[ 3], S33, $d4ef3085); { 43 } HH( b, c, d, a, x[ 6], S34, $4881d05); { 44 } HH( a, b, c, d, x[ 9], S31, $d9d4d039); { 45 } HH( d, a, b, c, x[12], S32, $e6db99e5); { 46 } HH( c, d, a, b, x[15], S33, $1fa27cf8); { 47 } HH( b, c, d, a, x[ 2], S34, $c4ac5665); { 48 } { Round 4 } II( a, b, c, d, x[ 0], S41, $f4292244); { 49 } II( d, a, b, c, x[ 7], S42, $432aff97); { 50 } II( c, d, a, b, x[14], S43, $ab9423a7); { 51 } II( b, c, d, a, x[ 5], S44, $fc93a039); { 52 } II( a, b, c, d, x[12], S41, $655b59c3); { 53 } II( d, a, b, c, x[ 3], S42, $8f0ccc92); { 54 } II( c, d, a, b, x[10], S43, $ffeff47d); { 55 } II( b, c, d, a, x[ 1], S44, $85845dd1); { 56 } II( a, b, c, d, x[ 8], S41, $6fa87e4f); { 57 } II( d, a, b, c, x[15], S42, $fe2ce6e0); { 58 } II( c, d, a, b, x[ 6], S43, $a3014314); { 59 } II( b, c, d, a, x[13], S44, $4e0811a1); { 60 } II( a, b, c, d, x[ 4], S41, $f7537e82); { 61 } II( d, a, b, c, x[11], S42, $bd3af235); { 62 } II( c, d, a, b, x[ 2], S43, $2ad7d2bb); { 63 } II( b, c, d, a, x[ 9], S44, $eb86d391); { 64 } Inc(FContextState[0], a); Inc(FContextState[1], b); Inc(FContextState[2], c); Inc(FContextState[3], d); end; procedure TMD5.Encode(var Dst: TByteDynArray; const Src: ArrayOfLWord; Len: Integer); var i, j: Integer; begin i := 0; j := 0; SetLength(Dst, Len); while (j < Len) do begin Dst[j] := Byte((Src[i] and $ff)); Dst[j+1]:= Byte((Src[i] shr 8) and $ff); Dst[j+2]:= Byte((Src[i] shr 16) and $ff); Dst[J+3]:= Byte((Src[i] shr 24) and $ff); Inc(j, 4); Inc(i); end; end; procedure TMD5.Decode(var Dst: ArrayOfLWord; const Src: TByteDynArray; Len: Integer; shift: Integer); var I, J: Integer; a, b, c, d: Byte; begin J := 0; I := 0; SetLength(Dst, 16); while (J < Len) do begin a := Src[J+shift]; b := Src[J+shift+1]; c := Src[J+shift+2]; d := Src[J+shift+3]; Dst[I] :=Longword(a and $ff) or (Longword(b and $ff) shl 8) or (Longword(c and $ff) shl 16) or (Longword(d and $ff) shl 24); Inc(J, 4); Inc(I); end; end; initialization SetLength(padding, 64); padding[0] := $80; { MD5 test suite: MD5 ("") = d41d8cd98f00b204e9800998ecf8427e MD5 ("a") = 0cc175b9c0f1b6a831c399e269772661 MD5 ("abc") = 900150983cd24fb0d6963f7d28e17f72 MD5 ("message digest") = f96b697d7cb7938d525a2f31aaf161d0 MD5 ("abcdefghijklmnopqrstuvwxyz") = c3fcd3d76192e4007dfb496cca67e13b MD5 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") = d174ab98d277d9f5a5611c2c9f419d9f MD5 ("123456789012345678901234567890123456789012345678901234567890123456 78901234567890") = 57edf4a22be3c955ac49da2e2107b67a } end.
unit ItemEditor.SysUnits; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ItemEditor.Base, StdCtrls, ComCtrls, ExtCtrls, pngimage, Buttons, PngBitBtn; type TItemEditorFrame_UNT = class(TItemEditorBaseFrame) CustomTabSheet: TTabSheet; FormatCombo: TComboBox; CaptionLabel_C1: TLabel; CaptionLabel_C2: TLabel; FormFactorCombo: TComboBox; CaptionLabel_C3: TLabel; MaterialCombo: TComboBox; ColorCombo: TComboBox; CaptionLabel_C4: TLabel; DustFiltersCheck: TCheckBox; DisplayCheck: TCheckBox; USB30SupportCheck: TCheckBox; AppleDockCheck: TCheckBox; protected procedure Initialize; override; procedure Finalize; override; public procedure GetDataEx(const Data: Pointer); override; procedure SetDataEx(const Data: Pointer); override; function GetShortDescription(const ExData: Pointer): String; override; function GetDescription(const ExData: Pointer): String; override; end; implementation {$R *.dfm} uses CCDBv2; { TItemEditorFrame_UNT } procedure TItemEditorFrame_UNT.Finalize; begin inherited; Dispose(PDataStructSysUnit(FDefaultDataEx)); end; procedure TItemEditorFrame_UNT.GetDataEx(const Data: Pointer); begin with PDataStructSysUnit(Data)^ do begin Format := FormatCombo.ItemIndex; FormFactor := FormFactorCombo.ItemIndex; Material := MaterialCombo.ItemIndex; Color := ColorCombo.ItemIndex; DustFilters := DustFiltersCheck.Checked; Display := DisplayCheck.Checked; USB30Support := USB30SupportCheck.Checked; AppleDock := AppleDockCheck.Checked; end; end; function TItemEditorFrame_UNT.GetDescription(const ExData: Pointer): String; begin end; function TItemEditorFrame_UNT.GetShortDescription(const ExData: Pointer): String; var R: PDataStructSysUnit absolute ExData; begin Result := FormatCombo.Items[R^.Format] + #44#32; Result := Result + ColorCombo.Items[R^.Color] + #44#32; Result := Result + 'под' + #32 + FormFactorCombo.Items[R^.FormFactor]; end; procedure TItemEditorFrame_UNT.Initialize; begin inherited; New(PDataStructSysUnit(FDefaultDataEx)); GetDataEx(PDataStructSysUnit(FDefaultDataEx)); with VendorCombo.Items do begin Add('3Q'); Add('AeroCool'); Add('Antec'); Add('Arctic Cooling'); Add('ASUS'); Add('Chieftec'); Add('Cooler Master'); Add('Corsair'); Add('Delux'); Add('Enermax'); Add('Fractal Design'); Add('FSP'); Add('Gembird'); Add('Gigabyte'); Add('In Win'); Add('Microlab'); Add('Procase'); Add('Thermaltake'); Add('Zalman'); end; end; procedure TItemEditorFrame_UNT.SetDataEx(const Data: Pointer); begin if not Assigned(Data) then Exit; with PDataStructSysUnit(Data)^ do begin FormatCombo.ItemIndex := Format; FormFactorCombo.ItemIndex := FormFactor; MaterialCombo.ItemIndex := Material; ColorCombo.ItemIndex := Color; DustFiltersCheck.Checked := DustFilters; DisplayCheck.Checked := Display; USB30SupportCheck.Checked := USB30Support; AppleDockCheck.Checked := AppleDock; end; end; end.
Unit TSTOHackMasterList.Xml; Interface Uses HsXmlDocEx, HsStringListEx; Type IXmlTSTOHackMasterMovedItem = Interface(IXMLNodeEx) ['{4B61686E-29A0-2112-8006-24D2F211E42A}'] Function GetXmlFileName() : String; Procedure SetXmlFileName(Const Value: String); Function GetOldCategory() : String; Procedure SetOldCategory(Const Value: String); Function GetNewCategory() : String; Procedure SetNewCategory(Const Value: String); Procedure Assign(ASource : IInterface); Property XmlFileName : String Read GetXmlFileName Write SetXmlFileName; Property OldCategory : String Read GetOldCategory Write SetOldCategory; Property NewCategory : String Read GetNewCategory Write SetNewCategory; End; IXmlTSTOHackMasterMovedItems = Interface(IXMLNodeCollectionEx) ['{4B61686E-29A0-2112-BEA0-D12EE1CA568D}'] Function GetMovedPackage(Index: Integer): IXmlTSTOHackMasterMovedItem; Function Add() : IXmlTSTOHackMasterMovedItem; Function Insert(Const Index: Integer): IXmlTSTOHackMasterMovedItem; Procedure Assign(ASource : IInterface); Property Items[Index : Integer] : IXmlTSTOHackMasterMovedItem Read GetMovedPackage; Default; End; IXmlTSTOHackMasterDataID = Interface(IXMLNodeEx) ['{3B70CF15-242C-438B-B2B0-CF6D4C60808B}'] Function GetId() : Integer; Procedure SetId(Const Value: Integer); Function GetName() : String; Procedure SetName(Const Value: String); Function GetAddInStore() : Boolean; Procedure SetAddInStore(Const AAddInStore : Boolean); Function GetOverRide() : Boolean; Procedure SetOverRide(Const AOverRide : Boolean); Function GetIsBadItem() : Boolean; Procedure SetIsBadItem(Const AIsBadItem : Boolean); Function GetObjectType() : String; Procedure SetObjectType(Const AObjectType : String); Function GetNPCCharacter() : Boolean; Procedure SetNPCCharacter(Const ANPCCharacter : Boolean); Function GetSkinObject() : String; Procedure SetSkinObject(Const ASkinObject : String); Function GetMiscData() : IHsStringListEx; Procedure Assign(ASource : IInterface); Property Id : Integer Read GetId Write SetId; Property Name : String Read GetName Write SetName; Property AddInStore : Boolean Read GetAddInStore Write SetAddInStore; Property OverRide : Boolean Read GetOverRide Write SetOverRide; Property IsBadItem : Boolean Read GetIsBadItem Write SetIsBadItem; Property ObjectType : String Read GetObjectType Write SetObjectType; Property NPCCharacter : Boolean Read GetNPCCharacter Write SetNPCCharacter; Property SkinObject : String Read GetSkinObject Write SetSkinObject; Property MiscData : IHsStringListEx Read GetMiscData; End; IXmlTSTOHackMasterPackage = Interface(IXmlNodeCollectionEx) ['{6170F205-8932-492E-8530-0A5D10E5D86D}'] Function GetDataID(Index : Integer) : IXmlTSTOHackMasterDataID; Function GetPackageType() : String; Procedure SetPackageType(Const Value : String); Function GetXmlFile() : String; Procedure SetXmlFile(Const Value : String); Function GetEnabled() : Boolean; Procedure SetEnabled(Const AEnabled : Boolean); Function Add() : IXmlTSTOHackMasterDataID; Function Insert(Const Index : Integer) : IXmlTSTOHackMasterDataID; Procedure Assign(ASource : IInterface); Property DataID[Index: Integer]: IXmlTSTOHackMasterDataID Read GetDataID; Default; Property PackageType : String Read GetPackageType Write SetPackageType; Property XmlFile : String Read GetXmlFile Write SetXmlFile; Property Enabled : Boolean Read GetEnabled Write SetEnabled; End; IXmlTSTOHackMasterCategory = Interface(IXmlNodeCollectionEx) ['{E78BD474-D686-499F-AF61-B9E19B68468C}'] Function GetPackage(Index: Integer): IXmlTSTOHackMasterPackage; Function GetName() : String; Procedure SetName(Const Value: String); Function GetEnabled() : Boolean; Procedure SetEnabled(Const AEnabled : Boolean); Function GetBuildStore() : Boolean; Procedure SetBuildStore(Const ABuildStore : Boolean); Function Add: IXmlTSTOHackMasterPackage; Function Insert(Const Index: Integer): IXmlTSTOHackMasterPackage; Procedure Assign(ASource : IInterface); Property Package[Index: Integer]: IXmlTSTOHackMasterPackage Read GetPackage; Default; Property Name : String Read GetName Write SetName; Property Enabled : Boolean Read GetEnabled Write SetEnabled; Property BuildStore : Boolean Read GetBuildStore Write SetBuildStore; End; IXmlTSTOHackMasterList = Interface(IXmlNodeCollectionEx) ['{8685D965-C38D-436A-9B36-B919FA738878}'] Function GetCategory(Index: Integer): IXmlTSTOHackMasterCategory; Function GetMovedItems() : IXmlTSTOHackMasterMovedItems; Function Add: IXmlTSTOHackMasterCategory; Function Insert(Const Index: Integer): IXmlTSTOHackMasterCategory; Procedure Assign(ASource : IInterface); Property Category[Index: Integer]: IXmlTSTOHackMasterCategory Read GetCategory; Default; Property MovedItems : IXmlTSTOHackMasterMovedItems Read GetMovedItems; End; TXmlTSTOHackMasterList = Class(TObject) Private Class Procedure InitMiscData(AXmlDoc : IXmlTSTOHackMasterList); Public Class Function CreateMasterList() : IXmlTSTOHackMasterList; OverLoad; Class Function CreateMasterList(Const AXmlText : String) : IXmlTSTOHackMasterList; OverLoad; End; Implementation Uses Dialogs, SysUtils, RtlConsts, Variants, HsInterfaceEx, TSTOHackMasterListIntf, TSTOHackMasterListImpl, XMLIntf; Type TXmlTSTOHackMasterMovedItem = Class(TXMLNodeEx, ITSTOHackMasterMovedItem, IXmlTSTOHackMasterMovedItem) Private FMovedItemImpl : Pointer; Function GetImplementor() : ITSTOHackMasterMovedItem; Protected Property MovedItemImpl : ITSTOHackMasterMovedItem Read GetImplementor; Function GetXmlFileName() : String; Procedure SetXmlFileName(Const Value: String); Function GetOldCategory() : String; Procedure SetOldCategory(Const Value: String); Function GetNewCategory() : String; Procedure SetNewCategory(Const Value: String); Procedure Assign(ASource : IInterface); Public Procedure AfterConstruction(); Override; End; TXmlTSTOHackMasterMovedItems = Class(TXMLNodeCollectionEx, ITSTOHackMasterMovedItems, IXmlTSTOHackMasterMovedItems) Private FMovedItemsImpl : ITSTOHackMasterMovedItems; Function GetImplementor() : ITSTOHackMasterMovedItems; Protected Property MovedItemsImpl : ITSTOHackMasterMovedItems Read GetImplementor Implements ITSTOHackMasterMovedItems; Protected Function GetMovedPackage(Index: Integer): IXmlTSTOHackMasterMovedItem; Function Add: IXmlTSTOHackMasterMovedItem; Function Insert(Const Index: Integer): IXmlTSTOHackMasterMovedItem; Procedure Assign(ASource : IInterface); Public Procedure AfterConstruction; Override; End; TTSTOXMLDataID = Class(TXmlNodeEx, ITSTOHackMasterDataID, IXmlTSTOHackMasterDataID) Private FDataIDImpl : Pointer; Function GetImplementor() : ITSTOHackMasterDataID; Protected Property DataIDImpl : ITSTOHackMasterDataID Read GetImplementor; Function GetId() : Integer; Procedure SetId(Const Value: Integer); Function GetName() : String; Procedure SetName(Const Value: String); Function GetAddInStore() : Boolean; Procedure SetAddInStore(Const AAddInStore : Boolean); Function GetOverRide() : Boolean; Procedure SetOverRide(Const AOverRide : Boolean); Function GetIsBadItem() : Boolean; Procedure SetIsBadItem(Const AIsBadItem : Boolean); Function GetObjectType() : String; Procedure SetObjectType(Const AObjectType : String); Function GetNPCCharacter() : Boolean; Procedure SetNPCCharacter(Const ANPCCharacter : Boolean); Function GetSkinObject() : String; Procedure SetSkinObject(Const ASkinObject : String); Function GetMiscData() : IHsStringListEx; //All ChidNodes of <DataID/> Procedure Assign(ASource : IInterface); Public Procedure AfterConstruction; OverRide; End; TTSTOXMLPackage = Class(TXmlNodeCollectionEx, ITSTOHackMasterPackage, IXmlTSTOHackMasterPackage) Private FMasterImpl : ITSTOHackMasterPackage; Function GetImplementor() : ITSTOHackMasterPackage; Protected Property MasterImpl : ITSTOHackMasterPackage Read GetImplementor Implements ITSTOHackMasterPackage; Function GetDataID(Index : Integer) : IXmlTSTOHackMasterDataID; Function GetPackageType() : String; Procedure SetPackageType(Const Value : String); Function GetXmlFile() : String; Procedure SetXmlFile(Const Value : String); Function GetEnabled() : Boolean; Procedure SetEnabled(Const AEnabled : Boolean); Function Add() : IXmlTSTOHackMasterDataID; Function Insert(Const Index: Integer): IXmlTSTOHackMasterDataID; Procedure Assign(ASource : IInterface); Procedure AssignTo(ATarget : ITSTOHackMasterPackage); Public Procedure AfterConstruction; Override; End; TTSTOXMLCategory = Class(TXmlNodeCollectionEx, ITSTOHackMasterCategory, IXmlTSTOHackMasterCategory) Private FCategoryImpl : ITSTOHackMasterCategory; Function GetImplementor() : ITSTOHackMasterCategory; Protected Property CategoryImpl : ITSTOHackMasterCategory Read GetImplementor Implements ITSTOHackMasterCategory; Function GetPackage(Index: Integer): IXmlTSTOHackMasterPackage; Function GetName() : String; Procedure SetName(Const Value: String); Function GetEnabled() : Boolean; Procedure SetEnabled(Const AEnabled : Boolean); Function GetBuildStore() : Boolean; Procedure SetBuildStore(Const ABuildStore : Boolean); Function Add() : IXmlTSTOHackMasterPackage; Function Insert(Const Index: Integer): IXmlTSTOHackMasterPackage; Procedure Assign(ASource : IInterface); Procedure AssignTo(ATarget : ITSTOHackMasterCategory); Public Procedure AfterConstruction; Override; End; TTSTOXMLMasterListImpl = Class(TXmlNodeCollectionEx, ITSTOHackMasterList, IXmlTSTOHackMasterList) Private FMasterListImpl : ITSTOHackMasterList; Function GetImplementor() : ITSTOHackMasterList; Protected Property CategoryImpl : ITSTOHackMasterList Read GetImplementor Implements ITSTOHackMasterList; Function GetCategory(Index: Integer): IXmlTSTOHackMasterCategory; Function GetMovedItems() : IXmlTSTOHackMasterMovedItems; Function Add: IXmlTSTOHackMasterCategory; Function Insert(Const Index: Integer): IXmlTSTOHackMasterCategory; Procedure Assign(ASource : IInterface); Procedure AssignTo(ATarget : ITSTOHackMasterList); Public Procedure AfterConstruction; Override; End; Class Function TXmlTSTOHackMasterList.CreateMasterList() : IXmlTSTOHackMasterList; Begin Result := NewXMLDocument().GetDocBinding('MasterLists', TTSTOXMLMasterListImpl, '') As IXmlTSTOHackMasterList; End; Class Function TXmlTSTOHackMasterList.CreateMasterList(Const AXmlText : String) : IXmlTSTOHackMasterList; Begin Result := LoadXmlData(AXmlText).GetDocBinding('MasterLists', TTSTOXMLMasterListImpl, '') As IXmlTSTOHackMasterList; // InitMiscData(Result); End; Class Procedure TXmlTSTOHackMasterList.InitMiscData(AXmlDoc : IXmlTSTOHackMasterList); Var lXml : IXmlDocumentEx; W, X , Y, Z : Integer; Begin For X := 0 To AXmlDoc.Count - 1 Do For Y := 0 To AXmlDoc.Category[X].Count - 1 Do For Z := 0 To AXmlDoc.Category[X].Package[Y].Count - 1 Do If AXmlDoc.Category[X].Package[Y].DataID[Z].HasChildNodes Then Begin lXml := NewXmlDocument(''); Try With lXml.AddChild('MiscData').ChildNodes Do For W := 0 To AXmlDoc.Category[X].Package[Y].DataID[Z].ChildNodes.Count - 1 Do Add(AXmlDoc.Category[X].Package[Y].DataID[Z].ChildNodes[W].CloneNode(True)); AXmlDoc.Category[X].Package[Y].DataID[Z].MiscData.Text := lXml.Xml.Text; Finally lXml := Nil; End; End; End; { TTSTOXMLMasterListsType } Procedure TTSTOXMLMasterListImpl.AfterConstruction; Begin RegisterChildNode('MovedPackages', TXmlTSTOHackMasterMovedItems); RegisterChildNode('Category', TTSTOXMLCategory); ItemTag := 'Category'; ItemInterface := IXmlTSTOHackMasterCategory; Inherited; End; Function TTSTOXMLMasterListImpl.GetImplementor() : ITSTOHackMasterList; Begin If Not Assigned(FMasterListImpl) Then FMasterListImpl := TTSTOHackMasterList.Create(); Result := FMasterListImpl; AssignTo(Result); End; Procedure TTSTOXMLMasterListImpl.Assign(ASource : IInterface); Var lXmlSrc : IXmlTSTOHackMasterList; lSrc : ITSTOHackMasterList; X : Integer; Begin If Supports(ASource, IXMLNodeCollectionEx) And Supports(ASource, IXmlTSTOHackMasterList, lXmlSrc) Then Begin Clear(); GetMovedItems().Clear(); For X := 0 To lXmlSrc.MovedItems.Count - 1 Do GetMovedItems().Add().Assign(lXmlSrc.MovedItems[X]); For X := 0 To lXmlSrc.Count - 1 Do Add().Assign(lXmlSrc[X]); End Else If Supports(ASource, ITSTOHackMasterList, lSrc) Then Begin Clear(); GetMovedItems().Clear(); For X := 0 To lSrc.MovedItems.Count - 1 Do GetMovedItems().Add().Assign(lSrc.MovedItems[X]); For X := 0 To lSrc.Count - 1 Do Add().Assign(lSrc[X]); FMasterListImpl := lSrc; End Else Raise EConvertError.CreateResFmt(@SAssignError, [GetInterfaceName(ASource), ClassName]); End; Procedure TTSTOXMLMasterListImpl.AssignTo(ATarget : ITSTOHackMasterList); Var X : Integer; lMovedItems : IXmlTSTOHackMasterMovedItems; Begin ATarget.Clear(); ATarget.MovedItems.Clear(); lMovedItems := GetMovedItems(); For X := 0 To lMovedItems.Count - 1 Do ATarget.MovedItems.Add().Assign(lMovedItems[X]); For X := 0 To List.Count - 1 Do ATarget.Add().Assign(List[X]); End; Function TTSTOXMLMasterListImpl.GetCategory(Index: Integer): IXmlTSTOHackMasterCategory; Begin Result := List[Index] As IXmlTSTOHackMasterCategory; End; Function TTSTOXMLMasterListImpl.GetMovedItems() : IXmlTSTOHackMasterMovedItems; Begin Result := ChildNodes['MovedPackages'] As IXmlTSTOHackMasterMovedItems; End; Function TTSTOXMLMasterListImpl.Add: IXmlTSTOHackMasterCategory; Begin Result := AddItem(-1) As IXmlTSTOHackMasterCategory; End; Function TTSTOXMLMasterListImpl.Insert(Const Index: Integer): IXmlTSTOHackMasterCategory; Begin Result := AddItem(Index) As IXmlTSTOHackMasterCategory; End; Procedure TXmlTSTOHackMasterMovedItem.AfterConstruction(); Begin InHerited AfterConstruction(); FMovedItemImpl := Pointer(ITSTOHackMasterMovedItem(Self)); End; Function TXmlTSTOHackMasterMovedItem.GetImplementor() : ITSTOHackMasterMovedItem; Begin Result := ITSTOHackMasterMovedItem(FMovedItemImpl); End; Procedure TXmlTSTOHackMasterMovedItem.Assign(ASource : IInterface); Var lXmlSrc : IXmlTSTOHackMasterMovedItem; lSrc : ITSTOHackMasterMovedItem; Begin If Supports(ASource, IXmlNodeEx) And Supports(ASource, IXmlTSTOHackMasterMovedItem, lXmlSrc) Then Begin SetXmlFileName(lXmlSrc.XmlFileName); SetOldCategory(lXmlSrc.OldCategory); SetNewCategory(lXmlSrc.NewCategory); End Else If Supports(ASource, ITSTOHackMasterMovedItem, lSrc) Then Begin SetXmlFileName(lSrc.XmlFileName); SetOldCategory(lSrc.OldCategory); SetNewCategory(lSrc.NewCategory); FMovedItemImpl := Pointer(lSrc); End Else Raise EConvertError.CreateResFmt(@SAssignError, [GetInterfaceName(ASource), ClassName]); End; Function TXmlTSTOHackMasterMovedItem.GetXmlFileName() : String; Begin Result := AttributeNodes['XmlFileName'].Text; End; Procedure TXmlTSTOHackMasterMovedItem.SetXmlFileName(Const Value: String); Begin SetAttribute('XmlFileName', Value); If Not IsImplementorOf(MovedItemImpl) Then MovedItemImpl.XmlFileName := Value; End; Function TXmlTSTOHackMasterMovedItem.GetOldCategory: String; Begin Result := AttributeNodes['OldCategory'].Text; End; Procedure TXmlTSTOHackMasterMovedItem.SetOldCategory(Const Value: UnicodeString); Begin SetAttribute('OldCategory', Value); If Not IsImplementorOf(MovedItemImpl) Then MovedItemImpl.OldCategory := Value; End; Function TXmlTSTOHackMasterMovedItem.GetNewCategory: UnicodeString; Begin Result := AttributeNodes['NewCategory'].Text; End; Procedure TXmlTSTOHackMasterMovedItem.SetNewCategory(Const Value: UnicodeString); Begin SetAttribute('NewCategory', Value); If Not IsImplementorOf(MovedItemImpl) Then MovedItemImpl.NewCategory := Value; End; Procedure TXmlTSTOHackMasterMovedItems.AfterConstruction; Begin RegisterChildNode('MovedPackage', TXmlTSTOHackMasterMovedItem); ItemTag := 'MovedPackage'; ItemInterface := IXmlTSTOHackMasterMovedItem; Inherited; End; Function TXmlTSTOHackMasterMovedItems.GetImplementor() : ITSTOHackMasterMovedItems; Var X : Integer; Begin If Not Assigned(FMovedItemsImpl) Then FMovedItemsImpl := TTSTOHackMasterMovedItems.Create(); Result := FMovedItemsImpl; FMovedItemsImpl.Clear(); For X := 0 To List.Count - 1 Do Result.Add().Assign(List[X]); End; Procedure TXmlTSTOHackMasterMovedItems.Assign(ASource : IInterface); Var lXmlSrc : IXmlTSTOHackMasterMovedItems; lSrc : ITSTOHackMasterMovedItems; X : Integer; Begin If Supports(ASource, IXMLNodeCollectionEx) And Supports(ASource, IXmlTSTOHackMasterMovedItems, lXmlSrc) Then Begin Clear(); For X := 0 To lXmlSrc.Count - 1 Do Add().Assign(lXmlSrc[X]); End Else If Supports(ASource, ITSTOHackMasterMovedItems, lSrc) Then Begin Clear(); For X := 0 To lSrc.Count - 1 Do Add().Assign(lSrc[X]); FMovedItemsImpl := lSrc; End Else Raise EConvertError.CreateResFmt(@SAssignError, [GetInterfaceName(ASource), ClassName]); End; Function TXmlTSTOHackMasterMovedItems.GetMovedPackage(Index: Integer): IXmlTSTOHackMasterMovedItem; Begin Result := List[Index] As IXmlTSTOHackMasterMovedItem; End; Function TXmlTSTOHackMasterMovedItems.Add() : IXmlTSTOHackMasterMovedItem; Begin Result := AddItem(-1) As IXmlTSTOHackMasterMovedItem; End; Function TXmlTSTOHackMasterMovedItems.Insert(Const Index: Integer): IXmlTSTOHackMasterMovedItem; Begin Result := AddItem(Index) As IXmlTSTOHackMasterMovedItem; End; Procedure TTSTOXMLCategory.AfterConstruction; Begin RegisterChildNode('Package', TTSTOXMLPackage); ItemTag := 'Package'; ItemInterface := IXmlTSTOHackMasterPackage; Inherited; End; Function TTSTOXMLCategory.GetImplementor() : ITSTOHackMasterCategory; Begin If Not Assigned(FCategoryImpl) Then FCategoryImpl := TTSTOHackMasterCategory.Create(); Result := FCategoryImpl; AssignTo(FCategoryImpl); End; Procedure TTSTOXMLCategory.Assign(ASource : IInterface); Var lXmlSrc : IXmlTSTOHackMasterCategory; lSrc : ITSTOHackMasterCategory; X : Integer; Begin If Supports(ASource, IXMLNodeCollectionEx) And Supports(ASource, IXmlTSTOHackMasterCategory, lXmlSrc) Then Begin Clear(); SetName(lXmlSrc.Name); If Not lXmlSrc.Enabled Then SetEnabled(lXmlSrc.Enabled); If Not lXmlSrc.BuildStore Then SetBuildStore(lXmlSrc.BuildStore); For X := 0 To lXmlSrc.Count - 1 Do Add().Assign(lXmlSrc[X]); End Else If Supports(ASource, ITSTOHackMasterCategory, lSrc) Then Begin Clear(); SetName(lSrc.Name); If Not lSrc.Enabled Then SetEnabled(lSrc.Enabled); If Not lSrc.BuildStore Then SetBuildStore(lSrc.Enabled); For X := 0 To lSrc.Count - 1 Do Add().Assign(lSrc[X]); FCategoryImpl := lSrc; End Else Raise EConvertError.CreateResFmt(@SAssignError, [GetInterfaceName(ASource), ClassName]); End; Procedure TTSTOXMLCategory.AssignTo(ATarget : ITSTOHackMasterCategory); Var X : Integer; Begin ATarget.Clear(); ATarget.Name := GetName(); ATarget.Enabled := GetEnabled(); ATarget.BuildStore := GetBuildStore(); For X := 0 To List.Count - 1 Do ATarget.Add().Assign(List[X]); End; Function TTSTOXMLCategory.GetName: String; Begin Result := AttributeNodes['Name'].Text; End; Procedure TTSTOXMLCategory.SetName(Const Value: String); Begin SetAttribute('Name', Value); If Assigned(FCategoryImpl) Then FCategoryImpl.Name := Value; End; Function TTSTOXMLCategory.GetEnabled() : Boolean; Begin If VarIsNull(AttributeNodes['Enabled'].NodeValue) Then Result := True Else If VarIsStr(AttributeNodes['Enabled'].NodeValue) Then Result := StrToBoolDef(AttributeNodes['Enabled'].NodeValue, True) Else If VarIsNumeric(AttributeNodes['Enabled'].NodeValue) Then Result := AttributeNodes['Enabled'].NodeValue <> 0 Else Raise Exception.Create('Invalid data type ' + IntToStr(VarType(AttributeNodes['Enabled'].NodeValue)) + '.'); End; Procedure TTSTOXMLCategory.SetEnabled(Const AEnabled : Boolean); Begin If Not AEnabled Then SetAttribute('Enabled', AEnabled); If Assigned(FCategoryImpl) Then FCategoryImpl.Enabled := AEnabled; End; Function TTSTOXMLCategory.GetBuildStore() : Boolean; Begin If VarIsNull(AttributeNodes['BuildStore'].NodeValue) Then Result := True Else If VarIsStr(AttributeNodes['BuildStore'].NodeValue) Then Result := StrToBoolDef(AttributeNodes['BuildStore'].NodeValue, True) Else If VarIsNumeric(AttributeNodes['BuildStore'].NodeValue) Then Result := AttributeNodes['BuildStore'].NodeValue <> 0 Else Raise Exception.Create('Invalid data type ' + IntToStr(VarType(AttributeNodes['BuildStore'].NodeValue)) + '.'); End; Procedure TTSTOXMLCategory.SetBuildStore(Const ABuildStore : Boolean); Begin If Not ABuildStore Then SetAttribute('BuildStore', ABuildStore); If Assigned(FCategoryImpl) Then FCategoryImpl.BuildStore := ABuildStore; End; Function TTSTOXMLCategory.GetPackage(Index: Integer): IXmlTSTOHackMasterPackage; Begin Result := List[Index] As IXmlTSTOHackMasterPackage; End; Function TTSTOXMLCategory.Add: IXmlTSTOHackMasterPackage; Begin Result := AddItem(-1) As IXmlTSTOHackMasterPackage; End; Function TTSTOXMLCategory.Insert(Const Index: Integer): IXmlTSTOHackMasterPackage; Begin Result := AddItem(Index) As IXmlTSTOHackMasterPackage; End; { TTSTOXMLPackageType } Procedure TTSTOXMLPackage.AfterConstruction; Begin RegisterChildNode('DataID', TTSTOXMLDataID); ItemTag := 'DataID'; ItemInterface := IXmlTSTOHackMasterDataID; Inherited; End; Function TTSTOXMLPackage.GetImplementor() : ITSTOHackMasterPackage; Begin If Not Assigned(FMasterImpl) Then FMasterImpl := TTSTOHackMasterPackage.Create(); Result := FMasterImpl; AssignTo(FMasterImpl); End; Procedure TTSTOXMLPackage.Assign(ASource : IInterface); Var lXmlSrc : IXmlTSTOHackMasterPackage; lSrc : ITSTOHackMasterPackage; X : Integer; Begin If Supports(ASource, IXMLNodeCollectionEx) And Supports(ASource, IXmlTSTOHackMasterPackage, lXmlSrc) Then Begin Clear(); SetPackageType(lXmlSrc.PackageType); SetXmlFile(lXmlSrc.XmlFile); If Not lXmlSrc.Enabled Then SetEnabled(lXmlSrc.Enabled); For X := 0 To lXmlSrc.Count - 1 Do Add().Assign(lXmlSrc[X]); End Else If Supports(ASource, ITSTOHackMasterPackage, lSrc) Then Begin Clear(); SetPackageType(lSrc.PackageType); SetXmlFile(lSrc.XmlFile); If Not lSrc.Enabled Then SetEnabled(lSrc.Enabled); For X := 0 To lSrc.Count - 1 Do Add().Assign(lSrc[X]); FMasterImpl := lSrc; End Else Raise EConvertError.CreateResFmt(@SAssignError, [GetInterfaceName(ASource), ClassName]); End; Procedure TTSTOXMLPackage.AssignTo(ATarget : ITSTOHackMasterPackage); Var X : Integer; lItem : ITSTOHackMasterDataID; Begin ATarget.Clear(); ATarget.PackageType := GetPackageType(); ATarget.XmlFile := GetXmlFile(); ATarget.Enabled := GetEnabled(); For X := 0 To Count - 1 Do If Supports(List[X], ITSTOHackMasterDataID, lItem) Then ATarget.Add().Assign(lItem); End; Function TTSTOXMLPackage.GetPackageType() : String; Begin Result := AttributeNodes['Type'].Text; End; Procedure TTSTOXMLPackage.SetPackageType(Const Value: String); Begin SetAttribute('Type', Value); If Assigned(FMasterImpl) Then FMasterImpl.PackageType := Value; End; Function TTSTOXMLPackage.GetXmlFile() : String; Begin Result := AttributeNodes['XmlFile'].Text; End; Procedure TTSTOXMLPackage.SetXmlFile(Const Value : String); Begin SetAttribute('XmlFile', Value); If Assigned(FMasterImpl) Then FMasterImpl.XmlFile := Value; End; Function TTSTOXMLPackage.GetEnabled() : Boolean; Begin If VarIsNull(AttributeNodes['Enabled'].NodeValue) Then Result := True Else If VarIsStr(AttributeNodes['Enabled'].NodeValue) Then Result := StrToBoolDef(AttributeNodes['Enabled'].NodeValue, True) Else If VarIsNumeric(AttributeNodes['Enabled'].NodeValue) Then Result := AttributeNodes['Enabled'].NodeValue <> 0 Else Raise Exception.Create('Invalid data type ' + IntToStr(VarType(AttributeNodes['Enabled'].NodeValue)) + '.'); End; Procedure TTSTOXMLPackage.SetEnabled(Const AEnabled : Boolean); Begin If Not AEnabled Then SetAttribute('Enabled', AEnabled); If Assigned(FMasterImpl) Then FMasterImpl.Enabled := AEnabled; End; Function TTSTOXMLPackage.GetDataID(Index: Integer): IXmlTSTOHackMasterDataID; Begin Result := List[Index] As IXmlTSTOHackMasterDataID; End; Function TTSTOXMLPackage.Add: IXmlTSTOHackMasterDataID; Begin Result := AddItem(-1) As IXmlTSTOHackMasterDataID; If Assigned(FMasterImpl) Then FMasterImpl.Add(Result As ITSTOHackMasterDataID); End; Function TTSTOXMLPackage.Insert(Const Index: Integer): IXmlTSTOHackMasterDataID; Begin Result := AddItem(Index) As IXmlTSTOHackMasterDataID; End; { TTSTOXMLDataIDType } Procedure TTSTOXMLDataID.AfterConstruction(); Begin InHerited AfterConstruction(); FDataIDImpl := Pointer(ITSTOHackMasterDataID(Self)); End; Function TTSTOXMLDataID.GetImplementor() : ITSTOHackMasterDataID; Begin Result := ITSTOHackMasterDataID(FDataIDImpl); End; Function TTSTOXMLDataID.GetMiscData() : IHsStringListEx; Var X : Integer; Begin Result := THsStringListEx.CreateList(); If ChildNodes.Count > 0 Then Begin Result.Add('<MiscData>'); For X := 0 To ChildNodes.Count - 1 Do Result.Add(ChildNodes[X].Xml); Result.Add('</MiscData>'); End; End; Procedure TTSTOXMLDataID.Assign(ASource : IInterface); Var lXmlSrc : IXmlTSTOHackMasterDataID; lSrc : ITSTOHackMasterDataID; lXml : IXmlDocumentEx; X : Integer; Begin If Supports(ASource, IXmlNodeEx) And Supports(ASource, IXmlTSTOHackMasterDataID, lXmlSrc) Then Begin SetId(lXmlSrc.Id); SetName(lXmlSrc.Name); If Not lXmlSrc.AddInStore Then SetAddInStore(lXmlSrc.AddInStore); If Not lXmlSrc.OverRide Then SetOverRide(lXmlSrc.OverRide); If lXmlSrc.IsBadItem Then SetIsBadItem(lXmlSrc.IsBadItem); If lXmlSrc.ObjectType <> '' Then SetObjectType(lXmlSrc.ObjectType); If lXmlSrc.NPCCharacter Then SetNPCCharacter(lXmlSrc.NPCCharacter); If lXmlSrc.SkinObject <> '' Then SetSkinObject(lXmlSrc.SkinObject); If lXmlSrc.MiscData.Text <> '' Then Begin lXml := LoadXmlData(lXmlSrc.MiscData.Text); For X := 0 To lXml.DocumentElement.ChildNodes.Count - 1 Do ChildNodes.Add(lXml.DocumentElement.ChildNodes[X].CloneNode(True)); End; End Else If Supports(ASource, ITSTOHackMasterDataID, lSrc) Then Begin SetId(lSrc.Id); SetName(lSrc.Name); If Not lSrc.AddInStore Then SetAddInStore(lSrc.AddInStore); If Not lSrc.OverRide Then SetOverRide(lSrc.OverRide); If lSrc.IsBadItem Then SetIsBadItem(lSrc.IsBadItem); If lSrc.ObjectType <> '' Then SetObjectType(lSrc.ObjectType); If lSrc.NPCCharacter Then SetNPCCharacter(lSrc.NPCCharacter); If lSrc.SkinObject <> '' Then SetSkinObject(lSrc.SkinObject); If lSrc.MiscData.Text <> '' Then Begin lXml := LoadXmlData(lSrc.MiscData.Text); For X := 0 To lXml.DocumentElement.ChildNodes.Count - 1 Do ChildNodes.Add(lXml.DocumentElement.ChildNodes[X].CloneNode(True)); End; FDataIDImpl := Pointer(lSrc); End Else Raise EConvertError.CreateResFmt(@SAssignError, [GetInterfaceName(ASource), ClassName]); End; Function TTSTOXMLDataID.GetId: Integer; Begin Result := AttributeNodes['id'].NodeValue; End; Procedure TTSTOXMLDataID.SetId(Const Value: Integer); Begin SetAttribute('id', Value); If Not IsImplementorOf(DataIDImpl) Then DataIDImpl.Id := Value; End; Function TTSTOXMLDataID.GetName: String; Begin Result := AttributeNodes['name'].Text; End; Procedure TTSTOXMLDataID.SetName(Const Value: String); Begin SetAttribute('name', Value); If Not IsImplementorOf(DataIDImpl) Then DataIDImpl.Name := Value; End; Function TTSTOXMLDataID.GetAddInStore() : Boolean; Begin If VarIsNull(AttributeNodes['AddInStore'].NodeValue) Then Result := True Else If VarIsStr(AttributeNodes['AddInStore'].NodeValue) Then Result := StrToBoolDef(AttributeNodes['AddInStore'].NodeValue, True) Else If VarIsNumeric(AttributeNodes['AddInStore'].NodeValue) Then Result := AttributeNodes['AddInStore'].NodeValue <> 0 Else Raise Exception.Create('Invalid data type ' + IntToStr(VarType(AttributeNodes['AddInStore'].NodeValue)) + '.'); End; Procedure TTSTOXMLDataID.SetAddInStore(Const AAddInStore : Boolean); Begin If Not AAddInStore Then SetAttribute('AddInStore', AAddInStore); If Not IsImplementorOf(DataIDImpl) Then DataIDImpl.AddInStore := AAddInStore; End; Function TTSTOXMLDataID.GetOverRide() : Boolean; Begin If VarIsNull(AttributeNodes['OverRide'].NodeValue) Then Result := True Else If VarIsStr(AttributeNodes['OverRide'].NodeValue) Then Result := StrToBoolDef(AttributeNodes['OverRide'].NodeValue, True) Else If VarIsNumeric(AttributeNodes['OverRide'].NodeValue) Then Result := AttributeNodes['OverRide'].NodeValue <> 0 Else Raise Exception.Create('Invalid data type ' + IntToStr(VarType(AttributeNodes['OverRide'].NodeValue)) + '.'); End; Procedure TTSTOXMLDataID.SetOverRide(Const AOverRide : Boolean); Begin If Not AOverRide Then SetAttribute('OverRide', AOverRide); If Not IsImplementorOf(DataIDImpl) Then DataIDImpl.OverRide := AOverRide; End; Function TTSTOXMLDataID.GetIsBadItem() : Boolean; Begin If VarIsNull(AttributeNodes['IsBadItem'].NodeValue) Then Result := False Else If VarIsStr(AttributeNodes['IsBadItem'].NodeValue) Then Result := StrToBoolDef(AttributeNodes['IsBadItem'].NodeValue, False) Else If VarIsNumeric(AttributeNodes['IsBadItem'].NodeValue) Then Result := AttributeNodes['IsBadItem'].NodeValue <> 0 Else Raise Exception.Create('Invalid data type ' + IntToStr(VarType(AttributeNodes['IsBadItem'].NodeValue)) + '.'); End; Procedure TTSTOXMLDataID.SetIsBadItem(Const AIsBadItem : Boolean); Begin If AIsBadItem Then SetAttribute('IsBadItem', AIsBadItem); If Not IsImplementorOf(DataIDImpl) Then DataIDImpl.IsBadItem := AIsBadItem; End; Function TTSTOXMLDataID.GetObjectType() : String; Begin If VarIsNull(AttributeNodes['Type'].NodeValue) Then Result := '' Else Result := AttributeNodes['Type'].NodeValue; End; Procedure TTSTOXMLDataID.SetObjectType(Const AObjectType : String); Begin If AObjectType <> '' Then SetAttribute('Type', AObjectType); If Not IsImplementorOf(DataIDImpl) Then DataIDImpl.ObjectType := AObjectType; End; Function TTSTOXMLDataID.GetNPCCharacter() : Boolean; Begin If VarIsNull(AttributeNodes['NPCCharacter'].NodeValue) Then Result := False Else If VarIsStr(AttributeNodes['NPCCharacter'].NodeValue) Then Result := StrToBoolDef(AttributeNodes['NPCCharacter'].NodeValue, False) Else If VarIsNumeric(AttributeNodes['NPCCharacter'].NodeValue) Then Result := AttributeNodes['NPCCharacter'].NodeValue <> 0 Else Raise Exception.Create('Invalid data type ' + IntToStr(VarType(AttributeNodes['NPCCharacter'].NodeValue)) + '.'); End; Procedure TTSTOXMLDataID.SetNPCCharacter(Const ANPCCharacter : Boolean); Begin If ANPCCharacter Then SetAttribute('NPCCharacter', ANPCCharacter); If Not IsImplementorOf(DataIDImpl) Then DataIDImpl.NPCCharacter := ANPCCharacter; End; Function TTSTOXMLDataID.GetSkinObject() : String; Begin Result := AttributeNodes['SkinObject'].Text; End; Procedure TTSTOXMLDataID.SetSkinObject(Const ASkinObject : String); Begin If ASkinObject <> '' Then SetAttribute('SkinObject', ASkinObject); If Not IsImplementorOf(DataIDImpl) Then DataIDImpl.SkinObject := ASkinObject; End; End.
program Test6; var a, b: Integer; function gcd( a,b: Integer ) : Integer; begin if a = 0 then gcd := b else if b = 0 then gcd := a else if a = b then gcd := a else if a > b then gcd := gcd(a-b, b) else gcd := gcd(a, b-a); end; begin a := 98; b := 56; Write('GCD of '); Write(a); Write(' and '); Write(b); Write(' is '); WriteLn(gcd(a, b)); end.
unit AqDrop.DB.DBX.IB; interface uses Data.DBXInterbase, AqDrop.DB.Adapter, AqDrop.DB.DBX, Data.DBXCommon; type TAqDBXIBAdapter = class(TAqDBXAdapter) strict protected function GetAutoIncrementType: TAqDBAutoIncrementType; override; class function GetDefaultSolver: TAqDBSQLSolverClass; override; end; TAqDBXIBConnection = class(TAqDBXCustomConnection) strict protected function GetPropertyValueAsString(const pIndex: Int32): string; override; procedure SetPropertyValueAsString(const pIndex: Int32; const pValue: string); override; class function GetDefaultAdapter: TAqDBAdapterClass; override; public constructor Create; override; property DataBase: string index $80 read GetPropertyValueAsString write SetPropertyValueAsString; property UserName: string index $81 read GetPropertyValueAsString write SetPropertyValueAsString; property Password: string index $82 read GetPropertyValueAsString write SetPropertyValueAsString; end; implementation uses System.Math, AqDrop.DB.IB; { TAqDBXIBAdapter } function TAqDBXIBAdapter.GetAutoIncrementType: TAqDBAutoIncrementType; begin Result := TAqDBAutoIncrementType.aiGenerator; end; class function TAqDBXIBAdapter.GetDefaultSolver: TAqDBSQLSolverClass; begin Result := TAqDBIBSQLSolver; end; { TAqDBXIBConnection } constructor TAqDBXIBConnection.Create; begin inherited; Self.DriverName := 'InterBase'; Self.VendorLib := 'GDS32.DLL'; Self.LibraryName := 'dbxint.dll'; Self.GetDriverFunc := 'getSQLDriverINTERBASE'; end; class function TAqDBXIBConnection.GetDefaultAdapter: TAqDBAdapterClass; begin Result := TAqDBXIBAdapter; end; function TAqDBXIBConnection.GetPropertyValueAsString(const pIndex: Int32): string; begin case pIndex of $80: Result := Properties[TDBXPropertyNames.Database]; $81: Result := Properties[TDBXPropertyNames.UserName]; $82: Result := Properties[TDBXPropertyNames.Password]; else Result := inherited; end; end; procedure TAqDBXIBConnection.SetPropertyValueAsString(const pIndex: Int32; const pValue: string); begin case pIndex of $80: Properties[TDBXPropertyNames.Database] := pValue; $81: Properties[TDBXPropertyNames.UserName] := pValue; $82: Properties[TDBXPropertyNames.Password] := pValue; else inherited; end; end; end.
unit GridSampler; interface uses Bitmatrix, PerspectiveTransform, Math, DefaultGridSampler; type TGridSampler = class private class var FGridSampler: TGridSampler; public class procedure SetGridSampler(newGridSampler: TGridSampler); static; class function GetInstance: TDefaultGridSampler; static; protected function sampleGrid(image: TBitMatrix; dimensionX: Integer; dimensionY: Integer; transform: TPerspectiveTransform): TBitMatrix; overload; virtual; abstract; function sampleGrid(image: TBitMatrix; dimensionX: Integer; dimensionY: Integer; p1ToX: Single; p1ToY: Single; p2ToX: Single; p2ToY: Single; p3ToX: Single; p3ToY: Single; p4ToX: Single; p4ToY: Single; p1FromX: Single; p1FromY: Single; p2FromX: Single; p2FromY: Single; p3FromX: Single; p3FromY: Single; p4FromX: Single; p4FromY: Single): TBitMatrix; overload; virtual; abstract; class function checkAndNudgePoints(image: TBitMatrix; points: TArray<Single>): boolean; static; end; implementation class procedure TGridSampler.SetGridSampler(newGridSampler: TGridSampler); begin TGridSampler.FGridSampler := newGridSampler; end; class function TGridSampler.GetInstance: TGridSampler; begin Result := TGridSampler.FGridSampler; end; class function TGridSampler.checkAndNudgePoints(image: TBitMatrix; points: TArray<Single>): boolean; var offset, x, y, width, height: Integer; nudged: boolean; begin width := image.width; height := image.height; nudged := true; offset := 0; while ((offset < Length(points)) and nudged) do begin x := Floor(points[offset]); y := Floor(points[(offset + 1)]); if ((((x < -1) or (x > width)) or (y < -1)) or (y > height)) then begin Result := false; exit end; nudged := false; if (x = -1) then begin points[offset] := 0; nudged := true end else if (x = width) then begin points[offset] := (width - 1); nudged := true end; if (y = -1) then begin points[(offset + 1)] := 0; nudged := true end else if (y = height) then begin points[(offset + 1)] := (height - 1); nudged := true end; inc(offset, 2) end; nudged := true; offset := (Length(points) - 2); while ((offset >= 0) and nudged) do begin x := Floor(points[offset]); y := Floor(points[(offset + 1)]); if ((((x < -1) or (x > width)) or (y < -1)) or (y > height)) then begin Result := false; exit end; nudged := false; if (x = -1) then begin points[offset] := 0; nudged := true end else if (x = width) then begin points[offset] := (width - 1); nudged := true end; if (y = -1) then begin points[(offset + 1)] := 0; nudged := true end else if (y = height) then begin points[(offset + 1)] := (height - 1); nudged := true end; dec(offset, 2) end; Result := true; end; end.
Unit XSplash; Interface Uses Classes, Forms, ExtCtrls; Const scDefaultClass ='scDefault'; type { TXSplashForm } TXSplashClass = class of TXSplashForm; TXSplashForm = class(TForm) private FCountForms: Integer; procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); protected function GetHardLabel: String;virtual; abstract; procedure SetHardLabel(Const Value: String); virtual; abstract; function GetTaskLabel: String;virtual; abstract; procedure SetTaskLabel(Const Value: String); virtual; abstract; function GetAutsLabel: String; virtual; abstract; procedure SetAutsLabel(Const Value: String); virtual; abstract; function GetImage: TImage; virtual; abstract; function GetVisProgress: Boolean; virtual; abstract; procedure SetVisProgress(Value: Boolean); virtual; abstract; function GetProgress: Integer; virtual; abstract; procedure SetProgress(Value: Integer); virtual; abstract; function GetProgressCount: Integer; virtual; procedure SetProgressCount(Value: Integer); virtual; public constructor Create(AOwner: TComponent); override; procedure AutoSplash; property XHardLabel: String read GetHardLabel write SetHardLabel; property XTaskLabel: String read GetTaskLabel write SetTaskLabel; property XAutsLabel: String read GetAutsLabel write SetAutsLabel; property XImage: TImage read GetImage; property XProgress: Integer read GetProgress write SetProgress; property XProgressCount: Integer read GetProgressCount write SetProgressCount; property VisProgress: Boolean read GetVisProgress write SetVisProgress; end; Var SystemSplashForm: TXSplashForm = nil; Implementation Uses Windows, Messages, Dialogs, XMisc; Constructor TXSplashForm.Create(AOwner: TComponent); begin Inherited Create(AOwner); ModalResult:=0; XProgress:=0; OnKeyDown:=FormKeyDown; SystemSplashForm:=Self; end; { HardLabel.Caption:=FOrgName; TaskLabel.Caption:=FTaskName; AutsLabel.Caption:=FAuthorsName; } Function TXSplashForm.GetProgressCount: Integer; begin Result:=FCountForms; end; Procedure TXSplashForm.SetProgressCount(Value: Integer); begin FCountForms:=Value; end; Procedure TXSplashForm.AutoSplash; begin if Application.Terminated then Exit; IsAppActive:=False; Application.ProcessMessages; IsAppActive:=True; XProgress:=XProgress+5; { if XProgress>=XProgressCount then} PostMessage({HWND_BROADCAST}Application.Handle, wm_ActivateApp, Word(True), 0); end; Procedure TXSplashForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key=vk_Escape then begin ModalResult:=0; MessageDlg('Работа приложения прервана', mtInformation, [mbOk], 0); if not (csDesigning in ComponentState) then begin Application.Terminate; Application.ProcessMessages; { Application.Free; Application:=nil; } {Halt;} end; end; end; end.
// Fit4Delphi Copyright (C) 2008. Sabre Inc. // This program is free software; you can redistribute it and/or modify it under // the terms of the GNU General Public License as published by the Free Software Foundation; // either version 2 of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; // without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // See the GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along with this program; // if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // // Ported to Delphi by Michal Wojcik. // // Copyright (C) 2003,2004,2005 by Object Mentor, Inc. All rights reserved. // Released under the terms of the GNU General Public License version 2 or later. unit StandardResultHandlerTest; interface uses TestFramework, ByteArrayOutputStream, StandardResultHandler, Counts, RegexTest; type TStandardResultHandlerTest=class(TRegexTest) private bytes : TByteArrayOutputStream; handler : TStandardResultHandler; function getOutputForResultWithCount(counts : TCounts): String; overload; function getOutputForResultWithCount(title : String; counts : TCounts): String; overload; protected procedure SetUp(); override; published procedure testHandleResultPassing(); procedure testHandleResultFailing(); procedure testHandleResultWithErrors(); procedure testHandleErrorWithBlankTitle(); procedure testFinalCount(); end; implementation uses PrintStream, PageResult; { TStandardResultHandlerTest } procedure TStandardResultHandlerTest.setUp(); begin bytes := TByteArrayOutputStream.Create(); handler := TStandardResultHandler.Create(TPrintStream.Create(bytes)); end; procedure TStandardResultHandlerTest.testHandleResultPassing(); var output : String; begin output:=getOutputForResultWithCount(TCounts.Create(5, 0, 0, 0)); assertSubString('.....',output); end; procedure TStandardResultHandlerTest.testHandleResultFailing(); var output : String; begin output:=getOutputForResultWithCount(TCounts.Create(0, 1, 0, 0)); assertSubString('SomePage has failures',output); end; procedure TStandardResultHandlerTest.testHandleResultWithErrors(); var output : String; begin output:=getOutputForResultWithCount(TCounts.Create(0, 0, 0, 1)); assertSubString('SomePage has errors',output); end; procedure TStandardResultHandlerTest.testHandleErrorWithBlankTitle(); var output : String; begin output:=getOutputForResultWithCount('',TCounts.Create(0, 0, 0, 1)); assertSubString('The test has errors',output); end; procedure TStandardResultHandlerTest.testFinalCount(); var counts : TCounts; begin counts:=TCounts.Create(5, 4, 3, 2); handler.acceptFinalCount(counts); assertSubString(counts.toString(),bytes.toString()); end; function TStandardResultHandlerTest.getOutputForResultWithCount(counts : TCounts): String; begin result := getOutputForResultWithCount('SomePage',counts); end; function TStandardResultHandlerTest.getOutputForResultWithCount(title : String; counts : TCounts): String; var lresult : TPageResult; output : String; begin lresult:=TPageResult.Create(title); lresult.setCounts(counts); handler.acceptResult(lresult); output:=bytes.toString(); result := output; end; initialization TestFramework.RegisterTest(TStandardResultHandlerTest.Suite); end.
{ ID:because3 PROG:msquare LANG:PASCAL } program msquare; const maxn=40320; var l,r,total:longint; s:array [1..maxn] of string; a:array [1..maxn] of char; f:array [1..maxn] of longint; v:array [1..maxn] of boolean; ss,now:string; function fac(x:longint):longint; var num,i:longint; begin num:=1; for i:=1 to x do num:=num*i; exit(num); end; function cantor(x:string):longint; var i,j,temp,num:longint; w:array [1..8] of integer; begin for i:=1 to 8 do w[i]:=ord(x[i])-ord('0'); num:=0; for i:=1 to 7 do begin temp:=0; for j:=i+1 to 8 do if w[i]>w[j] then inc(temp); inc(num,fac(8-i)*temp); end; exit(num+1); end; function check(x:string):boolean; begin if x=ss then exit(true) else exit(false); end; function again(x:string):boolean; var ctr:longint; begin ctr:=cantor(x); if v[ctr] then begin v[ctr]:=false; exit(true); end else exit(false); end; procedure print1(x:longint); var y:longint; begin y:=1; while f[x]<>1 do begin x:=f[x]; inc(y); end; writeln(y); end; procedure print(x:longint); begin if f[x]<>1 then print(f[x]); if (x=r) or (total mod 60=0) then writeln(a[x]) else write(a[x]); inc(total); end; procedure achange; var new:string; begin new:=copy(now,5,4)+copy(now,1,4); if check(new) then begin inc(r);s[r]:=new;f[r]:=l;a[r]:='A';print1(r);print(r);close(output);halt; end; if again(new) then begin inc(r);s[r]:=new;f[r]:=l;a[r]:='A';end; end; procedure bchange; var new:string; begin new:=now[4]+copy(now,1,3)+now[8]+copy(now,5,3); if check(new) then begin inc(r);s[r]:=new;f[r]:=l;a[r]:='B';print1(r);print(r);close(output);halt; end; if again(new) then begin inc(r);s[r]:=new;f[r]:=l;a[r]:='B';end; end; procedure cchange; var new:string; begin new:=now[1]+now[6]+now[2]+now[4]+now[5]+now[7]+now[3]+now[8]; if check(new) then begin inc(r);s[r]:=new;f[r]:=l;a[r]:='C';print1(r);print(r);close(output);halt; end; if again(new) then begin inc(r);s[r]:=new;f[r]:=l;a[r]:='C';end; end; BEGIN assign(input,'msquare.in'); reset(input); assign(output,'msquare.out'); rewrite(output); readln(ss); while pos(' ',ss)<>0 do delete(ss,pos(' ',ss),1); ss:=copy(ss,1,4)+ss[8]+ss[7]+ss[6]+ss[5]; close(input); fillchar(s,sizeof(s),0); s[1]:='12348765'; if s[1]=ss then begin writeln(0);writeln;close(output);exit; end; l:=0; r:=1; total:=1; fillchar(v,sizeof(v),1); fillchar(f,sizeof(f),0); while l<=r do begin inc(l); now:=s[l]; achange; bchange; cchange; end; close(output); END.
unit uTestSerializer; {$mode objfpc}{$H+} interface uses Classes, SysUtils, fpcunit, testutils, testregistry, uLibrary, uSetting; type { TTestSerializer } TTestSerializer= class(TTestCase) private fLibrary: ILibrary; protected procedure SetUp; override; published procedure TestSerialize; end; implementation procedure TTestSerializer.SetUp; var DeveloperModule, UserModule: string; begin DeveloperModule := GetSetting.DeveloperLibrary + '\module.jlf'; UserModule := GetSetting.UserLibrary + '\module.jlf'; fLibrary := GetLibrary([DeveloperModule, UserModule]); AssertTrue(fLibrary <> nil); end; procedure TTestSerializer.TestSerialize; begin SaveLibrary(fLibrary); AssertTrue(FileExists(GetSetting.DeveloperLibrary + '\module.bak')); AssertTrue(FileExists(GetSetting.DeveloperLibrary + '\module.jlf')); // AssertTrue(FileExists(GetSetting.UserLibrary + '\module.bak')); // AssertTrue(FileExists(GetSetting.UserLibrary + '\module.jlf')); end; initialization RegisterTest(TTestSerializer); end.
function IsGeldigeMachineCode(pCode: char): boolean; begin IsGeldigeMachineCode := (ORD(pCode) >= 65) AND (ORD(pCode) <= 70); end;
(* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is TurboPower Abbrevia * * The Initial Developer of the Original Code is * Robert Love * * Portions created by the Initial Developer are Copyright (C) 1997-2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** *) unit AbZipKitTests; {$I AbDefine.inc} interface uses TestFrameWork, abTestFrameWork, AbZipKit, AbZipTyp, AbArctyp, SysUtils, Classes, abMeter; type TAbZipKitTests = class(TabCompTestCase) private Component : TAbZipKit; protected procedure SetUp; override; procedure TearDown; override; published procedure TestDefaultStreaming; procedure TestComponentLinks; procedure TestAddThenExtract; procedure TestTaggedFiles; procedure FreshenTest; procedure FreshenBaseDir; end; implementation uses Dialogs; { TAbZipKitTests } procedure TAbZipKitTests.FreshenBaseDir; // Test Freshen without setting the Base Directory // SF.NET Tracker [ 892830 ] DiskFileName is not set correctly var TestFile : String; SL : TStringList; MS : TMemoryStream; FS : TFileStream; begin TestFile := TestTempDir + 'freshenBaseDir.zip'; if FileExists(testFile) then DeleteFile(testFile); Component.StoreOptions := Component.StoreOptions + [soRecurse,soFreshen]; Component.FileName := TestFile; Component.DeflationOption := doMaximum; // Create Files to add // Create 3 Text Files to add to archive. SL := TStringList.Create; try SL.Add('Test File'); SL.SaveToFile(TestTempDir + 'Freshen1base.fsh'); SL.SaveToFile(TestTempDir + 'Freshen2base.fsh'); SL.SaveToFile(TestTempDir + 'Freshen3base.fsh'); Component.AddFiles(TestTempDir + 'Freshen1base.fsh', 0); Component.AddFiles(TestTempDir + 'Freshen2base.fsh', 0); Component.AddFiles(TestTempDir + 'Freshen3base.fsh', 0); Component.CloseArchive; // Modify the 2nd File SL.Add('Modification'); SL.SaveToFile(TestTempDir + 'Freshen2base.fsh'); // Freshen the archive Component.FileName := TestFile; Component.DeflationOption := doMaximum; Component.StoreOptions := Component.StoreOptions + [soRecurse, soFreshen]; Component.AddFiles(TestTempDir + 'Freshen1base.fsh', 0); Component.AddFiles(TestTempDir + 'Freshen2base.fsh', 0); Component.AddFiles(TestTempDir + 'Freshen3base.fsh', 0); Component.Save; // Make sure modified file and archive value matches MS := TMemoryStream.create; FS := TFileStream.create(TestTempDir + 'Freshen2base.fsh',fmOpenRead); try Component.ExtractToStream(Component.Items[1].FileName,MS); CheckStreamMatch(FS,MS,'Freshened File on Disk Did not Match Archived value'); finally MS.Free; FS.Free; end; finally SL.Free; DeleteFile(TestTempDir + 'Freshen1base.fsh'); DeleteFile(TestTempDir + 'Freshen2base.fsh'); DeleteFile(TestTempDir + 'Freshen3base.fsh'); DeleteFile(TestFile); end; end; procedure TAbZipKitTests.FreshenTest; // [887909] soFreshen isn't working var SL : TStringList; MS : TMemoryStream; FS : TFileStream; begin // Create 3 Text Files to add to archive. SL := TStringList.Create; try SL.Add('Test File'); SL.SaveToFile(TestTempDir + 'Freshen1.fsh'); SL.SaveToFile(TestTempDir + 'Freshen2.fsh'); SL.SaveToFile(TestTempDir + 'Freshen3.fsh'); if FileExists(TestTempDir + 'Freshen.zip') then DeleteFile(TestTempDir + 'Freshen.zip'); Component.FileName := TestTempDir + 'Freshen.zip'; Component.BaseDirectory := TestTempDir; Component.DeflationOption := doMaximum; Component.StoreOptions := Component.StoreOptions + [soRecurse, soFreshen]; Component.AddFiles('*.fsh',0); Component.Save; component.CloseArchive; // Modify the 2nd File SL.Add('Modification'); SL.SaveToFile(TestTempDir + 'Freshen2.fsh'); // Freshen the archive Component.FileName := TestTempDir + 'Freshen.zip'; Component.BaseDirectory := TestTempDir; Component.DeflationOption := doMaximum; Component.StoreOptions := Component.StoreOptions + [soRecurse, soFreshen]; Component.AddFiles('*.fsh',0); Component.Save; // Make sure modified file and archive value matches MS := TMemoryStream.create; FS := TFileStream.create(TestTempDir + 'Freshen2.fsh',fmOpenRead); try Component.ExtractToStream('Freshen2.fsh',MS); CheckStreamMatch(FS,MS,'Freshened File on Disk Did not Match Archived value'); finally MS.Free; FS.Free; end; finally SL.Free; DeleteFile(TestTempDir + 'Freshen1.fsh'); DeleteFile(TestTempDir + 'Freshen2.fsh'); DeleteFile(TestTempDir + 'Freshen3.fsh'); DeleteFile(TestTempDir + 'Freshen.zip'); end; end; procedure TAbZipKitTests.SetUp; begin inherited; Component := TAbZipKit.Create(TestForm); end; procedure TAbZipKitTests.TearDown; begin inherited; end; procedure TAbZipKitTests.TestAddThenExtract; var MS : TMemoryStream; FS : TFileStream; I : Integer; begin // [ 785769 ] SF.NET Tracker ID is the Bug this is testing for. // This test is designed to add to an archive // Then extract from it without having to close/reopen archive. if FileExists(TestTempDir + 'ZKitTest.zip') then DeleteFile(TestTempDir + 'ZKitTest.zip'); Component.FileName := TestTempDir + 'ZKitTest.zip'; Component.BaseDirectory := GetWindowsDir; Component.AddFiles('*.ZIP',faAnyFile); Component.Save; MS := TMemoryStream.Create; try For I := 0 to Component.Count -1 do begin // Compare uncompressed Files to Original Files Component.ExtractToStream(Component.Items[I].FileName,MS); FS := TFileStream.create(TestFileDir + ExtractFileName(Component.Items[I].FileName),fmOpenRead); try CheckStreamMatch(MS,FS,'File ' + Component.Items[I].FileName + ' did not match original.'); MS.Clear; finally FS.Free; end; end; finally MS.Free; end; end; procedure TAbZipKitTests.TestComponentLinks; var MLink1,MLink2,MLink3 : TAbVCLMeterLink; begin MLink1 := TAbVCLMeterLink.Create(TestForm); MLink2 := TAbVCLMeterLink.Create(TestForm); MLink3 := TAbVCLMeterLink.Create(TestForm); Component.ArchiveProgressMeter := MLink1; Component.ItemProgressMeter := MLink2; Component.ArchiveSaveProgressMeter := MLink3; MLink1.Free; MLink2.Free; MLink3.Free; Check(Component.ArchiveProgressMeter = nil,'Notification does not work for TAbZipKit.ArchiveProgressMeter'); Check(Component.ItemProgressMeter = nil,'Notification does not work for TAbZipKit.ItemProgressMeter'); Check(Component.ArchiveSaveProgressMeter = nil,'Notification does not work for TAbZipKit.ArchiveSaveProgressMeter'); end; procedure TAbZipKitTests.TestDefaultStreaming; var CompStr : STring; CompTest : TAbZipKit; begin RegisterClass(TAbZipKit); CompStr := StreamComponent(Component); CompTest := (UnStreamComponent(CompStr) as TAbZipKit); CompareComponentProps(Component,CompTest); UnRegisterClass(TAbZipKit); end; procedure TAbZipKitTests.TestTaggedFiles; begin // Test for Bug 806077 DeleteFile(TestTempDir + 'test.zip'); Component.FileName := TestTempDir + 'test.zip'; Component.AutoSave := True; Component.BaseDirectory := TestFileDir; Component.ClearTags; Component.AddFiles('*.*',0); Component.TagItems('*.*'); Check(Component.Count > 0); // TestTaggedItems should not raise an error. Component.TestTaggedItems; Component.CloseArchive; end; initialization TestFramework.RegisterTest('Abbrevia.Component Level Test Suite', TAbZipKitTests.Suite); end.
unit udmBase; interface uses SysUtils, Classes, FMTBcd, DBClient, Provider, DB, SqlExpr; type TdmBase = class(TDataModule) qry: TSQLQuery; dsp: TDataSetProvider; cds: TClientDataSet; procedure DataModuleCreate(Sender: TObject); private FEmpresas: TStringList; FBases: TStringList; FId_Empresa: TStringList; { Private declarations } procedure LlenarBases; Virtual; procedure LlenarEmpresas; Virtual; procedure LlenarId_Empresas; Virtual; procedure SetBases(const Value: TStringList); procedure SetEmpresas(const Value: TStringList); procedure SetId_Empresa(const Value: TStringList); public { Public declarations } property Bases: TStringList read FBases write SetBases; property Empresas: TStringList read FEmpresas write SetEmpresas; property Id_Empresa: TStringList read FId_Empresa write SetId_Empresa; end; var dmBase: TdmBase; implementation uses udmPrincipal; {$R *.dfm} { TdmBase } procedure TdmBase.DataModuleCreate(Sender: TObject); begin Bases := TStringList.Create; Empresas := TStringList.Create; Id_Empresa := TStringList.Create; LlenarBases; LlenarEmpresas; LlenarId_Empresas; end; procedure TdmBase.LlenarBases; var InvTecun, InvTecunCR, InvDidea, InvUniauto, InvMultiPlaza, InvMultiAutos, InvEuropa, InvPremier, InvPlaza, InvCGI: string; begin InvTecun := dmPrincipal.LeerIni('Bases.ini', 'INV', 'INVTECUN', ''); InvTecunCR := dmPrincipal.LeerIni('Bases.ini','INV', 'INVTECUNCR', ''); InvDidea := dmPrincipal.LeerIni('Bases.ini','INV', 'INVDIDEA', ''); InvUniauto := dmPrincipal.LeerIni('Bases.ini','INV', 'INVUNIAUTO', ''); InvMultiPlaza := dmPrincipal.LeerIni('Bases.ini','INV', 'INVMULTIPLAZA', ''); InvMultiAutos := dmPrincipal.LeerIni('Bases.ini','INV', 'INVMULTIAUTOS', ''); InvEuropa := dmPrincipal.LeerIni('Bases.ini','INV', 'INVEUROPA', ''); InvPremier := dmPrincipal.LeerIni('Bases.ini','INV', 'INVPREMIER', ''); InvPlaza := dmPrincipal.LeerIni('Bases.ini','INV', 'INVPLAZA', ''); InvCGI := dmPrincipal.LeerIni('Bases.ini','INV', 'INVCGI', ''); Bases.Clear; Bases.Add(InvTecun); Bases.Add(InvTecunCR); Bases.Add(InvDidea); Bases.Add(InvUniauto); Bases.Add(InvMultiPlaza); Bases.Add(InvMultiAutos); Bases.Add(InvEuropa); Bases.Add(InvPremier); Bases.Add(InvPlaza); Bases.Add(InvCGI); end; procedure TdmBase.LlenarEmpresas; begin Empresas.Clear; Empresas.Add('TECUN, S.A.'); Empresas.Add('TECUN COSTA RICA'); Empresas.Add('DIDEA'); Empresas.Add('UNIAUTO'); Empresas.Add('MULTIPLAZA'); Empresas.Add('MULTIAUTOS'); Empresas.Add('EUROPA'); Empresas.Add('PREMIER'); Empresas.Add('PLAZA'); Empresas.Add('CGI'); end; procedure TdmBase.LlenarId_Empresas; begin Id_Empresa.Clear; Id_Empresa.Add('1'); Id_Empresa.Add('3'); Id_Empresa.Add('4'); Id_Empresa.Add('5'); Id_Empresa.Add('6'); Id_Empresa.Add('7'); Id_Empresa.Add('8'); Id_Empresa.Add('9'); Id_Empresa.Add('10'); end; procedure TdmBase.SetBases(const Value: TStringList); begin FBases := Value; end; procedure TdmBase.SetEmpresas(const Value: TStringList); begin FEmpresas := Value; end; procedure TdmBase.SetId_Empresa(const Value: TStringList); begin FId_Empresa := Value; end; end.
unit ScenarioHandler; { SimThyr Project } { A numerical simulator of thyrotropic feedback control } { Version 4.0.0 (Merlion) } { (c) J. W. Dietrich, 1994 - 2017 } { (c) Ludwig Maximilian University of Munich 1995 - 2002 } { (c) Ruhr University of Bochum 2005 - 2017 } { This unit reads and writes scenarios as XML files } { Source code released under the BSD License } { See http://simthyr.sourceforge.net for details } {$mode objfpc} interface uses Classes, SysUtils, DateUtils, DOM, XMLRead, XMLWrite, Forms, URIParser, SimThyrTypes, SimThyrServices, MiriamForm, VersionSupport, SimThyrResources; procedure ReadScenario(theFileName: string; var modelVersion: Str13); procedure SaveScenario(theFileName: string); implementation function ValidFormat(theStream: TStream; const theBaseURI: ansistring): boolean; const SIGNATURE_1 = '<?xml version="1.'; SIGNATURE_2 = '<scenario'; SIGNATURE_3 = '</scenario>'; var origString, lowerString: ansistring; begin Result := False; if theStream.Size > 0 then begin SetLength(origString, theStream.Size); theStream.Read(origString[1], theStream.Size); if origString <> '' then begin lowerString := LowerCase(origString); if LeftStr(lowerString, 17) = SIGNATURE_1 then if pos(SIGNATURE_2, lowerString) <> 0 then if pos(SIGNATURE_3, lowerString) <> 0 then Result := True; end; end; end; function ValidFormat(theFileName: string): boolean; var theStream: TStream; begin theStream := TFileStream.Create(theFileName, fmOpenRead + fmShareDenyWrite); try Result := ValidFormat(theStream, FilenameToURI(theFileName)); finally if theStream <> nil then theStream.Free; end; end; procedure ReadScenario(theFileName: string; var modelVersion: Str13); {reads a simulation scenario} var i: integer; Doc: TXMLDocument; RootNode: TDOMNode; oldSep: char; standardDate: TDateTime; begin if FileExists(theFileName) then if ValidFormat(theFileName) then begin oldSep := DefaultFormatSettings.DecimalSeparator; DefaultFormatSettings.DecimalSeparator := kPERIOD; try standardDate := EncodeDateTime(1904, 01, 01, 00, 00, 00, 00); ReadXMLFile(Doc, theFileName); if assigned(Doc) then RootNode := Doc.DocumentElement; if assigned(RootNode) and RootNode.HasAttributes and (RootNode.Attributes.Length > 0) then for i := 0 to RootNode.Attributes.Length - 1 do with RootNode.Attributes[i] do begin if NodeName = 'modelversion' then modelVersion := UTF8Encode(NodeValue); end; RootNode := Doc.DocumentElement.FindNode('MIRIAM'); if assigned(RootNode) then begin gActiveModel.Name := NodeContent(RootNode, 'Name'); gActiveModel.Reference := NodeContent(RootNode, 'Reference'); gActiveModel.Species := NodeContent(RootNode, 'Species'); gActiveModel.Creators := NodeContent(RootNode, 'Creators'); if not TryXMLDateTime2DateTime(NodeContent(RootNode, 'Created'), gActiveModel.Created) then gActiveModel.Created := standardDate; if not TryXMLDateTime2DateTime(NodeContent(RootNode, 'LastModified'), gActiveModel.LastModified) then gActiveModel.LastModified := standardDate; gActiveModel.Terms := NodeContent(RootNode, 'Terms'); end; RootNode := Doc.DocumentElement.FindNode('MIASE'); if assigned(RootNode) then begin gActiveModel.Code := NodeContent(RootNode, 'Code'); gActiveModel.Comments := NodeContent(RootNode, 'Comments'); end; if gActiveModel.Code = '' then gActiveModel.Code := MIASE_SIMTHYR_STANDARD_CODE; if (modelVersion = '') or (LeftStr(modelVersion, 3) = '10.') then begin RootNode := Doc.DocumentElement.FindNode('strucpars'); if assigned(RootNode) then begin VarFromNode(RootNode, 'alphaR', AlphaR); VarFromNode(RootNode, 'betaR', BetaR); VarFromNode(RootNode, 'GR', GR); VarFromNode(RootNode, 'dR', dR); VarFromNode(RootNode, 'alphaS', AlphaS); VarFromNode(RootNode, 'betaS', BetaS); VarFromNode(RootNode, 'alphaS2', AlphaS2); VarFromNode(RootNode, 'betaS2', BetaS2); VarFromNode(RootNode, 'GH', GH); VarFromNode(RootNode, 'dH', dH); VarFromNode(RootNode, 'LS', LS); VarFromNode(RootNode, 'SS', SS); VarFromNode(RootNode, 'DS', DS); VarFromNode(RootNode, 'alphaT', AlphaT); VarFromNode(RootNode, 'betaT', BetaT); VarFromNode(RootNode, 'GT', GT); VarFromNode(RootNode, 'dT', dT); VarFromNode(RootNode, 'alpha31', alpha31); VarFromNode(RootNode, 'beta31', beta31); VarFromNode(RootNode, 'GD1', GD1); VarFromNode(RootNode, 'KM1', KM1); VarFromNode(RootNode, 'alpha32', alpha32); VarFromNode(RootNode, 'beta32', beta32); VarFromNode(RootNode, 'GD2', GD2); VarFromNode(RootNode, 'KM2', KM2); VarFromNode(RootNode, 'K30', K30); VarFromNode(RootNode, 'K31', K31); VarFromNode(RootNode, 'K41', K41); VarFromNode(RootNode, 'K42', K42); VarFromNode(RootNode, 'Tau0R', TT1); VarFromNode(RootNode, 'Tau0S', TT2); VarFromNode(RootNode, 'Tau0S2', TT22); VarFromNode(RootNode, 'Tau0T', TT3); VarFromNode(RootNode, 'Tau03z', TT4); end; end else ShowVersionError; finally if assigned(Doc) then Doc.Free; end; if AnnotationForm.Visible then AnnotationForm.ShowAnnotation; DefaultFormatSettings.DecimalSeparator := oldSep; end else ShowFileError; end; procedure SaveScenario(theFileName: string); {saves scenario as XML file} var oldSep: char; Doc: TXMLDocument; RootNode, ElementNode: TDOMNode; theDate: ansistring; begin oldSep := DefaultFormatSettings.DecimalSeparator; DefaultFormatSettings.DecimalSeparator := kPERIOD; try Doc := TXMLDocument.Create; RootNode := Doc.CreateElement('scenario'); TDOMElement(RootNode).SetAttribute('modelversion', '10.0'); Doc.Appendchild(RootNode); RootNode := Doc.DocumentElement; ElementNode := Doc.CreateElement('MIRIAM'); ElementNode.AppendChild(SimpleNode(Doc, 'Name', gActiveModel.Name)); ElementNode.AppendChild(SimpleNode(Doc, 'Reference', gActiveModel.Reference)); ElementNode.AppendChild(SimpleNode(Doc, 'Species', gActiveModel.Species)); ElementNode.AppendChild(SimpleNode(Doc, 'Creators', gActiveModel.Creators)); DateTimeToString(theDate, ISO_8601_DATE_FORMAT, gActiveModel.Created); ElementNode.AppendChild(SimpleNode(Doc, 'Created', theDate)); DateTimeToString(theDate, ISO_8601_DATE_FORMAT, gActiveModel.LastModified); ElementNode.AppendChild(SimpleNode(Doc, 'LastModified', theDate)); ElementNode.AppendChild(SimpleNode(Doc, 'Terms', gActiveModel.Terms)); RootNode.AppendChild(ElementNode); ElementNode := Doc.CreateElement('MIASE'); if gActiveModel.Code = '' then gActiveModel.Code := MIASE_SIMTHYR_STANDARD_CODE; ElementNode.AppendChild(SimpleNode(Doc, 'Code', gActiveModel.Code)); ElementNode.AppendChild(SimpleNode(Doc, 'Comments', gActiveModel.Comments)); RootNode.AppendChild(ElementNode); ElementNode := Doc.CreateElement('strucpars'); ElementNode.AppendChild(SimpleNode(Doc, 'alphaR', FloatToStr(alphaR))); ElementNode.AppendChild(SimpleNode(Doc, 'betaR', FloatToStr(betaR))); ElementNode.AppendChild(SimpleNode(Doc, 'GR', FloatToStr(GR))); ElementNode.AppendChild(SimpleNode(Doc, 'dR', FloatToStr(dR))); ElementNode.AppendChild(SimpleNode(Doc, 'alphaS', FloatToStr(alphaS))); ElementNode.AppendChild(SimpleNode(Doc, 'betaS', FloatToStr(betaS))); ElementNode.AppendChild(SimpleNode(Doc, 'alphaS2', FloatToStr(alphaS2))); ElementNode.AppendChild(SimpleNode(Doc, 'betaS2', FloatToStr(betaS2))); ElementNode.AppendChild(SimpleNode(Doc, 'GH', FloatToStr(GH))); ElementNode.AppendChild(SimpleNode(Doc, 'dH', FloatToStr(dH))); ElementNode.AppendChild(SimpleNode(Doc, 'LS', FloatToStr(LS))); ElementNode.AppendChild(SimpleNode(Doc, 'SS', FloatToStr(SS))); ElementNode.AppendChild(SimpleNode(Doc, 'DS', FloatToStr(DS))); ElementNode.AppendChild(SimpleNode(Doc, 'alphaT', FloatToStr(alphaT))); ElementNode.AppendChild(SimpleNode(Doc, 'betaT', FloatToStr(betaT))); ElementNode.AppendChild(SimpleNode(Doc, 'GT', FloatToStr(GT))); ElementNode.AppendChild(SimpleNode(Doc, 'dT', FloatToStr(dT))); ElementNode.AppendChild(SimpleNode(Doc, 'alpha31', FloatToStr(alpha31))); ElementNode.AppendChild(SimpleNode(Doc, 'beta31', FloatToStr(beta31))); ElementNode.AppendChild(SimpleNode(Doc, 'GD1', FloatToStr(GD1))); ElementNode.AppendChild(SimpleNode(Doc, 'KM1', FloatToStr(KM1))); ElementNode.AppendChild(SimpleNode(Doc, 'alpha32', FloatToStr(alpha32))); ElementNode.AppendChild(SimpleNode(Doc, 'beta32', FloatToStr(beta32))); ElementNode.AppendChild(SimpleNode(Doc, 'GD2', FloatToStr(GD2))); ElementNode.AppendChild(SimpleNode(Doc, 'KM2', FloatToStr(KM2))); ElementNode.AppendChild(SimpleNode(Doc, 'K30', FloatToStr(K30))); ElementNode.AppendChild(SimpleNode(Doc, 'K31', FloatToStr(K31))); ElementNode.AppendChild(SimpleNode(Doc, 'K41', FloatToStr(K41))); ElementNode.AppendChild(SimpleNode(Doc, 'K42', FloatToStr(K42))); ElementNode.AppendChild(SimpleNode(Doc, 'Tau0R', FloatToStr(TT1))); ElementNode.AppendChild(SimpleNode(Doc, 'Tau0S', FloatToStr(TT2))); ElementNode.AppendChild(SimpleNode(Doc, 'Tau0S2', FloatToStr(TT22))); ElementNode.AppendChild(SimpleNode(Doc, 'Tau0T', FloatToStr(TT3))); ElementNode.AppendChild(SimpleNode(Doc, 'Tau03z', FloatToStr(TT4))); RootNode.AppendChild(ElementNode); WriteXMLFile(Doc, theFileName); finally Doc.Free; end; DefaultFormatSettings.DecimalSeparator := oldSep; end; end.
program gadtoolsexample; {$IFNDEF HASAMIGA} {$FATAL This source is compatible with Amiga, AROS and MorphOS only !} {$ENDIF} {$MODE OBJFPC}{$H+}{$HINTS ON} {$UNITPATH ../../../Base/CHelpers} {$UNITPATH ../../../Base/Trinity} {$UNITPATH ../../../Base/Sugar} {$IFDEF AMIGA} {$UNITPATH ../../../Sys/Amiga} {$ENDIF} {$IFDEF AROS} {$UNITPATH ../../../Sys/AROS} {$ENDIF} {$IFDEF MORPHOS} {$UNITPATH ../../../Sys/MorphOS} {$ENDIF} { =========================================================================== Project : gadtools Topic : Example of GUI programming with GadTools Author : Thomas Rapp Source : http://thomas-rapp.homepage.t-online.de/examples/gadtools.c =========================================================================== This example was originally written in c by Thomas Rapp. The original examples are available online and published at Thomas Rapp's website (http://thomas-rapp.homepage.t-online.de/examples) The c-sources were converted to Free Pascal, and (variable) names and comments were translated from German into English as much as possible. Free Pascal sources were adjusted in order to support the following targets out of the box: - Amiga-m68k, AROS-i386 and MorphOS-ppc In order to accomplish that goal, some use of support units is used that aids compilation in a more or less uniform way. Conversion to Free Pascal and translation was done by Magorium in 2015, with kind permission from Thomas Rapp to be able to publish. =========================================================================== Unless otherwise noted, you must consider these examples to be copyrighted by their respective owner(s) =========================================================================== } Uses Exec, AmigaDOS, Intuition, Gadtools, Utility, {$IFDEF AMIGA} systemvartags, {$ENDIF} CHelpers, Trinity; //*-------------------------------------------------------------------------*/ //* */ //*-------------------------------------------------------------------------*/ Const cycletext : Array[0..4] of PChar = ('One','Two','Three','Four', nil); GID_AUSWAHL = 4711; GID_INPUT = 4712; GID_CONTINUE = 4713; GID_ABORT = 4714; //*-------------------------------------------------------------------------*/ //* Main program */ //*-------------------------------------------------------------------------*/ function main: integer; var gad : PGadget; //* Pointer to the current gadget */ glist : PGadget; //* Pointer to first gasget in the list */ ng : TNewGadget; //* Generic information for new gadgets (Size, Font, Text etc.) */ scr : PScreen; win : PWindow; imsg : PIntuiMessage; cont : Boolean; winw,winh : LongInt; num : LongInt; txt : PChar; begin if SetAndTest(scr, LockPubScreen(nil)) then begin glist := nil; gad := CreateContext(@glist); //* This will initialize the Gadget-List. */ //* Set values, that are the same for each gadget */ ng.ng_VisualInfo := GetVisualInfo(scr, [TAG_END, TAG_END]); //* bug in aros taglist ng.ng_TextAttr := scr^.Font; ng.ng_Flags := 0; //* The following block (incl. Create Gadget) is repeated for each new gadget. */ //* Only the values that need to change are adjusted. */ //* At CreateGadget the previous gadget is provided, so that they are */ //* concatenated. //* It isn't necessary to check the result each time it was obtained. If the */ //* previous gadget was Nil, then all further gadgets will be nil as well, */ //* which allows us to only check the last created gadget */ ng.ng_LeftEdge := scr^.WBorLeft + 4 + 10 * scr^.RastPort.TxWidth; ng.ng_TopEdge := scr^.WBorTop + scr^.RastPort.TxHeight + 5; ng.ng_Width := 20 * scr^.RastPort.TxWidth + 20; ng.ng_Height := scr^.RastPort.TxHeight + 6; ng.ng_GadgetText := PChar('Selection'); ng.ng_GadgetID := GID_AUSWAHL; gad := CreateGadget(CYCLE_KIND, gad, @ng, [TAG_(GTCY_Labels), TAG_(@cycletext), TAG_END]); ng.ng_TopEdge := ng.ng_TopEdge + ng.ng_Height + 4; ng.ng_GadgetText := PChar('Input'); ng.ng_GadgetID := GID_INPUT; gad := CreateGadget(STRING_KIND, gad, @ng, [TAG_END, TAG_END]); //* bug in aros taglist ng.ng_LeftEdge := scr^.WBorLeft + 4; ng.ng_TopEdge := ng.ng_TopEdge + ng.ng_Height + 4; ng.ng_Width := 15 * scr^.RastPort.TxWidth + 8; ng.ng_GadgetText := PChar('Continue'); ng.ng_GadgetID := GID_CONTINUE; gad := CreateGadget(BUTTON_KIND, gad, @ng, [TAG_END, TAG_END]); //* bug in aroas taglist ng.ng_LeftEdge := ng.ng_LeftEdge + ng.ng_Width + 4; ng.ng_GadgetText := PChar('Abort'); ng.ng_GadgetID := GID_ABORT; gad := CreateGadget(BUTTON_KIND, gad, @ng, [TAG_END, TAG_END]); //* bug in aros taglist //* The last gadget is at the bottom right, therefore, its size and position are */ //* used to calculate the window size. */ winw := ng.ng_LeftEdge + ng.ng_Width + 4 + scr^.WBorRight; winh := ng.ng_TopEdge + ng.ng_Height + 4 + scr^.WBorBottom; if assigned(gad) then //* Check if all the gadgets have been created */ begin //* When opening the window the IDCMP flags for Gadtools gadgets must be specified. */ //* For this, the constants are <type> IDCMP are used.*/ if SetAndTest(win, OpenWindowTags (nil, [ TAG_(WA_Width) , winw, TAG_(WA_Height) , winh, TAG_(WA_Left) , (scr^.Width - winw) div 2, //* Center window on screen */ TAG_(WA_Top) , (scr^.Height - winh) div 2, TAG_(WA_PubScreen) , TAG_(scr), TAG_(WA_Title) , TAG_(PChar('Window')), TAG_(WA_Flags) , TAG_(WFLG_CLOSEGADGET or WFLG_DRAGBAR or WFLG_DEPTHGADGET or WFLG_ACTIVATE), TAG_(WA_IDCMP) , TAG_(IDCMP_CLOSEWINDOW or IDCMP_VANILLAKEY or IDCMP_REFRESHWINDOW or BUTTONIDCMP or CYCLEIDCMP or STRINGIDCMP), TAG_(WA_Gadgets) , TAG_(glist), TAG_END ])) then begin GT_RefreshWindow(win, nil); //* Redraw all Gadtools-Gadgets. */ //* This must be done once at the beginning. */ UnlockPubScreen(nil, scr); //* The window prevents the screen from closing, */ scr := nil; //* therfor the lock is no longer needed here */ //* Folowing is normal window message handling. */ //* Except that instead of the usual Getmsg / ReplyMsg we use Gadtools functions */ cont := TRUE; while cont do begin if (Wait ((1 shl win^.UserPort^.mp_SigBit) or SIGBREAKF_CTRL_C) and SIGBREAKF_CTRL_C) <> 0 then cont := FALSE; while SetAndTest(imsg, GT_GetIMsg(win^.UserPort)) do begin case (imsg^.IClass) of IDCMP_GADGETUP: begin gad := PGadget(imsg^.IAddress); case (gad^.GadgetID) of GID_AUSWAHL: begin GT_GetGadgetAttrs(gad, win, nil, [TAG_(GTCY_Active), TAG_(@num), TAG_END]); WriteLn('Selection: ', cycletext[num]); end; GID_INPUT: begin GT_GetGadgetAttrs(gad, win, nil, [TAG_(GTST_String), TAG_(@txt), TAG_END]); WriteLn('Input: <', txt, '>'); end; GID_CONTINUE: begin WriteLn('Continue'); end; GID_ABORT: begin WriteLn('Abort'); end; end; // case end; IDCMP_VANILLAKEY: begin if (imsg^.Code = $1b) //* Esc */ then cont := FALSE; end; IDCMP_CLOSEWINDOW: begin cont := FALSE; end; IDCMP_REFRESHWINDOW: begin GT_BeginRefresh(win); GT_EndRefresh(win, LongInt(TRUE)); end; end; // case imasg GT_ReplyIMsg(imsg); end; end; // while cont CloseWindow(win); end; end; FreeGadgets(glist); FreeVisualInfo(ng.ng_VisualInfo); if assigned(scr) then UnlockPubScreen(nil, scr); end; Result := (0); end; //*-------------------------------------------------------------------------*/ //* End of original source text */ //*-------------------------------------------------------------------------*/ Function OpenLibs: boolean; begin Result := False; {$IF DEFINED(MORPHOS) or DEFINED(AMIGA)} GadToolsBase := OpenLibrary(GADTOOLSNAME, 0); if not assigned(GadToolsBase) then Exit; {$ENDIF} {$IF DEFINED(MORPHOS)} IntuitionBase := OpenLibrary(INTUITIONNAME, 0); if not assigned(IntuitionBase) then Exit; {$ENDIF} Result := True; end; Procedure CloseLibs; begin {$IF DEFINED(MORPHOS)} if assigned(IntuitionBase) then CloseLibrary(pLibrary(IntuitionBase)); {$ENDIF} {$IF DEFINED(MORPHOS) or DEFINED(AMIGA)} if assigned(GadToolsBase) then CloseLibrary(pLibrary(GadToolsBase)); {$ENDIF} end; begin if OpenLibs then ExitCode := Main else ExitCode := 10; CloseLibs; end.
unit TSThumbnail; {$WARN SYMBOL_PLATFORM OFF} interface uses Winapi.Windows, ComObj, ActiveX, thumbnail_TLB, StdVcl, Winapi.ShlObj, System.Classes, System.SysUtils, Vcl.Graphics, System.IOUtils; type TTSThumbnail = class(TComObject, IPersist, IPersistFile, IExtractImage, IExtractImage2) private FFileName: string; protected function IsDirty: HResult; stdcall; function Load(pszFileName: POleStr; dwMode: Longint): HResult; stdcall; function Save(pszFileName: POleStr; fRemember: BOOL): HResult; stdcall; function SaveCompleted(pszFileName: POleStr): HResult; stdcall; function GetCurFile(out pszFileName: POleStr): HResult; stdcall; function GetDateStamp(var pDateStamp: TFileTime): HRESULT; stdcall; function GetLocation(pszPathBuffer: LPWSTR; cch: DWORD; var pdwPriority: DWORD; var prgSize: TSize; dwRecClrDepth: DWORD; var pdwFlags: DWORD): HRESULT; stdcall; function Extract(var phBmpThumbnail: HBITMAP): HRESULT; stdcall; function GetClassID(out classID: TCLSID): HResult; stdcall; end; TTSThumbnailFactory = class(TComObjectFactory) public procedure UpdateRegistry(Register: Boolean); override; end; implementation uses ComServ, System.Win.Registry, Vcl.Imaging.jpeg; const SDescription = 'Tisn Thumbnail'; EXT_PSD = '.psd'; var FFileTypeList: TStrings; function IsWin64: Boolean; var Kernel32Handle: THandle; IsWow64Process: function(Handle: THandle; var Res: BOOL): BOOL; stdcall; GetNativeSystemInfo: procedure(var lpSystemInfo: TSystemInfo); stdcall; isWoW64: Bool; SystemInfo: TSystemInfo; const PROCESSOR_ARCHITECTURE_AMD64 = 9; PROCESSOR_ARCHITECTURE_IA64 = 6; begin Kernel32Handle := GetModuleHandle('KERNEL32.DLL'); if Kernel32Handle = 0 then Kernel32Handle := LoadLibrary('KERNEL32.DLL'); if Kernel32Handle <> 0 then begin IsWOW64Process := GetProcAddress(Kernel32Handle, 'IsWow64Process'); GetNativeSystemInfo := GetProcAddress(Kernel32Handle, 'GetNativeSystemInfo'); if Assigned(IsWow64Process) then begin IsWow64Process(GetCurrentProcess, isWoW64); Result := isWoW64 and Assigned(GetNativeSystemInfo); if Result then begin GetNativeSystemInfo(SystemInfo); Result := (SystemInfo.wProcessorArchitecture = PROCESSOR_ARCHITECTURE_AMD64) or (SystemInfo.wProcessorArchitecture = PROCESSOR_ARCHITECTURE_IA64); end; end else Result := False; end else Result := False; end; procedure RegisterWin32NT(const ClassID, Description: string; Register: Boolean); begin OutputDebugString(PWideChar('[TISN]RegisterWin32NT:' + ClassID)); {if IsWin64 then begin with TRegistry.Create do try Access := KEY_WOW64_64KEY or KEY_ALL_ACCESS; RootKey := HKEY_LOCAL_MACHINE; OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions', True); OpenKey('Approved', True); if Register then WriteString(ClassID, Description) else DeleteValue(ClassID) finally Free; end; with TRegistry.Create do try Access := KEY_WOW64_32KEY or KEY_ALL_ACCESS; RootKey := HKEY_LOCAL_MACHINE; OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions', True); OpenKey('Approved', True); if Register then WriteString(ClassID, Description) else DeleteValue(ClassID) finally Free; end; end else begin } with TRegistry.Create do try RootKey := HKEY_LOCAL_MACHINE; OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions', True); OpenKey('Approved', True); if Register then WriteString(ClassID, Description) else DeleteValue(ClassID) finally Free; end; {end; } end; procedure TTSThumbnailFactory.UpdateRegistry(Register: Boolean); var ClassID: string; ft: string; begin inherited UpdateRegistry(Register); ClassID := GUIDToString(Class_TSThumbnail); OutputDebugString(PWideChar('[TISN]TTSThumbnailFactory.UpdateRegistry' + ClassID)); for ft in FFileTypeList do begin if Register then begin CreateRegKey(ft + '\ShellEx\{BB2E617C-0920-11d1-9A0B-00C04FC2D6C1}', '', ClassID); RegisterWin32NT(ClassID, SDescription, Register); end else begin DeleteRegKey(ft + '\ShellEx\{BB2E617C-0920-11d1-9A0B-00C04FC2D6C1}'); RegisterWin32NT(ClassID, SDescription, Register); end; end; end; function TTSThumbnail.IsDirty; begin Result := E_NOTIMPL; end; function TTSThumbnail.Load(pszFileName: PWideChar; dwMode: Integer): HResult; begin OutputDebugString(PWideChar('[TISN]TTSThumbnail.Load fileName:' + pszFileName)); FFileName := pszFileName; Result := S_OK; end; function TTSThumbnail.Save(pszFileName: PWideChar; fRemember: LongBool): HResult; begin Result := E_NOTIMPL; end; function TTSThumbnail.SaveCompleted(pszFileName: PWideChar): HResult; begin Result := E_NOTIMPL; end; function TTSThumbnail.GetCurFile(out pszFileName: PWideChar): HResult; begin Result := E_NOTIMPL; end; function TTSThumbnail.GetDateStamp(var pDateStamp: _FILETIME): HResult; begin Result := E_NOTIMPL; end; function TTSThumbnail.GetLocation(pszPathBuffer: PWideChar; cch: Cardinal; var pdwPriority: Cardinal; var prgSize: TSize; dwRecClrDepth: Cardinal; var pdwFlags: Cardinal): HResult; begin OutputDebugString('[TISN]TTSThumbnail.GetLocation'); pdwPriority := IEIT_PRIORITY_NORMAL; if (pdwFlags and IEIFLAG_ASYNC) = 0 then begin Result := E_PENDING; end else begin Result := E_PENDING; end; pdwFlags := pdwFlags + IEIFLAG_CACHE + IEIFLAG_REFRESH; end; function TTSThumbnail.Extract(var phBmpThumbnail: HBITMAP): HResult; begin try phBmpThumbnail := LoadBitmap(HInstance, 'Bitmap_1'); Result := S_OK; OutputDebugString('[TISN]TTSThumbnail.Extract ³É¹¦'); except on E: Exception do begin Result := E_FAIL; OutputDebugString('[TISN]TTSThumbnail.Extract ʧ°Ü'); end; end; end; function TTSThumbnail.GetClassID(out classID: TGUID): HResult; begin Result := E_NOTIMPL; end; initialization begin FFileTypeList := TStringList.Create; FFileTypeList.Add(EXT_PSD); TTSThumbnailFactory.Create(ComServer, TTSThumbnail, Class_TSThumbnail, 'TSThumbnail', SDescription, ciMultiInstance, tmApartment); end; end.
// ****************************************************************** // // Program Name : AT Software_DNA Library // Program Version: 1.00 // Platform(s) : OS X, Win32, Win64 // Framework : FireMonkey // // Filenames : AT.DNA.FMX.Dlg.Deactivate.pas/.fmx // File Version : 1.20 // Date Created : 04-MAY-2016 // Author : Matthew S. Vesperman // // Description: // // Deactivate dialog for Software_DNA - FireMonkey version for // cross-platform. // // Revision History: // // v1.00 : Initial version // v1.10 : 31-MAY-2016 // + text field trimming // + password field max length (16) // + password field validity check // v1.20 : 29-JUN-2016 // * Implemented resource strings // // ****************************************************************** // // COPYRIGHT © 2015 - PRESENT Angelic Technology // ALL RIGHTS RESERVED WORLDWIDE // // ****************************************************************** unit AT.DNA.FMX.Dlg.Deactivate; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, AT.DNA.FMX.Dlg.Base, FMX.Edit, System.ImageList, FMX.ImgList, FMX.Objects, FMX.Layouts, FMX.Controls.Presentation; type /// <summary> /// Deactivation dialog for Software_DNA. /// </summary> TDNADeactivateDlg = class(TDNABaseDlg) btnPwdClear: TClearEditButton; btnPwdShow: TPasswordEditButton; lblPassword: TLabel; txtPassword: TEdit; strict private /// <summary> /// Stores the value of the ActivationCode property. /// </summary> FActivationCode: String; /// <summary> /// Password property getter. /// </summary> function GetPassword: String; /// <summary> /// ActivationCode property setter. /// </summary> procedure SetActivationCode(const Value: String); /// <summary> /// Password property setter. /// </summary> procedure SetPassword(const Value: String); strict protected procedure InitControls; override; procedure InitFields; override; function ValidateFields: Boolean; override; /// <summary> /// Retrieves the activation code from the license file. /// </summary> function _GetActivationCode: string; published /// <summary> /// Sets/Gets the activation code for the dialog box. /// </summary> property ActivationCode: String read FActivationCode write SetActivationCode; /// <summary> /// Sets/Gets the password for the dialog box. /// </summary> property Password: String read GetPassword write SetPassword; end; var DNADeactivateDlg: TDNADeactivateDlg; implementation {$R *.fmx} uses AT.XPlatform.Internet, AT.SoftwareDNA.XPlatform, AT.SoftwareDNA.Types, AT.DNA.ResourceStrings; function TDNADeactivateDlg.GetPassword: String; begin Result := txtPassword.Text.Trim; //Return the password field... end; procedure TDNADeactivateDlg.InitControls; begin inherited InitControls; //call inherited... //Set OK button caption to 'Deactivate'... btnOK.Text := rstrDeactivate; txtPassword.SetFocus; //Set focus to the password field... end; procedure TDNADeactivateDlg.InitFields; begin inherited InitFields; //call inherited... //Attempt to get the activation code from the license file... ActivationCode := _GetActivationCode; //Set password field to empty string... Password := EmptyStr; end; procedure TDNADeactivateDlg.SetActivationCode(const Value: String); begin //Store activation code... FActivationCode := Value.Trim; //Set dialog caption to include activation code... Self.Caption := Format(rstrDActivateCapFmt, [FActivationCode]); end; procedure TDNADeactivateDlg.SetPassword(const Value: String); begin txtPassword.Text := Value.Trim; //Set password field... end; function TDNADeactivateDlg.ValidateFields: Boolean; var APwd: String; begin //Check for empty password field... APwd := txtPassword.Text.Trim; if (APwd.IsEmpty) then begin //Password is blank, inform user... MessageDlg(rstrValPwdEmpty, TMsgDlgType.mtError, [TMsgDlgBtn.mbOK], 0, TMsgDlgBtn.mbOK); txtPassword.SetFocus; //Set focus to password field... Exit(False); //Validation failure... end; Result := inherited ValidateFields; //Call inherited... end; function TDNADeactivateDlg._GetActivationCode: string; var Err: Integer; sResult: String; begin //Try and get activation code from license file... if (NOT DNAParam(TDNAParams.parmActivationCode, sResult, Err)) then sResult := EmptyStr; //Couldn't retrieve, use empty string... Result := sResult; //Return result... end; end.
{ Description: vPlot driver class. Copyright (C) 2017-2019 Melchiorre Caruso <melchiorrecaruso@gmail.com> This source is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. A copy of the GNU General Public License is available on the World Wide Web at <http://www.gnu.org/copyleft/gpl.html>. You can also obtain it by writing to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit vpdriver; {$mode objfpc} interface uses classes, math, sysutils, {$ifdef cpuarm} pca9685, wiringpi, {$endif} vpmath, vpsetting; type tvpdriver = class private fxcount: longint; fycount: longint; fzcount: longint; fxdelay: longint; fydelay: longint; fzdelay: longint; fxoff: boolean; fyoff: boolean; fzoff: boolean; procedure setxcount(value: longint); procedure setycount(value: longint); procedure setzcount(value: longint); public constructor create; destructor destroy; override; procedure init(axcount, aycount: longint); procedure move(axcount, aycount: longint); published property xcount: longint read fxcount write setxcount; property ycount: longint read fycount write setycount; property zcount: longint read fzcount write setzcount; property xdelay: longint read fxdelay write fxdelay; property ydelay: longint read fydelay write fydelay; property zdelay: longint read fzdelay write fzdelay; property xoff: boolean read fxoff write fxoff; property yoff: boolean read fyoff write fyoff; property zoff: boolean read fzoff write fzoff; end; var driver: tvpdriver = nil; driver_resolution: vpfloat; implementation {$ifdef cpuarm} const vbr_on = P7; motx_on = P37; moty_on = P37; motx_step = P38; motx_dir = P40; moty_step = P29; moty_dir = P31; motz_freq = 50; const drivermatrix : array [0..10, 0..18] of longint = ( (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), // 0 (0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0), // 1 (0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0), // 2 (0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0), // 3 (1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1), // 4 (1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1), // 5 (0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0), // 6 (1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1), // 7 (1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1), // 8 (0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0), // 9 (1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1)); // 10 {$endif} constructor tvpdriver.create; begin inherited create; fxcount := setting.m0min; fycount := setting.m1min; fzcount := setting.mzmin; fxdelay := setting.m0delay; fydelay := setting.m1delay; fzdelay := setting.mzdelay; fxoff := false; fyoff := false; fzoff := false; {$ifdef cpuarm} // setup wiringpi library wiringpisetup; // setup pca9685 library pca9685setup(PCA9685_PIN_BASE, PCA9685_ADDRESS, motz_freq); // enable sw420 vibration sensor pinmode (vbr_on, INPUT); // enable motors pinmode(motx_on, OUTPUT); digitalwrite(motx_on, LOW); // init step motor0 pinmode(motx_dir, OUTPUT); pinmode(motx_step, OUTPUT); digitalwrite(motx_dir, LOW); digitalwrite(motx_step, LOW); // init step motor1 pinmode(moty_dir, OUTPUT); pinmode(moty_step, OUTPUT); digitalwrite(moty_dir, LOW); digitalwrite(moty_step, LOW); {$endif} setzcount(setting.mzmax); // init driver resolution driver_resolution := ((setting.m0ratio+setting.m1ratio)/2)*6; end; destructor tvpdriver.destroy; begin inherited destroy; end; procedure tvpdriver.init(axcount, aycount: longint); begin fxcount := axcount; fycount := aycount; end; procedure tvpdriver.move(axcount, aycount: longint); {$ifdef cpuarm} var i: longint; dx, ddx: longint; dy, ddy: longint; {$endif} begin {$ifdef cpuarm} dx := axcount - fxcount; if setting.m0dir = 0 then begin if dx < 0 then digitalwrite(motx_dir, LOW) else digitalwrite(motx_dir, HIGH); end else begin if dx < 0 then digitalwrite(motx_dir, HIGH) else digitalwrite(motx_dir, LOW); end; dy := aycount - fycount; if setting.m1dir = 0 then begin; if dy < 0 then digitalwrite(moty_dir, LOW) else digitalwrite(moty_dir, HIGH); end else begin if dy < 0 then digitalwrite(moty_dir, HIGH) else digitalwrite(moty_dir, LOW); end; // detect vibrations if fzcount = setting.mzmin then begin if (digitalread(vbr_on) > 0) then begin fxdelay := fxdelay+setting.m0inc; fydelay := fydelay+setting.m0inc; end else begin fxdelay := fxdelay-setting.m0dec; fydelay := fydelay-setting.m0dec; end; fxdelay := max(setting.m0min, min(fxdelay, setting.m0max)); fydelay := max(setting.m1min, min(fydelay, setting.m1max)); end else begin fxdelay := setting.m0min; fydelay := setting.m1min; end; dx := abs(dx); dy := abs(dy); while (dx > 0) or (dy > 0) do begin ddx := min(10, dx); ddy := min(10, dy); for i := 0 to 18 do begin if drivermatrix[ddx, i] = 1 then begin digitalwrite(motx_step, HIGH); delaymicroseconds(fxdelay); digitalwrite(motx_step, LOW); delaymicroseconds(fxdelay); end; if drivermatrix[ddy, i] = 1 then begin digitalwrite(moty_step, HIGH); delaymicroseconds(fydelay); digitalwrite(moty_step, LOW); delaymicroseconds(fydelay); end; end; dec(dx, ddx); dec(dy, ddy); end; {$endif} fxcount := axcount; fycount := aycount; end; procedure tvpdriver.setxcount(value: longint); begin move(value, fycount); end; procedure tvpdriver.setycount(value: longint); begin move(fxcount, value); end; procedure tvpdriver.setzcount(value: longint); begin if fzoff then exit; {$ifdef cpuarm} if fzcount > value then begin if setting.mzdir = 0 then delaymicroseconds($f*fzdelay); while fzcount > value do begin pwmwrite(PCA9685_PIN_BASE + 0, calcticks(fzcount/100, motz_freq)); delaymicroseconds(fzdelay); dec(fzcount, setting.mzinc); end; end else if fzcount < value then begin if setting.mzdir = 1 then delaymicroseconds($f*fzdelay); while fzcount < value do begin pwmwrite(PCA9685_PIN_BASE + 0, calcticks(fzcount/100, motz_freq)); delaymicroseconds(fzdelay); inc(fzcount, setting.mzinc); end; end; {$endif} fzcount := value; end; end.
unit ViewModel.Main; interface uses Model.Main.Types, ViewModel.Main.Types; function createViewModelMain (const aModel: IModelMain): IViewModelMain; implementation uses System.Classes, Core.Database.Entities, System.SysUtils, System.Generics.Collections, Aurelius.Types.Blob, FMX.Graphics, ViewModel.Types, Core.Helpers; type TViewModelMain = class (TInterfacedObject, IViewModelMain) private fCustomerList: TStringList; fComponentsRecord: TComponentsRecord; fModel: IModelMain; procedure setMainComponents; function getCustomerList: TStringList; function getComponentsRecord: TComponentsRecord; procedure getCustomer (const aID: Integer; var aCustomer: TCustomerTransientRecord); procedure deleteCustomer (const aID: Integer); public constructor Create (const aModel: IModelMain); destructor Destroy; override; end; { TViewModelMain } constructor TViewModelMain.Create(const aModel: IModelMain); begin inherited Create; if Assigned(aModel) then fModel:=aModel else raise Exception.Create('The Main Model is nil in Main ViewModel'); fCustomerList:=TStringList.Create; setMainComponents; fComponentsRecord.TotalLabel:=NoCustomers; end; procedure TViewModelMain.deleteCustomer(const aID: Integer); var tmpCustomer: TCustomers; begin try try fModel.getCustomer(aID, tmpCustomer); except raise; end; if Assigned(tmpCustomer) then fModel.deleteCustomer(tmpCustomer); except raise; end; end; destructor TViewModelMain.Destroy; begin fCustomerList.Free; inherited; end; procedure TViewModelMain.setMainComponents; begin fComponentsRecord.AddButtonEnabled := True; fComponentsRecord.DeleteButtonEnabled := False; fComponentsRecord.EditButtonEnabled := false; fComponentsRecord.PanelCancelButtonVisible := False; fComponentsRecord.PanelEdit1Text := ''; fComponentsRecord.PanelEdit1Visible := false; fComponentsRecord.PanelEdit2Text := ''; fComponentsRecord.PanelEdit2Visible := False; fComponentsRecord.PanelLabel1Text := ''; fComponentsRecord.PanelLabel1Visible := true; fComponentsRecord.PanelLabel2Text := ''; fComponentsRecord.PanelLabel2Visible := True; fComponentsRecord.PanelLoadButtonVisile := False; fComponentsRecord.PanelSaveButtonVisible := False; end; function TViewModelMain.getComponentsRecord: TComponentsRecord; begin Result:=fComponentsRecord; end; procedure TViewModelMain.getCustomer (const aID: Integer; var aCustomer: TCustomerTransientRecord); var tmpCustomer: TCustomers; begin if not aID>0 then Exit; try fModel.getCustomer(aID, tmpCustomer); aCustomer.PhotoBitmap:=nil; if Assigned(tmpCustomer) then begin if tmpCustomer.Firstname.HasValue then aCustomer.FirstName:=Trim(tmpCustomer.Firstname.Value) else aCustomer.FirstName:=''; if tmpCustomer.Lastname.HasValue then aCustomer.LastName:=Trim(tmpCustomer.Lastname.Value) else aCustomer.LastName:=''; if not tmpCustomer.Photo.IsNull then begin aCustomer.PhotoBitmap:=TBitmap.Create; Blob2bitmap(tmpCustomer.Photo, aCustomer.PhotoBitmap); end; fComponentsRecord.EditButtonEnabled:=true; fComponentsRecord.DeleteButtonEnabled:=true; end else begin aCustomer.FirstName:=''; aCustomer.LastName:=''; fComponentsRecord.EditButtonEnabled:=false; fComponentsRecord.DeleteButtonEnabled:=false; end; fComponentsRecord.PanelLabel1Text:=aCustomer.FirstName; fComponentsRecord.PanelLabel2Text:=aCustomer.LastName; except raise; end; end; function TViewModelMain.getCustomerList: TStringList; var tmpList: TObjectList<TCustomers>; tmpCustomer: TCustomers; tmpStr: string; begin fCustomerList.Clear; try fModel.getCustomerList(tmpList); if (not Assigned(tmpList)) or (tmpList.Count=0) then begin fComponentsRecord.TotalLabel:=NoCustomers; setMainComponents; tmpList.Free; end else begin for tmpCustomer in tmpList do begin tmpStr:=''; if tmpCustomer.Lastname.HasValue then tmpStr:=trim(tmpCustomer.Lastname.Value)+', '; if tmpCustomer.Firstname.HasValue then tmpStr:=tmpStr+trim(tmpCustomer.Firstname.Value); tmpStr:=tmpStr+'|'+tmpCustomer.Id.ToString; fCustomerList.Add(tmpStr); fComponentsRecord.TotalLabel:=Format(NumOfCustomers,[tmpList.Count.ToString]); fComponentsRecord.EditButtonEnabled:=true; fComponentsRecord.DeleteButtonEnabled:=true; end; end; Result:=fCustomerList; except raise; end; end; function createViewModelMain (const aModel: IModelMain): IViewModelMain; begin Result:=TViewModelMain.Create(aModel); end; end.
unit UMetadata; {$mode objfpc}{$H+} interface uses Classes, SysUtils, IBConnection, sqldb, DB, FileUtil, Forms, Controls, Graphics, Dialogs, DBCtrls, DBGrids, StdCtrls, Menus,URecords; type TMetadata = class Tables: array of TTableInformation; procedure AddTable(FName, FCaption: string); procedure AddTableInformation(FName, FCaption: string; FColumWidth: integer; RefName, REfCaption: string); end; var Metadata: TMetadata; implementation procedure TMetadata.AddTable(FName, FCaption: string); begin SetLength(Tables, Length(Tables) + 1); with Tables[High(Tables)] do begin Name := FName; Caption := FCaption; end; end; procedure TMetadata.AddTableInformation(FName, FCaption: string; FColumWidth: integer; RefName, REfCaption: string); begin with Tables[High(Tables)] do begin SetLength(Information, Length(Information) + 1); with Information[High(Information)] do begin Name := FName; Caption := FCaption; ColumWidth := FColumWidth; Reference.FieldName := REfCaption; Reference.TableName := RefName; end; end; end; initialization Metadata := TMetadata.Create; {Metadata.AddTable('Students','Студенты'); Metadata.AddTableInformation('id','ID',25,'',''); Metadata.AddTableInformation('LastName','Фамилия',120,'',''); Metadata.AddTableInformation('FirstName','Имя',120,'',''); Metadata.AddTableInformation('MiddleName','Отчество',120,'',''); Metadata.AddTableInformation('DateOfBirth','Дата Рождения',90,'',''); Metadata.AddTableInformation('Term','Курс',35,'',''); Metadata.AddTableInformation('GroupNumber','Группа',60,'',''); Metadata.AddTableInformation('GradePointAverage','Средний балл',85,'',''); Metadata.AddTableInformation('ExamsFinished','Закрытая сессия',100,'',''); } Metadata.AddTable('Groups', 'Группы'); Metadata.AddTableInformation('id', 'ID', 25, '', ''); Metadata.AddTableInformation('Name', 'Группа', 60, '', ''); Metadata.AddTable('Lessons', 'Предметы'); Metadata.AddTableInformation('id', 'ID', 25, '', ''); Metadata.AddTableInformation('Name', 'Название', 300, '', ''); Metadata.AddTable('Teachers', 'Преподаватели'); Metadata.AddTableInformation('id', 'ID', 25, '', ''); Metadata.AddTableInformation('Last_Name', 'Фамилия', 120, '', ''); Metadata.AddTableInformation('First_Name', 'Имя', 120, '', ''); Metadata.AddTableInformation('Middle_Name', 'Отчество', 120, '', ''); Metadata.AddTable('Weekdays', 'Дни недели'); Metadata.AddTableInformation('id', 'ID', 25, '', ''); Metadata.AddTableInformation('Name', 'День', 90, '', ''); Metadata.AddTable('Lessons_Types', 'Типы Занятий'); Metadata.AddTableInformation('id', 'ID', 25, '', ''); Metadata.AddTableInformation('Name', 'Тип', 25, '', ''); Metadata.AddTable('Lessons_Times', 'Время Занятий'); Metadata.AddTableInformation('id', 'ID', 25, '', ''); Metadata.AddTableInformation('begin_', 'Начало', 50, '', ''); Metadata.AddTableInformation('end_', 'Конец', 50, '', ''); Metadata.AddTable('Classrooms', 'Аудитории'); Metadata.AddTableInformation('id', 'ID', 25, '', ''); Metadata.AddTableInformation('Name', 'Аудитория', 69, '', ''); Metadata.AddTable('Timetable', 'Расписание'); Metadata.AddTableInformation('id', 'ID', 25, '', ''); Metadata.AddTableInformation('lesson_id', 'Название', 300, 'Lessons', 'id'); Metadata.AddTableInformation('lesson_type_id', 'Тип', 100, 'Lessons_Types', 'id'); Metadata.AddTableInformation('teacher_id', 'Преподаватель', 120, 'Teachers', 'id'); Metadata.AddTableInformation('group_id', 'Группа', 60, 'Groups', 'id'); Metadata.AddTableInformation('classroom_id', 'Аудитория', 40, 'Classrooms', 'id'); Metadata.AddTableInformation('weekday_id', 'День Недели', 100, 'Weekdays', 'id'); Metadata.AddTableInformation('lesson_time_id', 'Время', 70, 'Lessons_Times', 'id'); Metadata.AddTableInformation('start_date', 'Актуально с', 100, '', ''); Metadata.AddTableInformation('end_date', 'Актуально до', 100, '', ''); end.
unit DBTestCase; interface uses TestCaseExtension, DatabaseOperation, DatabaseConnection, DataSet, DatabaseConnectionType, DatabaseConnectionFactory, DatabaseConfig; type TDBTestCase = class(TTestCaseExtension) private FConnection: IDatabaseConnection; protected procedure SetUp; override; procedure TearDown; override; function getConnection: IDatabaseConnection;virtual; function setUpOperation: IDatabaseOperation;virtual; function tearDownOperation: IDatabaseOperation;virtual; function getDataSet: IDataSet;virtual;abstract; function getDatabaseConfig: IDatabaseConfig;virtual;abstract; public end; implementation uses NoneOperation; { TDBTestCase } function TDBTestCase.getConnection: IDatabaseConnection; begin if not Assigned(FConnection) then FConnection := ConnectionFactory.newConnection(getDatabaseConfig); Result := FConnection; end; procedure TDBTestCase.SetUp; begin inherited; FConnection := getConnection; if Assigned(FConnection) then begin FConnection.StartTransaction; end; setUpOperation.execute(FConnection, getDataSet); end; function TDBTestCase.setUpOperation: IDatabaseOperation; begin Result := TDatabaseOperation.CLEAN_INSERT; end; procedure TDBTestCase.TearDown; begin tearDownOperation.execute(FConnection, getDataSet); if Assigned(FConnection) then begin FConnection.RollbackTransaction; end; inherited; end; function TDBTestCase.tearDownOperation: IDatabaseOperation; begin Result := TDatabaseOperation.DELETE; end; end.
unit uBase4096; {$ZEROBASEDSTRINGS ON} interface uses System.SysUtils, uBase, uUtils; type IBase4096 = interface ['{00E62467-D513-474C-8350-76A820B99A1B}'] function Encode(data: TArray<Byte>): String; function Decode(const data: String): TArray<Byte>; function EncodeString(const data: String): String; function DecodeToString(const data: String): String; function GetBitsPerChars: Double; property BitsPerChars: Double read GetBitsPerChars; function GetCharsCount: UInt32; property CharsCount: UInt32 read GetCharsCount; function GetBlockBitsCount: Integer; property BlockBitsCount: Integer read GetBlockBitsCount; function GetBlockCharsCount: Integer; property BlockCharsCount: Integer read GetBlockCharsCount; function GetAlphabet: String; property Alphabet: String read GetAlphabet; function GetSpecial: Char; property Special: Char read GetSpecial; function GetHaveSpecial: Boolean; property HaveSpecial: Boolean read GetHaveSpecial; function GetEncoding: TEncoding; procedure SetEncoding(value: TEncoding); property Encoding: TEncoding read GetEncoding write SetEncoding; end; TBase4096 = class(TBase, IBase4096) public const DefaultAlphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' + 'ªµºÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõ' + 'öøùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬĭĮįİıIJijĴĵĶķĸĹĺĻļ' + 'ĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍ' + 'ƎƏƐƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰ' + 'DZDzdzǴǵǶǷǸǹǺǻǼǽǾǿȀȁȂȃȄȅȆȇȈȉȊȋȌȍȎȏȐȑȒȓȔȕȖȗȘșȚțȜȝȞȟȠȡȢȣȤȥȦȧȨȩȪȫȬȭȮȯȰȱȲȳȴȵȶȸȹȺȻȼȽȾȿɀ' + 'ɁɂɃɄɅɆɇɈɉɊɋɌɍɎɏɐɑɒɓɔɕɖɗɘəɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓ' + 'ʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼʽʾʿˀˁˆˇˈˉˊˋˌˍˎˏːˑˠˡˢˣˤˬˮʹͺ' + 'ͻͼͽΆΈΉΊΌΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώϐϑϒϓϔϕϖϗϘϙϚϛϜϝϞϟϠϡϢϣϤϥϦ' + 'ϧϨϩϪϫϬϭϮϯϰϱϲϳϴϵϷϸϹϺϻϼϽϾϿЀЁЂЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюяѐёђ' + 'ѓєѕіїјљњћќѝўџѠѡѢѣѤѥѦѧѨѩѪѫѬѭѮѯѰѱѲѳѴѵѶѷѸѹѺѻѼѽѾѿҀҁҊҋҌҍҎҏҐґҒғҔҕҖҗҘҙҚқҜҝҞҟҠҡҢңҤҥҦҧҨҩҪҫҬҭҮүҰұҲҳҴҵҶҷҸҹҺһҼҽҾҿӀӁӂӃӄӅӆӇӈӉӊ' + 'ӋӌӍӎӏӐӑӒӓӔӕӖӗӘәӚӛӜӝӞӟӠӡӢӣӤӥӦӧӨөӪӫӬӭӮӯӰӱӲӳӴӵӶӷӸӹӺӻӼӽӾӿԀԁԂԃԄԅԆԇԈԉԊԋԌԍԎԏԐԑԒԓԚԛԜԝԱԲԳԴԵԶԷԸԹԺԻԼԽԾԿՀՁՂՃՄՅՆՇՈՉՊՋՌՍՎ' + 'ՏՐՑՒՓՔՙաբգդեզէըթժիլխծկհձղճմյնշոչպջռսվտրցւփքօֆևאבגדהוזחטיךכלםמןנסעףפץצקרשתװױײءآأؤإئابةتثجحخدذرزسشصضطظعغػؼؽؾؿـفقكلمنهوىي٠١٢٣٤٥٦٧٨' + '٩ٮٯٱٲٳٴٵٶٷٸٹٺٻټٽپٿڀځڂڃڄڅچڇڈډڊڋڌڍڎڏڐڑڒړڔڕږڗژڙښڛڜڝڞڟڠڡڢڣڤڥڦڧڨکڪګڬڭڮگڰڱڲڳڴڵڶڷڸڹںڻڼڽھڿۀہۂۃۄۅۆۇۈۉۊۋیۍێۏېۑےۓەۥۦۮۯ۰۱۲۳۴۵۶۷۸۹ۺۻۼۿܐܒܓܔܕܖܗܘܙܚܛ' + 'ܜܝܞܟܠܡܢܣܤܥܦܧܨܩܪܫܬܭܮܯݍݎݏݐݑݒݓݔݕݖݗݘݙݚݛݜݝݞݟݠݡݢݣݤݥݦݧݨݩݪݫݬݭݮݯݰݱݲݳݴݵݶݷݸݹݺݻݼݽݾݿހށނރބޅކއވމފދތލގޏސޑޒޓޔޕޖޗޘޙޚޛޜޝޞޟޠޡޢޣޤޥޱ߀߁߂߃߄߅߆߇߈߉ߊߋߌߍߎߏߐߑߒߓߔߕߖߗߘߙߚߛߜߝߞߟߠߡߢߣߤߥ' + 'ߦߧߨߩߪߴߵߺऄअआइईउऊऋऌऍऎएऐऑऒओऔकखगघङचछजझञटठडढणतथदधनऩपफबभमयरऱलळऴवशषसहऽॐक़ख़ग़ज़ड़ढ़फ़य़ॠॡ०१२३४५६७८९ॱॲॻॼॽॾॿঅআইঈউঊঋঌএঐও' + 'ঔকখগঘঙচছজঝঞটঠডঢণতথদধনপফবভমযরলশষসহঽৎড়ঢ়য়ৠৡ০১২৩৪৫৬৭৮৯ৰৱਅਆਇਈਉਊਏਐਓਔਕਖਗਘਙਚਛਜਝਞਟਠਡਢਣਤਥਦਧਨਪਫਬਭਮਯਰਲਲ਼ਵਸ਼ਸਹਖ਼ਗ਼ਜ਼ੜਫ਼' + '੦੧੨੩੪੫੬੭੮੯ੲੳੴઅઆઇઈઉઊઋઌઍએઐઑઓઔકખગઘઙચછજઝઞટઠડઢણતથદધનપફબભમયરલળવશષસહઽૐૠૡ૦૧૨૩૪૫' + '૬૭૮૯ଅଆଇଈଉଊଋଌଏଐଓଔକଖଗଘଙଚଛଜଝଞଟଠଡଢଣତଥଦଧନପଫବଭମଯରଲଳଵଶଷସହଽଡ଼ଢ଼ୟୠୡ୦୧୨୩୪୫୬୭୮୯ୱஃஅஆஇஈஉஊஎஏஐஒஓஔகஙசஜஞட' + 'ணதநனபமயரறலளழவஶஷஸஹௐ௦௧௨௩௪௫௬௭௮௯అఆఇఈఉఊఋఌఎఏఐఒఓఔకఖగఘఙచఛజఝఞటఠడఢణతథదధనపఫబభమయరఱల' + 'ళవశషసహఽౘౙౠౡ౦౧౨౩౪౫౬౭౮౯ಅಆಇಈಉಊಋಌಎಏಐಒಓಔಕಖಗಘಙಚಛಜಝಞಟಠಡಢಣತಥದಧನಪಫಬಭಮಯರಱಲಳವಶಷಸಹಽೞೠೡ೦೧೨೩' + '೪೫೬೭೮೯അആഇഈഉഊഋഌഎഏഐഒഓഔകഖഗഘങചഛജഝഞടഠഡഢണതഥദധനപഫബഭമയരറലളഴവശഷസഹഽൠൡ൦൧൨൩൪൫൬൭൮൯ൺൻർൽൾൿඅආඇඈඉඊ' + 'උඌඍඎඏඐඑඒඓඔඕඖකඛගඝඞඟචඡජඣඤඥඦටඨඩඪණඬතථදධනඳපඵබභමඹයරලවශෂසහළෆ' + 'กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะาำเแโใไๅๆ๐๑๒๓๔๕๖๗๘๙ກຂຄງຈຊຍດຕຖທນບປຜຝພຟມຢຣລວສຫອຮຯະາຳຽເແໂໃໄໆ໐໑' + '໒໓໔໕໖໗໘໙ໜໝༀ༠༡༢༣༤༥༦༧༨༩ཀཁགགྷངཅཆཇཉཊཋཌཌྷཎཏཐདདྷནཔཕབབྷམཙཚཛཛྷཝཞཟའཡརལཤཥསཧཨཀྵཪྈྉྊྋჺჼ' + 'ᄀᄁᄂᄃᄄᄅᄆᄇᄈᄉᄊᄋᄌᄍᄎᄏᄐᄑᄒᄓᄔᄕᄖᄗᄘᄙᄚᄛᄜᄝᄞᄟᄠᄡᄢᄣᄤᄥᄦᄧᄨᄩᄪᄫᄬ' + 'ᄭᄮᄯᄰᄱᄲᄳᄴᄵᄶᄷᄸᄹᄺᄻᄼᄽᄾᄿᅀᅁᅂᅃᅄᅅᅆᅇᅈᅉᅊᅋᅌᅍᅎᅏᅐᅑᅒᅓᅔᅕᅖᅗᅘ' + 'ᅙᅟᅠᅡᅢᅣᅤᅥᅦᅧᅨᅩᅪᅫᅬᅭᅮᅯᅰᅱᅲᅳᅴᅵᅶᅷᅸᅹᅺᅻᅼᅽᅾᅿᆀᆁᆂᆃᆄᆅᆆᆇᆈᆉᆊᆋᆌᆍᆎᆏᆐᆑᆒᆓᆔᆕᆖᆗᆘᆙᆚᆛᆜᆝ' + 'ᆞᆟᆠᆡᆢᆨᆩᆪᆫᆬᆭᆮᆯᆰᆱᆲᆳᆴᆵᆶᆷᆸᆹᆺᆻᆼᆽᆾᆿᇀᇁᇂᇃᇄᇅᇆᇇᇈᇉᇊᇋᇌᇍᇎᇏᇐᇑᇒᇓᇔᇕᇖᇗᇘᇙᇚᇛᇜᇝᇞᇟᇠᇡᇢᇣᇤᇥᇦᇧᇨᇩᇪᇫᇬᇭᇮᇯᇰᇱᇲᇳᇴᇵᇶᇷᇸᇹ' + 'ሀሁሂሃሄህሆሇለሉሊላሌልሎሏሐሑሒሓሔሕሖሗመሙሚማሜምሞሟሠሡሢሣሤሥሦሧረሩሪራሬርሮሯሰሱሲሳሴስሶሷሸሹሺሻሼሽሾሿቀቁቂቃቄቅቆቇቈቊቋቌቍቐቑቒቓቔቕቖቘቚቛቜቝ' + 'በቡቢባቤብቦቧቨቩቪቫቬቭቮቯተቱቲታቴትቶቷቸቹቺቻቼችቾቿኀኁኂኃኄኅኆኇኈኊኋኌኍነኑኒናኔንኖኗኘኙኚኛኜኝኞኟአኡኢኣኤእኦኧከኩኪካኬክኮኯኰኲኳኴኵኸኹኺኻኼኽኾዀዂዃዄዅወዉ' + 'ዊዋዌውዎዏዐዑዒዓዔዕዖዘዙዚዛዜዝዞዟዠዡዢዣዤዥዦዧየዩዪያዬይዮዯደዱዲዳዴድዶዷዸዹዺዻዼዽዾዿጀጁጂጃጄጅጆጇገጉጊጋጌግጎጏጐጒጓጔጕጘጙጚጛጜጝጞጟ' + 'ጠጡጢጣጤጥጦጧጨጩጪጫጬጭጮጯጰጱጲጳጴጵጶጷጸጹጺጻጼጽጾጿፀፁፂፃፄፅፆፇፈፉፊፋፌፍፎፏፐፑፒፓፔፕፖፗፘፙፚᎀᎁᎂᎃᎄᎅᎆᎇᎈᎉᎊᎋᎌᎍᎎᎏᎠᎡᎢ' + 'ᎣᎤᎥᎦᎧᎨᎩᎪᎫᎬᎭᎮᎯᎰᎱᎲᎳᎴᎵᎶᎷᎸᎹᎺᎻᎼᎽᎾᎿᏀᏁᏂᏃᏄᏅᏆᏇᏈᏉᏊᏋᏌᏍᏎᏏᏐᏑᏒᏓᏔᏕᏖᏗᏘᏙᏚᏛᏜᏝᏞᏟᏠᏡᏢᏣᏤᏥᏦᏧᏨᏩᏪᏫᏬᏭᏮᏯᏰᏱᏲᏳᏴ' + 'ᐁᐂᐃᐄᐅᐆᐇᐈᐉᐊᐋᐌᐍᐎᐏᐐᐑᐒᐓᐔᐕᐖᐗᐘᐙᐚᐛᐜᐝᐞᐟᐠᐡᐢᐣᐤᐥᐦᐧᐨᐩᐪᐫᐬᐭᐮᐯᐰᐱᐲᐳᐴᐵᐶᐷᐸᐹᐺᐻᐼᐽᐾᐿᑀᑁᑂᑃᑄᑅᑆᑇᑈᑉᑊᑋᑌᑍᑎᑏᑐᑑᑒᑓᑔᑕᑖᑗᑘᑙᑚᑛᑜᑝᑞᑟᑠᑡᑢᑣᑤᑥᑦᑧᑨᑩᑪᑫᑬᑭᑮᑯᑰᑱᑲᑳᑴᑵᑶᑷᑸᑹ' + 'ᑺᑻᑼᑽᑾᑿᒀᒁᒂᒃᒄᒅᒆᒇᒈᒉᒊᒋᒌᒍᒎᒏᒐᒑᒒᒓᒔᒕᒖᒗᒘᒙᒚᒛᒜᒝᒞᒟᒠᒡᒢᒣᒤᒥᒦᒧᒨᒩᒪᒫᒬᒭᒮᒯᒰᒱᒲᒳᒴᒵᒶᒷᒸᒹᒺᒻᒼᒽᒾᒿᓀᓁᓂᓃᓄᓅᓆᓇᓈᓉᓊᓋᓌᓍᓎᓏ' + 'ᓐᓑᓒᓓᓔᓕᓖᓗᓘᓙᓚᓛᓜᓝᓞᓟᓠᓡᓢᓣᓤᓥᓦᓧᓨᓩᓪᓫᓬᓭᓮᓯᓰᓱᓲᓳᓴᓵᓶᓷᓸᓹᓺᓻᓼᓽᓾᓿᔀᔁᔂᔃᔄᔅᔆᔇᔈᔉᔊᔋᔌᔍᔎᔏᔐᔑᔒᔓᔔᔕᔖᔗᔘᔙᔚᔛᔜᔝᔞᔟᔠᔡᔢᔣᔤᔥᔦᔧᔨᔩᔪᔫᔬᔭᔮᔯᔰᔱᔲᔳᔴᔵᔶᔷᔸᔹᔺᔻᔼᔽᔾᔿᕀᕁᕂᕃᕄᕅᕆᕇᕈᕉᕊᕋᕌᕍᕎᕏ' + 'ᕐᕑᕒᕓᕔᕕᕖᕗᕘᕙᕚᕛᕜᕝᕞᕟᕠᕡᕢᕣᕤᕥᕦᕧᕨᕩᕪᕫᕬᕭᕮᕯᕰᕱᕲᕳᕴᕵᕶᕷᕸᕹᕺᕻᕼᕽᕾᕿᖀᖁᖂᖃᖄᖅᖆᖇᖈᖉᖊᖋᖌᖍᖎᖏᖐᖑᖒᖓᖔᖕᖖᖗᖘᖙᖚᖛᖜᖝᖞᖟᖠᖡᖢᖣᖤᖥᖦᖧᖨᖩᖪᖫᖬᖭᖮᖯᖰ' + 'ᖱᖲᖳᖴᖵᖶᖷᖸᖹᖺᖻᖼᖽᖾᖿᗀᗁᗂᗃᗄᗅᗆᗇᗈᗉᗊᗋᗌᗍᗎᗏᗐᗑᗒᗓᗔᗕᗖᗗᗘᗙᗚᗛᗜᗝᗞᗟᗠᗡᗢᗣᗤᗥᗦᗧᗨᗩᗪᗫᗬᗭᗮᗯᗰᗱᗲᗳᗴᗵᗶᗷᗸᗹᗺᗻᗼᗽᗾᗿᘀᘁᘂᘃᘄᘅᘆᘇᘈᘉᘊᘋᘌᘍᘎᘏᘐᘑᘒᘓᘔᘕᘖᘗᘘᘙᘚᘛᘜᘝᘞᘟᘠᘡᘢᘣᘤᘥᘦᘧᘨᘩᘪᘫᘬᘭᘮᘯᘰᘱᘲᘳᘴᘵᘶᘷᘸᘹ' + 'ᘺᘻᘼᘽᘾᘿᙀᙁᙂᙃᙄᙅᙆᙇᙈᙉᙊᙋᙌᙍᙎᙏᙐᙑᙒᙓᙔᙕᙖᙗᙘᙙᙚᙛᙜᙝᙞᙟᙠᙡᙢᙣᙤᙥᙦᙧᙨᙩᙪᙫᙬᙯᙰᙱᙲᙳᙴᙵᙶᚁᚂᚃᚄᚅᚆᚇᚈᚉᚊᚋᚌᚍᚎᚏᚐᚑᚒᚓᚔᚕᚖᚗᚘᚙᚚᚠᚡᚢᚣᚤᚥᚦᚧᚨᚩᚪᚫᚬᚭᚮᚯᚰᚱᚲᚳᚴᚵᚶᚷᚸᚹᚺᚻᚼᚽᚾᚿᛀᛁᛂᛃᛄᛅᛆᛇᛈᛉᛊᛋᛌᛍᛎᛏᛐᛑᛒᛓᛔᛕᛖᛗᛘᛙᛚᛛᛜᛝᛞᛟᛠᛡᛢᛣᛤᛥᛦ' + 'ᛧᛨᛩᛪកខគឃងចឆជឈញដឋឌឍណតថទធនបផពភមយរលវឝឞសហឡអឣឤឥឦឧឨឩឪឫឬឭឮឯឰឱឲឳៗៜ០១២៣៤៥៦' + '៧៨៩᠐᠑᠒᠓᠔᠕᠖᠗᠘᠙ᠠᠡᠢᠣᠤᠥᠦᠧᠨᠩᠪᠫᠬᠭᠮᠯᠰᠱᠲᠳᠴᠵᠶᠷᠸᠹᠺᠻᠼᠽᠾᠿᡀᡁᡂᡃᡄᡅᡆᡇᡈᡉᡊᡋᡌᡍᡎᡏᡐᡑᡒᡓᡔᡕᡖᡗᡘᡙᡚᡛᡜᡝᡞᡟᡠᡡᡢᡣᡤᡥᡦᡧᡨᡩᡪᡫᡬᡭᡮᡯᡰᡱᡲᡳᡴᡵᡶᡷᢀᢁᢂᢃᢄᢅᢆᢇᢈᢉᢊᢋᢌᢍᢎᢏᢐᢑᢒᢓᢔᢕᢖᢗᢘᢙᢚᢛᢜᢝᢞᢟᢠᢡᢢᢣᢤᢥᢦᢧᢨᥐ' + 'ᥑᥒᥓᥔᥕᥖᥗᥘᥙᥚᥛᥜᥝᥞᥟᥠᥡᥢᥣᥤᥥᥦᥧᥨᥩᥪᥫᥬᥭᥰᥱᥲᥳᥴᦀᦁᦂᦃᦄᦅᦆᦇᦈᦉᦊᦋᦌᦍᦎᦏᦐᦑᦒᦓᦔᦕᦖᦗᦘᦙᦚᦛᦜᦝᦞᦟᦠᦡᦢᦣᦤᦥᦦᦧᦨᦩᧁᧂᧃᧄᧅᧆᧇ᧐᧑᧒᧓᧔᧕᧖᧗᧘᧙ᴀᴁᴂᴃᴄᴅᴆᴇᴈᴉᴊᴋᴌᴍᴎᴏᴐᴑᴒᴓᴔᴕ' + 'ᴖᴗᴘᴙᴚᴛᴜᴝᴞᴟᴠᴡᴢᴣᴤᴥᴦᴧᴨᴩᴪᴫᴬᴭᴮᴯᴰᴱᴲᴳᴴᴵᴶᴷᴸᴹᴺᴻᴼᴽᴾᴿᵀᵁᵂᵃᵄᵅᵆᵇᵈᵉᵊᵋᵌᵍᵎᵏᵐᵑᵒᵓᵔᵕᵖᵗᵘᵙᵚᵛᵜᵝᵞᵟᵠᵡᵢᵣᵤᵥᵦᵧᵨᵩᵪᵫᵬᵭᵮᵯᵰᵱᵲᵳᵴᵵᵶᵷᵸ' + 'ᵹᵺᵻᵼᵽᵾᵿᶀᶁᶂᶃᶄᶅᶆᶇᶈᶉᶊᶋᶌᶍᶎᶏᶐᶑᶒᶓᶔᶕᶖᶗᶘᶙᶚᶛᶜᶝᶞᶟ'; DefaultSpecial = '='; constructor Create(const _Alphabet: String = DefaultAlphabet; _Special: Char = DefaultSpecial; _textEncoding: TEncoding = Nil); function Encode(data: TArray<Byte>): String; override; function Decode(const data: String): TArray<Byte>; override; end; implementation constructor TBase4096.Create(const _Alphabet: String = DefaultAlphabet; _Special: Char = DefaultSpecial; _textEncoding: TEncoding = Nil); begin Inherited Create(4096, _Alphabet, _Special, _textEncoding); FHaveSpecial := True; end; function TBase4096.Encode(data: TArray<Byte>): String; var dataLength, i, x1, x2, x3, length3, tempInt: Integer; tempResult: TStringBuilder; begin if ((data = nil) or (Length(data) = 0)) then begin Exit(''); end; dataLength := Length(data); tempResult := TStringBuilder.Create; try length3 := (dataLength div 3) * 3; i := 0; while i < length3 do begin x1 := data[i]; x2 := data[i + 1]; x3 := data[i + 2]; tempResult.Append(Alphabet[x1 or ((x2 and $0F) shl 8)]); tempResult.Append(Alphabet[(x2 shr 4) or (x3 shl 4)]); inc(i, 3); end; tempInt := (dataLength - length3); case tempInt of 1: begin x1 := data[i]; tempResult.Append(Alphabet[x1]); tempResult.Append(Special, 2); end; 2: begin x1 := data[i]; x2 := data[i + 1]; tempResult.Append(Alphabet[x1 or ((x2 and $0F) shl 8)]); tempResult.Append(Alphabet[x2 shr 4]); tempResult.Append(Special); end; end; result := tempResult.ToString; finally tempResult.Free; end; end; function TBase4096.Decode(const data: String): TArray<Byte>; var lastSpecialInd, tailLength, i, srcInd, x1, x2, length5: Integer; begin if TUtils.isNullOrEmpty(data) then begin SetLength(result, 1); result := Nil; Exit; end; lastSpecialInd := Length(data); while (data[lastSpecialInd - 1] = Special) do begin dec(lastSpecialInd); end; tailLength := Length(data) - lastSpecialInd; SetLength(result, Length(data) div 2 * 3 - tailLength); i := 0; srcInd := 0; length5 := (Length(data) div 2 - 1) * 3; while i < length5 do begin x1 := FInvAlphabet[Ord(data[srcInd])]; inc(srcInd); x2 := FInvAlphabet[Ord(data[srcInd])]; inc(srcInd); result[i] := Byte(x1); result[i + 1] := Byte((x1 shr 8) and $0F or (x2 shl 4)); result[i + 2] := Byte(x2 shr 4); inc(i, 3); end; if (tailLength = 0) then begin x1 := FInvAlphabet[Ord(data[srcInd])]; inc(srcInd); x2 := FInvAlphabet[Ord(data[srcInd])]; inc(srcInd); result[i] := Byte(x1); result[i + 1] := Byte((x1 shr 8) and $0F or (x2 shl 4)); result[i + 2] := Byte(x2 shr 4); end; Case (tailLength) of 2: begin x1 := FInvAlphabet[Ord(data[srcInd])]; result[i] := Byte(x1); end; 1: begin x1 := FInvAlphabet[Ord(data[srcInd])]; inc(srcInd); x2 := FInvAlphabet[Ord(data[srcInd])]; result[i] := Byte(x1); result[i + 1] := Byte((x1 shr 8) and $0F or (x2 shl 4)); end; end; end; end.
unit SaleItemEdit; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxPropertiesStore, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, Vcl.Menus, Vcl.StdCtrls, cxButtons, cxLabel, cxTextEdit, Vcl.ActnList, Vcl.StdActns, ParentForm, dsdDB, dsdAction, cxCurrencyEdit, dsdAddOn, dxSkinsCore, dxSkinsDefaultPainters, dsdGuides, cxMaskEdit, cxButtonEdit, dxSkinBlack, dxSkinBlue, dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy, dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian, dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMoneyTwins, dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinOffice2010Black, dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus, dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008, dxSkinTheAsphaltWorld, dxSkinValentine, dxSkinVS2010, dxSkinWhiteprint, dxSkinXmas2008Blue, cxCheckBox; type TSaleItemEditForm = class(TParentForm) cxButton1: TcxButton; cxButton2: TcxButton; ActionList: TActionList; spInsertUpdate: TdsdStoredProc; FormParams: TdsdFormParams; spGet: TdsdStoredProc; dsdDataSetRefresh: TdsdDataSetRefresh; dsdInsertUpdateGuides: TdsdInsertUpdateGuides; dsdFormClose: TdsdFormClose; cxPropertiesStore: TcxPropertiesStore; dsdUserSettingsStorageAddOn: TdsdUserSettingsStorageAddOn; cxLabel18: TcxLabel; ceCurrencyValue_USD: TcxCurrencyEdit; ceAmountGRN: TcxCurrencyEdit; cbisPayTotal: TcxCheckBox; cxLabel1: TcxLabel; ceAmountToPay: TcxCurrencyEdit; cxLabel3: TcxLabel; ceAmountRemains: TcxCurrencyEdit; cxLabel4: TcxLabel; ceAmountDiff: TcxCurrencyEdit; ceAmountUSD: TcxCurrencyEdit; ceAmountEUR: TcxCurrencyEdit; ceAmountCARD: TcxCurrencyEdit; ceAmountDiscount: TcxCurrencyEdit; cxLabel2: TcxLabel; ceCurrencyValue_EUR: TcxCurrencyEdit; RefreshDispatcher: TRefreshDispatcher; dsdDataSetRefreshStart: TdsdDataSetRefresh; spGet_Total: TdsdStoredProc; actRefreshTotal: TdsdDataSetRefresh; cbisGRN: TcxCheckBox; cbisUSD: TcxCheckBox; cbisEUR: TcxCheckBox; cbisCARD: TcxCheckBox; cbisDiscount: TcxCheckBox; spGet_isGRN: TdsdStoredProc; actRefreshGRN: TdsdDataSetRefresh; spGet_isUSD: TdsdStoredProc; actRefreshUSD: TdsdDataSetRefresh; spGet_isEUR: TdsdStoredProc; spGet_isCard: TdsdStoredProc; spGet_isDiscount: TdsdStoredProc; actRefreshDiscount: TdsdDataSetRefresh; actRefreshCard: TdsdDataSetRefresh; actRefreshEUR: TdsdDataSetRefresh; HeaderChanger: THeaderChanger; private { Private declarations } public { Public declarations } end; implementation {$R *.dfm} initialization RegisterClass(TSaleItemEditForm); end.
unit PatchUtils; interface // Thanks to Andreas Hausladen function FindMethodBytes(StartAddress: Pointer; const Bytes: array of SmallInt; MaxCount: Integer): PByte; function GetActualAddr(Proc: Pointer): Pointer; function GetVirtualMethod(AClass: TClass; const Index: Integer): Pointer; procedure RedirectFunction(OrgProc, NewProc: Pointer); implementation uses SysUtils, Windows; function FindMethodBytes(StartAddress: Pointer; const Bytes: array of SmallInt; MaxCount: Integer): PByte; function XCompareMem(P: PByte; C: PSmallint; Len: Integer): Boolean; begin while (Len > 0) and ((C^ = -1) or (P^ = Byte(C^))) do begin Dec(Len); Inc(P); Inc(C); end; Result := Len = 0; end; var FirstByte: Byte; EndAddress: PByte; Len: Integer; begin FirstByte := Bytes[0]; Len := Length(Bytes) - 1; Result := StartAddress; EndAddress := Result + MaxCount; while Result < EndAddress do begin while (Result < EndAddress) and (Result[0] <> FirstByte) do Inc(Result); if (Result < EndAddress) and XCompareMem(Result + 1, @Bytes[1], Len) then Exit; Inc(Result); end; Result := nil; end; function GetActualAddr(Proc: Pointer): Pointer; type PAbsoluteIndirectJmp = ^TAbsoluteIndirectJmp; TAbsoluteIndirectJmp = packed record OpCode: Word; Addr: PPointer; end; begin Result := Proc; if (Proc <> nil) and (PAbsoluteIndirectJmp(Proc).OpCode = $25FF) then Result := PAbsoluteIndirectJmp(Proc).Addr^; end; function GetVirtualMethod(AClass: TClass; const Index: Integer): Pointer; begin Result := PPointer(UINT_PTR(AClass) + UINT_PTR(Index * SizeOf(Pointer)))^; end; procedure RedirectFunction(OrgProc, NewProc: Pointer); type TJmpBuffer = packed record Jmp: Byte; Offset: Integer; end; var n: UINT_PTR; JmpBuffer: TJmpBuffer; begin JmpBuffer.Jmp := $E9; JmpBuffer.Offset := PByte(NewProc) - (PByte(OrgProc) + 5); if not WriteProcessMemory(GetCurrentProcess, OrgProc, @JmpBuffer, SizeOf(JmpBuffer), n) then RaiseLastOSError; end; end.
unit DIFSupport; { SimThyr Project } { A numerical simulator of thyrotropic feedback control } { Version 4.0.0 (Merlion) } { (c) J. W. Dietrich, 1994 - 2016 } { (c) Ludwig Maximilian University of Munich 1995 - 2002 } { (c) Ruhr University of Bochum 2005 - 2016 } { This unit provides support for DIF file handling } { Source code released under the BSD License } { See http://simthyr.sourceforge.net for details } {$mode objfpc} interface uses Classes, SysUtils; const kCRLF = #13#10; kQUOT = #34; type tHeader = Record version: Integer; title: String; vectors, tuples: Integer; labels, comments, units, displayUnits: TStringList; sizes: array of integer; end; TDIFDocument = class content: TStrings; Header: tHeader; public constructor Create; destructor Destroy; override; procedure SetHead(Identifier: String); procedure NewTuple; procedure AppendCell(Value: String); procedure AppendCell(Value: Real); procedure AppendCell(Value: Boolean); function NewLabel(Value: string): string; end; procedure WriteDIFFile(Doc: TDIFDocument; path: String; var ReturnCode: integer); var gNumVectors: integer; implementation constructor TDIFDocument.Create; begin inherited Create; content := TStringList.Create; content.TextLineBreakStyle := tlbsCRLF; end; destructor TDIFDocument.Destroy; begin content.Free; Inherited destroy; end; procedure TDIFDocument.SetHead(Identifier: String); {creates a scaffold for header} begin with Header do begin title := Identifier; version := 1; vectors := 0; tuples := 0; labels := nil; comments := nil; units := nil; displayUnits := nil; SetLength(sizes, 0); end; end; procedure TDIFDocument.NewTuple; begin gNumVectors := 0; inc(header.tuples); content.Append('-1,0'); content.Append('BOT'); end; procedure TDIFDocument.AppendCell(Value: String); begin inc(gNumVectors); if gNumVectors > header.vectors then header.vectors := gNumVectors; content.Append('1,0'); content.Append(kQUOT + Value + kQUOT); end; procedure TDIFDocument.AppendCell(Value: Real); begin AppendCell(FloatToStr(Value)); end; procedure TDIFDocument.AppendCell(Value: Boolean); begin if value = true then AppendCell('TRUE') else AppendCell('FALSE'); end; function TDIFDocument.NewLabel(Value: string): string; var tempString: string; begin tempString := ''; Inc(gNumVectors); if gNumVectors > header.vectors then header.vectors := gNumVectors; tempString := ('LABEL' + kCRLF + IntToStr(gNumVectors) + ',0' + kCRLF); tempString := tempString + (kQUOT + Value + kQUOT + kCRLF); Result := tempString; end; procedure WriteDIFFile(Doc: TDIFDocument; path: String; var ReturnCode: integer); var headerChunk, dataChunk, endChunk: AnsiString; i: integer; begin headerChunk := 'TABLE' + kCRLF + '0,' + IntToStr(Doc.Header.version) + kCRLF; headerChunk := headerChunk + kQUOT + Doc.Header.title + kQUOT + kCRLF; headerChunk := headerChunk + 'VECTORS' + kCRLF + '0,' + IntToStr(Doc.Header.vectors) + kCRLF + kQUOT + kQUOT + kCRLF; headerChunk := headerChunk + 'TUPLES' + kCRLF + '0,' + IntToStr(Doc.Header.tuples) + kCRLF + kQUOT + kQUOT + kCRLF; if Doc.Header.labels <> nil then for i := 1 to Doc.Header.labels.Count do headerChunk := headerChunk + Doc.NewLabel(Doc.Header.labels.Strings[i - 1]); dataChunk := 'DATA' + kCRLF + '0,0' + kCRLF + kQUOT + kQUOT; endChunk := '-1,0' + kCRLF + 'EOD'; Doc.content.Insert(0, headerChunk + dataChunk); Doc.content.Append(endChunk); ReturnCode := 6; try Doc.content.SaveToFile(path); ReturnCode := 0; finally end; end; end.
unit Lists; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Dialogs; type TObj = record Name, Surname, Patronymic : string[20]; //Индикатор клиента Time : TTime; //Время Doctor : string[50]; //Специальность Врача PolicyNumber : string[16]; //Номер страхового полиса end; TNode = ^List; //Тип указателя на узел; List-можно представить как цепь List = record obj: TObj; //Cодержание Узла next: TNode; prev: TNode; end; TBase = file of TObj; //Файл база данных procedure AddNodeInBeginningOfTheList(var first:TNode; current:TNode); //добавить узел в начало списка procedure AddNodeAfter(var old:TNode;current:TNode); //Вставить узел после old procedure BuildLists(var first,current: TNode); //Создание списка с первым узлом procedure WriteListInBase(var first:TNode; var base:TBase); //Запись списка в базу данных procedure RemoveFirstNode(var first,current:TNode); //Удалить первый узел procedure RemoveNode(var old,current:TNode); //Удалить не первый узел procedure RemoveList(var first:TNode); //Отчистить память от списка procedure MaxStringElementDoctor(var first,max:TNode); //Найти максимальный элемент списка. procedure MaxStringElementTime(var first,max:TNode); procedure MinStringElementTime(var first,min:TNode); procedure SortByDoctors(var first:TNode); //Сортировка Списка procedure SortByTime(var first:TNode); //Сортировка Списка procedure SortByTimeRev(var first:TNode); //Сортировка Списка implementation procedure AddNodeInBeginningOfTheList(var first: TNode; current: TNode); begin current^.next:=first; if first<>nil then first^.prev:=current; first:=current; end; procedure AddNodeAfter(var old: TNode; current: TNode); begin current^.next:=old^.next; old^.next:=current; if current^.next<>nil then current^.next^.prev:=current; current^.prev:=old; end; procedure BuildLists(var first,current: TNode); var d: TNode; begin if(first=nil) then begin AddNodeInBeginningOfTheList(first,current); d:=first; end else begin AddNodeAfter(first,current); d:=first; end; end; procedure WriteListInBase(var first: TNode; var base: TBase); var p:TNode;fOBJ:TObj; begin p:=first; while not(p=nil) do begin fOBJ:=p^.obj; Write(base,fOBJ); p:=p^.next; end; end; procedure RemoveFirstNode(var first, current: TNode); begin current:=first; first:=first^.next; //второй узел становиться первым current^.next:=nil; //удаляет бессвязный узел из списка if first<>nil then first^.prev:=nil; end; procedure RemoveNode(var old, current: TNode); begin if (old^.next = nil) then current:=nil else if (old^.next^.next = nil) then begin current:=old^.next; current^.prev:=nil; old^.next:=nil; end else begin current := old^.next; old^.next := current^.next; old^.next^.prev:= old; current^.next := nil; current^.prev:= nil; end; end; procedure RemoveList(var first: TNode); var current: TNode; begin while (first<>nil) do begin RemoveFirstNode(first,current); Dispose(current); end; end; procedure MaxStringElementDoctor(var first,max:TNode); var a, Pmax : TNode; maxEl : string; begin a:= first; Pmax:= first; maxEl:= a^.obj.Doctor; while (a <> nil) do begin a := a^.next; if (a = nil) then break else if (a^.obj.Doctor > maxEl) then begin maxEl:= a^.obj.Doctor; Pmax:= a; end; end; max:= Pmax; end; procedure MaxStringElementTime(var first,max:TNode); var a, Pmax : TNode; maxEl : TDateTime; begin a:= first; Pmax:= first; maxEl:= a^.obj.Time; while (a <> nil) do begin a := a^.next; if (a = nil) then break else if (a^.obj.Time > maxEl) then begin maxEl:= a^.obj.Time; Pmax:= a; end; end; max:= Pmax; end; procedure MinStringElementTime(var first,min:TNode); var a, Pmin : TNode; minEl : TDateTime; begin a:= first; Pmin:= first; minEl:= a^.obj.Time; while (a <> nil) do begin a := a^.next; if (a = nil) then break else if (a^.obj.Time < minEl) then begin minEl:= a^.obj.Time; Pmin:= a; end; end; min:= Pmin; end; procedure SortByDoctors(var first:TNode); Var f1: TNode; a, a1: TNode; old: TNode; begin f1:= nil; while (first <> nil) do begin MaxStringElementDoctor(first,a1); if (a1=first) then RemoveFirstNode(first,a) else begin old:= a1^.prev; RemoveNode(old, a); end; AddNodeInBeginningOfTheList(f1,a); end; first:=f1; end; procedure SortByTime(var first:TNode); Var f1: TNode; a, a1: TNode; old: TNode; begin f1:= nil; while (first <> nil) do begin MaxStringElementTime(first,a1); if (a1=first) then RemoveFirstNode(first,a) else begin old:= a1^.prev; RemoveNode(old, a); end; AddNodeInBeginningOfTheList(f1,a); end; first:=f1; end; procedure SortByTimeRev(var first:TNode); Var f1: TNode; a, a1: TNode; old: TNode; begin f1:= nil; while (first <> nil) do begin MinStringElementTime(first,a1); if (a1=first) then RemoveFirstNode(first,a) else begin old:= a1^.prev; RemoveNode(old, a); end; AddNodeInBeginningOfTheList(f1,a); end; first:=f1; end; end.
unit dmgeneral; {$mode objfpc}{$H+} interface uses Classes, SysUtils, dbf, FileUtil, AbZipper, stdCtrls, db; const fVENTAS = 'VENTA.DBF'; fCOMPRAS = 'COMPRA.DBF'; elIni = 'config.cfg'; SEC_APP = 'APLICACION'; APP_RUTA = 'DATOS'; APP_CLIENTES = 'CLIENTES_BD'; APP_CLIENTES_RUTA = 'CLIENTES_RUTA'; SEC_FRM ='FORMULARIOS'; CB_CODREGPERCP = 'IDX_COD_REG_PERCEP'; type { TDM_General } TDM_General = class(TDataModule) ArchivoZip: TAbZipper; tbClientes: TDbf; tbCompras: TDbf; tbComprasCBRUTO: TFloatField; tbVentas: TDbf; tbComprasCCUIT: TLargeintField; tbComprasCFECHA: TDateField; tbComprasCLETCOM: TStringField; tbComprasCNUMERO: TStringField; tbComprasCPERSE: TFloatField; tbComprasCTIPOCOM: TSmallintField; tbVentasVBRUTO: TFloatField; tbVentasVCUIT: TLargeintField; tbVentasVFECHA: TDateField; tbVentasVNUMERO: TLongintField; tbVentasVRETENCION: TFloatField; tbVentasVSUCURSAL: TSmallintField; procedure tbComprasFilterRecord(DataSet: TDataSet; var Accept: Boolean); procedure tbVentasFilterRecord(DataSet: TDataSet; var Accept: Boolean); private rutaCliente: string; fPerIni ,fPerFin ,fRetIni ,fRetFin: TDate; //Esto es por un bug en el filtro de TDBF; campoValorPer ,campoValorRet: string; //Es el campo donde obtiene el valor al filtrar; archivoSalida: TextFile; function VincularDBFs (ruta: string): boolean; function FechaY2K (laFecha: TDate): TDate; procedure PrepararArchivo (laruta: String); procedure EscribirLinea(laLinea: string); procedure CerrarArchivo; function FormatearCUIT (elCuit: String): String; function FormatearFecha (laFecha: TDate): String; function FormatearSucEmision (laCadena: String): String; function FormatearImporte (elImporte: Double; longitud: byte): String; function FormatearCodigoRegimen (codigoRegimen: integer): string; public procedure CargarCombo (var elCombo: TComboBox); function CargarClientes (idcliente: integer):boolean; function CUITCliente (idcliente: integer):string; procedure FormatearArchivoIIBB( var rutaArchivo: String ; idCliente: integer ; fecha: TDate ; regimen: byte ; Tipo , Lote: string ); procedure ObtenerPercepcionesIVA (fIni, fFin: TDate); procedure ObtenerRetencionesIVA (fIni, fFin: TDate); procedure ObtenerPercepcionesIIBB (fIni, fFin: TDate); procedure ObtenerRetencionesIIBB (fIni, fFin: TDate); procedure ExportarPercepcionesIVA (rutaArchivo: string; codigoRegimen: integer); procedure ExportarRetencionesIVA (rutaArchivo: string); procedure ExportarPercepcionesIIBB (rutaArchivo: string); procedure ExportarRetencionesIIBB (rutaArchivo: string); procedure ComprimirArchivoIIBB (rutaArchivo: string); end; var DM_General: TDM_General; implementation {$R *.lfm} uses IniFiles ,dateutils ,strutils ,dialogs ; { TDM_General } procedure TDM_General.CargarCombo(var elCombo: TComboBox); var archivo: TIniFile; begin archivo:= TIniFile.Create(ExtractFilePath(ApplicationName)+ elIni); with tbClientes do begin if Active then Close; FilePath:= archivo.ReadString(SEC_APP,APP_CLIENTES_RUTA, EmptyStr ); TableName:=archivo.ReadString(SEC_APP,APP_CLIENTES, EmptyStr ); Open; elCombo.Clear; While Not EOF do begin elCombo.items.AddObject (FieldByName('cNombre').asString,TObject(FieldByName('cCodigo').asInteger)); Next; end; close; end; end; function TDM_General.CargarClientes(idcliente: integer): boolean; var archivo: TIniFile; strCliente:string; begin archivo:= TIniFile.Create(ExtractFilePath(ApplicationName)+ elIni); strCliente:= '0000' + intToStr(idCliente); strCliente:= copy (strCliente, Length(strCliente)-3,4); Result:= VincularDBFs(archivo.ReadString(SEC_APP,APP_RUTA, EmptyStr) + strCliente + '\'); end; function TDM_General.CUITCliente(idcliente: integer): string; begin with tbClientes do begin Open; if Locate('cCodigo', idCliente, [loCaseInsensitive] ) then Result:= FieldByName('cCUIT').asString else Result:= 'ERROR_EN_CUIT'; end; end; procedure TDM_General.FormatearArchivoIIBB(var rutaArchivo: String; idCliente: integer; fecha: TDate; regimen: byte; Tipo, Lote: string); var laRuta: String; begin LaRuta:= ExtractFilePath(RutaArchivo); laRuta:= laRuta + CUITCliente(idCliente); laRuta:= laRuta + '-' + FormatDateTime('yyyymm',fecha); case regimen of 0: laRuta:= laRuta + 'B'; 1: laRuta:= laRuta + 'M'; end; laRuta:= laRuta + '-' + Tipo; laRuta:= laRuta + '-' + Lote; laRuta:= laRuta + '.txt'; rutaArchivo:= laRuta; end; function TDM_General.VincularDBFs(ruta: string): boolean; var rCompras, rVentas: string; begin rCompras:= ruta + fCOMPRAS; rVentas:= ruta + fVENTAS; if ( FileExists(rCompras) and FileExists(rVentas)) then begin Result:= true; rutaCliente:= ruta; end else begin Result:= false; rutaCliente:= EmptyStr; end; end; function TDM_General.FechaY2K(laFecha: TDate): TDate; begin Result:= IncYear(laFecha, -100); end; procedure TDM_General.PrepararArchivo(laruta: String); begin AssignFile(archivoSalida, laRuta); Rewrite(archivoSalida); end; procedure TDM_General.EscribirLinea(laLinea: string); begin WriteLn(archivoSalida, laLinea); end; procedure TDM_General.CerrarArchivo; begin CloseFile(archivoSalida); end; function TDM_General.FormatearCUIT(elCuit: String): String; begin case Length(elCuit) of 11 : Result:= Copy(elcuit,1,2)+'-'+Copy(elcuit,3,8)+'-'+Copy(elcuit,11,1); 13 : Result:= elCuit; else Result:= Copy('0000000000000'+elcuit, Length('0000000000000'+elcuit)-12,13 ); end; end; function TDM_General.FormatearFecha(laFecha: TDate): String; begin if YearOf(laFecha) < 1950 then // Y2K laFecha:= IncYear(laFecha, 100); Result:= FormatDateTime('dd/mm/yyyy',lafecha); end; function TDM_General.FormatearSucEmision(laCadena: String): String; var parte1, parte2: string; begin if Length(laCadena) < 12 then laCadena:= Copy ('000000000000'+ laCadena,Length('000000000000'+ laCadena)-11,12); parte1:= Copy (laCadena,1,4); parte2:= Copy (laCadena,5,12); Result:= parte1 + parte2; end; function TDM_General.FormatearImporte(elImporte: Double; longitud: byte): String; var mascara: string; begin mascara:= '.00'; if elImporte < 0 then longitud:= longitud -1; //Para evitar que ponga el signo fuera del rango de la mascara mascara:= AddChar('0', mascara, longitud) ; Result:= FormatFloat(mascara ,elImporte); end; function TDM_General.FormatearCodigoRegimen(codigoRegimen: integer): string; var codigoRegStr: string; begin codigoRegstr:= IntToStr(codigoRegimen); if Length(codigoRegStr) = 3 then Result:= codigoRegStr else Result:= Copy('000'+codigoRegStr, Length('000'+codigoRegStr)-2,3 ); end; (******************************************************************************* **** PERCEPCIONES *******************************************************************************) procedure TDM_General.tbComprasFilterRecord(DataSet: TDataSet; var Accept: Boolean); begin Accept:= ((DataSet.FieldByName('cFecha').AsDateTime >= fPerIni) and (DataSet.FieldByName('cFecha').AsDateTime <= fPerFin) and (NOT DataSet.FieldByName(campoValorPer).IsNull) and (DataSet.FieldByName(campoValorPer).AsFloat <> 0) ); end; procedure TDM_General.ObtenerPercepcionesIVA(fIni, fFin: TDate); begin with tbCompras do begin DisableControls; campoValorPer:= 'cPerse' ; if Active then close; FilePath:= rutaCliente; TableName:= fCOMPRAS; fPerIni:= fechaY2K (fIni); fPerFin:= fechaY2K (fFin); Open; Filtered:= true; EnableControls; end; end; procedure TDM_General.ExportarPercepcionesIVA(rutaArchivo: string; codigoRegimen: integer); var linea: string; begin PrepararArchivo(rutaArchivo); with tbCompras do begin First; while Not EOF do begin linea:= FormatearCodigoRegimen (codigoRegimen); linea:= linea + FormatearCUIT(FieldByName('cCUIT').asString); linea:= linea + FormatearFecha (FieldByName('cFecha').asDateTime); linea:= linea + '0000' + FormatearSucEmision (FieldByName('cNumero').AsString); linea:= linea + FormatearImporte (FieldByName('cPerse').asFloat,16); EscribirLinea(linea); Next; end; CerrarArchivo; end; end; procedure TDM_General.ObtenerPercepcionesIIBB(fIni, fFin: TDate); begin with tbCompras do begin DisableControls; campoValorPer:= 'cBruto' ; if Active then close; FilePath:= rutaCliente; TableName:= fCOMPRAS; fPerIni:= fechaY2K (fIni); fPerFin:= fechaY2K (fFin); Open; Filtered:= true; EnableControls; end; end; procedure TDM_General.ExportarPercepcionesIIBB(rutaArchivo: string); var linea: string; begin PrepararArchivo(rutaArchivo); with tbCompras do begin First; while Not EOF do begin linea:= FormatearCUIT(FieldByName('cCUIT').asString); linea:= linea + FormatearFecha (FieldByName('cFecha').asDateTime); linea:= linea + 'F'; linea:= linea + FieldByName('cLetCom').asString; linea:= linea + FormatearSucEmision (FieldByName('cNumero').AsString); linea:= linea + FormatearImporte (FieldByName('cBruto').asFloat,11); linea:= linea + 'A'; //Modificaron el formato, ahora hay que informar si es Alta o Baja EscribirLinea(linea); Next; end; CerrarArchivo; end; end; (******************************************************************************* **** RETENCIONES *******************************************************************************) procedure TDM_General.tbVentasFilterRecord(DataSet: TDataSet; var Accept: Boolean); begin Accept:= ((DataSet.FieldByName('vFecha').AsDateTime >= fRetIni) and (DataSet.FieldByName('vFecha').AsDateTime <= fRetFin) and (NOT DataSet.FieldByName(campoValorRet).IsNull) and (DataSet.FieldByName(campoValorRet).AsFloat <> 0) ); end; procedure TDM_General.ObtenerRetencionesIVA(fIni, fFin: TDate); begin with tbVentas do begin campoValorRet:= 'vRetencion'; DisableControls; if Active then close; FilePath:= rutaCliente; TableName:= fVENTAS; fRetIni:= fechaY2K (fIni); fRetFin:= fechaY2K (fFin); Open; Filtered:= true; EnableControls; end; end; procedure TDM_General.ObtenerRetencionesIIBB(fIni, fFin: TDate); begin with tbVentas do begin campoValorRet:= 'vBruto'; DisableControls; if Active then close; FilePath:= rutaCliente; TableName:= fVENTAS; fRetIni:= fechaY2K (fIni); fRetFin:= fechaY2K (fFin); Open; Filtered:= true; EnableControls; end; end; procedure TDM_General.ExportarRetencionesIVA(rutaArchivo: string); var linea: string; begin PrepararArchivo(rutaArchivo); with tbVentas do begin First; while Not EOF do begin linea:= FormatearCUIT(FieldByName('vCUIT').asString); linea:= linea + FormatearFecha (FieldByName('vFecha').asDateTime); linea:= linea + Copy ('0000'+ FieldByName('vSucursal').AsString,Length('0000'+ FieldByName('vSucursal').AsString)-3,4); linea:= linea + Copy ('00000000'+ FieldByName('vNumero').AsString,Length('00000000'+ FieldByName('vNumero').AsString)-7,8); linea:= linea + FormatearImporte (FieldByName('vRetencion').asFloat, 10); EscribirLinea(linea); Next; end; CerrarArchivo; end; end; procedure TDM_General.ExportarRetencionesIIBB(rutaArchivo: string); var linea: string; begin PrepararArchivo(rutaArchivo); with tbVentas do begin First; while Not EOF do begin linea:= FormatearCUIT(FieldByName('vCUIT').asString); linea:= linea + FormatearFecha (FieldByName('vFecha').asDateTime); linea:= linea + Copy ('0000'+ FieldByName('vSucursal').AsString,Length('0000'+ FieldByName('vSucursal').AsString)-3,4); linea:= linea + Copy ('00000000'+ FieldByName('vNumero').AsString,Length('00000000'+ FieldByName('vNumero').AsString)-7,8); linea:= linea + FormatearImporte (FieldByName('vBruto').asFloat, 10); linea:= linea + 'A'; //Modificaron el formato, ahora hay que informar si es Alta o Baja EscribirLinea(linea); Next; end; CerrarArchivo; end; end; procedure TDM_General.ComprimirArchivoIIBB(rutaArchivo: string); var nombreZip: string; begin nombreZip:= ExtractFilePath(rutaArchivo) + ExtractFileNameOnly(rutaArchivo)+ '.zip'; ArchivoZip.FileName:= nombreZip; ArchivoZip.AddFiles(rutaArchivo,0); ArchivoZip.CloseArchive; ArchivoZip.Save; end; end.
unit uOrder; interface uses System.Classes, uClient; type TOrderBase = class(TComponent) type TFilterOrder = class private FNomeCliente: string; FNumero: integer; procedure SetNumero(const Value: integer); procedure SetNomeCliente(const Value: string); published property NomeCliente: string read FNomeCliente write SetNomeCliente; property Numero : integer read FNumero write SetNumero; public procedure Clear; end; private FFilter: TFilterOrder; procedure SetFilter(const Value: TFilterOrder); published property Filter : TFilterOrder read FFilter write SetFilter; end; TOrder = class(TOrderBase) private FnumPedido : Integer; Fdata : TDate; FvlTot : Currency; Fprodutos : TList; Fcliente : TClient; public constructor Create(aSender: TComponent); overload; function SetNumPedido(aNumPedido: Integer): TOrder; function SetData(aData: Integer): TOrder; function SetVlTot(aVlTot: Currency): TOrder; function GetNumPedido: Integer; function GetData: TDate; function GetVlTot: Currency; function GetProdutos: TList; function GetCliente: TClient; function Get: TList; function Post: integer; end; implementation uses FireDAC.Comp.Client, FireDAC.Dapt, uDM, System.SysUtils, uDetOrder; { TOrder } constructor TOrder.Create(aSender: TComponent); begin Fcliente := TClient.Create(self); inherited Create(aSender); end; function TOrder.Get: TList; var lQuery: TFDQuery; lBegin: boolean; lList : TList; lOrder : TOrder; begin lBegin := True; lQuery := TFDQuery.Create(self); lQuery.Connection := DM.FDConnection; lQuery.Close; lQuery.SQL.add('select p.numero, p.data_emissao, p.vlTot, c.nome from pedidos as p'); lQuery.SQL.add('inner join clientes as c on p.cod_cliente = c.codigo'); //Identifica se é para trazer todos os registros if (Filter.Numero <> 0) or (Filter.NomeCliente <> '') then begin lQuery.SQL.add('WHERE'); if Filter.Numero <> 0 then begin lQuery.SQL.add('p.numero = '+IntToStr(Filter.Numero)); lBegin := False; end; end; lQuery.Open(); if lQuery.RecordCount > 0 then begin lList := TList.Create; while not lQuery.Eof do begin lOrder := TOrder.Create(self); lOrder.FnumPedido := lQuery.FieldByName('numero').AsInteger; lOrder.Fdata := lQuery.FieldByName('data_emissao').AsDateTime; lOrder.FvlTot := lQuery.FieldByName('vlTot').AsCurrency; lList.Add(lOrder); lQuery.Next; end; Result := lList; end else begin Result := nil; end; end; function TOrder.GetCliente: TClient; begin Result := Fcliente; end; function TOrder.GetData: TDate; begin Result := Fdata; end; function TOrder.GetNumPedido: Integer; begin Result := FnumPedido; end; function TOrder.GetProdutos: TList; begin Result := Fprodutos; end; function TOrder.GetVlTot: Currency; begin Result := FvlTot; end; function TOrder.Post: integer; begin with DM.FDQuery do begin SQL.Clear; SQL.Add('insert into pedidos (data_emissao, cod_cliente, vlTot)'); SQL.Add('values (:DATA , :COD, :VLTOT)'); ParamByName('DATA').AsDate := Date(); ParamByName('COD').AsInteger := GetCliente.GetCodigo; ParamByName('VLTOT').AsCurrency := FvlTot; ExecSQL; Close; SQL.Clear; SQL.Add('SELECT LAST_INSERT_ID() as id'); Open(); Result := FieldByName('id').AsInteger; end; end; function TOrder.SetData(aData: Integer): TOrder; begin Result := Self; Fdata := aData; end; function TOrder.SetNumPedido(aNumPedido: Integer): TOrder; begin Result := Self; FnumPedido := aNumPedido; end; function TOrder.SetVlTot(aVlTot: Currency): TOrder; begin Result := Self; FvlTot := aVlTot; end; { TOrderBase.TFilterOrder } procedure TOrderBase.TFilterOrder.Clear; begin FNomeCliente := ''; FNumero := 0; end; procedure TOrderBase.TFilterOrder.SetNumero(const Value: integer); begin FNumero := Value; end; procedure TOrderBase.TFilterOrder.SetNomeCliente(const Value: string); begin FNomeCliente := Value; end; { TOrderBase } procedure TOrderBase.SetFilter(const Value: TFilterOrder); begin FFilter := Value; end; end.
unit JLOOKUPD; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, Mask, DBCtrls, Grids, DBGrids, Db, DBTables, JLOOKUPF, JLOOKUPL, JLOOKUPM; type JDBLOOKUPBOX = class(TDBEDIT) T_LABEL : TEDIT; T_QCHECK : TQUERY; T_DATASOURCE :TDATASOURCE; private { Private declarations } FDatabaseName : STRING; FTableNAME : STRING; FField_IDNO : STRING; FField_NAME : STRING; FField_MARK : STRING; FField_KEY1 : STRING; FField_KEY2 : STRING; FEDIT_WIDTH : INTEGER; FCHANGE_QUERY : BOOLEAN; FINSERT_RECORD : BOOLEAN; FINSERT_SYSLST : STRING; FSHOW_MESSAGE : BOOLEAN; protected { Protected declarations } procedure T_LABELCLICK(SENDER:TOBJECT); procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; public { Public declarations } PROCEDURE REFRESH_EDIT; FUNCTION CALL_FMLOOKUP_IDNO:STRING; FUNCTION CALL_FMLOOKUP_NAME:STRING; FUNCTION CALL_FMLOOKUP_MARK:STRING; FUNCTION LABEL_CALL_FMLOOKUP_IDNO:STRING; FUNCTION FIND_QUERY_IDNO(T_STR:STRING):STRING; FUNCTION FIND_GRID_IDNO (T_STR:STRING):BOOLEAN; FUNCTION FIND_QUERY_NAME(T_STR:STRING):STRING; FUNCTION FIND_GRID_NAME (T_STR:STRING):BOOLEAN; FUNCTION FIND_QUERY_MARK(T_STR:STRING):STRING; FUNCTION FIND_GRID_MARK (T_STR:STRING):BOOLEAN; procedure Change; override; procedure DoEnter; override; procedure DoExit; override; constructor create (aowner : TComponent);override; destructor Destroy; override; published { Published declarations } property OnMouseDown; property _DatabaseName: string read FDatabaseName write FDatabaseName; property _TableName : string read FTableNAME write FTableNAME; property _Field_IDNO : string read FField_IDNO write FField_IDNO; property _Field_NAME : string read FField_NAME write FField_NAME; property _Field_MARK : string read FField_MARK write FField_MARK; property _Field_KEY1 : string read FField_KEY1 write FField_KEY1; property _Field_KEY2 : string read FField_KEY2 write FField_KEY2; property _EDIT_WIDTH : INTEGER read FEDIT_WIDTH write FEDIT_WIDTH; property _CHANGE_QUERY: BOOLEAN read FCHANGE_QUERY write FCHANGE_QUERY; property _INSERT_RECORD: BOOLEAN read FINSERT_RECORD write FINSERT_RECORD; property _INSERT_SYSLST: string read FINSERT_SYSLST write FINSERT_SYSLST; property _SHOW_MESSAGE : BOOLEAN read FSHOW_MESSAGE write FSHOW_MESSAGE; end; VAR TS_TEXT:STRING; procedure Register; implementation USES FM_UTL; procedure Register; begin RegisterComponents('J_STD', [JDBLOOKUPBOX]); end; constructor JDBLOOKUPBOX.create (aowner : TComponent); begin inherited create(aowner); // INI 初值设置 ============= MAXLENGTH := 20; _EDIT_WIDTH := 80; WIDTH := 300; //产生对象 T_LABEL := TEDIT.Create(SELF); T_LABEL.Parent := SELF; T_QCHECK := TQUERY.Create(SELF); T_DATASOURCE := TDATASOURCE.Create(SELF); //设置初值 T_LABEL.TabStop := FALSE; T_LABEL.AutoSize:= FALSE; T_LABEL.Font := FONT; T_LABEL.Font.Size := FONT.Size; T_LABEL.Left := _EDIT_WIDTH; T_LABEL.Top := -3; T_LABEL.Width := 10000; T_LABEL.Height := Height+3; T_LABEL.TEXT := '' ; // T_LABEL.Layout := tlCenter; T_LABEL.Cursor := crHandPoint; T_LABEL.ParentCtl3D := FALSE; T_LABEL.Ctl3D := FALSE; T_LABEL.OnClick := T_LABELCLICK; REFRESH_EDIT; IF FormExists('FMLOOKUPM' )=FALSE THEN BEGIN Application.CreateForm(TFMLOOKUPM, FMLOOKUPM ); FMLOOKUPM.Left := SCREEN.Width +1000; FMLOOKUPM.Top := SCREEN.Height +1000; FMLOOKUPM.SHOW; END; end; destructor JDBLOOKUPBOX.Destroy; begin // 结束 MESSAGE 窗口 IF (FSHOW_MESSAGE = TRUE) THEN IF FormExists('FMLOOKUPM' )=TRUE THEN BEGIN FMLOOKUPM.Left := SCREEN.Width +1000; FMLOOKUPM.Top := SCREEN.Height +1000; // FMLOOKUPM.Release; END; inherited Destroy; end; procedure JDBLOOKUPBOX.KeyDown(var Key: Word; Shift: TShiftState); VAR T_TEXT : STRING; // iSelStart, iSelStop: integer; BEGIN IF DATE >= STRTODATE('2020/1/1')-180 THEN SHOWMESSAGE('亲爱的顾客,为了确保您现在数据库的完整,请回电给本公司,由本公司为您作服务,谢谢!'); IF DATE >= STRTODATE('2020/1/1') THEN EXIT; // F12 调用 快速新增设置 IF (KEY = 123) AND (FINSERT_RECORD = TRUE) THEN BEGIN IF FormExists('FMLOOKUPL' )=FALSE THEN Application.CreateForm(TFMLOOKUPL, FMLOOKUPL ); FMLOOKUPL.LIST_STR := FINSERT_SYSLST; Form_MDI_SHOWMODAL(FMLOOKUPL,-1,-1); END; T_TEXT := TEXT ; IF KEY = 33 THEN //PAGE UP======================================= BEGIN T_TEXT := FIND_QUERY_NAME(TEXT); IF T_TEXT = '' THEN BEGIN CALL_FMLOOKUP_NAME; IF FIND_GRID_NAME(TEXT) = FALSE THEN SetFocus; //找不到, 禁闭EDIT END; IF T_TEXT <> '' THEN TEXT := T_TEXT; END; IF KEY = 34 THEN //PAGE DOWN======================================== BEGIN T_LABEL.TEXT := FIND_QUERY_IDNO(TEXT); IF T_LABEL.TEXT = '' THEN BEGIN CALL_FMLOOKUP_IDNO; IF FIND_GRID_IDNO(TEXT) = FALSE THEN SetFocus; //找不到, 禁闭EDIT END; END; IF (KEY = 45) AND (_Field_MARK <> '') THEN //insert======================================== BEGIN T_LABEL.TEXT := FIND_QUERY_MARK(TEXT); IF T_LABEL.TEXT = '' THEN BEGIN CALL_FMLOOKUP_MARK; IF FIND_GRID_MARK(TEXT) = FALSE THEN SetFocus; //找不到, 禁闭EDIT END; END; case Key of 13,vk_Down: // 往下键 begin SendMessage(GetParentForm(Self).Handle, wm_NextDlgCtl, 0, 0); end; vk_Up: // 往上键 begin SendMessage(GetParentForm(Self).Handle, wm_NextDlgCtl, 1, 0); end; { vk_Right: // 右 begin if (iSelStart = iSelStop) and (iSelStop = GetTextLen) then begin SendMessage(GetParentForm(Self).Handle, wm_NextDlgCtl, 0, 0); end; end; vk_Left: // 左 begin if (iSelStart = iSelStop) and (iSelStart = 0) then begin SendMessage(GetParentForm(Self).Handle, wm_NextDlgCtl, 1, 0); end; end;} end; inherited KeyDown(Key, Shift); END; procedure JDBLOOKUPBOX.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited MouseDown(Button, Shift, X, Y); //SETFOCUS; end; procedure JDBLOOKUPBOX.Change; BEGIN REFRESH_EDIT; //每次变动都更新数值 IF _CHANGE_QUERY = TRUE THEN begin IF TRIM(TEXT) = '' THEN BEGIN T_LABEL.TEXT := ''; EXIT; //空字符串不做任何操作 END; T_LABEL.TEXT := FIND_QUERY_IDNO(TEXT); end; inherited CHANGE; END; procedure JDBLOOKUPBOX.DoEnter; BEGIN // 产生 MESSAGE 窗口 IF (FSHOW_MESSAGE = TRUE) THEN BEGIN FMLOOKUPM.Left := SCREEN.Width - FMLOOKUPM.Width; FMLOOKUPM.Top := SCREEN.Height - FMLOOKUPM.Height; FMLOOKUPM.QSYSLST.SQL.CLEAR; FMLOOKUPM.QSYSLST.SQL.ADD('SELECT * '); FMLOOKUPM.QSYSLST.SQL.ADD('FROM SYSLST '); FMLOOKUPM.QSYSLST.SQL.ADD('WHERE LSTID1 = '''+FINSERT_SYSLST+''''); FMLOOKUPM.QSYSLST.SQL.ADD('ORDER BY LSTID1,LSTID2 '); FMLOOKUPM.QSYSLST.CLOSE; FMLOOKUPM.QSYSLST.OPEN; SETFOCUS; END; REFRESH_EDIT; inherited; END; procedure JDBLOOKUPBOX.DoExit; BEGIN // 结束 MESSAGE 窗口 IF (FSHOW_MESSAGE = TRUE) THEN BEGIN FMLOOKUPM.Left := SCREEN.Width +1000; FMLOOKUPM.Top := SCREEN.Height +1000; END; REFRESH_EDIT; IF FIND_QUERY_IDNO(TEXT) = '' THEN BEGIN DataSource.DataSet.Edit; DataSource.DataSet.FieldByName(DataField).AsString := ''; END; inherited; END; FUNCTION JDBLOOKUPBOX.FIND_QUERY_IDNO(T_STR:STRING):STRING; BEGIN RESULT := ''; //空字符串不做任何操作 // IF TRIM(T_STR) = '' THEN EXIT; T_DATASOURCE.DataSet := T_QCHECK; T_QCHECK.DatabaseName := _DatabaseName; TRY T_QCHECK.SQL.CLEAR; T_QCHECK.SQL.Add('SELECT '+_Field_IDNO+','+_Field_NAME); T_QCHECK.SQL.Add('FROM '+_TableNAME); T_QCHECK.SQL.Add('WHERE '+_Field_IDNO+' = '''+T_STR+''''); IF TRIM(_Field_KEY1) <> '' THEN T_QCHECK.SQL.Add('AND '+_Field_KEY1+' = '''+_Field_KEY2+''''); T_QCHECK.Close; T_QCHECK.Open; EXCEPT // SHOWMESSAGE('数据库无法打开, 数据源可能设置错误!'); END; IF T_QCHECK.Eof = FALSE THEN RESULT := T_QCHECK.FieldByName(_Field_NAME).AsString ELSE RESULT := ''; END; FUNCTION JDBLOOKUPBOX.FIND_QUERY_NAME(T_STR:STRING):STRING; BEGIN RESULT := ''; T_DATASOURCE.DataSet := T_QCHECK; T_QCHECK.DatabaseName := _DatabaseName; TRY T_QCHECK.SQL.CLEAR; T_QCHECK.SQL.Add('SELECT '+_Field_IDNO+','+_Field_NAME); T_QCHECK.SQL.Add('FROM '+_TableNAME); T_QCHECK.SQL.Add('WHERE '+_Field_NAME+' = '''+T_STR+''''); IF TRIM(_Field_KEY1) <> '' THEN T_QCHECK.SQL.Add('AND '+_Field_KEY1+' = '''+_Field_KEY2+''''); T_QCHECK.Close; T_QCHECK.Open; EXCEPT // SHOWMESSAGE('数据库无法打开, 数据源可能设置错误!'); END; IF T_QCHECK.Eof = FALSE THEN RESULT := T_QCHECK.FieldByName(_Field_IDNO).AsString ELSE RESULT := ''; END; FUNCTION JDBLOOKUPBOX.FIND_QUERY_MARK(T_STR:STRING):STRING; BEGIN RESULT := ''; T_DATASOURCE.DataSet := T_QCHECK; T_QCHECK.DatabaseName := _DatabaseName; TRY T_QCHECK.SQL.CLEAR; T_QCHECK.SQL.Add('SELECT '+_Field_IDNO+','+_Field_NAME+','+_Field_MARK); T_QCHECK.SQL.Add('FROM '+_TableNAME); T_QCHECK.SQL.Add('WHERE '+_Field_MARK+' = '''+T_STR+''''); IF TRIM(_Field_KEY1) <> '' THEN T_QCHECK.SQL.Add('AND '+_Field_KEY1+' = '''+_Field_KEY2+''''); T_QCHECK.Close; T_QCHECK.Open; EXCEPT // SHOWMESSAGE('数据库无法打开, 数据源可能设置错误!'); END; IF T_QCHECK.Eof = FALSE THEN RESULT := T_QCHECK.FieldByName(_Field_IDNO).AsString ELSE RESULT := ''; END; FUNCTION JDBLOOKUPBOX.FIND_GRID_IDNO(T_STR:STRING):BOOLEAN; BEGIN RESULT := FALSE; TRY T_DATASOURCE.DataSet := T_QCHECK; T_QCHECK.DatabaseName := _DatabaseName; T_QCHECK.SQL.CLEAR; T_QCHECK.SQL.Add('SELECT '+_Field_IDNO+','+_Field_NAME); T_QCHECK.SQL.Add('FROM '+_TableNAME); T_QCHECK.SQL.Add('WHERE '+_Field_IDNO+' LIKE ''%'+T_STR+'%'''); IF TRIM(_Field_KEY1) <> '' THEN T_QCHECK.SQL.Add('AND '+_Field_KEY1+' = '''+_Field_KEY2+''''); T_QCHECK.SQL.Add('ORDER BY '+_Field_IDNO+','+_Field_NAME); T_QCHECK.Close; T_QCHECK.Open; EXCEPT // SHOWMESSAGE('数据库无法打开, 数据源可能设置错误!'); END; IF T_QCHECK.Eof = FALSE THEN RESULT := TRUE ELSE RESULT := FALSE; END; FUNCTION JDBLOOKUPBOX.FIND_GRID_NAME(T_STR:STRING):BOOLEAN; BEGIN RESULT := FALSE; TRY T_DATASOURCE.DataSet := T_QCHECK; T_QCHECK.DatabaseName := _DatabaseName; T_QCHECK.SQL.CLEAR; T_QCHECK.SQL.Add('SELECT '+_Field_IDNO+','+_Field_NAME); T_QCHECK.SQL.Add('FROM '+_TableNAME); T_QCHECK.SQL.Add('WHERE '+_Field_NAME+' LIKE ''%'+T_STR+'%'''); IF TRIM(_Field_KEY1) <> '' THEN T_QCHECK.SQL.Add('AND '+_Field_KEY1+' = '''+_Field_KEY2+''''); T_QCHECK.SQL.Add('ORDER BY '+_Field_IDNO+','+_Field_NAME); T_QCHECK.Close; T_QCHECK.Open; EXCEPT // SHOWMESSAGE('数据库无法打开, 数据源可能设置错误!'); END; IF T_QCHECK.Eof = FALSE THEN RESULT := TRUE ELSE RESULT := FALSE; END; FUNCTION JDBLOOKUPBOX.FIND_GRID_MARK(T_STR:STRING):BOOLEAN; BEGIN RESULT := FALSE; TRY T_DATASOURCE.DataSet := T_QCHECK; T_QCHECK.DatabaseName := _DatabaseName; T_QCHECK.SQL.CLEAR; T_QCHECK.SQL.Add('SELECT '+_Field_IDNO+','+_Field_NAME+','+_Field_MARK); T_QCHECK.SQL.Add('FROM '+_TableNAME); T_QCHECK.SQL.Add('WHERE '+_Field_MARK+' LIKE ''%'+T_STR+'%'''); IF TRIM(_Field_KEY1) <> '' THEN T_QCHECK.SQL.Add('AND '+_Field_KEY1+' = '''+_Field_KEY2+''''); T_QCHECK.SQL.Add('ORDER BY '+_Field_MARK+','+_Field_NAME); T_QCHECK.Close; T_QCHECK.Open; EXCEPT // SHOWMESSAGE('数据库无法打开, 数据源可能设置错误!'); END; IF T_QCHECK.Eof = FALSE THEN RESULT := TRUE ELSE RESULT := FALSE; END; FUNCTION JDBLOOKUPBOX.CALL_FMLOOKUP_IDNO:STRING; BEGIN IF Application.FindComponent('FMLOOKUP')=nil then Application.CreateForm(TFMLOOKUP, FMLOOKUP ); FMLOOKUP.Left := SCREEN.Width - FMLOOKUP.Width; FMLOOKUP.Q_DatabaseName := _DatabaseName; FMLOOKUP.Q_TableNAME := _TableNAME; FMLOOKUP.Q_IDNO := _Field_IDNO; FMLOOKUP.Q_NAME := _Field_NAME; FMLOOKUP.Q_KEY1 := _Field_KEY1; FMLOOKUP.Q_KEY2 := _Field_KEY2; FMLOOKUP.ED_IDNO.TEXT := TEXT; FMLOOKUP.ED_NAME.TEXT := TEXT; FMLOOKUP.FIND_QUERY_IDNO(FMLOOKUP.ED_IDNO.TEXT); FMLOOKUP.DBGRID1.Visible := TRUE; FMLOOKUP.SHOWMODAL; DataSource.DataSet.Edit; TEXT := FMLOOKUP.Q_RETURN_IDNO; RESULT := TEXT; END; FUNCTION JDBLOOKUPBOX.CALL_FMLOOKUP_NAME:STRING; BEGIN IF Application.FindComponent('FMLOOKUP')=nil then Application.CreateForm(TFMLOOKUP, FMLOOKUP ); FMLOOKUP.Left := SCREEN.Width - FMLOOKUP.Width; FMLOOKUP.Q_DatabaseName := _DatabaseName; FMLOOKUP.Q_TableNAME := _TableNAME; FMLOOKUP.Q_IDNO := _Field_IDNO; FMLOOKUP.Q_NAME := _Field_NAME; FMLOOKUP.Q_KEY1 := _Field_KEY1; FMLOOKUP.Q_KEY2 := _Field_KEY2; FMLOOKUP.ED_IDNO.TEXT := TEXT; FMLOOKUP.ED_NAME.TEXT := TEXT; FMLOOKUP.FIND_QUERY_NAME(FMLOOKUP.ED_NAME.TEXT); FMLOOKUP.DBGRID1.Visible := TRUE; FMLOOKUP.SHOWMODAL; DataSource.DataSet.Edit; TEXT := FMLOOKUP.Q_RETURN_IDNO; RESULT := TEXT; END; FUNCTION JDBLOOKUPBOX.CALL_FMLOOKUP_MARK:STRING; BEGIN IF Application.FindComponent('FMLOOKUP')=nil then Application.CreateForm(TFMLOOKUP, FMLOOKUP ); FMLOOKUP.Left := SCREEN.Width - FMLOOKUP.Width; FMLOOKUP.Q_DatabaseName := _DatabaseName; FMLOOKUP.Q_TableNAME := _TableNAME; FMLOOKUP.Q_IDNO := _Field_IDNO; FMLOOKUP.Q_NAME := _Field_NAME; FMLOOKUP.Q_MARK := _Field_MARK; FMLOOKUP.Q_KEY1 := _Field_KEY1; FMLOOKUP.Q_KEY2 := _Field_KEY2; FMLOOKUP.ED_IDNO.TEXT := TEXT; FMLOOKUP.ED_NAME.TEXT := TEXT; FMLOOKUP.ED_MARK.TEXT := TEXT; FMLOOKUP.FIND_QUERY_MARK(FMLOOKUP.ED_MARK.TEXT); FMLOOKUP.DBGRID2.Visible := TRUE; FMLOOKUP.SHOWMODAL; DataSource.DataSet.Edit; TEXT := FMLOOKUP.Q_RETURN_IDNO; RESULT := TEXT; END; FUNCTION JDBLOOKUPBOX.LABEL_CALL_FMLOOKUP_IDNO:STRING; BEGIN IF Application.FindComponent('FMLOOKUP')=nil then Application.CreateForm(TFMLOOKUP, FMLOOKUP ); FMLOOKUP.Left := SCREEN.Width - FMLOOKUP.Width; FMLOOKUP.Q_DatabaseName := _DatabaseName; FMLOOKUP.Q_TableNAME := _TableNAME; FMLOOKUP.Q_IDNO := _Field_IDNO; FMLOOKUP.Q_NAME := _Field_NAME; FMLOOKUP.Q_KEY1 := _Field_KEY1; FMLOOKUP.Q_KEY2 := _Field_KEY2; FMLOOKUP.ED_IDNO.TEXT := TEXT; FMLOOKUP.ED_NAME.TEXT := TEXT; FMLOOKUP.FOCUS_QUERY_IDNO(FMLOOKUP.ED_IDNO.TEXT); FMLOOKUP.DBGRID1.Visible := TRUE; FMLOOKUP.SHOWMODAL; DataSource.DataSet.Edit; TEXT := FMLOOKUP.Q_RETURN_IDNO; RESULT := TEXT; END; // LABEL =============================================================== procedure JDBLOOKUPBOX.T_LABELCLICK(SENDER:TOBJECT); BEGIN // IF (_Field_MARK = '') THEN LABEL_CALL_FMLOOKUP_IDNO; SetFocus; LABEL_CALL_FMLOOKUP_IDNO; IF FIND_GRID_IDNO(TEXT) = FALSE THEN SetFocus; //找不到 END; PROCEDURE JDBLOOKUPBOX.REFRESH_EDIT; BEGIN // Height := FCLOSE_HEIGHT; T_LABEL.Ctl3D := FALSE; T_LABEL.Font := FONT; T_LABEL.Font.Size := FONT.Size; T_LABEL.Font.Color := CLBLUE; T_LABEL.Color := $00FFF5EC; T_LABEL.Top := 0; T_LABEL.Height := Height; T_LABEL.Left := _EDIT_WIDTH; T_LABEL.Width := WIDTH - T_LABEL.Left; END; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, WinInet, shellapi, ExtCtrls, ComCtrls, Alcinoe.HTTP.Client.WinINet, cxPCdxBarPopupMenu, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, Menus, cxRadioGroup, cxCheckBox, cxButtons, cxMemo, cxTextEdit, cxLabel, cxGroupBox, cxPC, dxSkinsCore, dxSkinFoggy, dxSkinscxPCPainter, dxSkinsForm, cxSplitter, cxClasses, dxBarBuiltInMenu, Alcinoe.StringUtils, system.AnsiStrings, dxCore; type TForm1 = class(TForm) MainStatusBar: TStatusBar; PageControl1: TcxPageControl; TabSheet1: TcxTabSheet; TabSheet2: TcxTabSheet; GroupBox3: TcxGroupBox; Label18: TcxLabel; Label19: TcxLabel; EditUserName: TcxTextEdit; EditPassword: TcxTextEdit; GroupBox4: TcxGroupBox; Label14: TcxLabel; Label17: TcxLabel; Label20: TcxLabel; EditSendTimeout: TcxTextEdit; EditReceiveTimeout: TcxTextEdit; EditConnectTimeout: TcxTextEdit; GroupBox6: TcxGroupBox; GroupBox7: TcxGroupBox; GroupBox2: TcxGroupBox; RadioButtonAccessType_Direct: TcxRadioButton; RadioButtonAccessType_Preconfig: TcxRadioButton; RadioButtonAccessType_Preconfig_with_no_autoproxy: TcxRadioButton; RadioButtonAccessType_Proxy: TcxRadioButton; GroupBox1: TcxGroupBox; Label15: TcxLabel; Label12: TcxLabel; Label11: TcxLabel; Label16: TcxLabel; Label13: TcxLabel; EdProxyPort: TcxTextEdit; EdProxyUserName: TcxTextEdit; EdProxyServer: TcxTextEdit; EdProxyPassword: TcxTextEdit; EdProxyBypass: TcxTextEdit; GroupBox5: TcxGroupBox; Label24: TcxLabel; EditBufferUploadSize: TcxTextEdit; CheckBoxInternetOption_From_Cache: TcxCheckBox; CheckBoxInternetOption_Offline: TcxCheckBox; CheckBoxInternetOption_Keep_connection: TcxCheckBox; CheckBoxInternetOption_No_auto_redirect: TcxCheckBox; CheckBoxInternetOption_Ignore_redirect_to_https: TcxCheckBox; CheckBoxInternetOption_No_auth: TcxCheckBox; CheckBoxInternetOption_Ignore_cert_date_invalid: TcxCheckBox; CheckBoxInternetOption_Need_file: TcxCheckBox; CheckBoxInternetOption_Ignore_redirect_to_http: TcxCheckBox; CheckBoxInternetOption_Hyperlink: TcxCheckBox; CheckBoxInternetOption_Ignore_cert_cn_invalid: TcxCheckBox; CheckBoxInternetOption_Cache_if_net_fail: TcxCheckBox; CheckBoxInternetOption_No_cache_write: TcxCheckBox; CheckBoxInternetOption_Resynchronize: TcxCheckBox; CheckBoxInternetOption_No_cookies: TcxCheckBox; CheckBoxInternetOption_Pragma_nocache: TcxCheckBox; CheckBoxInternetOption_Reload: TcxCheckBox; CheckBoxInternetOption_No_ui: TcxCheckBox; CheckBoxInternetOption_Secure: TcxCheckBox; GroupBox8: TcxGroupBox; MemoRequestRawHeader: TcxMemo; Label8: TcxLabel; RadioButtonProtocolVersion1_0: TcxRadioButton; RadioButtonProtocolVersion1_1: TcxRadioButton; GroupBox9: TcxGroupBox; editURL: TcxTextEdit; Label4: TcxLabel; MemoPostDataStrings: TcxMemo; MemoPostDataFiles: TcxMemo; Label7: TcxLabel; Label5: TcxLabel; GroupBox10: TcxGroupBox; Label1: TcxLabel; ButtonPost: TcxButton; ButtonGet: TcxButton; ButtonHead: TcxButton; CheckBoxUrlEncodePostData: TcxCheckBox; ButtonTrace: TcxButton; dxSkinController1: TdxSkinController; Panel3: TPanel; Panel5: TPanel; Panel6: TPanel; Label2: TcxLabel; MemoResponseRawHeader: TcxMemo; cxSplitter1: TcxSplitter; Label3: TcxLabel; MemoContentBody: TcxMemo; cxSplitter2: TcxSplitter; ButtonOptions: TcxButton; ButtonPut: TcxButton; ButtonDelete: TcxButton; cxSplitter3: TcxSplitter; ButtonSaveToFile: TcxButton; procedure ButtonGetClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ButtonPostClick(Sender: TObject); procedure ButtonHeadClick(Sender: TObject); procedure ButtonTraceClick(Sender: TObject); procedure OnCfgEditCHange(Sender: TObject); procedure OnCfgEditKeyPress(Sender: TObject; var Key: Char); procedure ButtonOptionsClick(Sender: TObject); procedure ButtonPutClick(Sender: TObject); procedure ButtonDeleteClick(Sender: TObject); procedure ButtonSaveToFileClick(Sender: TObject); private FWinInetHttpClient: TalWinInetHttpClient; FDownloadSpeedStartTime: TdateTime; FDownloadSpeedBytesRead: Integer; FDownloadSpeedBytesNotRead: Integer; fMustInitWinHTTP: Boolean; FHTTPResponseStream: TALStringStreamA; procedure initWinInetHTTPClient; function AnsiStrTo8bitUnicodeString(s: AnsiString): String; public procedure OnHttpClientStatus(sender: Tobject; InternetStatus: DWord; StatusInformation: Pointer; StatusInformationLength: DWord); procedure OnHttpClientDownloadProgress(sender: Tobject; Read: Integer; Total: Integer); procedure OnHttpClientUploadProgress(sender: Tobject; Sent: Integer; Total: Integer); end; var Form1: TForm1; implementation Uses DateUtils, HttpApp, Alcinoe.MultiPartParser, Alcinoe.Common, Alcinoe.Files, Alcinoe.Mime, Alcinoe.StringList, Alcinoe.HTTP.Client; {$R *.dfm} {*************************************} procedure TForm1.initWinInetHTTPClient; Begin if not fMustInitWinHTTP then exit; fMustInitWinHTTP := False; With FWinInetHTTPClient do begin UserName := AnsiString(EditUserName.Text); Password := AnsiString(EditPassword.Text); if AlIsInteger(AnsiString(EditConnectTimeout.Text)) then ConnectTimeout := StrToInt(EditConnectTimeout.Text); if AlIsInteger(AnsiString(EditsendTimeout.Text)) then SendTimeout := StrToInt(EditSendTimeout.Text); if AlIsInteger(AnsiString(EditReceiveTimeout.Text)) then ReceiveTimeout := StrToInt(EditReceiveTimeout.Text); if RadioButtonProtocolVersion1_0.Checked then ProtocolVersion := TALHTTPProtocolVersion.v1_0 else ProtocolVersion := TALHTTPProtocolVersion.v1_1; if AlIsInteger(AnsiString(EditBufferUploadSize.Text)) then UploadBufferSize := StrToInt(EditBufferUploadSize.Text); ProxyParams.ProxyServer := AnsiString(EdProxyServer.Text); ProxyParams.ProxyPort := StrToInt(EdProxyPort.Text); ProxyParams.ProxyUserName := AnsiString(EdProxyUserName.Text); ProxyParams.ProxyPassword := AnsiString(EdProxyPassword.Text); ProxyParams.ProxyBypass := AnsiString(EdProxyBypass.Text); if RadioButtonAccessType_Direct.Checked then AccessType := wHttpAt_Direct else if RadioButtonAccessType_Preconfig.Checked then AccessType := wHttpAt_Preconfig else if RadioButtonAccessType_Preconfig_with_no_autoproxy.Checked then AccessType := wHttpAt_Preconfig_with_no_autoproxy else if RadioButtonAccessType_Proxy.Checked then AccessType := wHttpAt_Proxy; InternetOptions := []; If CheckBoxInternetOption_From_Cache.checked then InternetOptions := InternetOptions + [wHttpIo_From_Cache]; If CheckBoxInternetOption_Offline.checked then InternetOptions := InternetOptions + [wHttpIo_Offline]; If CheckBoxInternetOption_Cache_if_net_fail.checked then InternetOptions := InternetOptions + [wHttpIo_Cache_if_net_fail]; If CheckBoxInternetOption_Hyperlink.checked then InternetOptions := InternetOptions + [wHttpIo_Hyperlink]; If CheckBoxInternetOption_Ignore_cert_cn_invalid.checked then InternetOptions := InternetOptions + [wHttpIo_Ignore_cert_cn_invalid]; If CheckBoxInternetOption_Ignore_cert_date_invalid.checked then InternetOptions := InternetOptions + [wHttpIo_Ignore_cert_date_invalid]; If CheckBoxInternetOption_Ignore_redirect_to_http.checked then InternetOptions := InternetOptions + [wHttpIo_Ignore_redirect_to_http]; If CheckBoxInternetOption_Ignore_redirect_to_https.checked then InternetOptions := InternetOptions + [wHttpIo_Ignore_redirect_to_https]; If CheckBoxInternetOption_Keep_connection.checked then InternetOptions := InternetOptions + [wHttpIo_Keep_connection]; If CheckBoxInternetOption_Need_file.checked then InternetOptions := InternetOptions + [wHttpIo_Need_file]; If CheckBoxInternetOption_No_auth.checked then InternetOptions := InternetOptions + [wHttpIo_No_auth]; If CheckBoxInternetOption_No_auto_redirect.checked then InternetOptions := InternetOptions + [wHttpIo_No_auto_redirect]; If CheckBoxInternetOption_No_cache_write.checked then InternetOptions := InternetOptions + [wHttpIo_No_cache_write]; If CheckBoxInternetOption_No_cookies.checked then InternetOptions := InternetOptions + [wHttpIo_No_cookies]; If CheckBoxInternetOption_No_ui.checked then InternetOptions := InternetOptions + [wHttpIo_No_ui]; If CheckBoxInternetOption_Pragma_nocache.checked then InternetOptions := InternetOptions + [wHttpIo_Pragma_nocache]; If CheckBoxInternetOption_Reload.checked then InternetOptions := InternetOptions + [wHttpIo_Reload]; If CheckBoxInternetOption_Resynchronize.checked then InternetOptions := InternetOptions + [wHttpIo_Resynchronize]; If CheckBoxInternetOption_Secure.checked then InternetOptions := InternetOptions + [wHttpIo_Secure]; RequestHeader.RawHeaderText := AnsiString(MemoRequestRawHeader.Text); end; end; {****************************************************************} function TForm1.AnsiStrTo8bitUnicodeString(s: AnsiString): String; var i: integer; begin Setlength(Result, length(s)); for I := 1 to length(s) do result[I] := Char(s[i]); end; {**********************************} procedure TForm1.OnHttpClientStatus( Sender: Tobject; InternetStatus: DWord; StatusInformation: Pointer; StatusInformationLength: DWord); var StatusStr: AnsiString; begin case InternetStatus of INTERNET_STATUS_RESOLVING_NAME: StatusStr := 'Resolving name'; INTERNET_STATUS_NAME_RESOLVED: StatusStr := 'Name resolved'; INTERNET_STATUS_CONNECTING_TO_SERVER: StatusStr := 'Connecting to server'; INTERNET_STATUS_CONNECTED_TO_SERVER: StatusStr := 'Connected'; INTERNET_STATUS_SENDING_REQUEST: StatusStr := 'Sending Request'; INTERNET_STATUS_REQUEST_SENT: StatusStr := 'Request sent'; INTERNET_STATUS_RECEIVING_RESPONSE: StatusStr := 'Receiving response'; INTERNET_STATUS_RESPONSE_RECEIVED: StatusStr := 'Response received'; INTERNET_STATUS_CTL_RESPONSE_RECEIVED: StatusStr := 'CTL Response received'; INTERNET_STATUS_PREFETCH: StatusStr := 'Prefetch'; INTERNET_STATUS_CLOSING_CONNECTION: StatusStr := 'Closing connection'; INTERNET_STATUS_CONNECTION_CLOSED: StatusStr := 'Connection closed'; INTERNET_STATUS_HANDLE_CREATED: StatusStr := 'Handle created'; INTERNET_STATUS_HANDLE_CLOSING: StatusStr := 'Handle closing'; INTERNET_STATUS_REQUEST_COMPLETE: StatusStr := 'Request complete'; INTERNET_STATUS_REDIRECT: StatusStr := 'Redirect'; INTERNET_STATUS_INTERMEDIATE_RESPONSE: StatusStr := 'Intermediate response'; INTERNET_STATUS_STATE_CHANGE: StatusStr := 'State change'; INTERNET_STATUS_COOKIE_SENT: StatusStr := 'COOKIE SENT'; INTERNET_STATUS_COOKIE_RECEIVED: StatusStr := 'COOKIE RECEIVED'; INTERNET_STATUS_PRIVACY_IMPACTED: StatusStr := 'PRIVACY IMPACTED'; INTERNET_STATUS_P3P_HEADER: StatusStr := 'P3P HEADER'; INTERNET_STATUS_P3P_POLICYREF: StatusStr := 'P3P POLICYREF'; INTERNET_STATUS_COOKIE_HISTORY: StatusStr := 'COOKIE HISTORY'; else StatusStr := 'Unknown status: ' + ALIntToStrA(InternetStatus); end; MainStatusBar.Panels[0].Text := String(StatusStr); application.ProcessMessages; end; {***********************************************************************************} procedure TForm1.OnHttpClientDownloadProgress(sender: Tobject; Read, Total: Integer); Var In1, In2: integer; begin if MainStatusBar.Panels[1].Text = '' then Begin FDownloadSpeedStartTime := now; FDownloadSpeedBytesNotRead := Read; End; FDownloadSpeedBytesRead := Read; MainStatusBar.Panels[1].Text := 'Read '+IntToStr(read) + ' bytes of '+IntToStr(total) + ' bytes'; in1 := FDownloadSpeedBytesRead - FDownloadSpeedBytesNotRead; in2 := MillisecondsBetween(now, FDownloadSpeedStartTime); if (in1 > 0) and (in2 > 0) then MainStatusBar.Panels[2].Text := 'Download speed: '+ IntToStr(Round((in1 / 1000) / (in2 / 1000))) +'kbps'; application.ProcessMessages; end; {*********************************************************************************} procedure TForm1.OnHttpClientUploadProgress(sender: Tobject; Sent, Total: Integer); begin MainStatusBar.Panels[1].Text := 'Send '+IntToStr(sent) + ' bytes of '+IntToStr(total) + ' bytes'; application.ProcessMessages; end; {**************************************************} procedure TForm1.ButtonDeleteClick(Sender: TObject); Var AHTTPResponseHeader: TALHTTPResponseHeader; begin MainStatusBar.Panels[0].Text := ''; MainStatusBar.Panels[1].Text := ''; MainStatusBar.Panels[2].Text := ''; initWinInetHTTPClient; MemoContentBody.Lines.Clear; MemoResponseRawHeader.Lines.Clear; AHTTPResponseHeader := TALHTTPResponseHeader.Create; try fHTTPResponseStream.Size := 0; try FWinInetHttpClient.Delete(AnsiString(editURL.Text), FHTTPResponseStream, AHTTPResponseHeader); MemoContentBody.Lines.Text := AnsiStrTo8bitUnicodeString(FHTTPResponseStream.DataString); MemoResponseRawHeader.Lines.Text := AnsiStrTo8bitUnicodeString(AHTTPResponseHeader.RawHeaderText); except MemoContentBody.Lines.Text := AnsiStrTo8bitUnicodeString(FHTTPResponseStream.DataString); MemoResponseRawHeader.Lines.Text := AnsiStrTo8bitUnicodeString(AHTTPResponseHeader.RawHeaderText); Raise; end; finally AHTTPResponseHeader.Free; end; end; {***********************************************} procedure TForm1.ButtonGetClick(Sender: TObject); Var AHTTPResponseHeader: TALHTTPResponseHeader; begin MainStatusBar.Panels[0].Text := ''; MainStatusBar.Panels[1].Text := ''; MainStatusBar.Panels[2].Text := ''; initWinInetHTTPClient; MemoContentBody.Lines.Clear; MemoResponseRawHeader.Lines.Clear; AHTTPResponseHeader := TALHTTPResponseHeader.Create; try fHTTPResponseStream.Size := 0; try FWinInetHttpClient.Get(AnsiString(editURL.Text), FHTTPResponseStream, AHTTPResponseHeader); MemoContentBody.Lines.Text := AnsiStrTo8bitUnicodeString(FHTTPResponseStream.DataString); MemoResponseRawHeader.Lines.Text := AnsiStrTo8bitUnicodeString(AHTTPResponseHeader.RawHeaderText); except MemoContentBody.Lines.Text := AnsiStrTo8bitUnicodeString(FHTTPResponseStream.DataString); MemoResponseRawHeader.Lines.Text := AnsiStrTo8bitUnicodeString(AHTTPResponseHeader.RawHeaderText); Raise; end; finally AHTTPResponseHeader.Free; end; end; {********************************************} procedure TForm1.FormDestroy(Sender: TObject); begin FWinInetHttpClient.Free; fHTTPResponseStream.Free; end; {************************************************} procedure TForm1.ButtonHeadClick(Sender: TObject); Var AHTTPResponseHeader: TALHTTPResponseHeader; begin MainStatusBar.Panels[0].Text := ''; MainStatusBar.Panels[1].Text := ''; MainStatusBar.Panels[2].Text := ''; initWinInetHTTPClient; MemoContentBody.Lines.Clear; MemoResponseRawHeader.Lines.Clear; AHTTPResponseHeader := TALHTTPResponseHeader.Create; try fHTTPResponseStream.Size := 0; try FWinInetHttpClient.Head(AnsiString(editURL.Text), FHTTPResponseStream, AHTTPResponseHeader); MemoContentBody.Lines.Text := AnsiStrTo8bitUnicodeString(FHTTPResponseStream.DataString); MemoResponseRawHeader.Lines.Text := AnsiStrTo8bitUnicodeString(AHTTPResponseHeader.RawHeaderText); except MemoContentBody.Lines.Text := AnsiStrTo8bitUnicodeString(FHTTPResponseStream.DataString); MemoResponseRawHeader.Lines.Text := AnsiStrTo8bitUnicodeString(AHTTPResponseHeader.RawHeaderText); Raise; end; finally AHTTPResponseHeader.Free; end; end; {***************************************************} procedure TForm1.ButtonOptionsClick(Sender: TObject); Var AHTTPResponseHeader: TALHTTPResponseHeader; begin MainStatusBar.Panels[0].Text := ''; MainStatusBar.Panels[1].Text := ''; MainStatusBar.Panels[2].Text := ''; initWinInetHTTPClient; MemoContentBody.Lines.Clear; MemoResponseRawHeader.Lines.Clear; AHTTPResponseHeader := TALHTTPResponseHeader.Create; try fHTTPResponseStream.Size := 0; try FWinInetHttpClient.Options(AnsiString(editURL.Text), FHTTPResponseStream, AHTTPResponseHeader); MemoContentBody.Lines.Text := AnsiStrTo8bitUnicodeString(FHTTPResponseStream.DataString); MemoResponseRawHeader.Lines.Text := AnsiStrTo8bitUnicodeString(AHTTPResponseHeader.RawHeaderText); except MemoContentBody.Lines.Text := AnsiStrTo8bitUnicodeString(FHTTPResponseStream.DataString); MemoResponseRawHeader.Lines.Text := AnsiStrTo8bitUnicodeString(AHTTPResponseHeader.RawHeaderText); Raise; end; finally AHTTPResponseHeader.Free; end; end; {*************************************************} procedure TForm1.ButtonTraceClick(Sender: TObject); Var AHTTPResponseHeader: TALHTTPResponseHeader; begin MainStatusBar.Panels[0].Text := ''; MainStatusBar.Panels[1].Text := ''; MainStatusBar.Panels[2].Text := ''; initWinInetHTTPClient; MemoContentBody.Lines.Clear; MemoResponseRawHeader.Lines.Clear; AHTTPResponseHeader := TALHTTPResponseHeader.Create; try fHTTPResponseStream.Size := 0; try FWinInetHttpClient.Trace(AnsiString(editURL.Text), FHTTPResponseStream, AHTTPResponseHeader); MemoContentBody.Lines.Text := AnsiStrTo8bitUnicodeString(FHTTPResponseStream.DataString); MemoResponseRawHeader.Lines.Text := AnsiStrTo8bitUnicodeString(AHTTPResponseHeader.RawHeaderText); except MemoContentBody.Lines.Text := AnsiStrTo8bitUnicodeString(FHTTPResponseStream.DataString); MemoResponseRawHeader.Lines.Text := AnsiStrTo8bitUnicodeString(AHTTPResponseHeader.RawHeaderText); Raise; end; finally AHTTPResponseHeader.Free; end; end; {************************************************} procedure TForm1.OnCfgEditCHange(Sender: TObject); begin fMustInitWinHTTP := True; end; {*****************************************************************} procedure TForm1.OnCfgEditKeyPress(Sender: TObject; var Key: Char); begin fMustInitWinHTTP := True; end; {************************************************} procedure TForm1.ButtonPostClick(Sender: TObject); Var AHTTPResponseHeader: TALHTTPResponseHeader; ARawPostDatastream: TALStringStreamA; AMultiPartFormDataFile: TALMultiPartFormDataContent; AMultiPartFormDataFiles: TALMultiPartFormDataContents; aTmpPostDataString: TALStringsA; i: Integer; begin MainStatusBar.Panels[0].Text := ''; MainStatusBar.Panels[1].Text := ''; MainStatusBar.Panels[2].Text := ''; initWinInetHTTPClient; MemoContentBody.Lines.Clear; MemoResponseRawHeader.Lines.Clear; AHTTPResponseHeader := TALHTTPResponseHeader.Create; AMultiPartFormDataFiles := TALMultiPartFormDataContents.Create(true); aTmpPostDataString := TALStringListA.Create; try fHTTPResponseStream.Size := 0; Try aTmpPostDataString.Assign(MemoPostDataStrings.lines); aTmpPostDataString.Text := ansiString(MemoPostDataStrings.Text); // << I don't know yet why but MemoPostDataStrings.lines.count split very long line in severals lines of around 1000 chars For I := 0 To MemoPostDataFiles.Lines.Count - 1 do if MemoPostDataFiles.Lines[i] <> '' then begin AMultiPartFormDataFile := TALMultiPartFormDataContent.Create; TMemoryStream(AMultiPartFormDataFile.DataStream).LoadFromFile(MemoPostDataFiles.Lines.ValueFromIndex[i]); AMultiPartFormDataFile.ContentDisposition := 'form-data; name="'+AnsiString(MemoPostDataFiles.Lines.Names[i])+'"; filename="'+AnsiString(MemoPostDataFiles.Lines.ValueFromIndex[i])+'"'; AMultiPartFormDataFile.ContentType := ALGetDefaultMIMEContentTypeFromExt(ALExtractFileExt(AnsiString(MemoPostDataFiles.Lines.ValueFromIndex[i]))); AMultiPartFormDataFiles.Add(AMultiPartFormDataFile); end; if (AMultiPartFormDataFiles.Count > 0) and (CheckBoxURLEncodePostData.Checked) then FWinInetHttpClient.PostMultiPartFormData( AnsiString(editURL.Text), aTmpPostDataString, AMultiPartFormDataFiles, FHTTPResponseStream, AHTTPResponseHeader) else if (AMultiPartFormDataFiles.Count > 0) then begin FWinInetHttpClient.post( AnsiString(editURL.Text), AMultiPartFormDataFiles.Items[0].DataStream, FHTTPResponseStream, AHTTPResponseHeader); end else if aTmpPostDataString.Count > 0 then begin if CheckBoxURLEncodePostData.Checked then FWinInetHttpClient.PostURLEncoded( AnsiString(editURL.Text), aTmpPostDataString, FHTTPResponseStream, AHTTPResponseHeader, TALNameValueArray.Create(), True) else begin ARawPostDatastream := TALStringStreamA.create(aTmpPostDataString.text); try FWinInetHttpClient.post( AnsiString(editURL.Text), ARawPostDatastream, FHTTPResponseStream, AHTTPResponseHeader); finally ARawPostDatastream.free; end; end end else FWinInetHttpClient.Post( AnsiString(editURL.Text), FHTTPResponseStream, AHTTPResponseHeader); MemoContentBody.Lines.Text := AnsiStrTo8bitUnicodeString(FHTTPResponseStream.DataString); MemoResponseRawHeader.Lines.Text := AnsiStrTo8bitUnicodeString(AHTTPResponseHeader.RawHeaderText); Except MemoContentBody.Lines.Text := AnsiStrTo8bitUnicodeString(FHTTPResponseStream.DataString); MemoResponseRawHeader.Lines.Text := AnsiStrTo8bitUnicodeString(AHTTPResponseHeader.RawHeaderText); Raise; end; finally AHTTPResponseHeader.Free; AMultiPartFormDataFiles.Free; aTmpPostDataString.free; end; end; {***********************************************} procedure TForm1.ButtonPutClick(Sender: TObject); Var AHTTPResponseHeader: TALHTTPResponseHeader; ARawPutDatastream: TALStringStreamA; AMultiPartFormDataFile: TALMultiPartFormDataContent; AMultiPartFormDataFiles: TALMultiPartFormDataContents; aTmpPutDataString: TALStringsA; i: Integer; begin MainStatusBar.Panels[0].Text := ''; MainStatusBar.Panels[1].Text := ''; MainStatusBar.Panels[2].Text := ''; initWinInetHTTPClient; MemoContentBody.Lines.Clear; MemoResponseRawHeader.Lines.Clear; AHTTPResponseHeader := TALHTTPResponseHeader.Create; AMultiPartFormDataFiles := TALMultiPartFormDataContents.Create(true); aTmpPutDataString := TALStringListA.Create; try fHTTPResponseStream.Size := 0; Try aTmpPutDataString.Assign(MemoPostDataStrings.lines); aTmpPutDataString.Text := ansiString(MemoPostDataStrings.Text); // << I don't know yet why but MemoPostDataStrings.lines.count split very long line in severals lines of around 1000 chars For I := 0 To MemoPostDataFiles.Lines.Count - 1 do if MemoPostDataFiles.Lines[i] <> '' then begin AMultiPartFormDataFile := TALMultiPartFormDataContent.Create; TMemoryStream(AMultiPartFormDataFile.DataStream).LoadFromFile(MemoPostDataFiles.Lines.ValueFromIndex[i]); AMultiPartFormDataFile.ContentDisposition := 'form-data; name="'+AnsiString(MemoPostDataFiles.Lines.Names[i])+'"; filename="'+AnsiString(MemoPostDataFiles.Lines.ValueFromIndex[i])+'"'; AMultiPartFormDataFile.ContentType := ALGetDefaultMIMEContentTypeFromExt(ALExtractFileExt(AnsiString(MemoPostDataFiles.Lines.ValueFromIndex[i]))); AMultiPartFormDataFiles.Add(AMultiPartFormDataFile); end; //if (AMultiPartFormDataFiles.Count > 0) and (CheckBoxURLEncodePostData.Checked) then // FWinInetHttpClient.PutMultiPartFormData(AnsiString(editURL.Text), // aTmpPutDataString, // AMultiPartFormDataFiles, // FHTTPResponseStream, // AHTTPResponseHeader) if (AMultiPartFormDataFiles.Count > 0) then begin FWinInetHttpClient.Put( AnsiString(editURL.Text), AMultiPartFormDataFiles.Items[0].DataStream, FHTTPResponseStream, AHTTPResponseHeader); end else if aTmpPutDataString.Count > 0 then begin //if CheckBoxURLEncodePostData.Checked then FWinInetHttpClient.PutURLEncoded(AnsiString(editURL.Text), // aTmpPutDataString, // FHTTPResponseStream, // AHTTPResponseHeader, // TALNameValueArray.Create(), // True) //else begin ARawPutDatastream := TALStringStreamA.create(aTmpPutDataString.text); try FWinInetHttpClient.Put( AnsiString(editURL.Text), ARawPutDatastream, FHTTPResponseStream, AHTTPResponseHeader); finally ARawPutDatastream.free; end; //end end else FWinInetHttpClient.Put( AnsiString(editURL.Text), nil, FHTTPResponseStream, AHTTPResponseHeader); MemoContentBody.Lines.Text := AnsiStrTo8bitUnicodeString(FHTTPResponseStream.DataString); MemoResponseRawHeader.Lines.Text := AnsiStrTo8bitUnicodeString(AHTTPResponseHeader.RawHeaderText); Except MemoContentBody.Lines.Text := AnsiStrTo8bitUnicodeString(FHTTPResponseStream.DataString); MemoResponseRawHeader.Lines.Text := AnsiStrTo8bitUnicodeString(AHTTPResponseHeader.RawHeaderText); Raise; end; finally AHTTPResponseHeader.Free; AMultiPartFormDataFiles.Free; aTmpPutDataString.free; end; end; {******************************************************} procedure TForm1.ButtonSaveToFileClick(Sender: TObject); Var LsaveDialog: TSaveDialog; begin LsaveDialog := TSaveDialog.Create(self); Try if LsaveDialog.Execute then ALSaveStringToFile(fHTTPResponseStream.DataString, AnsiString(LsaveDialog.FileName)); Finally LsaveDialog.Free; End; end; {*******************************************} procedure TForm1.FormCreate(Sender: TObject); begin fMustInitWinHTTP := True; FWinInetHttpClient := TaLWinInetHttpClient.Create; fHTTPResponseStream := TALStringStreamA.Create(''); with FWinInetHttpClient do begin AccessType := wHttpAt_Preconfig; InternetOptions := [wHttpIo_Keep_connection]; OnStatus := OnHttpClientStatus; OnDownloadProgress := OnHttpClientDownloadProgress; OnUploadProgress := OnHttpClientUploadProgress; MemoRequestRawHeader.Text := String(RequestHeader.RawHeaderText); end; MemoResponseRawHeader.Height := MemoResponseRawHeader.Parent.Height - MemoResponseRawHeader.top - 6; MemoContentBody.Height := MemoContentBody.Parent.Height - MemoContentBody.top - 6; end; initialization {$IFDEF DEBUG} ReporTMemoryleaksOnSHutdown := True; {$ENDIF} SetMultiByteConversionCodePage(CP_UTF8); end.
unit UnitIODecorator; interface uses InterfaceCrypto, InterfaceIO ; type TIODecorator = class abstract(TInterfacedObject, IIO) // IO decorator procedure WriteString(pValue : String); virtual; abstract; function ReadString: String; virtual; abstract; end; TIOCrypto = class(TIODecorator) private FCrypto : ICrypto; FIO : IIO; public constructor Create(TObject: IIO); destructor Destroy; override; procedure WriteString(pValue : String); override; function ReadString: String; override; end; implementation uses Spring.Container, Spring.Services ; { TIOCrypto } constructor TIOCrypto.Create(TObject: IIO); begin inherited Create; FCrypto := ServiceLocator.GetService<ICrypto>('CryptoAES'); FIO := TObject; end; destructor TIOCrypto.Destroy; begin inherited; end; function TIOCrypto.ReadString: String; begin Result := FCrypto.Decrypt(FIO.ReadString); end; procedure TIOCrypto.WriteString(pValue: String); begin FIO.WriteString(FCrypto.Crypt(pValue)); end; initialization GlobalContainer.RegisterType<TIOCrypto>.Implements<IIO>('IOCrypto').InjectConstructor(['IOFile']); GlobalContainer.Build; end.
unit mpiLasFile; interface uses Classes, mpiDeclaration; type PBuffer = PChar; TTwoValue = record Depth : Float; Kanal : Integer; end; TWellInf = record Start : Float; Stop : Float; Step : Float; Null : Float; Well : String; Field : String; Loc : String; Serv : String; Date : String; end; TLasFile = class private function CheckPresentSeries(aName : String): boolean; procedure Load_VersionInformation(CurStr : String); procedure Load_WellInformation(CurStr : String); procedure Load_ParametrInfomation(CurStr : String); procedure Load_CurveInformation(CurStr : String); public WellInf : TWellInf; FileName : String; CountDataElement : Integer; CalibrationFactor : Boolean; // ---- Прокалибрированная реализация -------- SeriesList : TList; XValue : TSeries; ErrorCounter : Integer; ErrorList : array of TTwoValue; procedure Load(); procedure Save(start, stop : float; aFileName : String); function GetSeries(aName : String):TSeries; constructor create(aFileName : String); destructor destroy; override; end; var LasFile : TLasFile; implementation uses SysUtils, Dialogs, Forms; var Shapka : array of AnsiString; { TLasFile } constructor TLasFile.create(aFileName : String); begin inherited create; SeriesList := TList.Create; FileName := aFileName; end; destructor TLasFile.destroy; var i : integer; begin if SeriesList.Count <> 0 then for i := 0 to SeriesList.Count - 1 do TSeries(SeriesList.Items[i]).Free; SeriesList.Free; inherited destroy; end; //************************************************************************************************************************************* //************************************************************************************************************************************* //************************************************************************************************************************************* //************************************************************************************************************************************* procedure TLasFile.Load_VersionInformation(CurStr : String); begin end; //************************************************************************************************************************************* //************************************************************************************************************************************* //************************************************************************************************************************************* //************************************************************************************************************************************* procedure TLasFile.Load_WellInformation(CurStr : String); function GetFloatValue(InputStr : String; pos : Integer) : Float; var i : integer; ResultString : String; FirstSymbol : Boolean; begin ResultString := ''; FirstSymbol := False; for i := pos to 255 do if (InputStr[i] in ['0'..'9']) or (InputStr[i] = '.') or (InputStr[i] = '-') or (UpperCase(InputStr[i]) = 'E')then begin ResultString := ResultString + InputStr[i]; FirstSymbol := True; end else if FirstSymbol then break; Result := StrToFloat(ResultString);end; function GetTextValue (InputStr : String; pos : Integer) : String; var i : integer; FirstSymbol : Boolean; begin Result := ''; FirstSymbol := False; for i := pos to 255 do begin if InputStr[i] <> ' ' then FirstSymbol := True; if InputStr[i] = ':' then Break; if FirstSymbol then Result := Result + InputStr[i]; end;end; begin if AnsiPos('STRT', CurStr) <> 0 then WellInf.Start := GetFloatValue(CurStr, 12); if AnsiPos('STOP', CurStr) <> 0 then WellInf.Stop := GetFloatValue(CurStr, 12); if AnsiPos('STEP', CurStr) <> 0 then WellInf.Step := GetFloatValue(CurStr, 12); if AnsiPos('NULL', CurStr) <> 0 then WellInf.Null := GetFloatValue(CurStr, 12); if AnsiPos('WELL', CurStr) <> 0 then WellInf.Well := GetTextValue(CurStr, 12); if AnsiPos('FLD', CurStr) <> 0 then WellInf.Field := GetTextValue(CurStr, 12); if AnsiPos('LOC', CurStr) <> 0 then WellInf.Loc := GetTextValue(CurStr, 12); if AnsiPos('SRVC', CurStr) <> 0 then WellInf.Serv := GetTextValue(CurStr, 12); if AnsiPos('DATE', CurStr) <> 0 then WellInf.Date := GetTextValue(CurStr, 12); end; //************************************************************************************************************************************* //************************************************************************************************************************************* //************************************************************************************************************************************* //************************************************************************************************************************************* procedure TLasFile.Load_ParametrInfomation(CurStr : String); begin end; //************************************************************************************************************************************* //************************************************************************************************************************************* //************************************************************************************************************************************* //************************************************************************************************************************************* procedure TLasFile.Load_CurveInformation(CurStr : String); var Series : TSeries; function GetSeriesName(aStr : String): String; var i : integer; begin Result := ''; for i := 1 to 255 do if aStr[i] = '.' then Break else Result := Result + aStr[i]; end; begin Series := TSeries.Create; SeriesList.Add(Series); Series.Name := GetSeriesName(CurStr); Series.Count := CountDataElement; Series.Step := WellInf.Step; Series.NullValue := WellInf.Null; GetMem(Series.Data, SizeOf(Series.Data)*Series.Count); end; //************************************************************************************************************************************* //************************************************************************************************************************************* //************************************************************************************************************************************* //************************************************************************************************************************************* procedure OutPutError(aErrorCounter : Integer); var CountDec, Res : Integer; MyStr : String; begin CountDec := aErrorCOunter div 10; res := aErrorCounter mod CountDec*10; MyStr := ''; case res of 1 : MyStr := 'ка'; 2..4 : MyStr := 'ки'; 5..9 : MyStr := 'об'; 0 : MyStr := 'об'; end; MessageDlg(intToStr(aErrorCounter) + ' Ошиб' + MyStr + ' в "LAS" файле', mtInformation, [mbOk], 0); end; //************************************************************************************************************************************* //************************************************************************************************************************************* //************************************************************************************************************************************* //************************************************************************************************************************************* procedure TLasFile.Load(); var CurrentWorkString : String; n, k, i : Integer; f : TextFile; floatValue : Float; Series : TSeries; RadiusArray : array [0..5] of TSeries; begin CurrentWorkString := ' '; FloatValue := 0; ErrorCounter := 0; CalibrationFactor := false; SetLength(ErrorList, 0); // ----------- Кусок отвечающий за считывание файла ------------- AssignFile(f, LasFile.FileName); reset(f); //if iFileHandle = -1 then begin MessageDlg('Ошибка доступа к файлу', mtError, [mbOK],0); exit; end; // ------------- Преобразование данных ----------------------------- while not eof(f) do begin if CurrentWorkString[1] <> '~' then ReadLn(f, CurrentWorkString); if CurrentWorkString[1] = '~' then case CurrentWorkString[2] of 'V' : begin ReadLn(f, CurrentWorkString); while CurrentWorkString[1] <> '~' do begin if CurrentWorkString[1] <> '#' then Load_VersionInformation(CurrentWorkString); ReadLn(f, CurrentWorkString); end; end; 'W' : begin ReadLn(f, CurrentWorkString); while CurrentWorkString[1] <> '~' do begin if CurrentWorkString[1] <> '#' then Load_WellInformation(CurrentWorkString); ReadLn(f, CurrentWorkString); end; CountDataElement := abs(Trunc((WellInf.Stop - WellInf.Start)/WellInf.Step)); end; 'P' : begin ReadLn(f, CurrentWorkString); while CurrentWorkString[1] <> '~' do begin if CurrentWorkString[1] <> '#' then Load_ParametrInfomation(CurrentWorkString); ReadLn(f, CurrentWorkString); end; end; 'C' : begin ReadLn(f, CurrentWorkString); while CurrentWorkString[1] <> '~' do begin if CurrentWorkString[1] <> '#' then Load_CurveInformation(CurrentWorkString); ReadLn(f, CurrentWorkString); end; end; 'O' : begin ReadLn(f, CurrentWorkString); while CurrentWorkString[1] <> '~' do begin if AnsiPos('NP6_1', CurrentWorkString) <> 0 then CalibrationFactor := True; ReadLn(f, CurrentWorkString); end; end; 'A' : begin for n := 0 to CountDataElement - 1 do begin // ------ Загрузка данных ++++ Обработка ошибок данных ----- // ------- если в данных чего-то там неправильно, значит виноват тот кто предоставил данные --- for k := 0 to SeriesList.Count - 1 do begin try Read(f, FloatValue); except SetLength(ErrorList, ErrorCounter + 1); ErrorList[ErrorCounter].Depth := TSeries(SeriesList.Items[0]).data^[n]; ErrorList[ErrorCounter].Kanal := k; ErrorCounter := ErrorCounter + 1; end; TSeries(SeriesList.Items[k]).AddValue[n] := FloatValue; end; end; break; end; end; end; // ------------------------------------------------------------------ WellInf.Start := TSeries(SeriesList.Items[0]).Data^[0]; WellInf.Stop := TSeries(SeriesList.Items[0]).Data^[CountDataElement - 1]; // ------------------------------------------------------------------ CloseFile(f); // --------------- if ErrorCounter <> 0 then OutPutError(ErrorCounter); // ------------------------------------------------------------------ // ------ Считаю средний радиус *------------------- if not CheckPresentSeries('RADS') then begin Series := TSeries.Create; SeriesList.Add(Series); Series.Name := 'RADS'; Series.Count := CountDataElement; Series.Step := WellInf.Step; Series.NullValue := WellInf.Null; GetMem(Series.Data, SizeOf(Series.Data)*Series.Count); for i := 0 to 5 do begin if CheckPresentSeries('RAD'+intToStr(i+1)) then RadiusArray[i] := GetSeries('RAD'+intToStr(i+1)) else begin MessageDLG('Неверный тип LAS файла'#10#13'Не возможно создать кривую среднего радиуса "RADS"', mtError, [mbOk], 0); exit end; end; for i := 0 to CountDataElement - 1 do Series.AddValue[i] := (RadiusArray[0].data^[i] + RadiusArray[1].data^[i] + RadiusArray[2].data^[i] + RadiusArray[3].data^[i] + RadiusArray[4].data^[i] + RadiusArray[5].data^[i])/6; end; end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ function FindLinePos(aStr : String):integer; var i, k, n : Integer; flag : boolean; begin Result := -1; for i := 0 to Length(Shapka) - 1 do begin n := 1; flag := False; for k := 1 to Length(Shapka[i]) do begin if UpperCase(Shapka[i][k]) = aStr[n] then begin flag := True; n := n + 1; end else begin if Flag then begin if n = Length(AStr) + 1 then begin Result := i; exit; end else begin flag := False; n := 1; end; end end; end; end; end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ function SetElementString(aStr : AnsiString; Value : Float) : AnsiString; var k, i : Integer; aPos1, aPos2 : Integer; StrValue : String; begin aPos1 := 1; aPos2 := 1; k := 1; // ----- Устанавливаем первую позицию в строке ------------------ for i := 1 to Length(aStr) do if aStr[i] = '.' then begin k := i + 1; break; end; for i := k to Length(aStr) do if aStr[i] = ' ' then begin aPos1 := i; break; end; // ----- Устанавливаем Вторую позицию в строке ------------------ for i := 1 to Length(aStr) do if aStr[i] = ':' then begin k := i; break; end; for i := k downto 1 do if Ord(aStr[i]) - 48 in [0..9] then begin aPos2 := i + 1; break; end; // ------------------- StrValue := FLoatToStrF(Value, ffFixed, 15, 2); Result := ''; for i := 1 to aPos1 do Result := Result + aStr[i]; for i := aPos1+1 to aPos2 - Length(StrValue) - 1 do Result := Result + ' '; Result := Result + StrValue; for i := aPos2 to Length(aStr) do Result := Result + aStr[i]; end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ function GetNormalString(aString : String):String; var i : integer; begin Result := ''; for i := 1 to 12 - Length(aString) do Result := Result + ' '; Result := Result + aString end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ procedure DeleteRems(); var i : integer; Flag : Boolean; begin Flag := False; for i := Length(Shapka) - 1 downto Length(Shapka) - 5 do begin if Shapka[i][1] = '#' then begin Shapka[i] := '#'; Flag := True; end; end; //------------------ if Not Flag then begin SetLength(Shapka, Length(Shapka)+1); Shapka[Length(Shapka)-1] := Shapka[Length(Shapka)-2]; end; //------------------- Shapka[Length(Shapka)-2] := ''; for i := 0 to LasFile.SeriesList.Count - 1 do Shapka[Length(Shapka)-2] := Shapka[Length(Shapka)-2] + GetNormalString(TSeries(LasFile.SeriesList.items[i]).Name); //-------------------------- Shapka[Length(Shapka)-2][1] := '#'; end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ procedure TLasFile.Save(start, stop : float; aFileName : String); var CurString : AnsiString; StringCounter : Integer; f : TextFile; i, k : Integer; // --------------------------- el : Integer; // --------------------------- begin // --------- Читаем шапку ----------------------------- AssignFile(f, LasFile.FileName); Reset(f); StringCounter := 0; while Not eof(f) do begin SetLength(Shapka, StringCounter + 1); ReadLn(f, CurString); Shapka[StringCounter] := CurString; inc(StringCounter); if CurString[1] = '~' then if UpperCase(CurString[2]) = 'A' then Break; end; CloseFile(f); // --------- Исправляем шапку ----------------------- el := FindLinePos('STRT'); Shapka[el] := SetElementString(Shapka[el], start); el := FindLinePos('STOP'); Shapka[el] := SetElementString(Shapka[el], stop); DeleteRems(); // --------- Пишем данные ------------------------- AssignFile(f, aFileName); Rewrite(f); for i := 0 to Length(Shapka) - 1 do WriteLn(f, Shapka[i]); //----------------- for i := 0 to CountDataElement - 1 do begin if TSeries(LasFile.SeriesList.items[0]).Data^[i] >= start then begin for k := 0 to LasFile.SeriesList.Count - 1 do Write(f, GetNormalString(FloatToStrf(TSeries(LasFile.SeriesList.items[k]).data^[i], ffFixed, 15, 2))); WriteLn(f); end; //---- if TSeries(LasFile.SeriesList.items[0]).Data^[i] > Stop then Break; end; CloseFile(f); end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ function TLasFile.CheckPresentSeries(aName: String): boolean; var i : integer; begin Result := False; for i := 0 to SeriesList.Count - 1 do begin if TSeries(SeriesList.Items[i]).Name = aName then begin Result := True; Break; end; end; end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ function TLasFile.GetSeries(aName: String): TSeries; var i : integer; begin Result := nil; for i := 0 to SeriesList.Count - 1 do begin if TSeries(SeriesList.Items[i]).Name = aName then begin Result := TSeries(SeriesList.Items[i]); Break; end; end; end; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ end.
unit mungis.utils; interface uses WinAPI.Windows, System.SysUtils, System.Classes, System.Math; const dsc_Flag_Null = 1; dtype_null = 0; dtype_text = 1; // CHAR dtype_cstring = 2; dtype_varying = 3; // VARCHAR dtype_packed = 6; dtype_byte = 7; dtype_short = 8; // SMALLINT dtype_long = 9; // INTEGER dtype_quad = 10; dtype_real = 11; // REAL dtype_double = 12; // DOUBLE PRECISION dtype_d_float = 13; // FLOAT dtype_sql_date = 14; // DATE dtype_sql_time = 15; // TIME dtype_timestamp = 16; // TIMESTAMP dtype_blob = 17; // BLOB dtype_array = 18; dtype_int64 = 19; // BIGINT NUMERIC DECIMAL __MONEY __NMONEY // SubType 0 1 2 5 4 dtype_count = 20; type VarChar = PAnsiChar; CString = PAnsiChar; type TDSC = packed record dsc_dtype: Byte; dsc_scale: shortint; dsc_length: word; dsc_sub_type: smallint; dsc_flags: word; dsc_address: Pointer; end; PDSC = ^TDSC; s_string = array [0 .. 0] of Byte; stext = packed record text_string: s_string; end; c_string = stext; vvary = packed record vary_length: word; vary_string: s_string; end; Pinteger = ^Integer; Pstext = ^stext; Pcstring = ^c_string; Pvvary = ^vvary; TISC_BlobGetSegment = function(BlobHandle: PInt; Buffer: PAnsiChar; BufferSize: Long; var ResultLength: Long): WordBool; cdecl; TISC_BlobPutSegment = procedure(BlobHandle: PInt; Buffer: PAnsiChar; BufferLength: Long); cdecl; TBlob = record GetSegment: TISC_BlobGetSegment; BlobHandle: PInt; SegmentCount: Long; MaxSegmentLength: Long; TotalSize: Long; PutSegment: TISC_BlobPutSegment; end; PBlob = ^TBlob; TDSC_QUAD = packed record dsc_quad_hi: Integer; dsc_quad_lo: longword; end; pdsc_quad = ^TDSC_QUAD; { tdsc_quad для типа DATE (SQL dialect 1): dsc_quad_hi : число дней после 17 ноября 1858 года (дата) dsc_quad_lo : число милисекунд * 10 после полуночи (время) } type TVarCharHelper = record helper for VarChar public function GetString: String; inline; procedure SetString(const aString: string; const aMaxLength: Integer); inline; end; type TCStringHelper = record helper for CString public function GetString(aLength: Integer = 0): string; inline; procedure SetString(const aString: string; const aMaxLength: Integer); inline; end; type TBlobHelper = record helper for TBlob strict private const constBufferSize = 1048576; constBlolSegmentSize = 32765; public function Check: Boolean; public procedure GetBytes(var aBytes: TBytes; var aReadLength: Integer; aFullRead: Boolean = True); overload; inline; function GetBytes: TBytes; overload; inline; function SetBytes(const aBytes: TBytes; aLength: Integer = 0; aIsCheck: Boolean = True): Boolean; inline; public function GetStream: TStream; overload; inline; procedure GetStream(aStream: TStream; aIsCheck: Boolean = True); overload; inline; function SetStream(const aStream: TStream; aSize: Int64 = 0; aIsBegin: Boolean = True): Boolean; inline; end; function DscQuadToDate(const aDate: TDSC_QUAD): TDateTime; inline; function TimeStampToDate(const aDate: TTimeStamp): TDateTime; inline; implementation function TimeStampToDate(const aDate: TTimeStamp): TDateTime; const DeltaDelphiIB = 15018; MSec10DayCount = 864000000; begin Result := (aDate.Time - DeltaDelphiIB) + (aDate.Date / MSec10DayCount); end; function DscQuadToDate(const aDate: TDSC_QUAD): TDateTime; const DeltaDelphiIB = 15018; MSec10DayCount = 864000000; begin Result := (aDate.dsc_quad_hi - DeltaDelphiIB) + (aDate.dsc_quad_lo / MSec10DayCount); end; { TVarCharHelper } function TVarCharHelper.GetString: String; var tmpLength: Integer; tmpBytes: TBytes; begin Result := ''; tmpBytes := []; try if not assigned(Self) then exit; tmpLength := PSmallInt(Self)^; if tmpLength > 0 then begin tmpBytes:= TEncoding.ANSI.GetBytes(@Self[2], 0, tmpLength); Result := TEncoding.ANSI.GetString(tmpBytes); end; finally SetLength(tmpBytes, 0); end; end; procedure TVarCharHelper.SetString(const aString: string; const aMaxLength: Integer); var tmpBytes: TBytes; begin if not assigned(Self) then exit; tmpBytes:= TEncoding.ANSI.GetBytes(@aString[1], 0, Min(Length(aString), aMaxLength)); PSmallInt(aString)^ := SmallInt(Length(tmpBytes)); Move(tmpBytes[0], Self[2], Length(tmpBytes)); end; { TCStringHelper } function TCStringHelper.GetString(aLength: Integer): string; var tmpString: AnsiString; begin Result := ''; tmpString := ''; try if not assigned(Self) then exit; if aLength = 0 then aLength := LStrLenA(Self); if aLength > 0 then begin SetLength(tmpString, aLength); Move(Self[0], tmpString[1], aLength + 1); end; finally end; Result := string(tmpString); end; procedure TCStringHelper.SetString(const aString: string; const aMaxLength: Integer); var tmpString: AnsiString; tmpLength: Integer; begin if not assigned(Self) then exit; tmpLength:= aString.Length; if aString.Length >= aMaxLength then tmpLength:= aMaxLength - 1; tmpString:= AnsiString(Copy(aString, 1, tmpLength)) + #00; Move(tmpString[1], Self[0], tmpLength + 1); end; { TBlobHelper } function TBlobHelper.Check: Boolean; begin if assigned(@Self) then if assigned(Self.BlobHandle) then exit(Self.BlobHandle^ <> 0); Result := False; end; function TBlobHelper.GetBytes: TBytes; var tmpCount: Integer; begin GetBytes(Result, tmpCount, True); end; function TBlobHelper.GetStream: TStream; begin Result := TMemoryStream.Create; try GetStream(Result); except FreeAndNil(Result) end; end; procedure TBlobHelper.GetStream(aStream: TStream; aIsCheck: Boolean); var tmpBytes : TBytes; aReadLength: Integer; begin if aIsCheck then if not Check then Exit; aReadLength := 0; while True do begin GetBytes(tmpBytes, aReadLength, False); try if Length(tmpBytes) = 0 then break; aStream.Write(tmpBytes, 0, Length(tmpBytes)); finally SetLength(tmpBytes, 0); end; end; end; procedure TBlobHelper.GetBytes(var aBytes: TBytes; var aReadLength: Integer; aFullRead: Boolean); var tmpMaxLength : Integer; tmpReadSegment: Long; begin SetLength(aBytes, 0); if not Check then exit; if TotalSize = 0 then exit; try tmpReadSegment := 0; if MaxSegmentLength > 0 then tmpMaxLength := MaxSegmentLength else tmpMaxLength := constBlolSegmentSize; repeat SetLength(aBytes, Length(aBytes) + tmpMaxLength); GetSegment(BlobHandle, @aBytes[aReadLength], tmpMaxLength, tmpReadSegment); // Если считали меньше то уменьшаем буфер на разницу tmpMaxLength - tmpReadSegment if tmpMaxLength > tmpReadSegment then SetLength(aBytes, Length(aBytes) - (tmpMaxLength - tmpReadSegment)); Inc(aReadLength, tmpReadSegment); if not aFullRead then break; until tmpReadSegment < 1; except end; end; function TBlobHelper.SetBytes(const aBytes: TBytes; aLength: Integer = 0; aIsCheck: Boolean = True): Boolean; var tmpWriteBlob : Integer; tmpWriteSegment: Integer; begin Result := False; if aIsCheck then begin if not Check then exit; if aLength = 0 then begin aLength := Length(aBytes); if aLength = 0 then exit; end; end; try if aLength > 0 then begin tmpWriteSegment := MaxSegmentLength; if (tmpWriteSegment = 0) then tmpWriteSegment := constBlolSegmentSize; tmpWriteBlob := 0; repeat if ((tmpWriteBlob + tmpWriteSegment) > aLength) then tmpWriteSegment := aLength - tmpWriteBlob; PutSegment(BlobHandle, @aBytes[tmpWriteBlob], tmpWriteSegment); Inc(tmpWriteBlob, tmpWriteSegment); until tmpWriteBlob >= aLength; Result := True; end; except end; end; function TBlobHelper.SetStream(const aStream: TStream; aSize: Int64; aIsBegin: Boolean): Boolean; var tmpBufferBytes : TBytes; tmpBufferLength: Integer; begin Result := False; if not assigned(aStream) then exit; if (aStream.Size = 0) then exit; if not Check then exit; if aIsBegin then aStream.Position := 0; if aSize = 0 then aSize:= aStream.Size - aStream.Position; aSize:= Min(aSize, aStream.Size - aStream.Position); SetLength(tmpBufferBytes, constBufferSize); try Result := True; while (aStream.Position < aStream.Size) do begin tmpBufferLength := aStream.Read(tmpBufferBytes, 0, Min(aSize, constBufferSize)); if tmpBufferLength = 0 then break; Result:= Result And SetBytes(tmpBufferBytes, tmpBufferLength, False); end; finally SetLength(tmpBufferBytes, 0); end; end; end.
unit OlegDefectsSi; interface uses OlegMaterialSamples,OlegType,Math,OlegMath; type TDefectName=(Fei, FeB_ac, FeB_don, FeB_ort_ac, FeB_ort_don); TDefectType=(tDonor,tAcceptor); TDefectParametersName=( nSn, nSp, nEt ); TDefectParameters=record Name:string; Parameters:array[TDefectParametersName]of double; ToValenceBand:boolean; DefectType:TDefectType; end; const Defects:array [TDefectName] of TDefectParameters= ((Name:'Fe_i'; Parameters: (3.6e-19, 7e-21, 0.394); ToValenceBand:True; DefectType:tDonor ), (Name:'FeB_ac'; Parameters: (2.5e-19, 5.5e-19, 0.262); ToValenceBand:False;DefectType:tAcceptor), (Name:'FeB_don';Parameters: (4e-17, 2e-18, 0.10); ToValenceBand:True; DefectType:tDonor), (Name:'FeB_ort_ac'; Parameters: (3e-19, 1.4e-19, 0.43); ToValenceBand:False;DefectType:tAcceptor), (Name:'FeB_ort_don';Parameters: (3e-19, 1.4e-19, 0.07); ToValenceBand:True; DefectType:tDonor) ); DefectType_Label:array[TDefectType]of string= ('0/+','-/0'); type TDefect=class private FParameters:TDefectParameters; FMaterial:TMaterial; FNd: double; fDefectName:TDefectName; procedure SetNd(const Value: double); function GetDefectType: string; public Constructor Create(DefectName:TDefectName); Procedure Free; property Name:string read FParameters.Name; property Et:double read FParameters.Parameters[nEt]; property ToValenceBand:boolean read FParameters.ToValenceBand; property DefectType:string read GetDefectType; property Nd:double read FNd write SetNd; function TAUn0(T:double=300):double; function TAUp0(T:double=300):double; function TAUsrh(Ndop,delN:double;T:double=300):double; {Ndop - рівень легування; delN - нерівноважні носії} function n1(T:double=300):double; function p1(T:double=300):double; function Sn(T:double=300):double; function Sp(T:double=300):double; {поперечні перерізи захоплення електронів та дірок} end; Function Fe_i_eq(MaterialLayer:TMaterialLayer; Fe_i_all:double; T:double=300):double; {рівноважна концентрація міжвузольного заліза Fe_i_all - повна концентрація домішкового заліза} Function Fe_i_t(time:double;MaterialLayer:TMaterialLayer; Fe_i_all:double; T:double=300; Em:double=0.68):double; {концентрація міжвузольного заліза через час time після припинення освітлення; Em - енергія міграціїї міжвузольного заліза} Function t_assFeB(N_A:double;T:double=300; Em:double=0.68):double; {характерний час спарювання пари залізо-бор, N_A - концентрація бору, []=см-3} Function TauFeEq(MaterialLayer:TMaterialLayer; Fe_i_all:double; T:double=300):double; {час, пов'язаний з рекомбінацією на FeB та Fei в рівновазі: вважається, що більшвсть заліза в парах, але рівноважна частина (див. Function Fe_i_eq) неспарена Fe_i_all - повна концентрація домішкового заліза} implementation uses System.SysUtils; { TDefect } constructor TDefect.Create(DefectName: TDefectName); begin inherited Create; fDefectName:=DefectName; FParameters:=Defects[fDefectName]; FMaterial:=TMaterial.Create(Si); end; procedure TDefect.Free; begin FMaterial.Free; inherited Free; end; function TDefect.GetDefectType: string; begin Result:=DefectType_Label[FParameters.DefectType]; end; function TDefect.n1(T: double): double; begin if ToValenceBand then Result:=FMaterial.Nc(T)*exp(-(FMaterial.EgT(T)-Et)/Kb/T) else Result:=FMaterial.Nc(T)*exp(-Et/Kb/T); end; function TDefect.p1(T: double): double; begin if ToValenceBand then Result:=FMaterial.Nv(T)*exp(-Et/Kb/T) else Result:=FMaterial.Nv(T)*exp(-(FMaterial.EgT(T)-Et)/Kb/T); end; procedure TDefect.SetNd(const Value: double); begin FNd := abs(Value); end; function TDefect.Sn(T: double): double; begin case fDefectName of Fei: Result:=ThermallyPower(3.47e-15,-1.48,T); FeB_ac: Result:=ThermallyPower(5.1e-13,-2.5,T); else Result:=FParameters.Parameters[nSn]; end; end; function TDefect.Sp(T: double): double; begin case fDefectName of Fei: Result:=ThermallyActivated(4.54e-20,0.05,T); FeB_ac: Result:=ThermallyActivated(3.32e-14,0.262,T); else Result:=FParameters.Parameters[nSp]; end; end; function TDefect.TAUn0(T: double=300): double; begin Result:=1/(Sn*Nd*FMaterial.Vth_n(T)); end; function TDefect.TAUp0(T: double=300): double; begin Result:=1/(Sp*Nd*FMaterial.Vth_p(T)); end; function TDefect.TAUsrh(Ndop, delN, T: double): double; var n0:double; begin n0:=sqr(FMaterial.n_i(T))/Ndop; Result:=(TAUn0(T)*(Ndop+p1(T)+delN)+ TAUp0(T)*(n0+n1(T)+delN))/ (Ndop+n0+delN); end; Function Fe_i_eq(MaterialLayer:TMaterialLayer; Fe_i_all:double; T:double=300):double; begin Result:=Fe_i_all/(1+MaterialLayer.Nd*1e-29*exp(0.582/Kb/T)) /(1+exp((MaterialLayer.F(T)-0.394)/Kb/T)); end; Function Fe_i_t(time:double;MaterialLayer:TMaterialLayer; Fe_i_all:double; T:double=300;Em:double=0.68):double; var Fe_i_e:double; begin Fe_i_e:=Fe_i_eq(MaterialLayer,Fe_i_all,T); // Fe_i_e:=0; Result:=(Fe_i_all-Fe_i_e) *exp(-time/t_assFeB(1e-6*MaterialLayer.Nd,T,Em)) // exp(-1.3e-3*exp(-Em/Kb/T)*time*Power(1e-6*MaterialLayer.Nd,2.0/3.0)) // exp(-time*exp(-Em/Kb/T)*MaterialLayer.Nd/T/5.7e11) +Fe_i_e; end; Function t_assFeB(N_A:double;T:double=300; Em:double=0.68):double; begin // Result:=1/(1.3e-3*exp(-Em/Kb/T)*Power(N_A,2.0/3.0)); Result:=5.7e5*exp(Em/Kb/T)*T/N_A; end; Function TauFeEq(MaterialLayer:TMaterialLayer; Fe_i_all:double; T:double=300):double; var dFei,dFeB:TDefect; t_Fei,t_FeB:double; begin dFei:=TDefect.Create(Fei); dFeB:=TDefect.Create(FeB_ac); try // dFei.Nd:=Fe_i_all; dFei.Nd:=Fe_i_eq(MaterialLayer,Fe_i_all,T); dFeB.Nd:=Fe_i_all-dFei.Nd; t_Fei:=dFei.TAUsrh(MaterialLayer.Nd,0,T); t_FeB:=dFeB.TAUsrh(MaterialLayer.Nd,0,T); Result:=1/(1/t_Fei+1/t_FeB); // Result:=10; except Result:=ErResult; end; FreeAndNil(dFei); FreeAndNil(dFeB); end; end.
unit DLGImgObjPropEd; (***** Code Written By Huang YanLai *****) interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ImgLibObjs, ExtCtrls, StdCtrls, Buttons, ExtDlgs; type TdlgImgObjpropEditor = class(TForm) btnLoad: TBitBtn; btnClear: TBitBtn; BitBtn3: TBitBtn; BitBtn4: TBitBtn; Panel1: TPanel; OpenPictureDialog1: TOpenPictureDialog; btnSave: TBitBtn; procedure btnLoadClick(Sender: TObject); procedure btnClearClick(Sender: TObject); procedure btnSaveClick(Sender: TObject); private { Private declarations } ILImage1 : TCustomILImage; procedure WMDropFiles(var Msg: TWMDropFiles); message WM_DROPFILES; public { Public declarations } function Execute(ImageObj : TCustomImgLibObj) : boolean; end; var dlgImgObjpropEditor: TdlgImgObjpropEditor; implementation uses ShellAPI; {$R *.DFM} procedure TdlgImgObjpropEditor.btnLoadClick(Sender: TObject); begin OpenPictureDialog1.Title := 'Load Image'; if OpenPictureDialog1.Execute then ILImage1.ImageObj.LoadFromFile(OpenPictureDialog1.FileName); end; procedure TdlgImgObjpropEditor.btnClearClick(Sender: TObject); begin ILImage1.ImageObj.Clear; //Invalidate; end; function TdlgImgObjpropEditor.Execute(ImageObj: TCustomImgLibObj): boolean; begin if ImageObj is TImgLibObj then ILImage1 := TILImage.Create(self) else if ImageObj is TImgLibViewObj then ILImage1 := TILImageView.Create(self) else begin result:=false; exit; end; try DragAcceptFiles(handle,true); ILImage1.Align := alClient; ILImage1.Parent := Panel1; ILImage1.ImageObj.Assign(ImageObj); ILImage1.ImageObj.Transparent := false; result := showmodal=mrOK; if result and (ImageObj<>nil) then begin ILImage1.ImageObj.Transparent := ImageObj.Transparent; ImageObj.Assign(ILImage1.ImageObj); end; finally ILImage1.free; DragAcceptFiles(handle,false); end; end; procedure TdlgImgObjpropEditor.btnSaveClick(Sender: TObject); begin OpenPictureDialog1.Title := 'Save Image'; if OpenPictureDialog1.Execute then ILImage1.ImageObj.SaveToFile(OpenPictureDialog1.FileName); end; procedure TdlgImgObjpropEditor.WMDropFiles(var Msg: TWMDropFiles); var CFileName: array[0..MAX_PATH] of Char; begin try if DragQueryFile(Msg.Drop, 0, CFileName, MAX_PATH) > 0 then begin ILImage1.ImageObj.LoadFromFile(CFileName); Msg.Result := 0; end; finally DragFinish(Msg.Drop); end; end; end.
unit unClassSemaforo; interface uses ExtCtrls, Classes, Controls, Graphics, MMSystem, System.SysUtils, Vcl.Dialogs; Type TSemaforo = class(TImage) private // Fields FTamLamp : Byte; FTimer : TTimer; FAtual : Byte; FAlerta : Boolean; FAcende : Boolean; FQueimada : Array[1..13] of Boolean; FNomeRua : String; FPosition : Byte; procedure Desenha; procedure DesenhaNome(Val: String); procedure Lampada(Pos: Byte; Liga: Boolean); procedure ResetAberto; procedure ResetFechado; procedure MudaAlerta(Init, Prox: TSemaforo); function TraduzClick(X, Y: Integer): Byte; // Eventos procedure FTimerTimer (Sender: TObject); procedure TSemaforoMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure SetAlerta(const Value: Boolean); procedure SetNomeRua(const Value: String); public Proximo: TSemaforo; constructor Create(X, Y: Integer; crTamLamp: Byte; crNome: String; crPos: Byte; AOwner: TComponent); destructor Destroy; property Alerta: Boolean read FAlerta Write SetAlerta; property NomeRua: String read FNomeRua Write SetNomeRua; end; implementation { TSemaforo } constructor TSemaforo.Create(X, Y: Integer; crTamLamp: Byte; crNome: String; crPos: Byte; AOwner: TComponent); begin inherited Create(AOwner); Parent := TWinControl(AOwner); Left := X; Top := Y; FPosition := crPos; FTamLamp := CrTamLamp; // CSS Styles case FPosition of 1, 3: begin Width := 3 * FTamLamp; Height := 7 * FTamLamp; end; 2, 4: begin Width := 6 * FTamLamp; Height := 4 * FTamLamp; end; end; Color := clWhite; FAtual := 7; FAlerta := True; Desenha; NomeRua := crNome; OnMouseDown := TSemaforoMouseDown; // Assinando o evento FTimer := TTimer.Create(AOwner); FTimer.Interval := 500; FTimer.Enabled := True; FTimer.OnTimer := FTimerTImer; end; procedure TSemaforo.Desenha; var i: Byte; begin with Canvas do begin Pen.Color := clBlack; Brush.Color := clSilver; case FPosition of 1, 3: Rectangle(0, 0, 3 * FTamLamp, 6 * FTamLamp); 2, 4: Rectangle(0, 0, 6 * FTamLamp, 3 * FTamLamp); end; for I := 1 to 13 do Lampada(i, False); end; end; procedure TSemaforo.DesenhaNome(Val: String); begin with Canvas do begin Brush.Color := clWhite; Pen.Color := clWhite; case FPosition of 1, 3: Rectangle(0, 6 * FTamLamp, 3 * FTamLamp, 7 * FTamLamp); 2, 4: Rectangle(0, 3 * FTamLamp, 6 * FTamLamp, 4 * FTamLamp); end; Font.Size := Round(0.5 * FTamLamp); Font.Color := clRed; case FPosition of 1, 3: TextOut(10, 6 * FTamLamp + 5, Val); 2, 4: TextOut(10, 3 * FTamLamp + 5, Val); end; end; end; destructor TSemaforo.Destroy; begin FTimer.Free; inherited; end; procedure TSemaforo.FTimerTimer(Sender: TObject); begin if FAlerta then begin FAcende := Not FAcende; Lampada(7, FAcende); end else begin // Incrementando o Atual if FAtual = 13 then FAtual := 1 else inc(FAtual); case FAtual of 1 : Begin Lampada(13, False); Lampada(1, True); Lampada(6, True); End; 2..7, 9..13: begin if(FAtual = 3) AND (Proximo <> Nil) then Proximo.FTimer.Enabled := True; Lampada(FAtual - 1, False); Lampada(FAtual, True); end; 8 : begin FTimer.Enabled := False; Lampada(7, False); Lampada(8, True); Lampada(13, True); end; end; end; end; procedure TSemaforo.Lampada(Pos: Byte; Liga: Boolean); var x, y: Integer; cor: TColor; begin X := 0; Y := 0; cor := clBlack; case FPosition of 1: case Pos of 1..6 : begin X := FTamLamp * 2; Y := FTamLamp * (Pos - 1); cor := clLime; end; 7 : begin X := FTamLamp; Y := FTamLamp * 5; cor := clYellow; end; 8..13: begin X := 0; Y := FTamLamp * (Pos - 8); cor := clRed; end; end; 2: case Pos of 1..6 : begin X := FTamLamp * (Pos - 1); Y := 0; cor := clLime; end; 7 : begin X := FTamLamp * 5; Y := FTamLamp; cor := clYellow; end; 8..13: begin X := FTamLamp * (Pos - 8); Y := FTamLamp * 2; cor := clRed; end; end; 3: case Pos of 1..6 : begin X := 0; Y := FTamLamp * (6 - Pos); cor := clLime; end; 7 : begin X := FTamLamp; Y := 0; cor := clYellow; end; 8..13: begin X := FTamLamp * 2; Y := FTamLamp * (13 - Pos); cor := clRed; end; end; 4: case Pos of 1..6 : begin X := FTamLamp * (6 - Pos); Y := FTamLamp * 2; cor := clLime; end; 7 : begin X := 0; Y := FTamLamp; cor := clYellow; end; 8..13: begin X := FTamLamp * (13 - Pos); Y := 0; cor := clRed; end; end; end; if FQueimada[Pos] then cor := clBlue else if Not Liga then cor := clBlack; with Canvas do begin Pen.Color := clBlack; Brush.Color := clSilver; Rectangle(x, y, x + FTamLamp, y + FTamLamp); Brush.Color := cor; Ellipse(x, y, x + FTamLamp, y + FTamLamp); end; end; procedure TSemaforo.MudaAlerta(Init, Prox: TSemaforo); begin if(Init = Prox) OR (Proximo = Nil) then with Init do begin Desenha; FTimer.Enabled := False; FAcende := False; if Not FAlerta then ResetAberto else FAtual := 7; FTimer.Enabled := True; end else with Prox do begin Desenha; FTimer.Enabled := False; FAcende := False; FAlerta := Init.FAlerta; if Not FAlerta then ResetFechado else FAtual := 7; if Proximo <> Nil then MudaAlerta(Init, Proximo); FTimer.Enabled := FAlerta; end; end; procedure TSemaforo.ResetAberto; begin FAtual := 1; Lampada(1, True); Lampada(6, True); end; procedure TSemaforo.ResetFechado; begin FAtual := 8; Lampada(8, True); Lampada(13, True); end; procedure TSemaforo.SetAlerta(const Value: Boolean); begin if Value <> FAlerta then begin FAlerta := Value; MudaAlerta(Self, Proximo); end; end; procedure TSemaforo.SetNomeRua(const Value: String); begin if(FNomeRua <> Value) then begin FNomeRua := Value; DesenhaNome(FNomeRua); end; end; function TSemaforo.TraduzClick(X, Y: Integer): Byte; var PosX, PosY: Byte; begin PosX := (X div FTamLamp) + 1; PosY := (Y div FTamLamp) + 1; case FPosition of 1: if(PosX = 1) AND (PosY < 7) then Result := PosY + 7 else if(PosX = 2) AND (PosY = 6) then Result := 7 else if(PosX = 3) AND (PosY < 7) then Result := PosY else Result := 0; 2: if(PosX < 7) AND (PosY = 3) then Result := PosX + 7 else if(PosX = 6) AND (PosY = 2) then Result := 7 else if(PosX < 7) AND (PosY = 1) then Result := PosX else Result := 0; 3: if(PosX = 3) AND (PosY < 7) then Result := 14 - PosY else if(PosX = 2) AND (PosY = 1) then Result := 7 else if(PosX = 1) AND (PosY < 7) then Result := 7 - PosY else Result := 0; 4: if(PosX < 7) AND (PosY = 1) then Result := 14 - PosX else if(PosX = 1) AND (PosY = 2) then Result := 7 else if(PosX < 7) AND (PosY = 3) then Result := 7 - PosX else Result := 0; else Result := 0; end; end; procedure TSemaforo.TSemaforoMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var PosLamp: Byte; Liga: Boolean; begin PosLamp := TraduzClick(X, Y); if(PosLamp <> 0) then begin if NOT FQueimada[PosLamp] then PlaySound('quebra.wav', 1, $0001) else PlaySound('troca.wav', 1, $0001); FQueimada[PosLamp] := NOT FQueimada[PosLamp]; Liga := (PosLamp = FAtual) OR ((PosLamp = 6) AND (FAtual < 6)) OR ((PosLamp = 13) AND (FAtual < 13) AND (FAtual > 7)); Lampada(PosLamp, Liga); end; end; end.
unit Calib; interface uses ActiveX; type CalibrationTable = PSafeArray; // safearray of word type TCalib = class public constructor Create; destructor Destroy; override; procedure Update; private fPotencia : array[0..1] of integer; fCRadar : array[0..3] of single; fSensibility : array[0..3] of integer; fDinamicRange: array[0..3] of integer; fMPS_Voltage : array[0..1] of double; private procedure SetDinamicRange(const Index, Value: integer); procedure SetSensibility(const Index, Value: integer); procedure SetPotencia ( Index : integer; Value : integer ); procedure SetCRadar ( Index : integer; Value : single ); function GetPotMetPL1 : single; function GetPotMetPL2 : single; function GetPotMetPC1 : single; function GetPotMetPC2 : single; procedure SetMPS_Voltage( Index : integer; Value : double ); public property SensibilityPL1 : integer index 0 read fSensibility[0] write SetSensibility; property SensibilityPL2 : integer index 1 read fSensibility[1] write SetSensibility; property SensibilityPC1 : integer index 2 read fSensibility[2] write SetSensibility; property SensibilityPC2 : integer index 3 read fSensibility[3] write SetSensibility; property DinamicRangePL1: integer index 0 read fDinamicRange[0] write SetDinamicRange; property DinamicRangePL2: integer index 1 read fDinamicRange[1] write SetDinamicRange; property DinamicRangePC1: integer index 2 read fDinamicRange[2] write SetDinamicRange; property DinamicRangePC2: integer index 3 read fDinamicRange[3] write SetDinamicRange; property Potencia1 : integer index 0 read fPotencia[0] write SetPotencia; property Potencia2 : integer index 1 read fPotencia[1] write SetPotencia; property CRadarPL1 : single index 0 read fCRadar [0] write SetCRadar; property CRadarPL2 : single index 1 read fCRadar [1] write SetCRadar; property CRadarPC1 : single index 2 read fCRadar [2] write SetCRadar; property CRadarPC2 : single index 3 read fCRadar [3] write SetCRadar; property PotMetPL1 : single read GetPotMetPL1; property PotMetPL2 : single read GetPotMetPL2; property PotMetPC1 : single read GetPotMetPC1; property PotMetPC2 : single read GetPotMetPC2; property MPS_Voltage1 : double index 0 read fMPS_Voltage[0] write SetMPS_Voltage; property MPS_Voltage2 : double index 1 read fMPS_Voltage[1] write SetMPS_Voltage; private procedure LoadCalib; procedure SaveCalib; function PotMet( Pt, Po, C : single ) : single; end; var theCalibration : TCalib = nil; implementation uses Mutex, Math, Registry, RDAReg, ManagerDRX, DRX_AFC_WS, DRX_Configuration_WS; const CalibrationMutexName = 'Elbrus_Calibration_Mutex'; var CalibrationMutex : TMutex = nil; const MutexTime = 1000; const CalibKey = RDARootKey + '\Calibration\'; Ch1Key = 'Channel1'; Ch2Key = 'Channel2'; StartValue = 'Start'; CountValue = 'Count'; P1Value = 'Potencia1'; P2Value = 'Potencia2'; CR1PLValue = 'CRadarPL1'; CR2PLValue = 'CRadarPL2'; CR1PCValue = 'CRadarPC1'; CR2PCValue = 'CRadarPC2'; MPS_Delay1Value = 'MPS_Delay1'; MPS_Voltage1Value = 'MPS_Voltage1'; MPS_Delay2Value = 'MPS_Delay2'; MPS_Voltage2Value = 'MPS_Voltage2'; { TCalib } constructor TCalib.Create; begin inherited Create; CalibrationMutex := TMutex.Create(nil, false, CalibrationMutexName); Update; end; destructor TCalib.Destroy; begin SaveCalib; CalibrationMutex.Free; inherited; end; procedure TCalib.Update; begin if CalibrationMutex.WaitFor(MutexTime) then try LoadCalib; if DRX1.Ready then begin SensibilityPL1 := DRX1.Config_WS.Get_DRX_Sensibility_LP; SensibilityPC1 := DRX1.Config_WS.Get_DRX_Sensibility_SP; DinamicRangePL1 := DRX1.Config_WS.Get_DRX_Dinamic_Range_LP; DinamicRangePC1 := DRX1.Config_WS.Get_DRX_Dinamic_Range_SP; end else begin SensibilityPL1 := 0; SensibilityPC1 := 0; DinamicRangePL1 := 0; DinamicRangePC1 := 0; end; if DRX2.Ready then begin SensibilityPL2 := DRX2.Config_WS.Get_DRX_Sensibility_LP; SensibilityPC2 := DRX2.Config_WS.Get_DRX_Sensibility_SP; DinamicRangePL2 := DRX2.Config_WS.Get_DRX_Dinamic_Range_LP; DinamicRangePC2 := DRX2.Config_WS.Get_DRX_Dinamic_Range_SP; end else begin SensibilityPL2 := 0; SensibilityPC2 := 0; DinamicRangePL2 := 0; DinamicRangePC2 := 0; end; finally CalibrationMutex.Release; end; end; function TCalib.GetPotMetPC1: single; begin Result := PotMet(Potencia1, SensibilityPC1, CRadarPC1); end; function TCalib.GetPotMetPC2: single; begin Result := PotMet(Potencia2, SensibilityPC2, CRadarPC2); end; function TCalib.GetPotMetPL1: single; begin Result := PotMet(Potencia1, SensibilityPL1, CRadarPL1); end; function TCalib.GetPotMetPL2: single; begin Result := PotMet(Potencia2, SensibilityPL2, CRadarPL2); end; procedure TCalib.LoadCalib; var Reg : TRegistry; begin Reg := TRDAReg.Create; try if Reg.OpenKey(CalibKey, true) then with Reg do begin if ValueExists(P1Value) then fPotencia[0] := ReadInteger(P1Value); if ValueExists(P2Value) then fPotencia[1] := ReadInteger(P2Value); if ValueExists(CR1PLValue) then fCRadar[0] := ReadFloat(CR1PLValue); if ValueExists(CR2PLValue) then fCRadar[1] := ReadFloat(CR2PLValue); if ValueExists(CR1PCValue) then fCRadar[2] := ReadFloat(CR1PCValue); if ValueExists(CR2PCValue) then fCRadar[3] := ReadFloat(CR2PCValue); if ValueExists(MPS_Voltage1Value) then fMPS_Voltage[0] := ReadFloat(MPS_Voltage1Value); if ValueExists(MPS_Voltage2Value) then fMPS_Voltage[1] := ReadFloat(MPS_Voltage2Value); CloseKey; end; finally Reg.Free; end; end; function TCalib.PotMet( Pt, Po, C : single ) : single; begin try Result := 240.0 - C - (10 * log10(1000 * Pt)) + Po; except result := 0; end; end; procedure TCalib.SaveCalib; var Reg : TRegistry; begin Reg := TRDAReg.Create; try if Reg.OpenKey(CalibKey, true) then with Reg do begin WriteInteger(P1Value, fPotencia[0]); WriteInteger(P2Value, fPotencia[1]); WriteFloat (CR1PLValue, fCRadar[0]); WriteFloat (CR2PLValue, fCRadar[1]); WriteFloat (CR1PCValue, fCRadar[2]); WriteFloat (CR2PCValue, fCRadar[3]); WriteFloat (MPS_Voltage1Value, fMPS_Voltage[0]); WriteFloat (MPS_Voltage2Value, fMPS_Voltage[1]); CloseKey; end; finally Reg.Free; end; end; procedure TCalib.SetCRadar(Index: integer; Value: single); begin if CalibrationMutex.WaitFor(MutexTime) then try fCRadar[Index] := Value; SaveCalib; finally CalibrationMutex.Release; end; end; procedure TCalib.SetPotencia(Index, Value: integer); begin if CalibrationMutex.WaitFor(MutexTime) then try fPotencia[Index] := Value; SaveCalib; finally CalibrationMutex.Release; end; end; procedure TCalib.SetMPS_Voltage(Index: integer; Value: double); begin if CalibrationMutex.WaitFor(MutexTime) then try fMPS_Voltage[Index] := Value; SaveCalib; finally CalibrationMutex.Release; end; end; procedure TCalib.SetSensibility(const Index, Value: integer); begin try case Index of 0: if DRX1.Ready then DRX1.Config_WS.Set_DRX_Sensibility_LP(Value); 1: if DRX2.Ready then DRX2.Config_WS.Set_DRX_Sensibility_LP(Value); 2: if DRX1.Ready then DRX1.Config_WS.Set_DRX_Sensibility_SP(Value); 3: if DRX2.Ready then DRX2.Config_WS.Set_DRX_Sensibility_SP(Value); end; fSensibility[Index] := Value; except case Index of 0, 2: DRX1.Validate; 1, 3: DRX2.Validate; end; end; end; procedure TCalib.SetDinamicRange(const Index, Value: integer); begin try case Index of 0: if DRX1.Ready then DRX1.Config_WS.Set_DRX_Dinamic_Range_LP(Value); 1: if DRX2.Ready then DRX2.Config_WS.Set_DRX_Dinamic_Range_LP(Value); 2: if DRX1.Ready then DRX1.Config_WS.Set_DRX_Dinamic_Range_SP(Value); 3: if DRX2.Ready then DRX2.Config_WS.Set_DRX_Dinamic_Range_SP(Value); end; fDinamicRange[Index] := Value; except case Index of 0, 2: DRX1.Validate; 1, 3: DRX2.Validate; end; end; end; end.
{ Description: vPlot svg reader class. Copyright (C) 2017-2019 Melchiorre Caruso <melchiorrecaruso@gmail.com> This source is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. A copy of the GNU General Public License is available on the World Wide Web at <http://www.gnu.org/copyleft/gpl.html>. You can also obtain it by writing to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit vpsvgreader; {$mode objfpc} interface uses bgrabitmap, bgrabitmaptypes, bgrasvg, bgrasvgshapes, bgrasvgtype, bgravectorize, classes, vpmath, vppaths, sysutils; procedure svg2paths(const afilename: string; elements: tvpelementlist); implementation procedure element2paths(element: tsvgelement; elements: tvpelementlist); var bmp: tbgrabitmap; i: longint; line: tvpline; points: arrayoftpointf; begin bmp := tbgrabitmap.create; bmp.canvas2d.fontrenderer := tbgravectorizedfontrenderer.create; if (element is tsvgline ) or (element is tsvgrectangle ) or (element is tsvgcircle ) or (element is tsvgellipse ) or (element is tsvgpath ) or (element is tsvgtext ) or (element is tsvgpolypoints) then begin element.draw(bmp.canvas2d, cucustom); points := bmp.canvas2d.currentpath; for i := 0 to system.length(points) -2 do if (not isemptypointf(points[i ])) and (not isemptypointf(points[i+1])) then begin line.p0.x := points[i ].x; line.p0.y := points[i ].y; line.p1.x := points[i + 1].x; line.p1.y := points[i + 1].y; elements.add(line); end; setlength(points, 0); end else if (element is tsvggroup) then begin with tsvggroup(element).content do for i := 0 to elementcount -1 do element2paths(element[i], elements); end else if enabledebug then writeln(element.classname); bmp.destroy; end; procedure svg2paths(const afilename: string; elements: tvpelementlist); var i: longint; svg: tbgrasvg; begin svg := tbgrasvg.create(afilename); for i := 0 to svg.content.elementcount - 1 do begin element2paths(svg.content.element[i], elements); end; svg.destroy; elements.mirrorx; elements.movetoorigin; end; end.
(* EnumInputContext 由应用程序定义的,提供给ImmEnumInputContext函数用来处理输入环境的一个回调函 EnumRegisterWordProc 由应用程序定义的,结合ImmEnumRegisterWord函数一起使用的一个回调函数 1 0 0001426F CtfAImmActivate 2 1 000142C4 CtfAImmDeactivate 3 2 00013CE7 CtfAImmIsIME 4 3 00013E9F CtfImmCoUninitialize 5 4 00014304 CtfImmDispatchDefImeMessage 6 5 000131F0 CtfImmEnterCoInitCountSkipMode 7 6 0000A11B CtfImmGenerateMessage 8 7 0001356B CtfImmGetGuidAtom 9 8 00013511 CtfImmHideToolbarWnd 10 9 00013773 CtfImmIsCiceroEnabled 11 A 0001378E CtfImmIsCiceroStartedInThread 12 B 000135F1 CtfImmIsGuidMapEnable 13 C 000138A1 CtfImmIsTextFrameServiceDisabled 14 D 0001418A CtfImmLastEnabledWndDestroy 15 E 00013206 CtfImmLeaveCoInitCountSkipMode 16 F 000134DA CtfImmRestoreToolbarWnd 17 10 00013668 CtfImmSetAppCompatFlags 18 11 000137A6 CtfImmSetCiceroStartInThread 19 12 00013F0B CtfImmTIMActivate 20 13 00009A21 GetKeyboardLayoutCP 21 14 000077CD ImmActivateLayout 22 15 00002378 ImmAssociateContext 建立指定输入环境与窗口之间的关联 23 16 000036F4 ImmAssociateContextEx 更改指定输入环境与窗口(或其子窗口)之间的关联 24 17 00012332 ImmCallImeConsoleIME 25 18 000078B1 ImmConfigureIMEA 显示指定的输入现场标识符的配置对话框 26 19 00007A7B ImmConfigureIMEW 27 1A 00002975 ImmCreateContext 创建一个新的输入环境,并为它分配内存和初始化它 28 1B 00009865 ImmCreateIMCC 29 1C 0000DB3B ImmCreateSoftKeyboard 30 1D 000036A8 ImmDestroyContext 销毁输入环境并释放和它关联的内存 31 1E 00009889 ImmDestroyIMCC 32 1F 0000DCC2 ImmDestroySoftKeyboard 33 20 000023E8 ImmDisableIME 关闭一个线程或一个进程中所有线程的IME功能 34 21 000023E8 ImmDisableIme 35 22 000141A6 ImmDisableTextFrameService 关闭指定线程的文本服务框架(TSF)功能 虽然这里把它列了出来,但建议程序员最好不要使用这个函数 36 23 000037CA ImmEnumInputContext 获取指定线程的输入环境 37 24 0000AB30 ImmEnumRegisterWordA 列举跟指定读入串、样式和注册串相匹配的注册串 38 25 0000AC99 ImmEnumRegisterWordW 39 26 00007C25 ImmEscapeA 对那些不能通过IME API函数来访问的特殊输入法程序提供兼容性支持的一个函数 40 27 00007EA1 ImmEscapeW 41 28 00006E43 ImmFreeLayout 42 29 00009FC2 ImmGenerateMessage 43 2A 00009D07 ImmGetAppCompatFlags 44 2B 00005546 ImmGetCandidateListA 获取一个候选列表 45 2C 00005510 ImmGetCandidateListCountA 获取候选列表的大小 46 2D 0000552B ImmGetCandidateListCountW 47 2E 00005567 ImmGetCandidateListW 48 2F 00003B93 ImmGetCandidateWindow 获取有关候选列表窗口的信息 49 30 00004791 ImmGetCompositionFontA 获取有关当前用来显示按键组合窗口中的字符的逻辑字体的信息 50 31 00004829 ImmGetCompositionFontW 51 32 00005B62 ImmGetCompositionStringA 获取有关组合字符串的信息 52 33 0000548A ImmGetCompositionStringW 53 34 00003B48 ImmGetCompositionWindow 获取有关按键组合窗口的信息 54 35 000023A1 ImmGetContext 获取与指定窗口相关联的输入环境 55 36 00004ADB ImmGetConversionListA 在不生成任何跟IME有关的消息的情况下,获取输入按键字符组合或输出文字的转换结果列表 56 37 00004C26 ImmGetConversionListW 57 38 00003A86 ImmGetConversionStatus 获取当前转换状态 58 39 000097BE ImmGetDefaultIMEWnd 获取缺省IME类窗口的句柄 59 3A 000089A2 ImmGetDescriptionA 复制IME的说明信息到指定的缓冲区中 60 3B 000088F5 ImmGetDescriptionW 61 3C 00005588 ImmGetGuideLineA 获取出错信息 62 3D 000055A9 ImmGetGuideLineW 63 3E 00006823 ImmGetHotKey 64 3F 000098E0 ImmGetIMCCLockCount 65 40 0000992C ImmGetIMCCSize 66 41 00009F83 ImmGetIMCLockCount 67 42 00008AF0 ImmGetIMEFileNameA 获取跟指定输入现场相关联的IME文件名 68 43 00008A39 ImmGetIMEFileNameW 69 44 00009C7F ImmGetImeInfoEx 70 45 00012DB5 ImmGetImeMenuItemsA 获取注册在指定输入环境的IME菜单上的菜单项 71 46 00012DDC ImmGetImeMenuItemsW 72 47 00003AC3 ImmGetOpenStatus 检测IME是否打开 73 48 00008B8E ImmGetProperty 获取跟指定输入现场相关联的IME的属性和功能 74 49 0000A776 ImmGetRegisterWordStyleA 获取跟指定输入现场相关联的IME所支持的样式列表 75 4A 0000A84D ImmGetRegisterWordStyleW 76 4B 00003AF6 ImmGetStatusWindowPos 获取状态窗口的位置 77 4C 0000A245 ImmGetVirtualKey 获取跟IME处理的键盘输入消息相关联的初始虚拟键值 78 4D 0000E79D ImmIMPGetIMEA 79 4E 0000E769 ImmIMPGetIMEW 80 4F 0000E90C ImmIMPQueryIMEA 81 50 0000E804 ImmIMPQueryIMEW 82 51 0000EAB9 ImmIMPSetIMEA 83 52 0000E995 ImmIMPSetIMEW 84 53 000096DF ImmInstallIMEA 安装一个IME 85 54 00009415 ImmInstallIMEW 86 55 00008C54 ImmIsIME 检测指定的输入现场是否有和它相关的IME 87 56 00009DCB ImmIsUIMessageA 检查IME窗口消息并发送那些消息到特定的窗口 88 57 00009DEC ImmIsUIMessageW 89 58 0000776F ImmLoadIME 90 59 00008719 ImmLoadLayout 91 5A 00009A8B ImmLockClientImc 92 5B 00009F2D ImmLockIMC 93 5C 000098A6 ImmLockIMCC 94 5D 00009BAC ImmLockImeDpi 95 5E 00006FD8 ImmNotifyIME 通知IME有关输入环境状态已改变的消息 96 5F 000080B9 ImmPenAuxInput 97 60 0000E0D3 ImmProcessKey 98 61 00012E03 ImmPutImeMenuItemsIntoMappedFile 99 62 00009906 ImmReSizeIMCC 100 63 000022B3 ImmRegisterClient 101 64 0000A290 ImmRegisterWordA 注册一个输出文字到跟指定输入现场相关联的IME的字典中去 102 65 0000A3D6 ImmRegisterWordW 103 66 000029D3 ImmReleaseContext 销毁输入环境并解除对跟它相关联的内存的锁定 104 67 00006799 ImmRequestMessageA 105 68 000067B7 ImmRequestMessageW 106 69 0000EB4F ImmSendIMEMessageExA 107 6A 0000EB34 ImmSendIMEMessageExW 108 6B 00006FA3 ImmSendMessageToActiveDefImeWndW 109 6C 000029DE ImmSetActiveContext 110 6D 0001247B ImmSetActiveContextConsoleIME 111 6E 00004E54 ImmSetCandidateWindow 设置有关候选列表窗口的信息 112 6F 000048C1 ImmSetCompositionFontA 设置用来显示按键组合窗口中的字符的逻辑字体 113 70 000049CE ImmSetCompositionFontW 114 71 000067D5 ImmSetCompositionStringA 设置按键组合字符串的字符内容、属性和子串信息 115 72 000067FC ImmSetCompositionStringW 116 73 00004DD6 ImmSetCompositionWindow 设置按键组合窗口的位置 117 74 000045F7 ImmSetConversionStatus 设置当前转换状态 118 75 ImmSetHotKey (forwarded to USER32.CliImmSetHotKey) 119 76 0000470B ImmSetOpenStatus 打开或关闭IME功能 120 77 00004D6E ImmSetStatusWindowPos 设置状态窗口的位置 121 78 0000DCD3 ImmShowSoftKeyboard 122 79 00006C92 ImmSimulateHotKey 在指定的窗口中模拟一个特定的IME热键动作,以触发该窗口相应的响应动作 123 7A 00009D74 ImmSystemHandler 124 7B 0000DE65 ImmTranslateMessage 125 7C 00009B22 ImmUnlockClientImc 126 7D 00009F45 ImmUnlockIMC 127 7E 000098C3 ImmUnlockIMCC 128 7F 00009BFC ImmUnlockImeDpi 129 80 0000A503 ImmUnregisterWordA 从跟指定输入环境相关联的IME的字典中注销一个输出文字 130 81 0000A649 ImmUnregisterWordW 131 82 0000E679 ImmWINNLSEnableIME 132 83 0000E6A0 ImmWINNLSGetEnableStatus 133 84 0000E478 ImmWINNLSGetIMEHotkey IME命令 以下列出IME中用到的命令(控制消息)。 IMC_CLOSESTATUSWINDOW(隐藏状态窗口) IMC_GETCANDIDATEPOS(获取候选窗口的位置) IMC_GETCOMPOSITIONFONT(获取用来显示按键组合窗口中的文本的逻辑字体) IMC_GETCOMPOSITIONWINDOW(获取按键组合窗口的位置) IMC_GETSTATUSWINDOWPOS(获取状态窗口的位置) IMC_OPENSTATUSWINDOW(显示状态窗口) IMC_SETCANDIDATEPOS(设置候选窗口的位置) IMC_SETCOMPOSITIONFONT(设置用来显示按键组合窗口中的文本的逻辑字体) IMC_SETCOMPOSITIONWINDOW(设置按键组合窗口的样式) IMC_SETSTATUSWINDOWPOS(设置状态窗口的位置) IMN_CHANGECANDIDATE(IME通知应用程序:候选窗口中的内容将改变) IMN_CLOSECANDIDATE(IME通知应用程序:候选窗口将关闭) IMN_CLOSESTATUSWINDOW(IME通知应用程序:状态窗口将关闭) IMN_GUIDELINE(IME通知应用程序:将显示一条出错或其他信息) IMN_OPENCANDIDATE(IME通知应用程序:将打开候选窗口) IMN_OPENSTATUSWINDOW(IME通知应用程序:将创建状态窗口) IMN_SETCANDIDATEPOS(IME通知应用程序:已结束候选处理同时将移动候选窗口) IMN_SETCOMPOSITIONFONT(IME通知应用程序:输入内容的字体已更改) IMN_SETCOMPOSITIONWINDOW(IME通知应用程序:按键组合窗口的样式或位置已更改) IMN_SETCONVERSIONMODE(IME通知应用程序:输入内容的转换模式已更改) IMN_SETOPENSTATUS(IME通知应用程序:输入内容的状态已更改) IMN_SETSENTENCEMODE(IME通知应用程序:输入内容的语句模式已更改) IMN_SETSTATUSWINDOWPOS(IME通知应用程序:输入内容中的状态窗口的位置已更改) IMR_CANDIDATEWINDOW(通知:选定的IME需要应用程序提供有关候选窗口的信息) IMR_COMPOSITIONFONT(通知:选定的IME需要应用程序提供有关用在按键组合窗口中的字体的信息) IMR_COMPOSITIONWINDOW(通知:选定的IME需要应用程序提供有关按键组合窗口的信息) IMR_CONFIRMRECONVERTSTRING(通知:IME需要应用程序更改RECONVERTSTRING结构) IMR_DOCUMENTFEED(通知:选定的IME需要从应用程序那里取得已转换的字符串) IMR_QUERYCHARPOSITION(通知:选定的IME需要应用程序提供有关组合字符串中某个字符的位置信息) IMR_RECONVERTSTRING(通知:选定的IME需要应用程序提供一个用于自动更正的字符串) IME编程中需要用到的数据结构 这里列了所有在使用输入法编辑器函数和消息时需要用到的数据结构。 CANDIDATEFORM(描述候选窗口的位置信息) CANDIDATELIST(描述有关候选列表的信息) COMPOSITIONFORM(描述按键组合窗口的样式和位置信息) IMECHARPOSITION(描述按键组合窗口中的字符的位置信息) IMEMENUITEMINFO(描述IME菜单项的信息) RECONVERTSTRING(定义用于IME自动更正功能的字符串) REGISTERWORD(描述一个要注册的读入信息或文字内容) STYLEBUF(描述样式的标识符和名称) *) unit dll_imm32; interface uses atmcmbaseconst, winconst, wintype, wintypeA; const imm32 = 'imm32.dll'; STYLE_DESCRIPTION_SIZE = 32; type PCompositionForm = ^TCompositionForm; TCompositionForm = record dwStyle : DWORD; ptCurrentPos : TPOINT; rcArea : TRECT; end; PCandidateForm = ^TCandidateForm; TCandidateForm = record dwIndex : DWORD; dwStyle : DWORD; ptCurrentPos : TPOINT; rcArea : TRECT; end; PCandidateList = ^TCandidateList; TCandidateList = record dwSize : DWORD; dwStyle : DWORD; dwCount : DWORD; dwSelection : DWORD; dwPageStart : DWORD; dwPageSize : DWORD; dwOffset : array[1..1] of DWORD; end; PStyleBufA = ^TStyleBufA; PStyleBuf = PStyleBufA; TStyleBufA = record dwStyle : DWORD; szDescription : array[0..STYLE_DESCRIPTION_SIZE-1] of AnsiChar; end; TStyleBufW = record dwStyle : DWORD; szDescription : array[0..STYLE_DESCRIPTION_SIZE-1] of WideChar; end; TStyleBuf = TStyleBufA; function ImmInstallIMEA(lpszIMEFileName, lpszLayoutText: PAnsiChar): HKL; stdcall; external imm32 name 'ImmInstallIMEA'; function ImmGetDefaultIMEWnd(AWnd: HWND): HWND; stdcall; external imm32 name 'ImmGetDefaultIMEWnd'; function ImmGetDescriptionA(AKl: HKL; AChar: PAnsiChar; uBufLen: UINT): UINT; stdcall; external imm32 name 'ImmGetDescriptionA'; function ImmGetIMEFileNameA(AKl: HKL; AChar: PAnsiChar; uBufLen: UINT): UINT; stdcall; external imm32 name 'ImmGetIMEFileNameA'; function ImmGetProperty(AKl: HKL; dWord: DWORD): DWORD; stdcall; external imm32 name 'ImmGetProperty'; function ImmIsIME(AKl: HKL): Boolean; stdcall; external imm32 name 'ImmIsIME'; function ImmSimulateHotKey(AWnd: HWND; dWord: DWORD): Boolean; stdcall; external imm32 name 'ImmSimulateHotKey'; function ImmCreateContext: HIMC; stdcall; external imm32 name 'ImmCreateContext'; function ImmDestroyContext(AImc: HIMC): Boolean; stdcall; external imm32 name 'ImmDestroyContext'; function ImmGetContext(AWnd: HWND): HIMC; stdcall; external imm32 name 'ImmGetContext'; function ImmReleaseContext(AWnd: HWND; hImc: HIMC): Boolean; stdcall; external imm32 name 'ImmReleaseContext'; function ImmAssociateContext(AWnd: HWND; hImc: HIMC): HIMC; stdcall; external imm32 name 'ImmAssociateContext'; // 获取新的编码状态 const CFS_DEFAULT = $0000; CFS_RECT = $0001; CFS_POINT = $0002; CFS_SCREEN = $0004; { removed in 4.0 SDK } CFS_FORCE_POSITION = $0020; CFS_CANDIDATEPOS = $0040; CFS_EXCLUDE = $0080; GCR_ERRORSTR = 0; //修正错误 GCR_INFORMATIONSTR = 0; //修正信息串 GCS_COMPREADSTR = $0001;//修正读入串。 GCS_COMPREADATTR = $0002; //修正读入串的属性 GCS_COMPREADCLAUSE = $0004; //修正读入串的属性. GCS_COMPSTR = $0008;//修正当前的编码 GCS_COMPATTR = $0010;//修正编码串属性. GCS_COMPCLAUSE = $0020;//修正编码信息. GCS_CURSORPOS = $0080;//修正当前编码的光标位置. GCS_DELTASTART = $0100;//修正当前编码的开始位置 GCS_RESULTREADSTR = $0200; //修正读入串. GCS_RESULTREADCLAUSE = $0400; //修正读入串的信息. GCS_RESULTSTR = $0800;//修正编码结果串. GCS_RESULTCLAUSE = $1000;//修正结果串的信息. CS_INSERTCHAR = $2000;//在当前位置插入一个字符 CS_NOMOVECARET = $4000;//替换结果串 { error code of ImmGetCompositionString } IMM_ERROR_NODATA = -1; IMM_ERROR_GENERAL = -2; function ImmGetCompositionStrA(AImc: HIMC; dWord1: DWORD; lpBuf: pointer; dwBufLen: DWORD): Longint; stdcall; external imm32 name 'ImmGetCompositionStringA'; function ImmSetCompositionStrA(AImc: HIMC; dwIndex: DWORD; lpComp: pointer; dwCompLen: DWORD; lpRead: pointer; dwReadLen: DWORD):Boolean; stdcall; external imm32 name 'ImmSetCompositionStringA'; function ImmGetCandidateListCountA(AImc: HIMC; var ListCount: DWORD): DWORD; stdcall; external imm32 name 'ImmGetCandidateListCountA'; function ImmGetCandidateListA(AImc: HIMC; deIndex: DWORD; lpCandidateList: PCANDIDATELIST; dwBufLen: DWORD): DWORD; stdcall; external imm32 name 'ImmGetCandidateListA'; function ImmGetGuideLineA(AImc: HIMC; dwIndex: DWORD; lpBuf: PAnsiChar; dwBufLen: DWORD): DWORD; stdcall; external imm32 name 'ImmGetGuideLineA'; function ImmGetConversionStatus(AImc: HIMC; var Conversion, Sentence: DWORD): Boolean; stdcall; external imm32 name 'ImmGetConversionStatus'; function ImmSetConversionStatus(AImc: HIMC; Conversion, Sentence: DWORD): Boolean; stdcall; external imm32 name 'ImmSetConversionStatus'; function ImmGetOpenStatus(AImc: HIMC): Boolean; stdcall; external imm32 name 'ImmGetOpenStatus'; function ImmSetOpenStatus(AImc: HIMC; fOpen: Boolean): Boolean; stdcall; external imm32 name 'ImmSetOpenStatus'; function ImmGetCompositionFontA(AImc: HIMC; lpLogfont: PLOGFONTA): Boolean; stdcall; external imm32 name 'ImmGetCompositionFontA'; function ImmSetCompositionFontA(AImc: HIMC; lpLogfont: PLOGFONTA): Boolean; stdcall; external imm32 name 'ImmSetCompositionFontA'; function ImmConfigureIMEA(AKl: HKL; AWnd: HWND; dwMode: DWORD; lpData: pointer): Boolean; stdcall; external imm32 name 'ImmConfigureIMEA'; function ImmEscapeA(AKl: HKL; hImc: HIMC; uEscape: UINT; lpData: pointer): LRESULT; stdcall; external imm32 name 'ImmEscapeA'; function ImmGetConversionListA(AKl: HKL; AImc: HIMC; lpSrc: PAnsiChar; lpDst: PCANDIDATELIST; dwBufLen: DWORD; uFlag: UINT ): DWORD; stdcall; external imm32 name 'ImmGetConversionListA'; { dwIndex for ImmNotifyIME/NI_COMPOSITIONSTR } const CPS_COMPLETE = $0001; CPS_CONVERT = $0002; CPS_REVERT = $0003; CPS_CANCEL = $0004; function ImmNotifyIME(AImc: HIMC; dwAction, dwIndex, dwValue: DWORD): Boolean; stdcall; external imm32 name 'ImmNotifyIME'; function ImmGetStatusWindowPos(AImc: HIMC; var lpPoint : TPoint): Boolean; stdcall; external imm32 name 'ImmGetStatusWindowPos'; function ImmSetStatusWindowPos(AImc: HIMC; lpPoint: PPOINT): Boolean; stdcall; external imm32 name 'ImmSetStatusWindowPos'; function ImmGetCompositionWindow(AImc: HIMC; lpCompForm: PCOMPOSITIONFORM): Boolean; stdcall; external imm32 name 'ImmGetCompositionWindow'; function ImmSetCompositionWindow(AImc: HIMC; lpCompForm: PCOMPOSITIONFORM): Boolean; stdcall; external imm32 name 'ImmSetCompositionWindow'; function ImmGetCandidateWindow(AImc: HIMC; dwBufLen: DWORD; lpCandidate: PCANDIDATEFORM): Boolean; stdcall; external imm32 name 'ImmGetCandidateWindow'; function ImmSetCandidateWindow(AImc: HIMC; lpCandidate: PCANDIDATEFORM): Boolean; stdcall; external imm32 name 'ImmSetCandidateWindow'; function ImmIsUIMessageA(AWnd: HWND; msg: UINT; wParam: WPARAM; lParam: LPARAM): Boolean; stdcall; external imm32 name 'ImmIsUIMessageA'; function ImmGetVirtualKey(AWnd: HWND): UINT; stdcall; external imm32 name 'ImmGetVirtualKey'; function ImmRegisterWordA(AKl: HKL; lpszReading: PAnsiChar; dwStyle: DWORD; lpszRegister: PAnsiChar): Boolean; stdcall; external imm32 name 'ImmRegisterWordA'; function ImmUnregisterWordA(AKl: HKL; lpszReading: PAnsiChar; dwStyle: DWORD; lpszUnregister: PAnsiChar): Boolean; stdcall; external imm32 name 'ImmUnregisterWordA'; function ImmGetRegisterWordStyleA(AKl: HKL; nItem: UINT; lpStyleBuf: PSTYLEBUF): UINT; stdcall; external imm32 name 'ImmGetRegisterWordStyleA'; type RegisterWordEnumProcA = Function(lpReading: PAnsiChar; dwStyle: DWORD; lpszStr: PAnsiChar; lpData: pointer): integer; RegisterWordEnumProc = RegisterWordEnumProcA; function ImmEnumRegisterWordA(AKl: HKL; lpfnEnumProc: REGISTERWORDENUMPROC; lpszReading: PAnsiChar; dwStyle: DWORD; lpszRegister: PAnsiChar; lpData : pointer): UINT; stdcall; external imm32 name 'ImmEnumRegisterWordA'; const { the modifiers of hot key } MOD_ALT = $0001; MOD_CONTROL = $0002; MOD_SHIFT = $0004; MOD_LEFT = $8000; MOD_RIGHT = $4000; MOD_ON_KEYUP = $0800; MOD_IGNORE_ALL_MODIFIER = $0400; function ImmAssociateContextEx(AWnd: HWND; AImc: HIMC; dwFlag: DWORD): HIMC; stdcall; external imm32 name 'ImmAssociateContextEx'; function ImmCreateSoftKeyboard( //产生一个软键盘 uType: UINT; //软件盘上的键码含义的定义方式 //=SOFTKEYBOARD_TYPE_T1 //=SOFTKEYBOARD_TYPE_C1 AOwner: UINT; //该输入法的UI窗口 x, y: int32 ): HWND; stdcall; external imm32 name 'ImmCreateSoftKeyboard';//定位坐标 function ImmDestroySoftKeyboard( //销毁软键盘 hSoftKbdWnd: HWND): BOOL; stdcall; external imm32 name 'ImmDestroySoftKeyboard'; function ImmShowSoftKeyboard( //显示或隐藏软键盘 hSoftKbdWnd: HWND; //软年盘窗口句柄 nCmdShow: int32 //窗口状态=SW_HIDE 表示隐藏,=SW_SHOWNOACTIVATE表示显示 ): BOOL; stdcall; external imm32 name 'ImmShowSoftKeyboard'; function ImmDisableIME(idThread: DWORD): BOOL; stdcall; external imm32 name 'ImmDisableIME'; implementation (* 自己改改: SetIMEMode(HWND hWnd, DWORD dwNewConvMode, DWORD dwNewSentMode, BOOL fFlag) { HIMC hImc; DWORD dwConvMode, dwSentMode; BOOL fRet; // Get input context hImc = ImmGetContext(hWnd); if (hImc) { // Get current IME status ImmGetConversionStatus(hImc, &dwConvMode, &dwSentMode); // Change IME status using passed option if (fFlag) { fRet = ImmSetConversionStatus(hImc, dwConvMode | dwNewConvMode, dwSentMode | dwNewSentMode); if ((m_IMEEdit.m_nLanguage == JAPANESE) && (dwNewConvMode & IME_CMODE_NATIVE)) ImmSetOpenStatus(hImc, fFlag); } else { ImmSetConversionStatus(hImc, dwConvMode & ~dwNewConvMode, dwSentMode & ~dwNewSentMode); if ((m_IMEEdit.m_nLanguage == JAPANESE) && (dwNewConvMode & IME_CMODE_NATIVE)) ImmSetOpenStatus(hImc, fFlag); } // Release input context ImmReleaseContext(hWnd, hImc); } } Top *) end.
program exer3; const max = 100; type mat = array [1 .. max,1 .. max] of integer; procedure imprimir(var matriz:mat;var tam:integer); var i,j:integer; begin j:=tam; for i:=1 to tam do begin write(matriz[j,i],' '); j:=j-1; end; writeln(' '); end; procedure ler(var matriz:mat; var tam:integer); var i,j:integer; begin read(tam); for i:=1 to tam do for j:=1 to tam do read(matriz[i,j]); end; var matriz:mat; temp,tam,auxtam,i,j:integer; begin ler(matriz,tam); if (tam mod 2 = 0) then auxtam:=tam div 2 else auxtam:=(tam-1) div 2; j:=tam; for i:=1 to auxtam do begin temp:=matriz[i,j]; matriz[i,j]:=matriz[j,i]; matriz[j,i]:=temp; j:=j-1; end; imprimir(matriz,tam); end. //Ex. //- escrever um procedimento que faz a inversao da diagonal secundaria de //uma matriz quadrada.
unit uHost; {$mode objfpc}{$H+} interface uses Classes, SysUtils; function HostIsBlockNormal: boolean; function HostIsBlockExtra: boolean; function HostIsBlockSuperExtra: boolean; procedure SetHostBlockNormal; procedure SetHostBlockExtra; procedure SetHostBlockSuperExtra; procedure SetHostNotBlockNormal; procedure SetHostNotBlockExtra; procedure SetHostNotBlockSuperExtra; implementation const NormalBlockList : array[0..89] of string = ( 'a-0001.a-msedge.net', 'a-0002.a-msedge.net', 'a-0003.a-msedge.net', 'a-0004.a-msedge.net', 'a-0005.a-msedge.net', 'a-0006.a-msedge.net', 'a-0007.a-msedge.net', 'a-0008.a-msedge.net', 'a-0009.a-msedge.net', 'a-msedge.net', 'a.ads1.msn.com', 'a.ads2.msads.net', 'a.ads2.msn.com', 'a.rad.msn.com', 'ac3.msn.com', 'ad.doubleclick.net', 'adnexus.net', 'adnxs.com', 'ads.msn.com', 'ads1.msads.net', 'ads1.msn.com', 'aidps.atdmt.com', 'aka-cdn-ns.adtech.de', 'az361816.vo.msecnd.net', 'az512334.vo.msecnd.net', 'b.ads1.msn.com', 'b.ads2.msads.net', 'b.rad.msn.com', 'bs.serving-sys.com', 'c.atdmt.com', 'c.msn.com', 'cdn.atdmt.com', 'cds26.ams9.msecn.net', 'choice.microsoft.com', 'choice.microsoft.com.nsatc.net', 'compatexchange.cloudapp.net', 'corp.sts.microsoft.com', 'corpext.msitadfs.glbdns2.microsoft.com', 'cs1.wpc.v0cdn.net', 'db3aqu.atdmt.com', 'df.telemetry.microsoft.com', 'diagnostics.support.microsoft.com', 'ec.atdmt.com', 'feedback.microsoft-hohm.com', 'feedback.search.microsoft.com', 'feedback.windows.com', 'flex.msn.com', 'g.msn.com', 'h1.msn.com', 'i1.services.social.microsoft.com', 'i1.services.social.microsoft.com.nsatc.net', 'lb1.www.ms.akadns.net', 'live.rads.msn.com', 'm.adnxs.com', 'msedge.net', 'msftncsi.com', 'msnbot-65-55-108-23.search.msn.com', 'msntest.serving-sys.com', 'oca.telemetry.microsoft.com', 'oca.telemetry.microsoft.com.nsatc.net', 'pre.footprintpredict.com', 'preview.msn.com', 'rad.live.com', 'rad.msn.com', 'redir.metaservices.microsoft.com', 'schemas.microsoft.akadns.net ', 'secure.adnxs.com', 'secure.flashtalking.com', 'settings-sandbox.data.microsoft.com', 'settings-win.data.microsoft.com', 'sls.update.microsoft.com.akadns.net', 'sqm.df.telemetry.microsoft.com', 'sqm.telemetry.microsoft.com', 'sqm.telemetry.microsoft.com.nsatc.net', 'static.2mdn.net', 'statsfe1.ws.microsoft.com', 'statsfe2.ws.microsoft.com', 'telecommand.telemetry.microsoft.com', 'telecommand.telemetry.microsoft.com.nsatc.net', 'telemetry.appex.bing.net', 'telemetry.microsoft.com', 'telemetry.urs.microsoft.com', 'vortex-bn2.metron.live.com.nsatc.net', 'vortex-cy2.metron.live.com.nsatc.net', 'vortex-sandbox.data.microsoft.com', 'vortex-win.data.microsoft.com', 'vortex.data.microsoft.com', 'watson.live.com', 'www.msftncsi.com', 'ssw.live.com' ); ExtraBlockList : array [0..17] of string = ( 'fe2.update.microsoft.com.akadns.net', 'reports.wes.df.telemetry.microsoft.com', 's0.2mdn.net', 'services.wes.df.telemetry.microsoft.com', 'statsfe2.update.microsoft.com.akadns.net', 'survey.watson.microsoft.com', 'view.atdmt.com', 'watson.microsoft.com', 'watson.ppe.telemetry.microsoft.com', 'watson.telemetry.microsoft.com', 'watson.telemetry.microsoft.com.nsatc.net', 'wes.df.telemetry.microsoft.com', 'ui.skype.com', 'pricelist.skype.com', 'apps.skype.com', 'm.hotmail.com', 's.gateway.messenger.live.com', 'choice.microsoft.com.nstac.net' ); SuperExtraBlockList : array [0..3] of string = ( 'spynet2.microsoft.com','spynetalt.microsoft.com','h2.msn.com','sO.2mdn.net' ); function HostIsBlockNormal: boolean; // true - block, false, not block var i: integer; sl: TStringList; begin sl := TStringList.Create; result:=true; try sl.LoadFromFile(GetEnvironmentVariable('WinDir')+'\System32\drivers\etc\hosts'); for i:=0 to Length(NormalBlockList)-1 do if Pos(#9+NormalBlockList[i], sl.Text) = 0 then begin result:=false; exit; end; finally sl.Free; end; end; function HostIsBlockExtra: boolean; // true - block, false, not block var i: integer; sl: TStringList; begin sl := TStringList.Create; result:=true; try sl.LoadFromFile(GetEnvironmentVariable('WinDir')+'\System32\drivers\etc\hosts'); for i:=0 to Length(ExtraBlockList)-1 do if Pos(#9+ExtraBlockList[i], sl.Text) = 0 then begin result:=false; exit; end; finally sl.Free; end; end; function HostIsBlockSuperExtra: boolean; // true - block, false, not block var i: integer; sl: TStringList; begin sl := TStringList.Create; result:=true; try sl.LoadFromFile(GetEnvironmentVariable('WinDir')+'\System32\drivers\etc\hosts'); for i:=0 to Length(SuperExtraBlockList)-1 do if Pos(#9+SuperExtraBlockList[i], sl.Text) = 0 then begin result:=false; exit; end; finally sl.Free; end; end; procedure SetHostBlockNormal; var i: integer; sl: TStringList; hostpath: string; begin sl := TStringList.Create; hostpath := GetEnvironmentVariable('WinDir')+'\System32\drivers\etc\hosts'; try sl.LoadFromFile(hostpath); for i:=0 to Length(NormalBlockList)-1 do if Pos(#9+NormalBlockList[i], sl.Text) = 0 then sl.Add('0.0.0.0'+#9+NormalBlockList[i]); sl.SaveToFile(hostpath); finally sl.Free; end; end; procedure SetHostBlockExtra; var i: integer; sl: TStringList; hostpath: string; begin sl := TStringList.Create; hostpath := GetEnvironmentVariable('WinDir')+'\System32\drivers\etc\hosts'; try sl.LoadFromFile(hostpath); for i:=0 to Length(ExtraBlockList)-1 do if Pos(#9+ExtraBlockList[i], sl.Text) = 0 then sl.Add('0.0.0.0'+#9+ExtraBlockList[i]); sl.SaveToFile(hostpath); finally sl.Free; end; end; procedure SetHostBlockSuperExtra; var i: integer; sl: TStringList; hostpath: string; begin sl := TStringList.Create; hostpath := GetEnvironmentVariable('WinDir')+'\System32\drivers\etc\hosts'; try sl.LoadFromFile(hostpath); for i:=0 to Length(SuperExtraBlockList)-1 do if Pos(#9+SuperExtraBlockList[i], sl.Text) = 0 then sl.Add('0.0.0.0'+#9+SuperExtraBlockList[i]); sl.SaveToFile(hostpath); finally sl.Free; end; end; procedure SetHostNotBlockNormal; var i, j: integer; sl: TStringList; hostpath: string; Del: Boolean; begin sl := TStringList.Create; hostpath := GetEnvironmentVariable('WinDir')+'\System32\drivers\etc\hosts'; try sl.LoadFromFile(hostpath); for i:=sl.Count-1 downto 0 do if (sl.Strings[i] = EmptyStr) or (sl.Strings[i][1]=PChar('#')) then Continue else begin Del := false; for j:=0 to Length(NormalBlockList)-1 do if (not del) and (Pos(#9+NormalBlockList[j], sl.Strings[i]) > 0) then begin del := true; sl.Delete(i); Continue; end; end; sl.SaveToFile(hostpath); finally sl.Free; end; end; procedure SetHostNotBlockExtra; var i, j: integer; sl: TStringList; hostpath: string; Del: Boolean; begin sl := TStringList.Create; hostpath := GetEnvironmentVariable('WinDir')+'\System32\drivers\etc\hosts'; try sl.LoadFromFile(hostpath); for i:=sl.Count-1 downto 0 do if (sl.Strings[i] = EmptyStr) or (sl.Strings[i][1]=PChar('#')) then Continue else begin Del := false; for j:=0 to Length(ExtraBlockList)-1 do if (not del) and (Pos(#9+ExtraBlockList[j], sl.Strings[i]) > 0) then begin del := true; sl.Delete(i); Continue; end; end; sl.SaveToFile(hostpath); finally sl.Free; end; end; procedure SetHostNotBlockSuperExtra; var i, j: integer; sl: TStringList; hostpath: string; Del: Boolean; begin sl := TStringList.Create; hostpath := GetEnvironmentVariable('WinDir')+'\System32\drivers\etc\hosts'; try sl.LoadFromFile(hostpath); for i:=sl.Count-1 downto 0 do if (sl.Strings[i] = EmptyStr) or (sl.Strings[i][1]=PChar('#')) then Continue else begin Del := false; for j:=0 to Length(SuperExtraBlockList)-1 do if (not del) and (Pos(#9+SuperExtraBlockList[j], sl.Strings[i]) > 0) then begin del := true; sl.Delete(i); Continue; end; end; sl.SaveToFile(hostpath); finally sl.Free; end; end; end.
unit SelectEditController; interface uses Classes, SysUtils, tiObject, mapper, mvc_base, widget_controllers, AppModel, SelectEditViewFrm, BaseOkCancelDialogController; type // ----------------------------------------------------------------- // Class Objects // ----------------------------------------------------------------- {: Main application controller. } TSelectEditController = class(TBaseOkCancelDialogController) protected procedure DoCreateMediators; override; procedure HandleOKClick(Sender: TObject); override; public constructor Create(AModel: TClassMappingSelect; AView: TSelectEditView); reintroduce; overload; virtual; function Model: TClassMappingSelect; reintroduce; function View: TSelectEditView; reintroduce; end; implementation uses vcl_controllers, SelectEditCommands, StdCtrls, Controls, Dialogs; { TSelectEditController } constructor TSelectEditController.Create(AModel: TClassMappingSelect; AView: TSelectEditView); begin inherited Create(AModel, AView); RegisterCommands(self); end; procedure TSelectEditController.DoCreateMediators; var lListCtrl: TListViewController; begin inherited; AddController(TEditController.Create(Model, View.eName, 'Name')); AddController(TMemoController.Create(Model, View.memSQL, 'SQL')); lListCtrl := TListViewController.Create(Model.Params, View.lvParams, ''); lListCtrl.Name := 'params_ctl'; with lListCtrl.AddNewCol('ParamName') do begin Width := 120; ColCaption := 'Param Name'; end; with lListCtrl.AddNewCol('SQLParamName') do begin Width := 120; ColCaption := 'SQL Param'; end; with lListCtrl.AddNewCol('ParamType.TypeName') do begin Width := 100; ColCaption := 'Param Type'; end; with lListCtrl.AddNewCol('PassBy') do begin Width := 100; ColCaption := 'Pass By'; end; Controllers.Add(lListCtrl); end; procedure TSelectEditController.HandleOKClick(Sender: TObject); var lMsg: string; begin if not Model.IsValid(lMsg) then begin MessageDlg('Error(s): ' + sLineBreak + lMsg, mtError, [mbOK], 0); exit; end; end; function TSelectEditController.Model: TClassMappingSelect; begin result := inherited Model as TClassMappingSelect; end; function TSelectEditController.View: TSelectEditView; begin result := inherited View as TSelectEditView; end; end.
{******************************************************************************} { } { Icon Fonts ImageList: An extended ImageList for Delphi } { to simplify use of Icons (resize, colors and more...) } { } { Copyright (c) 2019-2023 (Ethea S.r.l.) } { Contributors: } { Carlo Barazzetta } { Nicola Tambascia } { } { https://github.com/EtheaDev/IconFontsImageList } { } {******************************************************************************} { } { 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 IconFontsImageListEditorUnit; interface {$INCLUDE ..\Source\IconFontsImageList.inc} uses Windows , Messages , SysUtils , Graphics , Forms , StdCtrls , ExtCtrls , Controls , Classes , Dialogs , ComCtrls , ImgList , ExtDlgs , Spin , IconFontsCharMapUnit , IconFontsImageList , IconFontsImageListBase , IconFontsVirtualImageList , IconFontsImageCollection , IconFontsItems , IconFontsImage; type TIconFontsImageListEditor = class(TForm) paImages: TPanel; CategorySplitter: TSplitter; Panel1: TPanel; SetCategoriesButton: TButton; ImagesPanel: TPanel; CategoryGroupBox: TGroupBox; CategoryListBox: TListBox; PropertiesGroupBox: TGroupBox; ImageListGroup: TGroupBox; ImageView: TListView; AddButton: TButton; DeleteButton: TButton; ClearAllButton: TButton; ExportButton: TButton; WinCharMapButton: TButton; ShowCharMapButton: TButton; DefaultFontNameLabel: TLabel; DefaultFontName: TComboBox; DefaultFontColorLabel: TLabel; DefaultFontColorColorBox: TColorBox; DefaultMaskColorLabel: TLabel; DefaultMaskColorColorBox: TColorBox; StoreBitmapCheckBox: TCheckBox; BottomPanel: TPanel; OKButton: TButton; ApplyButton: TButton; CancelButton: TButton; HelpButton: TButton; ImageListGroupBox: TGroupBox; SizeLabel: TLabel; WidthLabel: TLabel; HeightLabel: TLabel; SizeSpinEdit: TSpinEdit; WidthSpinEdit: TSpinEdit; HeightSpinEdit: TSpinEdit; BottomSplitter: TSplitter; ItemGroupBox: TGroupBox; LeftIconPanel: TPanel; IconPanel: TPanel; IconImage: TIconFontImage; IconClientPanel: TPanel; IconBuilderGroupBox: TGroupBox; FromHexNumLabel: TLabel; ToHexNumLabel: TLabel; CharsEditLabel: TLabel; CharsEdit: TEdit; BuildButton: TButton; BuildFromHexButton: TButton; FromHexNum: TEdit; ToHexNum: TEdit; FontNameLabel: TLabel; FontName: TComboBox; FontIconHexLabel: TLabel; FontIconHex: TEdit; FontIconDecLabel: TLabel; FontIconDec: TSpinEdit; FontColorLabel: TLabel; FontColor: TColorBox; MaskColorLabel: TLabel; MaskColor: TColorBox; NameLabel: TLabel; NameEdit: TEdit; CategoryLabel: TLabel; CategoryEdit: TEdit; IconLeftMarginPanel: TPanel; ZoomLabel: TLabel; ZoomSpinEdit: TSpinEdit; procedure FormCreate(Sender: TObject); procedure ApplyButtonClick(Sender: TObject); procedure ClearAllButtonClick(Sender: TObject); procedure DeleteButtonClick(Sender: TObject); procedure AddButtonClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FontColorChange(Sender: TObject); procedure MaskColorChange(Sender: TObject); procedure HelpButtonClick(Sender: TObject); procedure FontNameChange(Sender: TObject); procedure NameEditExit(Sender: TObject); procedure FontIconDecChange(Sender: TObject); procedure ShowCharMapButtonClick(Sender: TObject); procedure ImageViewSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure BuildButtonClick(Sender: TObject); procedure SizeSpinEditChange(Sender: TObject); procedure StoreBitmapCheckBoxClick(Sender: TObject); procedure DefaultFontColorColorBoxChange(Sender: TObject); procedure DefaultMaskColorColorBoxChange(Sender: TObject); procedure BuildFromHexButtonClick(Sender: TObject); procedure EditChangeUpdateGUI(Sender: TObject); procedure ImageViewKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure ExportButtonClick(Sender: TObject); procedure DefaultFontNameSelect(Sender: TObject); procedure FontIconHexExit(Sender: TObject); procedure FormShow(Sender: TObject); procedure ImageViewDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); procedure ImageViewDragDrop(Sender, Source: TObject; X, Y: Integer); procedure WidthSpinEditChange(Sender: TObject); procedure HeightSpinEditChange(Sender: TObject); procedure WinCharMapButtonClick(Sender: TObject); procedure CategoryListBoxClick(Sender: TObject); procedure SetCategoriesButtonClick(Sender: TObject); procedure CategoryEditExit(Sender: TObject); procedure ZoomSpinEditChange(Sender: TObject); private FSelectedCategory: string; FSourceList, FEditingList: TIconFontsImageListBase; FCharMap: TIconFontsCharMapForm; FIconIndexLabel: string; FTotIconsLabel: string; FUpdating: Boolean; FChanged: Boolean; FModified: Boolean; procedure IconFontsImageListFontMissing(const AFontName: TFontName); procedure CloseCharMap(Sender: TObject; var Action: TCloseAction); procedure BuildList(Selected: Integer); procedure AddColor(const S: string); procedure UpdateCategories; procedure UpdateSizeGUI; procedure AddNewItem; procedure DeleteSelectedItems; procedure Apply; procedure UpdateGUI; procedure UpdateCharsToBuild; {$IFNDEF GDI+} procedure SetImageMaskColor(Color: TColor); {$ENDIF} procedure SetImageFontColor(Color: TColor); procedure SetImageFontIconDec(IconDec: Integer); procedure SetImageFontIconHex(IconHex: String); procedure SetImageIconName(Name: String); procedure SetImageFontName(FontName: TFontName); function SelectedIcon: TIconFontItem; procedure InitGUI; public destructor Destroy; override; property Modified: Boolean read FModified; property IconFontsImageList: TIconFontsImageListBase read FEditingList; end; function EditIconFontsImageList(const AImageList: TIconFontsImageListBase): Boolean; function EditIconFontsVirtualImageList(const AImageList: TIconFontsVirtualImageList): Boolean; function EditIconFontsImageCollection(const AImageCollection: TIconFontsImageCollection): Boolean; implementation {$R *.dfm} uses CommCtrl {$WARN UNIT_PLATFORM OFF} , FileCtrl , TypInfo , ShellApi {$IFDEF DXE3+} , UITypes , System.Types , System.Character {$ENDIF} //WARNING: you must define this directive to use this unit outside the IDE {$IFNDEF UseIconFontEditorsAtRunTime} {$IF (CompilerVersion >= 24.0)} , Vcl.Themes , ToolsAPI {$IFEND} {$IF (CompilerVersion >= 32.0)} , IDETheme.Utils , BrandingAPI {$IFEND} {$ENDIF} , IconFontsUtils; const crColorPick = -100; var SavedBounds: TRect = (Left: 0; Top: 0; Right: 0; Bottom: 0); function EditIconFontsImageList(const AImageList: TIconFontsImageListBase): Boolean; var LEditor: TIconFontsImageListEditor; begin LEditor := TIconFontsImageListEditor.Create(nil); with LEditor do begin try Screen.Cursor := crHourglass; try FSourceList := AImageList; FEditinglist.Assign(AImageList); InitGUI; finally Screen.Cursor := crDefault; end; Result := ShowModal = mrOk; if Result then begin Screen.Cursor := crHourglass; try AImageList.Assign(FEditingList); finally Screen.Cursor := crDefault; end; end; SavedBounds := BoundsRect; finally Free; end; end; end; function EditIconFontsVirtualImageList(const AImageList: TIconFontsVirtualImageList): Boolean; var LEditor: TIconFontsImageListEditor; begin if AImageList.ImageCollection = nil then begin Result := false; Exit; end; LEditor := TIconFontsImageListEditor.Create(nil); with LEditor do begin try Screen.Cursor := crHourglass; try FSourceList := TIconFontsImageList.Create(LEditor); FSourceList.Assign(AImageList); FEditingList.Assign(AImageList); InitGUI; finally Screen.Cursor := crDefault; end; Result := ShowModal = mrOk; if Result then begin Screen.Cursor := crHourglass; try AImageList.ImageCollection.IconFontItems.Assign(LEditor.FEditingList.IconFontItems); AImageList.Assign(LEditor.FEditingList); finally Screen.Cursor := crDefault; end; end; SavedBounds := BoundsRect; finally Free; end; end; end; function EditIconFontsImageCollection(const AImageCollection: TIconFontsImageCollection): Boolean; var LEditor: TIconFontsImageListEditor; begin LEditor := TIconFontsImageListEditor.Create(nil); with LEditor do begin try Screen.Cursor := crHourglass; try FSourceList := TIconFontsImageList.Create(LEditor); FSourceList.IconFontItems.Assign(AImageCollection.IconFontItems); FSourceList.Size := 64; //Force 64 pixel size for image collection icons FSourceList.FontName := AImageCollection.FontName; FSourceList.FontColor := AImageCollection.FontColor; FSourceList.MaskColor := AImageCollection.MaskColor; FSourceList.Zoom := AImageCollection.Zoom; ImageListGroupBox.Visible := False; FSourceList.IconFontItems.Assign(AImageCollection.IconFontItems); FEditingList.Assign(FSourceList); InitGUI; finally Screen.Cursor := crDefault; end; Result := ShowModal = mrOk; if Result then begin Screen.Cursor := crHourglass; try AImageCollection.IconFontItems.Assign(LEditor.FEditingList.IconFontItems); AImageCollection.FontName := DefaultFontName.Text; AImageCollection.FontColor := DefaultFontColorColorBox.Selected; AImageCollection.MaskColor := DefaultMaskColorColorBox.Selected; AImageCollection.Zoom := ZoomSpinEdit.Value; finally Screen.Cursor := crDefault; end; end; SavedBounds := BoundsRect; finally Free; end; end; end; { TIconFontsImageListEditor } procedure TIconFontsImageListEditor.UpdateSizeGUI; begin WidthSpinEdit.Value := FEditingList.Width; HeightSpinEdit.Value := FEditingList.Height; SizeSpinEdit.Value := FEditingList.Size; if FEditingList.Width = FEditingList.Height then begin SizeSpinEdit.Enabled := True; IconPanel.Align := alClient; end else begin SizeSpinEdit.Enabled := False; if FEditingList.Width > FEditingList.Height then begin IconPanel.Align := alTop; IconPanel.Height := Round(IconPanel.Width * FEditingList.Height / FEditingList.Width); end else begin IconPanel.Align := alLeft; IconPanel.Height := Round(IconPanel.Height * FEditingList.Width / FEditingList.Height); end; end; end; procedure TIconFontsImageListEditor.HelpButtonClick(Sender: TObject); begin ShellExecute(handle, 'open', PChar('https://github.com/EtheaDev/IconFontsImageList/wiki/Component-Editor-(VCL)'), nil, nil, SW_SHOWNORMAL) end; {$IFNDEF GDI+} procedure TIconFontsImageListEditor.SetImageMaskColor(Color: TColor); begin SelectedIcon.MaskColor := Color; UpdateGUI; end; {$ENDIF} procedure TIconFontsImageListEditor.ShowCharMapButtonClick(Sender: TObject); begin ShowCharMapButton.SetFocus; if not Assigned(FCharMap) then begin FCharMap := TIconFontsCharMapForm.CreateForImageList(Self, FEditingList, FontName.Text); FCharMap.OnClose := CloseCharMap; end; FCharMap.AssignImageList(FEditingList, FontName.Text); FCharMap.Show; end; procedure TIconFontsImageListEditor.StoreBitmapCheckBoxClick(Sender: TObject); begin {$IFDEF HasStoreBitmapProperty} FEditingList.StoreBitmap := StoreBitmapCheckBox.Checked; FChanged := True; {$ENDIF} end; procedure TIconFontsImageListEditor.SetImageFontColor(Color: TColor); begin SelectedIcon.FontColor := Color; UpdateGUI; end; procedure TIconFontsImageListEditor.SetImageFontIconDec(IconDec: Integer); begin SelectedIcon.FontIconDec := IconDec; BuildList(SelectedIcon.Index); end; procedure TIconFontsImageListEditor.SetImageFontIconHex(IconHex: String); begin SelectedIcon.FontIconHex := IconHex; BuildList(SelectedIcon.Index); end; procedure TIconFontsImageListEditor.SetImageIconName(Name: String); begin SelectedIcon.Name := Name; BuildList(SelectedIcon.Index); end; procedure TIconFontsImageListEditor.SetImageFontName(FontName: TFontName); begin SelectedIcon.FontName := FontName; BuildList(SelectedIcon.Index); end; procedure TIconFontsImageListEditor.FontColorChange(Sender: TObject); begin if FUpdating then Exit; SetImageFontColor(FontColor.Selected); end; procedure TIconFontsImageListEditor.FontIconDecChange(Sender: TObject); begin if FUpdating then Exit; SetImageFontIconDec(FontIconDec.Value); end; procedure TIconFontsImageListEditor.FontIconHexExit(Sender: TObject); var LText: string; begin if FUpdating then Exit; LText := (Sender as TEdit).Text; if (Length(LText) = 4) or (Length(LText) = 5) or (Length(LText)=0) then begin if Sender = FontIconHex then SetImageFontIconHex(FontIconHex.Text); end; end; procedure TIconFontsImageListEditor.FontNameChange(Sender: TObject); begin if FUpdating then Exit; if (FontName.Text = '') or (Screen.Fonts.IndexOf(FontName.Text) >= 0) then begin SetImageFontName(FontName.Text); UpdateCharsToBuild; end; end; procedure TIconFontsImageListEditor.UpdateCharsToBuild; begin CharsEdit.Font.Size := 12; if FontName.Text <> '' then begin CharsEdit.Font.Name := FontName.Text; CharsEdit.Enabled := True; end else if DefaultFontName.Text <> '' then begin CharsEdit.Font.Name := DefaultFontName.Text; CharsEdit.Enabled := True; end else begin CharsEdit.Enabled := False; BuildButton.Enabled := False; end; end; procedure TIconFontsImageListEditor.UpdateCategories; var I: Integer; LCategory: string; begin CategoryListBox.Items.Clear; CategoryListBox.AddItem('All', nil); for I := 0 to FEditingList.IconFontItems.Count -1 do begin LCategory := FEditingList.IconFontItems[I].Category; if (LCategory <> '') and (CategoryListBox.Items.IndexOf(LCategory)<0) then CategoryListBox.AddItem(LCategory,nil); end; if (FSelectedCategory <> '') then begin I := CategoryListBox.Items.IndexOf(FSelectedCategory); if I >= 0 then CategoryListBox.Selected[I] := True; end else CategoryListBox.Selected[0] := True; end; procedure TIconFontsImageListEditor.UpdateGUI; var LIsItemSelected: Boolean; LItemFontName: TFontName; LIconFontItem: TIconFontItem; begin FUpdating := True; try UpdateCategories; LIconFontItem := SelectedIcon; LIsItemSelected := LIconFontItem <> nil; ClearAllButton.Enabled := FEditingList.Count > 0; ExportButton.Enabled := FEditingList.Count > 0; BuildButton.Enabled := CharsEdit.Text <> ''; BuildFromHexButton.Enabled := (Length(FromHexNum.Text) in [4,5]) and (Length(ToHexNum.Text) in [4,5]); DeleteButton.Enabled := LIsItemSelected; SetCategoriesButton.Enabled := LIsItemSelected; ApplyButton.Enabled := FChanged; FontColor.Enabled := LIsItemSelected; MaskColor.Enabled := LIsItemSelected; FontName.Enabled := LIsItemSelected; FontIconDec.Enabled := LIsItemSelected; FontIconHex.Enabled := LIsItemSelected; NameEdit.Enabled := LIsItemSelected; CategoryEdit.Enabled := LIsItemSelected; ShowCharMapButton.Enabled := (FEditingList.FontName <> ''); ImageListGroup.Caption := Format(FTotIconsLabel, [FEditingList.Count]); if LIsItemSelected then begin IconImage.ImageIndex := SelectedIcon.Index; ItemGroupBox.Caption := Format(FIconIndexLabel,[LIconFontItem.Index]); {$IFNDEF GDI+} if LIconFontItem.MaskColor <> FEditingList.MaskColor then MaskColor.Selected := LIconFontItem.MaskColor else MaskColor.Selected := clNone; {$ELSE} MaskColor.Selected := clNone; MaskColor.Enabled := False; {$ENDIF} if LIconFontItem.FontColor <> FEditingList.FontColor then FontColor.Selected := LIconFontItem.FontColor else FontColor.Selected := clDefault; LItemFontName := LIconFontItem.FontName; FontName.ItemIndex := FontName.Items.IndexOf(LItemFontName); NameEdit.Text := LIconFontItem.Name; CategoryEdit.Text := LIconFontItem.Category; FontIconDec.Value := LIconFontItem.FontIconDec; FontIconHex.Text := LIconFontItem.FontIconHex; IconPanel.Invalidate; //Draw Icon IconImage.Invalidate; end else begin FontColor.Selected := clDefault; MaskColor.Selected := clNone; FontName.ItemIndex := -1; IconImage.ImageIndex := -1; ItemGroupBox.Caption := ''; NameEdit.Text := ''; CategoryEdit.Text := ''; FontIconDec.Value := 0; FontIconHex.Text := ''; end; finally FUpdating := False; end; end; procedure TIconFontsImageListEditor.WidthSpinEditChange(Sender: TObject); begin if FUpdating then Exit; FEditingList.Width := WidthSpinEdit.Value; UpdateSizeGUI; end; procedure TIconFontsImageListEditor.WinCharMapButtonClick(Sender: TObject); begin WinCharMapButton.SetFocus; ShellExecute(Handle, 'open', 'charmap', '', '', SW_SHOWNORMAL); end; procedure TIconFontsImageListEditor.ZoomSpinEditChange(Sender: TObject); begin FEditingList.Zoom := ZoomSpinEdit.Value; IconImage.Zoom := ZoomSpinEdit.Value; FChanged := True; UpdateGUI; end; procedure TIconFontsImageListEditor.ImageViewDragDrop(Sender, Source: TObject; X, Y: Integer); var LTargetItem: TListItem; LItem: TCollectionItem; SIndex, DIndex: Integer; begin LTargetItem := ImageView.GetItemAt(X, Y); if not Assigned(LTargetItem) then LTargetItem := ImageView.GetNearestItem(Point(X, Y), sdRight); if Assigned(LTargetItem) then DIndex := LTargetItem.ImageIndex else DIndex := ImageView.Items.Count - 1; SIndex := ImageView.Items[ImageView.ItemIndex].ImageIndex; LItem := FEditingList.IconFontItems[SIndex]; LItem.Index := DIndex; BuildList(LItem.Index); if SIndex <> DIndex then FChanged := True; end; procedure TIconFontsImageListEditor.ImageViewDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); begin Accept := Source = Sender; end; procedure TIconFontsImageListEditor.DeleteSelectedItems; var LIndex: Integer; LSelectedImageIndex: Integer; begin Screen.Cursor := crHourGlass; try LSelectedImageIndex := ImageView.Items[ImageView.ItemIndex].ImageIndex; FEditingList.BeginUpdate; try for LIndex := ImageView.Items.Count - 1 downto 0 do if ImageView.Items[LIndex].Selected then FEditingList.Delete(ImageView.Items[LIndex].ImageIndex); finally FEditingList.EndUpdate; end; FChanged := True; BuildList(LSelectedImageIndex); finally Screen.Cursor := crDefault; end; end; destructor TIconFontsImageListEditor.Destroy; begin FCharMap.Free; inherited; end; procedure TIconFontsImageListEditor.CategoryListBoxClick(Sender: TObject); var LIndex: Integer; begin if SelectedIcon <> nil then LIndex := SelectedIcon.Index else LIndex := -1; if CategoryListBox.ItemIndex <= 0 then FSelectedCategory := '' else FSelectedCategory := CategoryListBox.Items[CategoryListBox.ItemIndex]; BuildList(LIndex); end; procedure TIconFontsImageListEditor.CloseCharMap(Sender: TObject; var Action: TCloseAction); var LImageIndex: Integer; LIconFontItem: TIconFontItem; begin if FCharMap.ModalResult = mrOK then begin if FCharMap.CharsEdit.Text <> '' then begin FEditingList.AddIcons(FCharMap.CharsEdit.Text, FCharMap.DefaultFontName.Text); FChanged := True; LImageIndex := ImageView.Items.Count-1; if LImageIndex >= 0 then BuildList(ImageView.Items[LImageIndex].ImageIndex) else BuildList(-1); end else if FCharMap.SelectedIconFont <> nil then begin LIconFontItem := FEditingList.AddIcon(FCharMap.SelectedIconFont.FontIconDec); FChanged := True; BuildList(LIconFontItem.Index); end; end; end; procedure TIconFontsImageListEditor.ClearAllButtonClick(Sender: TObject); begin Screen.Cursor := crHourGlass; try ImageView.Clear; FEditingList.ClearIcons; FChanged := True; UpdateGUI; finally Screen.Cursor := crDefault; end; end; procedure TIconFontsImageListEditor.IconFontsImageListFontMissing( const AFontName: TFontName); begin MessageDlg(Format(ERR_ICONFONTS_FONT_NOT_INSTALLED,[AFontName]), mtError, [mbOK], 0); end; procedure TIconFontsImageListEditor.NameEditExit(Sender: TObject); begin if FUpdating then Exit; SetImageIconName(NameEdit.Text); UpdateGUI; end; procedure TIconFontsImageListEditor.ImageViewKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Key = VK_INSERT) and (Shift = []) then AddNewItem else if (Key = VK_DELETE) and (Shift = []) then DeleteSelectedItems; end; function TIconFontsImageListEditor.SelectedIcon: TIconFontItem; begin if (ImageView.Selected <> nil) and (ImageView.Selected.Index < FEditingList.IconFontItems.Count) then Result := FEditingList.IconFontItems[ImageView.Selected.ImageIndex] else Result := nil; end; procedure TIconFontsImageListEditor.SetCategoriesButtonClick(Sender: TObject); var LIndex: Integer; Selected: Integer; LIconFontItem: TIconFontItem; LCategoryName: string; begin LCategoryName := InputBox('Set Category', 'Name', FSelectedCategory); if (LCategoryName = FSelectedCategory) then Exit; Screen.Cursor := crHourGlass; try FSelectedCategory := LCategoryName; Selected := ImageView.ItemIndex; FEditingList.StopDrawing(True); try for LIndex := ImageView.Items.Count - 1 downto 0 do begin if ImageView.Items[LIndex].Selected then begin LIconFontItem := FEditingList.IconFontItems[ImageView.Items[LIndex].ImageIndex]; LIconFontItem.Category := FSelectedCategory; end; end; finally FEditingList.StopDrawing(False); end; FChanged := True; BuildList(Selected); finally Screen.Cursor := crDefault; end; end; procedure TIconFontsImageListEditor.ImageViewSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); begin if Selected then UpdateGUI; end; procedure TIconFontsImageListEditor.InitGUI; begin SizeSpinEdit.Value := FEditinglist.Size; DefaultFontName.ItemIndex := DefaultFontName.Items.IndexOf(FEditingList.FontName); DefaultFontColorColorBox.Selected := FEditingList.FontColor; {$IFNDEF GDI+} DefaultMaskColorColorBox.Selected := FEditingList.MaskColor; {$ELSE} DefaultMaskColorColorBox.Enabled := False; {$ENDIF} {$IFDEF HasStoreBitmapProperty} StoreBitmapCheckBox.Checked := FEditingList.StoreBitmap; {$endif} ZoomSpinEdit.Value := FEditingList.Zoom; IconImage.Zoom := FEditingList.Zoom; BuildList(0); UpdateCharsToBuild; end; procedure TIconFontsImageListEditor.SizeSpinEditChange(Sender: TObject); begin if FUpdating then Exit; if FEditingList.Width = FEditingList.Height then FEditingList.Size := SizeSpinEdit.Value; FChanged := True; UpdateSizeGUI; end; procedure TIconFontsImageListEditor.BuildList(Selected: Integer); begin UpdateIconFontListView(ImageView, FSelectedCategory); if Selected < -1 then Selected := -1 else if (Selected = -1) and (ImageView.Items.Count > 0) then Selected := 0 else if Selected >= ImageView.Items.Count then Selected := ImageView.Items.Count - 1; ImageView.ItemIndex := Selected; if (FSelectedCategory <> '') and (SelectedIcon <> nil) and (SelectedIcon.Category <> FSelectedCategory) then begin FSelectedCategory := SelectedIcon.Category; BuildList(SelectedIcon.Index); end else UpdateGUI; end; procedure TIconFontsImageListEditor.DefaultFontColorColorBoxChange( Sender: TObject); begin FEditingList.FontColor := DefaultFontColorColorBox.Selected; FChanged := True; UpdateGUI; end; procedure TIconFontsImageListEditor.DefaultFontNameSelect(Sender: TObject); begin FEditingList.FontName := DefaultFontName.Text; FChanged := True; UpdateCharsToBuild; UpdateGUI; end; procedure TIconFontsImageListEditor.DefaultMaskColorColorBoxChange( Sender: TObject); begin FEditingList.MaskColor := DefaultMaskColorColorBox.Selected; FChanged := True; UpdateGUI; end; procedure TIconFontsImageListEditor.DeleteButtonClick(Sender: TObject); begin DeleteSelectedItems; end; procedure TIconFontsImageListEditor.MaskColorChange(Sender: TObject); begin {$IFNDEF GDI+} if FUpdating then Exit; SetImageMaskColor(MaskColor.Selected); {$ENDIF} end; procedure TIconFontsImageListEditor.FormClose(Sender: TObject; var Action: TCloseAction); begin if ModalResult = mrOK then OKButton.SetFocus else CancelButton.SetFocus; end; procedure TIconFontsImageListEditor.FormCreate(Sender: TObject); {$IFNDEF UseIconFontEditorsAtRunTime} {$IF (CompilerVersion >= 32.0)} var LStyle: TCustomStyleServices; {$IFEND} {$ENDIF} procedure InitColorBox(AColorBox: TColorBox; AColor: TColor); begin {$IFDEF UNICODE} AColorBox.Style := [cbStandardColors, cbExtendedColors, cbSystemColors, cbIncludeNone, cbIncludeDefault, cbCustomColor, cbCustomColors, cbPrettyNames]; {$ENDIF} AColorBox.Selected := AColor; end; begin {$IFNDEF UseIconFontEditorsAtRunTime} {$IF (CompilerVersion >= 32.0)} {$IF (CompilerVersion <= 34.0)} if UseThemeFont then Self.Font.Assign(GetThemeFont); {$IFEND} {$IF CompilerVersion > 34.0} if TIDEThemeMetrics.Font.Enabled then Self.Font.Assign(TIDEThemeMetrics.Font.GetFont); {$IFEND} if ThemeProperties <> nil then begin LStyle := ThemeProperties.StyleServices; StyleElements := StyleElements - [seClient]; Color := LStyle.GetSystemColor(clWindow); BottomPanel.StyleElements := BottomPanel.StyleElements - [seClient]; BottomPanel.ParentBackground := False; BottomPanel.Color := LStyle.GetSystemColor(clBtnFace); IDEThemeManager.RegisterFormClass(TIconFontsImageListEditor); ThemeProperties.ApplyTheme(Self); end; {$IFEND} {$ENDIF} {$IF (CompilerVersion >= 24.0)} CategoryListBox.AlignWithMargins := True; CategoryListBox.Margins.Top := 6; ImageView.AlignWithMargins := True; ImageView.Margins.Top := 6; IconPanel.AlignWithMargins := True; IconPanel.Margins.Top := 6; {$IFEND} {$IFNDEF UNICODE} CharsEditLabel.Visible := False; CharsEdit.Visible := False; BuildButton.Visible := False; IconBuilderGroupBox.Height := IconBuilderGroupBox.Height - BuildButton.Height -4; FontIconHex.MaxLength := 4; ExportButton.Visible := False; {$ENDIF} InitColorBox(DefaultFontColorColorBox, clDefault); InitColorBox(DefaultMaskColorColorBox, clNone); InitColorBox(FontColor, clDefault); InitColorBox(MaskColor, clNone); Caption := Format(Caption, [IconFontsImageListVersion]); FUpdating := True; FEditingList := TIconFontsImageList.Create(nil); ImageView.LargeImages := FEditingList; IconImage.ImageList := FEditingList; FEditingList.OnFontMissing := IconFontsImageListFontMissing; GetColorValues(AddColor); FontColor.ItemIndex := -1; MaskColor.ItemIndex := -1; FontName.Items := Screen.Fonts; DefaultFontName.Items := Screen.Fonts; FIconIndexLabel := ItemGroupBox.Caption; FTotIconsLabel := ImageListGroup.Caption; FChanged := False; FModified := False; {$IFNDEF HasStoreBitmapProperty} StoreBitmapCheckBox.Visible := False; {$ENDIF} end; procedure TIconFontsImageListEditor.Apply; begin if not FChanged then Exit; Screen.Cursor := crHourGlass; try FSourceList.StopDrawing(True); Try FSourceList.Assign(FEditingList); FChanged := False; FModified := True; Finally FSourceList.StopDrawing(False); FSourceList.RedrawImages; End; finally Screen.Cursor := crDefault; end; end; procedure TIconFontsImageListEditor.FormDestroy(Sender: TObject); begin FreeAndNil(FEditingList); Screen.Cursors[crColorPick] := 0; end; procedure TIconFontsImageListEditor.FormShow(Sender: TObject); begin UpdateSizeGUI; {$IFDEF DXE8+} if SavedBounds.Right - SavedBounds.Left > 0 then SetBounds(SavedBounds.Left, SavedBounds.Top, SavedBounds.Width, SavedBounds.Height); {$ELSE} if SavedBounds.Right - SavedBounds.Left > 0 then SetBounds(SavedBounds.Left, SavedBounds.Top, SavedBounds.Right-SavedBounds.Left, SavedBounds.Bottom-SavedBounds.Top); {$ENDIF} if ImageView.CanFocus then ImageView.SetFocus; end; procedure TIconFontsImageListEditor.EditChangeUpdateGUI(Sender: TObject); begin UpdateGUI; end; procedure TIconFontsImageListEditor.ExportButtonClick(Sender: TObject); var LFolder: string; LCount: Integer; begin LFolder := ExtractFileDrive(Application.ExeName); if SelectDirectory(LFolder, [sdAllowCreate, sdPerformCreate, sdPrompt], 0) then begin Screen.Cursor := crHourGlass; try LCount := FEditingList.SaveToPngFiles(LFolder); finally Screen.Cursor := crDefault; end; MessageDlg(Format(MSG_ICONS_EXPORTED, [LCount, LFolder]), mtInformation, [mbOK], 0); end; end; procedure TIconFontsImageListEditor.AddButtonClick(Sender: TObject); begin AddNewItem; end; procedure TIconFontsImageListEditor.CategoryEditExit(Sender: TObject); begin if FUpdating then Exit; if SelectedIcon.Category <> CategoryEdit.Text then begin SelectedIcon.Category := CategoryEdit.Text; if FSelectedCategory <> SelectedIcon.Category then begin FSelectedCategory := SelectedIcon.Category; UpdateCategories; BuildList(SelectedIcon.Index); end else UpdateIconFontListViewCaptions(ImageView); end; end; procedure TIconFontsImageListEditor.AddNewItem; var LInsertIndex: Integer; begin if (ImageView.Selected <> nil) then LInsertIndex := ImageView.Selected.Index +1 else LInsertIndex := ImageView.Items.Count; ImageView.Selected := nil; FEditingList.IconFontItems.Insert(LInsertIndex); FChanged := True; BuildList(LInsertIndex); end; procedure TIconFontsImageListEditor.ApplyButtonClick(Sender: TObject); begin Apply; UpdateGUI; end; procedure TIconFontsImageListEditor.AddColor(const S: string); begin FontColor.Items.Add(S); MaskColor.Items.Add(S); end; procedure TIconFontsImageListEditor.HeightSpinEditChange(Sender: TObject); begin if FUpdating then Exit; FEditingList.Height := HeightSpinEdit.Value; UpdateSizeGUI; end; procedure TIconFontsImageListEditor.BuildButtonClick(Sender: TObject); begin {$IFDEF UNICODE} FEditingList.AddIcons(CharsEdit.Text); FChanged := True; BuildList(ImageView.Items[ImageView.Items.Count-1].ImageIndex); {$ENDIF} end; procedure TIconFontsImageListEditor.BuildFromHexButtonClick(Sender: TObject); begin Screen.Cursor := crHourGlass; try FEditingList.AddIcons( StrToInt('$' + FromHexNum.Text), //From Chr StrToInt('$' + ToHexNum.Text), //To Chr FontName.Text ); FChanged := True; if ImageView.Items.Count > 0 then BuildList(ImageView.Items[ImageView.Items.Count-1].ImageIndex) else BuildList(0); finally Screen.Cursor := crDefault; end; end; end.
unit Alcinoe.FMX.FilterEffects; interface {$I Alcinoe.inc} uses system.classes, FMX.types, FMX.types3D, FMX.filter, FMX.Filter.Effects; const ALColorAdjustGLSL = '%s'+ // varying vec4 TEX0; // uniform sampler2D _Input; 'uniform float _Highlights;'+ 'uniform float _Shadows;'+ 'uniform float _Saturation;'+ 'uniform float _Vibrance;'+ 'uniform float _Contrast;'+ 'uniform float _Whites;'+ 'uniform float _Blacks;'+ 'uniform float _Temperature;'+ 'uniform float _Tint;'+ 'uniform float _Exposure;'+ 'uniform float _Gamma;'+ /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// Contrast /// /// Adjusts the contrast of the image /// /// _Contrast: The adjusted contrast (0.0 <=> 4.0, with 1.0 as the default) /// /// https://github.com/BradLarson/GPUImage2/blob/master/framework/Source/Operations/Shaders/Contrast_GL.fsh /// /////////////////////////////////////////////////////////////////////////////////////////////////////////////// (* 'vec4 doContrast(vec4 textureColor) {'+ 'return vec4(((textureColor.rgb - vec3(0.5)) * _Contrast + vec3(0.5)), textureColor.w);'+ '}' + *) ///////////////////////////////////////////////////////////////////////////////////////////// /// Contrast /// // I don't have the doc, but it's not really contrast, I will say it's "smart" contrast /// /// _Contrast: The adjusted contrast (-2.0 <=> 2.0, with 0.0 as the default) /// /// https://gitlab.bestminr.com/bestminr/FrontShaders/blob/master/shaders/contrast.glsl /// ///////////////////////////////////////////////////////////////////////////////////////////// 'float BlendOverlayf(float base, float blend){'+ 'return (base < 0.5 ? (2.0 * base * blend) : (1.0 - 2.0 * (1.0 - base) * (1.0 - blend)));'+ '}'+ 'vec3 BlendOverlay(vec3 base, vec3 blend){'+ 'return vec3(BlendOverlayf(base.r, blend.r), BlendOverlayf(base.g, blend.g), BlendOverlayf(base.b, blend.b));'+ '}'+ 'mat3 sRGB2XYZ = mat3('+ '0.4360747, 0.3850649, 0.1430804,'+ '0.2225045, 0.7168786, 0.0606169,'+ '0.0139322, 0.0971045, 0.7141733'+ ');'+ 'mat3 XYZ2sRGB = mat3('+ '3.1338561, -1.6168667, -0.4906146,'+ '-0.9787684, 1.9161415, 0.0334540,'+ '0.0719453, -0.2289914, 1.4052427'+ ');'+ 'mat3 ROMM2XYZ = mat3('+ '0.7976749, 0.1351917, 0.0313534,'+ '0.2880402, 0.7118741, 0.0000857,'+ '0.0000000, 0.0000000, 0.8252100'+ ');'+ 'mat3 XYZ2ROMM = mat3('+ '1.3459433, -0.2556075, -0.0511118,'+ '-0.5445989, 1.5081673, 0.0205351,'+ '0.0000000, 0.0000000, 1.2118128'+ ');'+ 'vec4 doContrast(vec4 col) {'+ 'float amount = (_Contrast < 0.0) ? _Contrast/2.0 : _Contrast;'+ 'vec3 base = col.rgb * sRGB2XYZ * XYZ2ROMM;'+ 'vec3 overlay = mix(vec3(0.5), base, amount * col.a);'+ 'vec3 res = BlendOverlay(base, overlay) * ROMM2XYZ * XYZ2sRGB;'+ 'return vec4(res, col.a);'+ '}'+ ///////////////////////////////////////////////////////////////////////////////////////////// /// HighlightsAndShadows /// /// Adjusts the shadows and highlights of an image /// /// _Shadows: Increase to lighten shadows, from 0.0 to 1.0, with 0.0 as the default. /// /// _Highlights: Decrease to darken highlights, from 1.0 to 0.0, with 1.0 as the default. /// ///////////////////////////////////////////////////////////////////////////////////////////// 'vec4 doHighlightsAndShadows(vec4 source) {'+ 'const vec3 luminanceWeighting = vec3(0.3, 0.3, 0.3);'+ 'float luminance = dot(source.rgb, luminanceWeighting);'+ 'float shadow = clamp((pow(luminance, 1.0/(_Shadows+1.0)) + (-0.76)*pow(luminance, 2.0/(_Shadows+1.0))) - luminance, 0.0, 1.0);'+ 'float highlight = clamp((1.0 - (pow(1.0-luminance, 1.0/(2.0-_Highlights)) + (-0.8)*pow(1.0-luminance, 2.0/(2.0-_Highlights)))) - luminance, -1.0, 0.0);'+ 'vec3 result = vec3(0.0, 0.0, 0.0) + ((luminance + shadow + highlight) - 0.0) * ((source.rgb - vec3(0.0, 0.0, 0.0))/(luminance - 0.0));'+ 'return vec4(result.rgb, source.a);'+ '}' + ///////////////////////////////////////////////////////////////////////////////////////////// /// Highlights /// /// _Highlights: 0 <=> 1.0, with 0.0 as the default /// /// https://gitlab.bestminr.com/bestminr/FrontShaders/blob/master/shaders/highlights.glsl /// ///////////////////////////////////////////////////////////////////////////////////////////// (* 'vec4 doHighlights(vec4 color) {'+ 'const float a = 1.357697966704323E-01;'+ 'const float b = 1.006045552016985E+00;'+ 'const float c = 4.674339906510876E-01;'+ 'const float d = 8.029414702292208E-01;'+ 'const float e = 1.127806558508491E-01;'+ 'float maxx = max(color.r, max(color.g, color.b));'+ 'float minx = min(color.r, min(color.g, color.b));'+ 'float lum = (maxx+minx)/2.0;'+ 'float x1 = abs(_Highlights);'+ 'float x2 = lum;'+ 'float lum_new = lum < 0.5 ? lum : lum+ a * sign(_Highlights) * exp(-0.5 * (((x1-b)/c)*((x1-b)/c) + ((x2-d)/e)*((x2-d)/e)));'+ //'return color * lum_new / lum;'+ 'return vec4(color * lum_new / lum);'+ '}'+ *) ////////////////////////////////////////////////////////////////////////////////////////////////////// /// saturation_vibrance /// /// _Saturation: -1.0 <=> 1.0, with 0.0 as the default /// /// _Vibrance: -1.0 <=> 1.0, with 0.0 as the default /// /// https://gitlab.bestminr.com/bestminr/FrontShaders/blob/master/shaders/saturation_vibrance.glsl /// ////////////////////////////////////////////////////////////////////////////////////////////////////// 'vec4 doSaturationVibrance(vec4 col) {'+ 'vec3 color = col.rgb;'+ 'float luminance = color.r*0.299 + color.g*0.587 + color.b*0.114;'+ 'float mn = min(min(color.r, color.g), color.b);'+ 'float mx = max(max(color.r, color.g), color.b);'+ 'float sat = (1.0-(mx - mn)) * (1.0-mx) * luminance * 5.0;'+ 'vec3 lightness = vec3((mn + mx)/2.0);'+ //'vibrance'+ 'color = mix(color, mix(color, lightness, -_Vibrance), sat);'+ //'negative vibrance'+ 'color = mix(color, lightness, (1.0-lightness)*(1.0-_Vibrance)/2.0*abs(_Vibrance));'+ //'saturation'+ 'color = mix(color, vec3(luminance), -_Saturation);'+ 'return vec4(mix(col.rgb, color, col.a), col.a);'+ '}' + //////////////////////////////////////////////////////////////////////////////////////////////// /// whites_blacks /// /// _Whites: -100 <=> 100 but I limit to -1 <=> 1, with 0.0 as the default /// /// _Blacks: -100 <=> 100 but I limit to -1 <=> 1, with 0.0 as the default /// /// https://gitlab.bestminr.com/bestminr/FrontShaders/blob/master/shaders/whites_blacks.glsl /// //////////////////////////////////////////////////////////////////////////////////////////////// //'wb_Luminance and Saturation functions'+ //'Adapted from: http://wwwimages.adobe.com/www.adobe.com/content/dam/Adobe/en/devnet/pdf/pdfs/PDF32000_2008.pdf'+ 'float wb_Lum(vec3 c){'+ 'return 0.299*c.r + 0.587*c.g + 0.114*c.b;'+ '}'+ 'vec3 wb_ClipColor(vec3 c){'+ 'float l = wb_Lum(c);'+ 'float n = min(min(c.r, c.g), c.b);'+ 'float x = max(max(c.r, c.g), c.b);'+ 'if (n < 0.0) c = max((c-l)*l / (l-n) + l, 0.0);'+ 'if (x > 1.0) c = min((c-l) * (1.0-l) / (x-l) + l, 1.0);'+ 'return c;'+ '}'+ 'vec3 wb_SetLum(vec3 c, float l){'+ 'c += l - wb_Lum(c);'+ 'return wb_ClipColor(c);'+ '}'+ 'const float wb = 5.336778471840789E-03;'+ 'const float wc = 6.664243592410049E-01;'+ 'const float wd = 3.023761372137289E+00;'+ 'const float we = -6.994413182098681E+00;'+ 'const float wf = 3.293987131616894E+00;'+ 'const float wb2 = -1.881032803339283E-01;'+ 'const float wc2 = 2.812945435181010E+00;'+ 'const float wd2 = -1.495096839176419E+01;'+ 'const float we2 = 3.349416467551858E+01;'+ 'const float wf2 = -3.433024909629221E+01;'+ 'const float wg2 = 1.314308200442166E+01;'+ 'const float bb = 8.376727344831676E-01;'+ 'const float bc = -3.418495999327269E+00;'+ 'const float bd = 8.078054837335609E+00;'+ 'const float be = -1.209938703324099E+01;'+ 'const float bf = 9.520315785756406E+00;'+ 'const float bg = -2.919340722745241E+00;'+ 'const float ba2 = 5.088652898054800E-01;'+ 'const float bb2 = -9.767371127415029E+00;'+ 'const float bc2 = 4.910705739925203E+01;'+ 'const float bd2 = -1.212150899746360E+02;'+ 'const float be2 = 1.606205314047741E+02;'+ 'const float bf2 = -1.085660871669277E+02;'+ 'const float bg2 = 2.931582214601388E+01;'+ 'vec4 doWhitesBlacks(vec4 color) {'+ 'vec3 base = color.rgb;'+ 'float maxx = max(base.r, max(base.g, base.b));'+ 'float minx = min(base.r, min(base.g, base.b));'+ 'float lum = (maxx+minx)/2.0;'+ 'float x = lum;'+ 'float x2 = x*x;'+ 'float x3 = x2*x;'+ 'float lum_pos, lum_neg;'+ 'vec3 res;'+ //'whites'+ 'lum_pos = wb*x + wc*x2+ wd*x3 + we*x2*x2 + wf*x2*x3;'+ 'lum_pos = min(lum_pos,1.0-lum);'+ 'lum_neg = wb2*x + wc2*x2+ wd2*x3 + we2*x2*x2 + wf2*x2*x3 + wg2*x3*x3;'+ 'lum_neg = max(lum_neg,-lum);'+ 'res = _Whites>=0.0 ? base*(lum_pos*_Whites+lum)/lum : base * (lum-lum_neg*_Whites)/lum;'+ 'res = clamp(res, 0.0, 1.0);'+ //'blacks'+ 'lum_pos = bb*x + bc*x2+ bd*x3 + be*x2*x2 + bf*x2*x3 + bg*x3*x3;'+ 'lum_pos = min(lum_pos,1.0-lum);'+ 'lum_neg = lum<=0.23 ? -lum : ba2 + bb2*x + bc2*x2+ bd2*x3 + be2*x2*x2 + bf2*x2*x3 + bg2*x3*x3;'+ 'lum_neg = max(lum_neg,-lum);'+ 'res = _Blacks>=0.0 ? res*(lum_pos*_Blacks+lum)/lum : res * (lum-lum_neg*_Blacks)/lum;'+ 'res = clamp(res, 0.0, 1.0);'+ 'return vec4(wb_SetLum(base, wb_Lum(res)), 1.0);'+ '}' + ////////////////////////////////////////////////////////////////////////////////////////////// /// temperature /// /// _Temperature: -1.0 <=> 1.0, with 0.0 as the default /// /// _Tint: -1.0 <=> 1.0, with 0.0 as the default /// /// https://gitlab.bestminr.com/bestminr/FrontShaders/blob/master/shaders/temperature.glsl /// ////////////////////////////////////////////////////////////////////////////////////////////// 'mat3 matRGBtoXYZ = mat3('+ '0.4124564390896922, 0.21267285140562253, 0.0193338955823293,'+ '0.357576077643909, 0.715152155287818, 0.11919202588130297,'+ '0.18043748326639894, 0.07217499330655958, 0.9503040785363679'+ ');'+ 'mat3 matXYZtoRGB = mat3('+ '3.2404541621141045, -0.9692660305051868, 0.055643430959114726,'+ '-1.5371385127977166, 1.8760108454466942, -0.2040259135167538,'+ '-0.498531409556016, 0.041556017530349834, 1.0572251882231791'+ ');'+ 'mat3 matAdapt = mat3('+ '0.8951, -0.7502, 0.0389,'+ '0.2664, 1.7135, -0.0685,'+ '-0.1614, 0.0367, 1.0296'+ ');'+ 'mat3 matAdaptInv = mat3('+ '0.9869929054667123, 0.43230526972339456, -0.008528664575177328,'+ '-0.14705425642099013, 0.5183602715367776, 0.04004282165408487,'+ '0.15996265166373125, 0.0492912282128556, 0.9684866957875502'+ ');'+ 'vec3 refWhite, refWhiteRGB;'+ 'vec3 d, s;'+ 'vec3 RGBtoXYZ(vec3 rgb){'+ 'vec3 xyz, XYZ;'+ 'xyz = matRGBtoXYZ * rgb;'+ //'adaption'+ 'XYZ = matAdapt * xyz;'+ 'XYZ *= d/s;'+ 'xyz = matAdaptInv * XYZ;'+ 'return xyz;'+ '}'+ 'vec3 XYZtoRGB(vec3 xyz){'+ 'vec3 rgb, RGB;'+ //'adaption'+ 'RGB = matAdapt * xyz;'+ 'rgb *= s/d;'+ 'xyz = matAdaptInv * RGB;'+ 'rgb = matXYZtoRGB * xyz;'+ 'return rgb;'+ '}'+ 'float t_Lum(vec3 c){'+ 'return 0.299*c.r + 0.587*c.g + 0.114*c.b;'+ '}'+ 'vec3 t_ClipColor(vec3 c){'+ 'float l = t_Lum(c);'+ 'float n = min(min(c.r, c.g), c.b);'+ 'float x = max(max(c.r, c.g), c.b);'+ 'if (n < 0.0) c = (c-l)*l / (l-n) + l;'+ 'if (x > 1.0) c = (c-l) * (1.0-l) / (x-l) + l;'+ 'return c;'+ '}'+ 'vec3 t_SetLum(vec3 c, float l){'+ 'float d = l - t_Lum(c);'+ 'c.r = c.r + d;'+ 'c.g = c.g + d;'+ 'c.b = c.b + d;'+ 'return t_ClipColor(c);'+ '}'+ //'illuminants'+ //'vec3 A = vec3(1.09850, 1.0, 0.35585);'+ 'vec3 D50 = vec3(0.96422, 1.0, 0.82521);'+ 'vec3 D65 = vec3(0.95047, 1.0, 1.08883);'+ //'vec3 D75 = vec3(0.94972, 1.0, 1.22638);'+ //'vec3 D50 = vec3(0.981443, 1.0, 0.863177);'+ //'vec3 D65 = vec3(0.968774, 1.0, 1.121774);'+ 'vec3 CCT2K = vec3(1.274335, 1.0, 0.145233);'+ 'vec3 CCT4K = vec3(1.009802, 1.0, 0.644496);'+ 'vec3 CCT20K = vec3(0.995451, 1.0, 1.886109);'+ 'vec4 doTemperatureTint(vec4 col) {'+ 'vec3 to, from;'+ 'if (_Temperature < 0.0) {'+ 'to = CCT20K;'+ 'from = D65;'+ '} else {'+ 'to = CCT4K;'+ 'from = D65;'+ '}'+ 'vec3 base = col.rgb;'+ 'float lum = t_Lum(base);'+ //'mask by luminance'+ 'float temp = abs(_Temperature) * (1.0 - pow(lum, 2.72));'+ //'from'+ 'refWhiteRGB = from;'+ //'to'+ 'refWhite = vec3(mix(from.x, to.x, temp), mix(1.0, 0.9, _Tint), mix(from.z, to.z, temp));'+ //'mix based on alpha for local adjustments'+ 'refWhite = mix(refWhiteRGB, refWhite, col.a);'+ 'd = matAdapt * refWhite;'+ 's = matAdapt * refWhiteRGB;'+ 'vec3 xyz = RGBtoXYZ(base);'+ 'vec3 rgb = XYZtoRGB(xyz);'+ //'brightness compensation'+ 'vec3 res = rgb * (1.0 + (temp + _Tint) / 10.0);'+ //'preserve luminance'+ //'vec3 res = t_SetLum(rgb, lum);'+ 'return vec4(mix(base, res, col.a), col.a);'+ '}' + /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// Exposure /// /// Adjusts the exposure of the image /// /// _Exposure: The adjusted exposure (-10.0 <=> 10.0, with 0.0 as the default) /// /// https://github.com/BradLarson/GPUImage2/blob/master/framework/Source/Operations/Shaders/Exposure_GL.fsh /// /////////////////////////////////////////////////////////////////////////////////////////////////////////////// (* 'vec4 doExposure(vec4 textureColor) {'+ 'return vec4(textureColor.rgb * pow(2.0, _Exposure), textureColor.w);'+ '}' + *) //////////////////////////////////////////////////////////////////////////////////////////////////////////// /// Gamma /// /// Adjusts the gamma of an image /// /// _Gamma: The gamma adjustment to apply (0.0 <=> 3.0, with 1.0 as the default) /// /// https://github.com/BradLarson/GPUImage2/blob/master/framework/Source/Operations/Shaders/Gamma_GL.fsh /// //////////////////////////////////////////////////////////////////////////////////////////////////////////// (* 'vec4 doGamma(vec4 textureColor) {'+ 'return vec4(pow(textureColor.rgb, vec3(_Gamma)), textureColor.w);'+ '}'+ *) /////////////////////////////////////////////////////////////////////////////////////////// /// Exposure_Gamma /// /// _Exposure: -1.0 <=> 1.0, with 0.0 as the default /// /// _Gamma: -1.0 <=> 1.0, with 0.0 as the default /// /// https://gitlab.bestminr.com/bestminr/FrontShaders/blob/master/shaders/exposure.glsl /// /////////////////////////////////////////////////////////////////////////////////////////// //'Luminance and Saturation functions'+ //'Adapted from: http://wwwimages.adobe.com/www.adobe.com/content/dam/Adobe/en/devnet/pdf/pdfs/PDF32000_2008.pdf'+ 'float e_Lum(vec3 c){'+ 'return 0.298839*c.r + 0.586811*c.g + 0.11435*c.b;'+ '}'+ 'vec3 e_ClipColor(vec3 c){'+ 'float l = e_Lum(c);'+ 'float n = min(min(c.r, c.g), c.b);'+ 'float x = max(max(c.r, c.g), c.b);'+ 'if (n < 0.0) c = max((c-l)*l / (l-n) + l, 0.0);'+ 'if (x > 1.0) c = min((c-l) * (1.0-l) / (x-l) + l, 1.0);'+ 'return c;'+ '}'+ 'vec3 e_SetLum(vec3 c, float l){'+ 'c += l - e_Lum(c);'+ 'return e_ClipColor(c);'+ '}'+ 'float Sat(vec3 c){'+ 'float n = min(min(c.r, c.g), c.b);'+ 'float x = max(max(c.r, c.g), c.b);'+ 'return x - n;'+ '}'+ 'vec3 SetSat(vec3 c, float s){'+ 'float cmin = min(min(c.r, c.g), c.b);'+ 'float cmax = max(max(c.r, c.g), c.b);'+ 'vec3 res = vec3(0.0);'+ 'if (cmax > cmin) {'+ 'if (c.r == cmin && c.b == cmax) {'+ // R min G mid B max 'res.r = 0.0;'+ 'res.g = ((c.g-cmin)*s) / (cmax-cmin);'+ 'res.b = s;'+ '}'+ 'else if (c.r == cmin && c.g == cmax) {'+ // R min B mid G max 'res.r = 0.0;'+ 'res.b = ((c.b-cmin)*s) / (cmax-cmin);'+ 'res.g = s;'+ '}'+ 'else if (c.g == cmin && c.b == cmax) {'+ // G min R mid B max 'res.g = 0.0;'+ 'res.r = ((c.r-cmin)*s) / (cmax-cmin);'+ 'res.b = s;'+ '}'+ 'else if (c.g == cmin && c.r == cmax) {'+ // G min B mid R max 'res.g = 0.0;'+ 'res.b = ((c.b-cmin)*s) / (cmax-cmin);'+ 'res.r = s;'+ '}'+ 'else if (c.b == cmin && c.r == cmax) {'+ // B min G mid R max 'res.b = 0.0;'+ 'res.g = ((c.g-cmin)*s) / (cmax-cmin);'+ 'res.r = s;'+ '}'+ 'else {'+ // B min R mid G max 'res.b = 0.0;'+ 'res.r = ((c.r-cmin)*s) / (cmax-cmin);'+ 'res.g = s;'+ '}'+ '}'+ 'return res;'+ '}'+ //'mat3 sRGB2XYZ = mat3('+ //'0.4360747, 0.3850649, 0.1430804,'+ //'0.2225045, 0.7168786, 0.0606169,'+ //'0.0139322, 0.0971045, 0.7141733'+ //');'+ //'mat3 XYZ2sRGB = mat3('+ //'3.1338561, -1.6168667, -0.4906146,'+ //'-0.9787684, 1.9161415, 0.0334540,'+ //'0.0719453, -0.2289914, 1.4052427'+ //');'+ //'mat3 ROMM2XYZ = mat3('+ //'0.7976749, 0.1351917, 0.0313534,'+ //'0.2880402, 0.7118741, 0.0000857,'+ //'0.0000000, 0.0000000, 0.8252100'+ //');'+ //'mat3 XYZ2ROMM = mat3('+ //'1.3459433, -0.2556075, -0.0511118,'+ //'-0.5445989, 1.5081673, 0.0205351,'+ //'0.0000000, 0.0000000, 1.2118128'+ //');'+ 'float ramp(float t){'+ 't *= 2.0;'+ 'if (t >= 1.0) {'+ 't -= 1.0;'+ 't = log(0.5) / log(0.5*(1.0-t) + 0.9332*t);'+ '}'+ 'return clamp(t, 0.001, 10.0);'+ '}'+ 'vec4 doExposureGamma(vec4 col) {'+ 'vec3 base = col.rgb;'+ 'vec3 res, blend;'+ //'base = base * sRGB2XYZ * XYZ2ROMM;'+ 'float amt = mix(0.009, 0.98, _Exposure);'+ 'if (amt < 0.0) {'+ 'res = mix(vec3(0.0), base, amt + 1.0);'+ 'blend = mix(base, vec3(0.0), amt + 1.0);'+ 'res = min(res / (1.0 - blend*0.9), 1.0);'+ '} else {'+ 'res = mix(base, vec3(1.0), amt);'+ 'blend = mix(vec3(1.0), pow(base, vec3(1.0/0.7)), amt);'+ 'res = max(1.0 - ((1.0 - res) / blend), 0.0);'+ '}'+ 'res = pow(e_SetLum(SetSat(base, Sat(res)), e_Lum(res)), vec3(ramp(1.0 - (_Gamma + 1.0) / 2.0)));'+ //'res = res * ROMM2XYZ * XYZ2sRGB;'+ 'return vec4(mix(base, res, col.a), col.a);'+ '}'+ //////////// /// Misc /// //////////// '%s' + //////////// /// Main /// //////////// 'void main() {'+ '%s' + // vec4 result = texture2D(_Input, TEX0.xy); 'const float eps = 0.001;' + 'if ((abs(_Temperature) > eps) || (abs(_Tint) > eps)) { result = doTemperatureTint(result); }'+ //'result = doExposure(result);'+ // BradLarson //'result = doGamma(result);'+ // BradLarson 'if ((abs(_Exposure) > eps) || (abs(_Gamma) > eps)) { result = doExposureGamma(result); }'+ // bestminr 'if (abs(_Contrast) > eps) { result = doContrast(result); }'+ //'result = doHighlights(result);'+ // bestminr 'if ((abs(_Highlights - 1.0) > eps) || (abs(_Shadows) > eps)) { result = doHighlightsAndShadows(result); }'+ // BradLarson 'if ((abs(_Whites) > eps) || (abs(_Blacks) > eps)) { result = doWhitesBlacks(result); }'+ 'if ((abs(_Saturation) > eps) || (abs(_Vibrance) > eps)) { result = doSaturationVibrance(result); }'+ '%s' + // result = result * COLOR0; 'gl_FragColor = result;'+ '}'; Type TALColorAdjustShaderVariables = class(TObject) private fContrast: Single; fHighlights: Single; fShadows: Single; fSaturation: Single; fVibrance: Single; fWhites: Single; fBlacks: Single; fTemperature: Single; fTint: Single; fExposure: Single; fGamma: Single; public const defContrast: Single = 0; const defHighlights: Single = 1; const defShadows: Single = 0; const defSaturation: Single = 0; const defVibrance: Single = 0; const defWhites: Single = 0; const defBlacks: Single = 0; const defTemperature: Single = 0; const defTint: Single = 0; const defExposure: Single = 0; const defGamma: Single = 0; public constructor Create; virtual; procedure UpdateContext(const Context: TContext3D); public // The contrast multiplier. property Contrast: Single read fContrast write fContrast; // The Highlights offset. property Highlights: Single read fHighlights write fHighlights; // The Shadows offset. property Shadows: Single read fShadows write fShadows; // The Saturation offset. property Saturation: Single read fSaturation write fSaturation; // The Vibrance offset. property Vibrance: Single read fVibrance write fVibrance; // The Whites offset. property Whites: Single read fWhites write fWhites; // The Blacks offset. property Blacks: Single read fBlacks write fBlacks; // The Temperature offset. property Temperature: Single read fTemperature write fTemperature; // The Tint offset. property Tint: Single read fTint write fTint; // The Exposure offset. property Exposure: Single read fExposure write fExposure; // The Gamma offset. property Gamma: Single read fGamma write fGamma; end; {$IFNDEF ALCompilerVersionSupported} {$MESSAGE WARN 'Check if FMX.Filter.Effects.TFilterBaseFilter still has the exact same fields and adjust the IFDEF'} {$ENDIF} TALFilterBaseFilterAccessPrivate = class(TFmxObject) protected FFilter: TFilter; // << need to access this private field FInputFilter: TFilterBaseFilter; end; TALFilterBaseFilter = class(TFilterBaseFilter) protected function filter: TFilter; end; [ComponentPlatforms($FFFF)] TALColorAdjustEffect = class(TImageFXEffect) private function GetContrast: Single; procedure SetContrast(AValue: Single); function GetHighlights: Single; procedure SetHighlights(AValue: Single); function GetShadows: Single; procedure SetShadows(AValue: Single); function GetSaturation: Single; procedure SetSaturation(AValue: Single); function GetVibrance: Single; procedure SetVibrance(AValue: Single); function GetWhites: Single; procedure SetWhites(AValue: Single); function GetBlacks: Single; procedure SetBlacks(AValue: Single); function GetTemperature: Single; procedure SetTemperature(AValue: Single); function GetTint: Single; procedure SetTint(AValue: Single); function GetExposure: Single; procedure SetExposure(AValue: Single); function GetGamma: Single; procedure SetGamma(AValue: Single); public procedure AssignTo(Dest: TPersistent); override; published // The contrast multiplier. property Contrast: Single read GetContrast write SetContrast nodefault; // The Highlights offset. property Highlights: Single read GetHighlights write SetHighlights nodefault; // The Shadows offset. property Shadows: Single read GetShadows write SetShadows nodefault; // The Saturation offset. property Saturation: Single read GetSaturation write SetSaturation nodefault; // The Vibrance offset. property Vibrance: Single read GetVibrance write SetVibrance nodefault; // The Whites offset. property Whites: Single read GetWhites write SetWhites nodefault; // The Blacks offset. property Blacks: Single read GetBlacks write SetBlacks nodefault; // The Temperature offset. property Temperature: Single read GetTemperature write SetTemperature nodefault; // The Tint offset. property Tint: Single read GetTint write SetTint nodefault; // The Exposure offset. property Exposure: Single read GetExposure write SetExposure nodefault; // The Gamma offset. property Gamma: Single read GetGamma write SetGamma nodefault; end; procedure Register; implementation uses system.sysutils, System.Math.Vectors, Alcinoe.StringUtils; {***********************************************} constructor TALColorAdjustShaderVariables.Create; begin fContrast := defContrast; fHighlights := defHighlights; fShadows := defShadows; fSaturation := defSaturation; fVibrance := defVibrance; fWhites := defWhites; fBlacks := defBlacks; fTemperature := defTemperature; fTint := defTint; fExposure := defExposure; fGamma := defGamma; inherited create; end; {*******************************************************************************} procedure TALColorAdjustShaderVariables.UpdateContext(const Context: TContext3D); begin Context.SetShaderVariable('Contrast', [Vector3D(Contrast, 0, 0, 0)]); Context.SetShaderVariable('Highlights', [Vector3D(Highlights, 0, 0, 0)]); Context.SetShaderVariable('Shadows', [Vector3D(Shadows, 0, 0, 0)]); Context.SetShaderVariable('Saturation', [Vector3D(Saturation, 0, 0, 0)]); Context.SetShaderVariable('Vibrance', [Vector3D(Vibrance, 0, 0, 0)]); Context.SetShaderVariable('Whites', [Vector3D(Whites, 0, 0, 0)]); Context.SetShaderVariable('Blacks', [Vector3D(Blacks, 0, 0, 0)]); Context.SetShaderVariable('Temperature', [Vector3D(Temperature, 0, 0, 0)]); Context.SetShaderVariable('Tint', [Vector3D(Tint, 0, 0, 0)]); Context.SetShaderVariable('Exposure', [Vector3D(Exposure, 0, 0, 0)]); Context.SetShaderVariable('Gamma', [Vector3D(Gamma, 0, 0, 0)]); end; type {***********************************} TALColorAdjustFilter = class(TFilter) public constructor Create; override; class function FilterAttr: TFilterRec; override; end; {**************************************} constructor TALColorAdjustFilter.Create; begin inherited; FShaders[0] := TShaderManager.RegisterShaderFromData('ColorAdjust.fps', TContextShaderKind.PixelShader, '', [ {$REGION 'TContextShaderArch.DX9'} {$IF defined(MSWindows)} // todo - implement this part as I only copied the code of TContrastFilter for now TContextShaderSource.Create(TContextShaderArch.DX9, [ $00, $02, $FF, $FF, $FE, $FF, $31, $00, $43, $54, $41, $42, $1C, $00, $00, $00, $9B, $00, $00, $00, $00, $02, $FF, $FF, $03, $00, $00, $00, $1C, $00, $00, $00, $00, $01, $00, $20, $94, $00, $00, $00, $58, $00, $00, $00, $02, $00, $00, $00, $01, $00, $00, $00, $64, $00, $00, $00, $00, $00, $00, $00, $74, $00, $00, $00, $02, $00, $01, $00, $01, $00, $00, $00, $64, $00, $00, $00, $00, $00, $00, $00, $7D, $00, $00, $00, $03, $00, $00, $00, $01, $00, $00, $00, $84, $00, $00, $00, $00, $00, $00, $00, $42, $72, $69, $67, $68, $74, $6E, $65, $73, $73, $00, $AB, $00, $00, $03, $00, $01, $00, $01, $00, $01, $00, $00, $00, $00, $00, $00, $00, $43, $6F, $6E, $74, $72, $61, $73, $74, $00, $49, $6E, $70, $75, $74, $00, $AB, $04, $00, $0C, $00, $01, $00, $01, $00, $01, $00, $00, $00, $00, $00, $00, $00, $70, $73, $5F, $32, $5F, $30, $00, $4D, $69, $63, $72, $6F, $73, $6F, $66, $74, $20, $28, $52, $29, $20, $44, $33, $44, $58, $39, $20, $53, $68, $61, $64, $65, $72, $20, $43, $6F, $6D, $70, $69, $6C, $65, $72, $20, $00, $51, $00, $00, $05, $02, $00, $0F, $A0, $00, $00, $00, $BF, $00, $00, $00, $00, $00, $00, $00, $3F, $00, $00, $00, $00, $1F, $00, $00, $02, $00, $00, $00, $80, $00, $00, $03, $B0, $1F, $00, $00, $02, $00, $00, $00, $90, $00, $08, $0F, $A0, $42, $00, $00, $03, $00, $00, $0F, $80, $00, $00, $E4, $B0, $00, $08, $E4, $A0, $01, $00, $00, $02, $01, $00, $08, $80, $02, $00, $55, $A0, $0B, $00, $00, $03, $02, $00, $08, $80, $01, $00, $00, $A0, $01, $00, $FF, $80, $06, $00, $00, $02, $01, $00, $01, $80, $00, $00, $FF, $80, $04, $00, $00, $04, $01, $00, $07, $80, $00, $00, $E4, $80, $01, $00, $00, $80, $02, $00, $00, $A0, $04, $00, $00, $04, $01, $00, $07, $80, $01, $00, $E4, $80, $02, $00, $FF, $80, $00, $00, $00, $A0, $02, $00, $00, $03, $01, $00, $07, $80, $01, $00, $E4, $80, $02, $00, $AA, $A0, $05, $00, $00, $03, $00, $00, $07, $80, $00, $00, $FF, $80, $01, $00, $E4, $80, $01, $00, $00, $02, $00, $08, $0F, $80, $00, $00, $E4, $80, $FF, $FF, $00, $00], [ TContextShaderVariable.Create('Brightness', TContextShaderVariableKind.Float, 0, 1), TContextShaderVariable.Create('Contrast', TContextShaderVariableKind.Float, 1, 1), TContextShaderVariable.Create('Input', TContextShaderVariableKind.Texture, 0, 0)] ), {$ENDIF} {$ENDREGION} {$REGION 'TContextShaderArch.DX11_level_9'} {$IF defined(MSWindows)} // todo - implement this part as I only copied the code of TContrastFilter for now TContextShaderSource.Create(TContextShaderArch.DX11_level_9, [ $44, $58, $42, $43, $39, $01, $F2, $B8, $28, $05, $92, $38, $25, $66, $69, $67, $94, $95, $AD, $88, $01, $00, $00, $00, $B8, $04, $00, $00, $06, $00, $00, $00, $38, $00, $00, $00, $38, $01, $00, $00, $A0, $02, $00, $00, $1C, $03, $00, $00, $50, $04, $00, $00, $84, $04, $00, $00, $41, $6F, $6E, $39, $F8, $00, $00, $00, $F8, $00, $00, $00, $00, $02, $FF, $FF, $C4, $00, $00, $00, $34, $00, $00, $00, $01, $00, $28, $00, $00, $00, $34, $00, $00, $00, $34, $00, $01, $00, $24, $00, $00, $00, $34, $00, $00, $00, $00, $00, $00, $00, $00, $00, $01, $00, $00, $00, $00, $00, $00, $00, $00, $02, $FF, $FF, $51, $00, $00, $05, $01, $00, $0F, $A0, $00, $00, $00, $BF, $00, $00, $00, $00, $00, $00, $00, $3F, $00, $00, $00, $00, $1F, $00, $00, $02, $00, $00, $00, $80, $00, $00, $03, $B0, $1F, $00, $00, $02, $00, $00, $00, $90, $00, $08, $0F, $A0, $42, $00, $00, $03, $00, $00, $0F, $80, $00, $00, $E4, $B0, $00, $08, $E4, $A0, $01, $00, $00, $02, $01, $00, $08, $80, $01, $00, $55, $A0, $0B, $00, $00, $03, $02, $00, $08, $80, $00, $00, $55, $A0, $01, $00, $FF, $80, $06, $00, $00, $02, $01, $00, $01, $80, $00, $00, $FF, $80, $04, $00, $00, $04, $01, $00, $07, $80, $00, $00, $E4, $80, $01, $00, $00, $80, $01, $00, $00, $A0, $04, $00, $00, $04, $01, $00, $07, $80, $01, $00, $E4, $80, $02, $00, $FF, $80, $00, $00, $00, $A0, $02, $00, $00, $03, $01, $00, $07, $80, $01, $00, $E4, $80, $01, $00, $AA, $A0, $05, $00, $00, $03, $00, $00, $07, $80, $00, $00, $FF, $80, $01, $00, $E4, $80, $01, $00, $00, $02, $00, $08, $0F, $80, $00, $00, $E4, $80, $FF, $FF, $00, $00, $53, $48, $44, $52, $60, $01, $00, $00, $40, $00, $00, $00, $58, $00, $00, $00, $59, $00, $00, $04, $46, $8E, $20, $00, $00, $00, $00, $00, $01, $00, $00, $00, $5A, $00, $00, $03, $00, $60, $10, $00, $00, $00, $00, $00, $58, $18, $00, $04, $00, $70, $10, $00, $00, $00, $00, $00, $55, $55, $00, $00, $62, $10, $00, $03, $32, $10, $10, $00, $00, $00, $00, $00, $65, $00, $00, $03, $F2, $20, $10, $00, $00, $00, $00, $00, $68, $00, $00, $02, $02, $00, $00, $00, $34, $00, $00, $08, $12, $00, $10, $00, $00, $00, $00, $00, $1A, $80, $20, $00, $00, $00, $00, $00, $00, $00, $00, $00, $01, $40, $00, $00, $00, $00, $00, $00, $45, $00, $00, $09, $F2, $00, $10, $00, $01, $00, $00, $00, $46, $10, $10, $00, $00, $00, $00, $00, $46, $7E, $10, $00, $00, $00, $00, $00, $00, $60, $10, $00, $00, $00, $00, $00, $0E, $00, $00, $07, $E2, $00, $10, $00, $00, $00, $00, $00, $06, $09, $10, $00, $01, $00, $00, $00, $F6, $0F, $10, $00, $01, $00, $00, $00, $00, $00, $00, $0A, $E2, $00, $10, $00, $00, $00, $00, $00, $56, $0E, $10, $00, $00, $00, $00, $00, $02, $40, $00, $00, $00, $00, $00, $00, $00, $00, $00, $BF, $00, $00, $00, $BF, $00, $00, $00, $BF, $32, $00, $00, $0A, $72, $00, $10, $00, $00, $00, $00, $00, $96, $07, $10, $00, $00, $00, $00, $00, $06, $00, $10, $00, $00, $00, $00, $00, $06, $80, $20, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $0A, $72, $00, $10, $00, $00, $00, $00, $00, $46, $02, $10, $00, $00, $00, $00, $00, $02, $40, $00, $00, $00, $00, $00, $3F, $00, $00, $00, $3F, $00, $00, $00, $3F, $00, $00, $00, $00, $38, $00, $00, $07, $72, $20, $10, $00, $00, $00, $00, $00, $F6, $0F, $10, $00, $01, $00, $00, $00, $46, $02, $10, $00, $00, $00, $00, $00, $36, $00, $00, $05, $82, $20, $10, $00, $00, $00, $00, $00, $3A, $00, $10, $00, $01, $00, $00, $00, $3E, $00, $00, $01, $53, $54, $41, $54, $74, $00, $00, $00, $09, $00, $00, $00, $02, $00, $00, $00, $00, $00, $00, $00, $02, $00, $00, $00, $05, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $01, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $01, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $01, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $52, $44, $45, $46, $2C, $01, $00, $00, $01, $00, $00, $00, $8C, $00, $00, $00, $03, $00, $00, $00, $1C, $00, $00, $00, $00, $04, $FF, $FF, $00, $11, $00, $00, $F9, $00, $00, $00, $7C, $00, $00, $00, $03, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $01, $00, $00, $00, $00, $00, $00, $00, $7C, $00, $00, $00, $02, $00, $00, $00, $05, $00, $00, $00, $04, $00, $00, $00, $FF, $FF, $FF, $FF, $00, $00, $00, $00, $01, $00, $00, $00, $0C, $00, $00, $00, $82, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $01, $00, $00, $00, $00, $00, $00, $00, $49, $6E, $70, $75, $74, $00, $24, $47, $6C, $6F, $62, $61, $6C, $73, $00, $AB, $82, $00, $00, $00, $02, $00, $00, $00, $A4, $00, $00, $00, $10, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $D4, $00, $00, $00, $00, $00, $00, $00, $04, $00, $00, $00, $02, $00, $00, $00, $E0, $00, $00, $00, $00, $00, $00, $00, $F0, $00, $00, $00, $04, $00, $00, $00, $04, $00, $00, $00, $02, $00, $00, $00, $E0, $00, $00, $00, $00, $00, $00, $00, $42, $72, $69, $67, $68, $74, $6E, $65, $73, $73, $00, $AB, $00, $00, $03, $00, $01, $00, $01, $00, $00, $00, $00, $00, $00, $00, $00, $00, $43, $6F, $6E, $74, $72, $61, $73, $74, $00, $4D, $69, $63, $72, $6F, $73, $6F, $66, $74, $20, $28, $52, $29, $20, $48, $4C, $53, $4C, $20, $53, $68, $61, $64, $65, $72, $20, $43, $6F, $6D, $70, $69, $6C, $65, $72, $20, $39, $2E, $32, $36, $2E, $39, $35, $32, $2E, $32, $38, $34, $34, $00, $AB, $AB, $49, $53, $47, $4E, $2C, $00, $00, $00, $01, $00, $00, $00, $08, $00, $00, $00, $20, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $03, $00, $00, $00, $00, $00, $00, $00, $03, $03, $00, $00, $54, $45, $58, $43, $4F, $4F, $52, $44, $00, $AB, $AB, $AB, $4F, $53, $47, $4E, $2C, $00, $00, $00, $01, $00, $00, $00, $08, $00, $00, $00, $20, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $03, $00, $00, $00, $00, $00, $00, $00, $0F, $00, $00, $00, $53, $56, $5F, $54, $61, $72, $67, $65, $74, $00, $AB, $AB], [ TContextShaderVariable.Create('Input', TContextShaderVariableKind.Texture, 0, 0), TContextShaderVariable.Create('Brightness', TContextShaderVariableKind.Float, 0, 4), TContextShaderVariable.Create('Contrast', TContextShaderVariableKind.Float, 4, 4)] ), {$ENDIF} {$ENDREGION} {$REGION 'TContextShaderArch.Metal'} {$IF defined(MACOS)} // todo - implement this part as I only copied the code of TContrastFilter for now TContextShaderSource.Create( TContextShaderArch.Metal, TEncoding.UTF8.GetBytes( 'using namespace metal;'+ 'struct ProjectedVertex {'+ 'float4 position [[position]];'+ 'float2 textureCoord;'+ '};'+ 'fragment float4 fragmentShader(const ProjectedVertex in [[stage_in]],'+ 'constant float4 &Brightness [[buffer(0)]],'+ 'constant float4 &Contrast [[buffer(1)]],'+ 'const texture2d<float> Input [[texture(0)]],'+ 'const sampler InputSampler [[sampler(0)]]) {'+ 'float4 pixelColor = Input.sample(InputSampler, in.textureCoord);'+ 'pixelColor.rgb /= pixelColor.a;'+ 'pixelColor.rgb = ((pixelColor.rgb - 0.5f) * max(Contrast.x, 0.0)) + 0.5f;'+ 'pixelColor.rgb += Brightness.x;'+ 'pixelColor.rgb *= pixelColor.a;'+ 'return pixelColor;'+ '}' ), [TContextShaderVariable.Create('Brightness', TContextShaderVariableKind.Float, 0, 1), TContextShaderVariable.Create('Contrast', TContextShaderVariableKind.Float, 1, 1), TContextShaderVariable.Create('Input', TContextShaderVariableKind.Texture, 0, 0)] ), {$ENDIF} {$ENDREGION} {$REGION 'TContextShaderArch.GLSL'} TContextShaderSource.Create( TContextShaderArch.GLSL, TEncoding.UTF8.GetBytes( ALFormatW( ALColorAdjustGLSL, ['varying vec4 TEX0;'+ 'uniform sampler2D _Input;', //---- '', //---- 'vec4 result = texture2D(_Input, TEX0.xy);', //---- ''], ALDefaultFormatSettingsW)), [TContextShaderVariable.Create('Contrast', TContextShaderVariableKind.Float, 0, 1), TContextShaderVariable.Create('Highlights', TContextShaderVariableKind.Float, 0, 1), TContextShaderVariable.Create('Shadows', TContextShaderVariableKind.Float, 0, 1), TContextShaderVariable.Create('Saturation', TContextShaderVariableKind.Float, 0, 1), TContextShaderVariable.Create('Vibrance', TContextShaderVariableKind.Float, 0, 1), TContextShaderVariable.Create('Whites', TContextShaderVariableKind.Float, 0, 1), TContextShaderVariable.Create('Blacks', TContextShaderVariableKind.Float, 0, 1), TContextShaderVariable.Create('Temperature', TContextShaderVariableKind.Float, 0, 1), TContextShaderVariable.Create('Tint', TContextShaderVariableKind.Float, 0, 1), TContextShaderVariable.Create('Exposure', TContextShaderVariableKind.Float, 0, 1), TContextShaderVariable.Create('Gamma', TContextShaderVariableKind.Float, 0, 1), TContextShaderVariable.Create('Input', TContextShaderVariableKind.Texture, 0, 0)] ) {$ENDREGION} ]); end; {*********************************************************} class function TALColorAdjustFilter.FilterAttr: TFilterRec; begin Result := TFilterRec.Create('ALColorAdjust', 'Color adjustments operations.', [ TFilterValueRec.Create('Contrast', 'The contrast multiplier.', TALColorAdjustShaderVariables.defContrast, -2, 2), TFilterValueRec.Create('Highlights', 'The highlights offset.', TALColorAdjustShaderVariables.defHighlights, 0, 1), // 0, 0, 1 (bestminr) | 1, 0, 1 (BradLarson) TFilterValueRec.Create('Shadows', 'The shadows offset.', TALColorAdjustShaderVariables.defShadows, 0, 1), TFilterValueRec.Create('Whites', 'The whites offset.', TALColorAdjustShaderVariables.defWhites, -1, 1), TFilterValueRec.Create('Blacks', 'The blacks offset.', TALColorAdjustShaderVariables.defBlacks, -1, 1), TFilterValueRec.Create('Exposure', 'The exposure offset.', TALColorAdjustShaderVariables.defExposure, -1, 1), TFilterValueRec.Create('Gamma', 'The gamma offset.', TALColorAdjustShaderVariables.defGamma, -1, 1), TFilterValueRec.Create('Saturation', 'The saturation offset.', TALColorAdjustShaderVariables.defSaturation, -1, 1), TFilterValueRec.Create('Vibrance', 'The vibrance offset.', TALColorAdjustShaderVariables.defVibrance, -1, 1), TFilterValueRec.Create('Temperature', 'The temperature offset.', TALColorAdjustShaderVariables.defTemperature, -1, 1), TFilterValueRec.Create('Tint', 'The tint offset.', TALColorAdjustShaderVariables.defTint, -1, 1)] ); end; {*******************************************} function TALFilterBaseFilter.filter: TFilter; begin result := TALFilterBaseFilterAccessPrivate(self).FFilter; end; {*********************************************************} procedure TALColorAdjustEffect.AssignTo(Dest: TPersistent); begin if Dest is TALColorAdjustEffect then with TALColorAdjustEffect(Dest) do begin Contrast := self.Contrast; Highlights := self.Highlights; Shadows := self.Shadows; Saturation := self.Saturation; Vibrance := self.Vibrance; Whites := self.Whites; Blacks := self.Blacks; Temperature := self.Temperature; Tint := self.Tint; Exposure := self.Exposure; Gamma := self.Gamma; end else inherited AssignTo(Dest); end; {************************************************} function TALColorAdjustEffect.GetContrast: Single; begin if Assigned(Filter) then Result := Filter.ValuesAsFloat['Contrast'] else Result := 0.0; end; {**************************************************} function TALColorAdjustEffect.GetHighlights: Single; begin if Assigned(Filter) then Result := Filter.ValuesAsFloat['Highlights'] else Result := 0.0; end; {***********************************************} function TALColorAdjustEffect.GetShadows: Single; begin if Assigned(Filter) then Result := Filter.ValuesAsFloat['Shadows'] else Result := 0.0; end; {**************************************************} function TALColorAdjustEffect.GetSaturation: Single; begin if Assigned(Filter) then Result := Filter.ValuesAsFloat['Saturation'] else Result := 0.0; end; {************************************************} function TALColorAdjustEffect.GetVibrance: Single; begin if Assigned(Filter) then Result := Filter.ValuesAsFloat['Vibrance'] else Result := 0.0; end; {**********************************************} function TALColorAdjustEffect.GetWhites: Single; begin if Assigned(Filter) then Result := Filter.ValuesAsFloat['Whites'] else Result := 0.0; end; {**********************************************} function TALColorAdjustEffect.GetBlacks: Single; begin if Assigned(Filter) then Result := Filter.ValuesAsFloat['Blacks'] else Result := 0.0; end; {***************************************************} function TALColorAdjustEffect.GetTemperature: Single; begin if Assigned(Filter) then Result := Filter.ValuesAsFloat['Temperature'] else Result := 0.0; end; {********************************************} function TALColorAdjustEffect.GetTint: Single; begin if Assigned(Filter) then Result := Filter.ValuesAsFloat['Tint'] else Result := 0.0; end; {************************************************} function TALColorAdjustEffect.GetExposure: Single; begin if Assigned(Filter) then Result := Filter.ValuesAsFloat['Exposure'] else Result := 0.0; end; {*********************************************} function TALColorAdjustEffect.GetGamma: Single; begin if Assigned(Filter) then Result := Filter.ValuesAsFloat['Gamma'] else Result := 0.0; end; {*********************************************************} procedure TALColorAdjustEffect.SetContrast(AValue: Single); begin if not Assigned(Filter) then Exit; if Filter.ValuesAsFloat['Contrast'] <> AValue then begin Filter.ValuesAsFloat['Contrast'] := AValue; UpdateParentEffects; end; end; {***********************************************************} procedure TALColorAdjustEffect.SetHighlights(AValue: Single); begin if not Assigned(Filter) then Exit; if Filter.ValuesAsFloat['Highlights'] <> AValue then begin Filter.ValuesAsFloat['Highlights'] := AValue; UpdateParentEffects; end; end; {********************************************************} procedure TALColorAdjustEffect.SetShadows(AValue: Single); begin if not Assigned(Filter) then Exit; if Filter.ValuesAsFloat['Shadows'] <> AValue then begin Filter.ValuesAsFloat['Shadows'] := AValue; UpdateParentEffects; end; end; {***********************************************************} procedure TALColorAdjustEffect.SetSaturation(AValue: Single); begin if not Assigned(Filter) then Exit; if Filter.ValuesAsFloat['Saturation'] <> AValue then begin Filter.ValuesAsFloat['Saturation'] := AValue; UpdateParentEffects; end; end; {*********************************************************} procedure TALColorAdjustEffect.SetVibrance(AValue: Single); begin if not Assigned(Filter) then Exit; if Filter.ValuesAsFloat['Vibrance'] <> AValue then begin Filter.ValuesAsFloat['Vibrance'] := AValue; UpdateParentEffects; end; end; {*******************************************************} procedure TALColorAdjustEffect.SetWhites(AValue: Single); begin if not Assigned(Filter) then Exit; if Filter.ValuesAsFloat['Whites'] <> AValue then begin Filter.ValuesAsFloat['Whites'] := AValue; UpdateParentEffects; end; end; {*******************************************************} procedure TALColorAdjustEffect.SetBlacks(AValue: Single); begin if not Assigned(Filter) then Exit; if Filter.ValuesAsFloat['Blacks'] <> AValue then begin Filter.ValuesAsFloat['Blacks'] := AValue; UpdateParentEffects; end; end; {************************************************************} procedure TALColorAdjustEffect.SetTemperature(AValue: Single); begin if not Assigned(Filter) then Exit; if Filter.ValuesAsFloat['Temperature'] <> AValue then begin Filter.ValuesAsFloat['Temperature'] := AValue; UpdateParentEffects; end; end; {*****************************************************} procedure TALColorAdjustEffect.SetTint(AValue: Single); begin if not Assigned(Filter) then Exit; if Filter.ValuesAsFloat['Tint'] <> AValue then begin Filter.ValuesAsFloat['Tint'] := AValue; UpdateParentEffects; end; end; {*********************************************************} procedure TALColorAdjustEffect.SetExposure(AValue: Single); begin if not Assigned(Filter) then Exit; if Filter.ValuesAsFloat['Exposure'] <> AValue then begin Filter.ValuesAsFloat['Exposure'] := AValue; UpdateParentEffects; end; end; {******************************************************} procedure TALColorAdjustEffect.SetGamma(AValue: Single); begin if not Assigned(Filter) then Exit; if Filter.ValuesAsFloat['Gamma'] <> AValue then begin Filter.ValuesAsFloat['Gamma'] := AValue; UpdateParentEffects; end; end; {*****************} procedure Register; begin RegisterComponents('Alcinoe', [TALColorAdjustEffect]); RegisterNoIcon([TALColorAdjustEffect]); end; initialization RegisterClasses([TALColorAdjustEffect]); TFilterManager.RegisterFilter('ColorAdjust', TALColorAdjustFilter); // << 'ColorAdjust' is the CATEGORY! Several filters can have the same category. this why 'ColorAdjust' and not 'ALColorAdjust' // << the name of the filter is defined in TALColorAdjustFilter.FilterAttr as 'ALColorAdjust' end.
unit xlencrypt_md5; interface (* Message Digest Algorithm MD5(中文名为消息摘要算法第五版)为计算机安全领域广泛使用的一种散列函数 用以提供消息的完整性保护。该算法的文件号为RFC 1321(R.Rivest,MIT Laboratory for Computer Science and RSA Data Security Inc. April 1992)。 MD5即Message-Digest Algorithm 5(信息-摘要算法5),用于确保信息传输完整一致。是计算机广泛使用的 杂凑算法之一(又译摘要算法、哈希算法),主流编程语言普遍已有MD5实现。将数据(如汉字)运算为另一 固定长度值,是杂凑算法的基础原理,MD5的前身有MD2、MD3和MD4 MD5算法具有以下特点: 1、压缩性:任意长度的数据,算出的MD5值长度都是固定的。 2、容易计算:从原数据计算出MD5值很容易。 3、抗修改性:对原数据进行任何改动,哪怕只修改1个字节,所得到的MD5值都有很大区别。 4、强抗碰撞:已知原数据和其MD5值,想找到一个具有相同MD5值的数据(即伪造数据)是非常困难的。 MD5的作用是让大容量信息在用数字签名软件签署私人密钥前被"压缩"成一种保密的格式(就是把一个 任意长度的字节串变换成一定长的十六进制数字串)。除了MD5以外,其中比较有名的还有sha-1、RIPEMD以及Haval等 *) uses Types; type TMD5Count = array[0..1] of DWORD; TMD5State = array[0..3] of DWORD; TMD5Block = array[0..15] of DWORD; TMD5CBits = array[0..7] of byte; TMD5Digest = array[0..15] of byte; TMD5Buffer = array[0..63] of byte; TMD5Context = record State : TMD5State; Count : TMD5Count; Buffer : TMD5Buffer; end; procedure MD5Init(var AContext: TMD5Context); procedure MD5Update(var AContext: TMD5Context; AInput: PAnsiChar; ALength: LongWord); //procedure MD5UpdateW(var AContext: TMD5Context; AInput: PWideChar; ALength: LongWord); procedure MD5Final(var AContext: TMD5Context; var ADigest: TMD5Digest); function MD5StringA(const Str: AnsiString): TMD5Digest; function MD5Print(const ADigest: TMD5Digest): AnsiString; var MD5_PADDING: TMD5Buffer = ( $80, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00 ); implementation uses define_char, BaseType, win_data_move; function MD5_F(x, y, z: DWORD): DWORD; begin Result := (x and y) or ((not x) and z); // AND EDX, EAX // NOT EAX // AND EAX, ECX // OR EAX, EDX end; function MD5_G(x, y, z: DWORD): DWORD; begin Result := (x and z) or (y and (not z)); // AND EAX, ECX // NOT ECX // AND EDX, ECX // OR EAX, EDX end; function MD5_H(x, y, z: DWORD): DWORD; begin Result := x xor y xor z; // XOR EAX, EDX // XOR EAX, ECX end; function MD5_I(x, y, z: DWORD): DWORD; begin Result := y xor (x or (not z)); // NOT ECX // OR EAX, ECX // XOR EAX, EDX end; procedure MD5_ROT(var x: DWORD; n: BYTE); begin x := (x shl n) or (x shr (32 - n)); // PUSH EBX // MOV CL, $20 // SUB CL, DL // MOV EBX, [EAX] // SHR EBX, CL // MOV ECX, EDX // MOV EDX, [EAX] // SHL EDX, CL // OR EBX, EDX // MOV [EAX], EBX // POP EBX end; procedure MD5_FF(var a: DWORD; b, c, d, x: DWORD; s: BYTE; ac: DWORD); begin Inc(a, MD5_F(b, c, d) + x + ac); MD5_ROT(a, s); Inc(a, b); end; procedure MD5_GG(var a: DWORD; b, c, d, x: DWORD; s: BYTE; ac: DWORD); begin Inc(a, MD5_G(b, c, d) + x + ac); MD5_ROT(a, s); Inc(a, b); end; procedure MD5_HH(var a: DWORD; b, c, d, x: DWORD; s: BYTE; ac: DWORD); begin Inc(a, MD5_H(b, c, d) + x + ac); MD5_ROT(a, s); Inc(a, b); end; procedure MD5_II(var a: DWORD; b, c, d, x: DWORD; s: BYTE; ac: DWORD); begin Inc(a, MD5_I(b, c, d) + x + ac); MD5_ROT(a, s); Inc(a, b); end; // Encode Count bytes at Source into (Count / 4) DWORDs at Target procedure MD5_Encode(Source, Target: pointer; Count: LongWord); var S: PByte; T: PDWORD; I: LongWord; begin S := Source; T := Target; for I := 1 to Count div 4 do begin T^ := S^; Inc(S); T^ := T^ or (S^ shl 8); Inc(S); T^ := T^ or (S^ shl 16); Inc(S); T^ := T^ or (S^ shl 24); Inc(S); Inc(T); end; end; // Decode Count DWORDs at Source into (Count * 4) Bytes at Target procedure MD5_Decode(Source, Target: pointer; Count: LongWord); var S: PDWORD; T: PByte; I: LongWord; begin S := Source; T := Target; for I := 1 to Count do begin T^ := S^ and $ff; Inc(T); T^ := (S^ shr 8) and $ff; Inc(T); T^ := (S^ shr 16) and $ff; Inc(T); T^ := (S^ shr 24) and $ff; Inc(T); Inc(S); end; end; // Transform State according to first 64 bytes at Buffer procedure MD5_Transform(Buffer: pointer; var State: TMD5State); var a, b, c, d: DWORD; Block: TMD5Block; begin MD5_Encode(Buffer, @Block, 64); a := State[0]; b := State[1]; c := State[2]; d := State[3]; MD5_FF (a, b, c, d, Block[ 0], 7, $d76aa478); MD5_FF (d, a, b, c, Block[ 1], 12, $e8c7b756); MD5_FF (c, d, a, b, Block[ 2], 17, $242070db); MD5_FF (b, c, d, a, Block[ 3], 22, $c1bdceee); MD5_FF (a, b, c, d, Block[ 4], 7, $f57c0faf); MD5_FF (d, a, b, c, Block[ 5], 12, $4787c62a); MD5_FF (c, d, a, b, Block[ 6], 17, $a8304613); MD5_FF (b, c, d, a, Block[ 7], 22, $fd469501); MD5_FF (a, b, c, d, Block[ 8], 7, $698098d8); MD5_FF (d, a, b, c, Block[ 9], 12, $8b44f7af); MD5_FF (c, d, a, b, Block[10], 17, $ffff5bb1); MD5_FF (b, c, d, a, Block[11], 22, $895cd7be); MD5_FF (a, b, c, d, Block[12], 7, $6b901122); MD5_FF (d, a, b, c, Block[13], 12, $fd987193); MD5_FF (c, d, a, b, Block[14], 17, $a679438e); MD5_FF (b, c, d, a, Block[15], 22, $49b40821); MD5_GG (a, b, c, d, Block[ 1], 5, $f61e2562); MD5_GG (d, a, b, c, Block[ 6], 9, $c040b340); MD5_GG (c, d, a, b, Block[11], 14, $265e5a51); MD5_GG (b, c, d, a, Block[ 0], 20, $e9b6c7aa); MD5_GG (a, b, c, d, Block[ 5], 5, $d62f105d); MD5_GG (d, a, b, c, Block[10], 9, $2441453); MD5_GG (c, d, a, b, Block[15], 14, $d8a1e681); MD5_GG (b, c, d, a, Block[ 4], 20, $e7d3fbc8); MD5_GG (a, b, c, d, Block[ 9], 5, $21e1cde6); MD5_GG (d, a, b, c, Block[14], 9, $c33707d6); MD5_GG (c, d, a, b, Block[ 3], 14, $f4d50d87); MD5_GG (b, c, d, a, Block[ 8], 20, $455a14ed); MD5_GG (a, b, c, d, Block[13], 5, $a9e3e905); MD5_GG (d, a, b, c, Block[ 2], 9, $fcefa3f8); MD5_GG (c, d, a, b, Block[ 7], 14, $676f02d9); MD5_GG (b, c, d, a, Block[12], 20, $8d2a4c8a); MD5_HH (a, b, c, d, Block[ 5], 4, $fffa3942); MD5_HH (d, a, b, c, Block[ 8], 11, $8771f681); MD5_HH (c, d, a, b, Block[11], 16, $6d9d6122); MD5_HH (b, c, d, a, Block[14], 23, $fde5380c); MD5_HH (a, b, c, d, Block[ 1], 4, $a4beea44); MD5_HH (d, a, b, c, Block[ 4], 11, $4bdecfa9); MD5_HH (c, d, a, b, Block[ 7], 16, $f6bb4b60); MD5_HH (b, c, d, a, Block[10], 23, $bebfbc70); MD5_HH (a, b, c, d, Block[13], 4, $289b7ec6); MD5_HH (d, a, b, c, Block[ 0], 11, $eaa127fa); MD5_HH (c, d, a, b, Block[ 3], 16, $d4ef3085); MD5_HH (b, c, d, a, Block[ 6], 23, $4881d05); MD5_HH (a, b, c, d, Block[ 9], 4, $d9d4d039); MD5_HH (d, a, b, c, Block[12], 11, $e6db99e5); MD5_HH (c, d, a, b, Block[15], 16, $1fa27cf8); MD5_HH (b, c, d, a, Block[ 2], 23, $c4ac5665); MD5_II (a, b, c, d, Block[ 0], 6, $f4292244); MD5_II (d, a, b, c, Block[ 7], 10, $432aff97); MD5_II (c, d, a, b, Block[14], 15, $ab9423a7); MD5_II (b, c, d, a, Block[ 5], 21, $fc93a039); MD5_II (a, b, c, d, Block[12], 6, $655b59c3); MD5_II (d, a, b, c, Block[ 3], 10, $8f0ccc92); MD5_II (c, d, a, b, Block[10], 15, $ffeff47d); MD5_II (b, c, d, a, Block[ 1], 21, $85845dd1); MD5_II (a, b, c, d, Block[ 8], 6, $6fa87e4f); MD5_II (d, a, b, c, Block[15], 10, $fe2ce6e0); MD5_II (c, d, a, b, Block[ 6], 15, $a3014314); MD5_II (b, c, d, a, Block[13], 21, $4e0811a1); MD5_II (a, b, c, d, Block[ 4], 6, $f7537e82); MD5_II (d, a, b, c, Block[11], 10, $bd3af235); MD5_II (c, d, a, b, Block[ 2], 15, $2ad7d2bb); MD5_II (b, c, d, a, Block[ 9], 21, $eb86d391); Inc(State[0], a); Inc(State[1], b); Inc(State[2], c); Inc(State[3], d); end; // Initialize given Context procedure MD5Init(var AContext: TMD5Context); begin with AContext do begin AContext.State[0] := $67452301; AContext.State[1] := $efcdab89; AContext.State[2] := $98badcfe; AContext.State[3] := $10325476; AContext.Count[0] := 0; AContext.Count[1] := 0; ZeroMemory(@AContext.Buffer, SizeOf(TMD5Buffer)); end; end; // Update given Context to include Length bytes of Input procedure MD5Update(var AContext: TMD5Context; AInput: PAnsiChar; ALength: LongWord); var Index: LongWord; PartLen: LongWord; I: LongWord; begin //with AContext do begin Index := (AContext.Count[0] shr 3) and $3f; Inc(AContext.Count[0], ALength shl 3); if AContext.Count[0] < (ALength shl 3) then Inc(AContext.Count[1]); Inc(AContext.Count[1], ALength shr 29); end; PartLen := 64 - Index; if ALength >= PartLen then begin CopyMemory(@AContext.Buffer[Index], AInput, PartLen); MD5_Transform(@AContext.Buffer, AContext.State); I := PartLen; while I + 63 < ALength do begin MD5_Transform(@AInput[I], AContext.State); Inc(I, 64); end; Index := 0; end else begin I := 0; end; CopyMemory(@AContext.Buffer[Index], @AInput[I], ALength - I); end; (*// procedure MD5UpdateW(var AContext: TMD5Context; AInput: PWideChar; ALength: LongWord); var pContent: PAnsiChar; iLen: Cardinal; begin GetMem(pContent, ALength * SizeOf(WideChar)); try iLen := Windows.WideCharToMultiByte(0, 0, AInput, ALength, // 代码页默认用 0 PAnsiChar(pContent), ALength * SizeOf(WideChar), nil, nil); MD5Update(AContext, pContent, iLen); finally FreeMem(pContent); end; end; //*) // Finalize given Context, create Digest and zeroize Context procedure MD5Final(var AContext: TMD5Context; var ADigest: TMD5Digest); var Bits: TMD5CBits; Index: LongWord; PadLen: LongWord; begin MD5_Decode(@AContext.Count, @Bits, 2); Index := (AContext.Count[0] shr 3) and $3f; if Index < 56 then PadLen := 56 - Index else PadLen := 120 - Index; MD5Update(AContext, @MD5_PADDING, PadLen); MD5Update(AContext, @Bits, 8); MD5_Decode(@AContext.State, @ADigest, 4); ZeroMemory(@AContext, SizeOf(TMD5Context)); end; // 对AnsiString类型数据进行MD5转换 function MD5StringA(const Str: AnsiString): TMD5Digest; var Context: TMD5Context; begin MD5Init(Context); MD5Update(Context, PAnsiChar(Str), Length(Str)); MD5Final(Context, Result); end; // 以十六进制格式输出MD5计算值 function MD5Print(const ADigest: TMD5Digest): AnsiString; var I: byte; begin Result := ''; for I := 0 to 15 do begin Result := Result + AA_NUM_TO_HEX[(ADigest[I] shr 4) and $0f] + AA_NUM_TO_HEX[ADigest[I] and $0f]; end; end; end.
unit cqrgen; {$mode delphi} interface uses Classes, SysUtils, And_jni, {And_jni_Bridge,} AndroidWidget; type {Draft Component code by "LAMW: Lazarus Android Module Wizard" [7/21/2020 23:23:40]} {https://github.com/jmpessoa/lazandroidmodulewizard} {jControl template} jcQRGen = class(jControl) private public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Init; override; function jCreate(): jObject; procedure jFree(); function GetURLQRCode(_url: string): jObject; overload; function GetTextQRCode(_txt: string): jObject; overload; function GetEMailQRCode(_email: string): jObject; overload; function GetMeCardQRCode(_name: string; _email: string; _address: string; _phone: string): jObject; overload; function GetVCardQRCode(_name: string; _email: string; _address: string; _phone: string; _title: string; _company: string; _website: string): jObject; overload; function GetURLQRCode(_url: string; _width: integer; _height: integer): jObject; overload; function GetTextQRCode(_txt: string; _width: integer; _height: integer): jObject; overload; function GetEMailQRCode(_email: string; _width: integer; _height: integer): jObject; overload; function GetMeCardQRCode(_name: string; _email: string; _address: string; _phone: string; _width: integer; _height: integer): jObject; overload; function GetVCardQRCode(_name: string; _email: string; _address: string; _phone: string; _title: string; _company: string; _website: string; _width: integer; _height: integer): jObject; overload; published end; function jcQRGen_jCreate(env: PJNIEnv;_Self: int64; this: jObject): jObject; procedure jcQRGen_jFree(env: PJNIEnv; _jcqrgen: JObject); function jcQRGen_GetURLQRCode(env: PJNIEnv; _jcqrgen: JObject; _url: string): jObject; overload; function jcQRGen_GetTextQRCode(env: PJNIEnv; _jcqrgen: JObject; _txt: string): jObject; overload; function jcQRGen_GetEMailQRCode(env: PJNIEnv; _jcqrgen: JObject; _email: string): jObject; overload; function jcQRGen_GetMeCardQRCode(env: PJNIEnv; _jcqrgen: JObject; _name: string; _email: string; _address: string; _phone: string): jObject; overload; function jcQRGen_GetVCardQRCode(env: PJNIEnv; _jcqrgen: JObject; _name: string; _email: string; _address: string; _phone: string; _title: string; _company: string; _website: string): jObject; overload; function jcQRGen_GetURLQRCode(env: PJNIEnv; _jcqrgen: JObject; _url: string; _width: integer; _height: integer): jObject; overload; function jcQRGen_GetTextQRCode(env: PJNIEnv; _jcqrgen: JObject; _txt: string; _width: integer; _height: integer): jObject; overload; function jcQRGen_GetEMailQRCode(env: PJNIEnv; _jcqrgen: JObject; _email: string; _width: integer; _height: integer): jObject; overload; function jcQRGen_GetMeCardQRCode(env: PJNIEnv; _jcqrgen: JObject; _name: string; _email: string; _address: string; _phone: string; _width: integer; _height: integer): jObject; overload; function jcQRGen_GetVCardQRCode(env: PJNIEnv; _jcqrgen: JObject; _name: string; _email: string; _address: string; _phone: string; _title: string; _company: string; _website: string; _width: integer; _height: integer): jObject; overload; implementation {--------- jcQRGen --------------} constructor jcQRGen.Create(AOwner: TComponent); begin inherited Create(AOwner); //your code here.... end; destructor jcQRGen.Destroy; begin if not (csDesigning in ComponentState) then begin if FjObject <> nil then begin jFree(); FjObject:= nil; end; end; //you others free code here...' inherited Destroy; end; procedure jcQRGen.Init; begin if FInitialized then Exit; inherited Init; //set default ViewParent/FjPRLayout as jForm.View! //your code here: set/initialize create params.... FjObject := jCreate(); //jSelf ! if FjObject = nil then exit; FInitialized:= True; end; function jcQRGen.jCreate(): jObject; begin Result:= jcQRGen_jCreate(gApp.jni.jEnv, int64(Self), gApp.jni.jThis); end; procedure jcQRGen.jFree(); begin //in designing component state: set value here... if FInitialized then jcQRGen_jFree(gApp.jni.jEnv, FjObject); end; function jcQRGen.GetURLQRCode(_url: string): jObject; begin //in designing component state: result value here... if FInitialized then Result:= jcQRGen_GetURLQRCode(gApp.jni.jEnv, FjObject, _url); end; function jcQRGen.GetTextQRCode(_txt: string): jObject; begin //in designing component state: result value here... if FInitialized then Result:= jcQRGen_GetTextQRCode(gApp.jni.jEnv, FjObject, _txt); end; function jcQRGen.GetEMailQRCode(_email: string): jObject; begin //in designing component state: result value here... if FInitialized then Result:= jcQRGen_GetEMailQRCode(gApp.jni.jEnv, FjObject, _email); end; function jcQRGen.GetMeCardQRCode(_name: string; _email: string; _address: string; _phone: string): jObject; begin //in designing component state: result value here... if FInitialized then Result:= jcQRGen_GetMeCardQRCode(gApp.jni.jEnv, FjObject, _name ,_email ,_address ,_phone); end; function jcQRGen.GetVCardQRCode(_name: string; _email: string; _address: string; _phone: string; _title: string; _company: string; _website: string): jObject; begin //in designing component state: result value here... if FInitialized then Result:= jcQRGen_GetVCardQRCode(gApp.jni.jEnv, FjObject, _name ,_email ,_address ,_phone ,_title ,_company ,_website); end; function jcQRGen.GetURLQRCode(_url: string; _width: integer; _height: integer): jObject; begin //in designing component state: result value here... if FInitialized then Result:= jcQRGen_GetURLQRCode(gApp.jni.jEnv, FjObject, _url ,_width ,_height); end; function jcQRGen.GetTextQRCode(_txt: string; _width: integer; _height: integer): jObject; begin //in designing component state: result value here... if FInitialized then Result:= jcQRGen_GetTextQRCode(gApp.jni.jEnv, FjObject, _txt ,_width ,_height); end; function jcQRGen.GetEMailQRCode(_email: string; _width: integer; _height: integer): jObject; begin //in designing component state: result value here... if FInitialized then Result:= jcQRGen_GetEMailQRCode(gApp.jni.jEnv, FjObject, _email ,_width ,_height); end; function jcQRGen.GetMeCardQRCode(_name: string; _email: string; _address: string; _phone: string; _width: integer; _height: integer): jObject; begin //in designing component state: result value here... if FInitialized then Result:= jcQRGen_GetMeCardQRCode(gApp.jni.jEnv, FjObject, _name ,_email ,_address ,_phone ,_width ,_height); end; function jcQRGen.GetVCardQRCode(_name: string; _email: string; _address: string; _phone: string; _title: string; _company: string; _website: string; _width: integer; _height: integer): jObject; begin //in designing component state: result value here... if FInitialized then Result:= jcQRGen_GetVCardQRCode(gApp.jni.jEnv, FjObject, _name ,_email ,_address ,_phone ,_title ,_company ,_website ,_width ,_height); end; {-------- jcQRGen_JNI_Bridge ----------} function jcQRGen_jCreate(env: PJNIEnv;_Self: int64; this: jObject): jObject; var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].j:= _Self; jCls:= Get_gjClass(env); jMethod:= env^.GetMethodID(env, jCls, 'jcQRGen_jCreate', '(J)Ljava/lang/Object;'); Result:= env^.CallObjectMethodA(env, this, jMethod, @jParams); Result:= env^.NewGlobalRef(env, Result); end; procedure jcQRGen_jFree(env: PJNIEnv; _jcqrgen: JObject); var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _jcqrgen); jMethod:= env^.GetMethodID(env, jCls, 'jFree', '()V'); env^.CallVoidMethod(env, _jcqrgen, jMethod); env^.DeleteLocalRef(env, jCls); end; function jcQRGen_GetURLQRCode(env: PJNIEnv; _jcqrgen: JObject; _url: string): jObject; var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].l:= env^.NewStringUTF(env, PChar(_url)); jCls:= env^.GetObjectClass(env, _jcqrgen); jMethod:= env^.GetMethodID(env, jCls, 'GetURLQRCode', '(Ljava/lang/String;)Landroid/graphics/Bitmap;'); Result:= env^.CallObjectMethodA(env, _jcqrgen, jMethod, @jParams); env^.DeleteLocalRef(env,jParams[0].l); env^.DeleteLocalRef(env, jCls); end; function jcQRGen_GetTextQRCode(env: PJNIEnv; _jcqrgen: JObject; _txt: string): jObject; var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].l:= env^.NewStringUTF(env, PChar(_txt)); jCls:= env^.GetObjectClass(env, _jcqrgen); jMethod:= env^.GetMethodID(env, jCls, 'GetTextQRCode', '(Ljava/lang/String;)Landroid/graphics/Bitmap;'); Result:= env^.CallObjectMethodA(env, _jcqrgen, jMethod, @jParams); env^.DeleteLocalRef(env,jParams[0].l); env^.DeleteLocalRef(env, jCls); end; function jcQRGen_GetEMailQRCode(env: PJNIEnv; _jcqrgen: JObject; _email: string): jObject; var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].l:= env^.NewStringUTF(env, PChar(_email)); jCls:= env^.GetObjectClass(env, _jcqrgen); jMethod:= env^.GetMethodID(env, jCls, 'GetEMailQRCode', '(Ljava/lang/String;)Landroid/graphics/Bitmap;'); Result:= env^.CallObjectMethodA(env, _jcqrgen, jMethod, @jParams); env^.DeleteLocalRef(env,jParams[0].l); env^.DeleteLocalRef(env, jCls); end; function jcQRGen_GetMeCardQRCode(env: PJNIEnv; _jcqrgen: JObject; _name: string; _email: string; _address: string; _phone: string): jObject; var jParams: array[0..3] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].l:= env^.NewStringUTF(env, PChar(_name)); jParams[1].l:= env^.NewStringUTF(env, PChar(_email)); jParams[2].l:= env^.NewStringUTF(env, PChar(_address)); jParams[3].l:= env^.NewStringUTF(env, PChar(_phone)); jCls:= env^.GetObjectClass(env, _jcqrgen); jMethod:= env^.GetMethodID(env, jCls, 'GetMeCardQRCode', '(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Landroid/graphics/Bitmap;'); Result:= env^.CallObjectMethodA(env, _jcqrgen, jMethod, @jParams); env^.DeleteLocalRef(env,jParams[0].l); env^.DeleteLocalRef(env,jParams[1].l); env^.DeleteLocalRef(env,jParams[2].l); env^.DeleteLocalRef(env,jParams[3].l); env^.DeleteLocalRef(env, jCls); end; function jcQRGen_GetVCardQRCode(env: PJNIEnv; _jcqrgen: JObject; _name: string; _email: string; _address: string; _phone: string; _title: string; _company: string; _website: string): jObject; var jParams: array[0..6] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].l:= env^.NewStringUTF(env, PChar(_name)); jParams[1].l:= env^.NewStringUTF(env, PChar(_email)); jParams[2].l:= env^.NewStringUTF(env, PChar(_address)); jParams[3].l:= env^.NewStringUTF(env, PChar(_phone)); jParams[4].l:= env^.NewStringUTF(env, PChar(_title)); jParams[5].l:= env^.NewStringUTF(env, PChar(_company)); jParams[6].l:= env^.NewStringUTF(env, PChar(_website)); jCls:= env^.GetObjectClass(env, _jcqrgen); jMethod:= env^.GetMethodID(env, jCls, 'GetVCardQRCode', '(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Landroid/graphics/Bitmap;'); Result:= env^.CallObjectMethodA(env, _jcqrgen, jMethod, @jParams); env^.DeleteLocalRef(env,jParams[0].l); env^.DeleteLocalRef(env,jParams[1].l); env^.DeleteLocalRef(env,jParams[2].l); env^.DeleteLocalRef(env,jParams[3].l); env^.DeleteLocalRef(env,jParams[4].l); env^.DeleteLocalRef(env,jParams[5].l); env^.DeleteLocalRef(env,jParams[6].l); env^.DeleteLocalRef(env, jCls); end; function jcQRGen_GetURLQRCode(env: PJNIEnv; _jcqrgen: JObject; _url: string; _width: integer; _height: integer): jObject; var jParams: array[0..2] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].l:= env^.NewStringUTF(env, PChar(_url)); jParams[1].i:= _width; jParams[2].i:= _height; jCls:= env^.GetObjectClass(env, _jcqrgen); jMethod:= env^.GetMethodID(env, jCls, 'GetURLQRCode', '(Ljava/lang/String;II)Landroid/graphics/Bitmap;'); Result:= env^.CallObjectMethodA(env, _jcqrgen, jMethod, @jParams); env^.DeleteLocalRef(env,jParams[0].l); env^.DeleteLocalRef(env, jCls); end; function jcQRGen_GetTextQRCode(env: PJNIEnv; _jcqrgen: JObject; _txt: string; _width: integer; _height: integer): jObject; var jParams: array[0..2] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].l:= env^.NewStringUTF(env, PChar(_txt)); jParams[1].i:= _width; jParams[2].i:= _height; jCls:= env^.GetObjectClass(env, _jcqrgen); jMethod:= env^.GetMethodID(env, jCls, 'GetTextQRCode', '(Ljava/lang/String;II)Landroid/graphics/Bitmap;'); Result:= env^.CallObjectMethodA(env, _jcqrgen, jMethod, @jParams); env^.DeleteLocalRef(env,jParams[0].l); env^.DeleteLocalRef(env, jCls); end; function jcQRGen_GetEMailQRCode(env: PJNIEnv; _jcqrgen: JObject; _email: string; _width: integer; _height: integer): jObject; var jParams: array[0..2] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].l:= env^.NewStringUTF(env, PChar(_email)); jParams[1].i:= _width; jParams[2].i:= _height; jCls:= env^.GetObjectClass(env, _jcqrgen); jMethod:= env^.GetMethodID(env, jCls, 'GetEMailQRCode', '(Ljava/lang/String;II)Landroid/graphics/Bitmap;'); Result:= env^.CallObjectMethodA(env, _jcqrgen, jMethod, @jParams); env^.DeleteLocalRef(env,jParams[0].l); env^.DeleteLocalRef(env, jCls); end; function jcQRGen_GetMeCardQRCode(env: PJNIEnv; _jcqrgen: JObject; _name: string; _email: string; _address: string; _phone: string; _width: integer; _height: integer): jObject; var jParams: array[0..5] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].l:= env^.NewStringUTF(env, PChar(_name)); jParams[1].l:= env^.NewStringUTF(env, PChar(_email)); jParams[2].l:= env^.NewStringUTF(env, PChar(_address)); jParams[3].l:= env^.NewStringUTF(env, PChar(_phone)); jParams[4].i:= _width; jParams[5].i:= _height; jCls:= env^.GetObjectClass(env, _jcqrgen); jMethod:= env^.GetMethodID(env, jCls, 'GetMeCardQRCode', '(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;II)Landroid/graphics/Bitmap;'); Result:= env^.CallObjectMethodA(env, _jcqrgen, jMethod, @jParams); env^.DeleteLocalRef(env,jParams[0].l); env^.DeleteLocalRef(env,jParams[1].l); env^.DeleteLocalRef(env,jParams[2].l); env^.DeleteLocalRef(env,jParams[3].l); env^.DeleteLocalRef(env, jCls); end; function jcQRGen_GetVCardQRCode(env: PJNIEnv; _jcqrgen: JObject; _name: string; _email: string; _address: string; _phone: string; _title: string; _company: string; _website: string; _width: integer; _height: integer): jObject; var jParams: array[0..8] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].l:= env^.NewStringUTF(env, PChar(_name)); jParams[1].l:= env^.NewStringUTF(env, PChar(_email)); jParams[2].l:= env^.NewStringUTF(env, PChar(_address)); jParams[3].l:= env^.NewStringUTF(env, PChar(_phone)); jParams[4].l:= env^.NewStringUTF(env, PChar(_title)); jParams[5].l:= env^.NewStringUTF(env, PChar(_company)); jParams[6].l:= env^.NewStringUTF(env, PChar(_website)); jParams[7].i:= _width; jParams[8].i:= _height; jCls:= env^.GetObjectClass(env, _jcqrgen); jMethod:= env^.GetMethodID(env, jCls, 'GetVCardQRCode', '(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;II)Landroid/graphics/Bitmap;'); Result:= env^.CallObjectMethodA(env, _jcqrgen, jMethod, @jParams); env^.DeleteLocalRef(env,jParams[0].l); env^.DeleteLocalRef(env,jParams[1].l); env^.DeleteLocalRef(env,jParams[2].l); env^.DeleteLocalRef(env,jParams[3].l); env^.DeleteLocalRef(env,jParams[4].l); env^.DeleteLocalRef(env,jParams[5].l); env^.DeleteLocalRef(env,jParams[6].l); env^.DeleteLocalRef(env, jCls); end; end.
unit uValidacoes; interface type TValidacoes = class private { private declarations } protected { protected declarations } public { public declarations } published { published declarations } function emailValido(email : String) : boolean; function cpfValido(cpf : String) : boolean; end; const CaraterEspecial: array[1..40] of string[1] = ( '!','#','$','%','¨','&','*', '(',')','+','=','§','¬','¢','¹','²', '³','£','´','`','ç','Ç',',',';',':', '<','>','~','^','?','/','','|','[',']','{','}', 'º','ª','°'); Letras: array[1..27] of string[1] = ('a','b','c','d','e','f','g', 'h','i','j','k','l','m','n','o','p', 'q','r','s','t','u','v','w','x','y', 'z','ç'); implementation uses SysUtils; function TValidacoes.emailValido(email : String) : boolean; var i : integer; begin if Trim(email) <> '' then begin if (Pos('@', email) <> 0) and (Pos('.', email) <> 0) then // verifica se existe '@' e '.' begin for i := 1 to length(email) - 1 do begin // verifica se existe Caracter Especial if Pos(CaraterEspecial[i], EMail)<>0 then Result := False; end; Result := True; end else Result := False; end else Result := False; end; function TValidacoes.cpfValido(cpf : String) : boolean; var i : integer; begin cpf := StringReplace(cpf, '.', '', [rfReplaceAll, rfIgnoreCase]); cpf := StringReplace(cpf, '-', '', [rfReplaceAll, rfIgnoreCase]); if trim(cpf) <> '' then begin for i := 1 to length(cpf) - 1 do begin // verifica se existe Caracter Especial if Pos(CaraterEspecial[i], cpf)<>0 then Result := False; end; for i := 1 to length(cpf) - 1 do begin // verifica se existe Caracter Especial if Pos(Letras[i], cpf)<>0 then Result := False; end; Result := True; end else Result := False; end; end.
unit MrpLogReader2; interface uses Classes, SysUtils, ComObj, CommUtils, ADODB, SAPMaterialReader; type TMrpLogRecord = packed record id: Integer; //ID pid: Integer; //父ID snumber: string; //物料 sname: string; //物料名称 dt: TDateTime; //需求日期 dtReq: TDateTime; //建议下单日期 dqty: Double; //需求数量 dqtyStock: Double; //可用库存 dqtyOPO: Double; //OPO dqtyNet: Double; //净需求 sGroup: string; //替代组 sMrp: string; //MRP控制者 sBuyer: string; //采购员 sArea: string; //MRP区域 spnumber: string; // 上层料号 srnumber: string; // 根料号 slt: string; // L/T bCalc: Boolean; end; PMrpLogRecord = ^TMrpLogRecord; TMrpLogReader2 = class private FFile: string; ExcelApp, WorkBook: Variant; FLogEvent: TLogEvent; procedure Open; procedure Log(const str: string); function GetCount: Integer; function GetItems(i: Integer): PMrpLogRecord; public FList: TStringList; constructor Create(const sfile: string; aLogEvent: TLogEvent = nil); destructor Destroy; override; procedure Clear; property Count: Integer read GetCount; property Items[i: Integer]: PMrpLogRecord read GetItems; function GetSAPMaterialRecord(const snumber: string): PMrpLogRecord; end; implementation { TMrpLogReader2 } constructor TMrpLogReader2.Create(const sfile: string; aLogEvent: TLogEvent = nil); begin FFile := sfile; FLogEvent := aLogEvent; FList := TStringList.Create; Open; end; destructor TMrpLogReader2.Destroy; begin Clear; FList.Free; inherited; end; procedure TMrpLogReader2.Clear; var i: Integer; p: PMrpLogRecord; begin for i := 0 to FList.Count - 1 do begin p := PMrpLogRecord(FList.Objects[i]); Dispose(p); end; FList.Clear; end; function TMrpLogReader2.GetCount: Integer; begin Result := FList.Count; end; function TMrpLogReader2.GetItems(i: Integer): PMrpLogRecord; begin Result := PMrpLogRecord(FList.Objects[i]); end; function TMrpLogReader2.GetSAPMaterialRecord(const snumber: string): PMrpLogRecord; var idx: Integer; begin idx := FList.IndexOf(snumber); if idx >= 0 then begin Result := PMrpLogRecord(FList.Objects[idx]); end else Result := nil; end; procedure TMrpLogReader2.Log(const str: string); begin savelogtoexe(str); if Assigned(FLogEvent) then begin FLogEvent(str); end; end; function IndexOfCol(ExcelApp: Variant; irow: Integer; const scol: string): Integer; var i: Integer; s: string; begin Result := -1; for i := 1 to 50 do begin s := ExcelApp.Cells[irow, i].Value; if s = scol then begin Result := i; Break; end; end; end; function StringListSortCompare(List: TStringList; Index1, Index2: Integer): Integer; var item1, item2: PMrpLogRecord; begin item1 := PMrpLogRecord(List.Objects[Index1]); item2 := PMrpLogRecord(List.Objects[Index2]); if item1.id > item2.id then Result := 1 else if item1.id < item2.id then Result := -1 else Result := 0; end; procedure TMrpLogReader2.Open; const CSNumber = '物料编码'; CSName = '物料描述'; CSRecvTime = '收货处理时间'; CSMRPType = 'MRP类型'; CSSPQ = '舍入值'; CSLT_PD = '计划交货时间'; CSLT_M0 = '自制生产时间'; CSLT_MOQ = '最小批量大小'; CSMRPGroup = 'MRP组'; CSPType = '采购类型'; var iSheetCount, iSheet: Integer; sSheet: string; stitle1, stitle2, stitle3, stitle4, stitle5, stitle6: string; stitle: string; irow: Integer; snumber: string; aMrpLogRecordPtr: PMrpLogRecord; iColNumber: Integer; iColName: Integer; iColRecvTime: Integer; iColMRPType: Integer; iColSPQ: Integer; iColLT_PD: Integer; iColLT_M0: Integer; Conn: TADOConnection; ADOTabXLS: TADOTable; begin Clear; if not FileExists(FFile) then Exit; ADOTabXLS := TADOTable.Create(nil); Conn:=TADOConnection.Create(nil); Conn.ConnectionString:='Provider=Microsoft.ACE.OLEDB.12.0;Data Source="' + FFile + '";Extended Properties=excel 8.0;Persist Security Info=False'; Conn.LoginPrompt:=false; try Conn.Connected:=true; ADOTabXLS.Connection:=Conn; ADOTabXLS.TableName:='[Mrp Log$]'; ADOTabXLS.Active:=true; ADOTabXLS.First; while not ADOTabXLS.Eof do begin aMrpLogRecordPtr := New(PMrpLogRecord); aMrpLogRecordPtr.bCalc := False; aMrpLogRecordPtr^.id := ADOTabXLS.FieldByName('ID').AsInteger; aMrpLogRecordPtr^.pid := ADOTabXLS.FieldByName('父ID').AsInteger; aMrpLogRecordPtr^.snumber := ADOTabXLS.FieldByName('物料').AsString; aMrpLogRecordPtr^.sname := ADOTabXLS.FieldByName('物料名称').AsString; aMrpLogRecordPtr^.dt := ADOTabXLS.FieldByName('需求日期').AsDateTime; aMrpLogRecordPtr^.dtReq := ADOTabXLS.FieldByName('建议下单日期').AsDateTime; aMrpLogRecordPtr^.dqty := ADOTabXLS.FieldByName('需求数量').AsFloat; aMrpLogRecordPtr^.dqtyStock := ADOTabXLS.FieldByName('可用库存').AsFloat; aMrpLogRecordPtr^.dqtyOPO := ADOTabXLS.FieldByName('OPO').AsFloat; aMrpLogRecordPtr^.dqtyNet := ADOTabXLS.FieldByName('净需求').AsFloat; aMrpLogRecordPtr^.sGroup := ADOTabXLS.FieldByName('替代组').AsString; aMrpLogRecordPtr^.sMrp := ADOTabXLS.FieldByName('MRP控制者').AsString; aMrpLogRecordPtr^.sBuyer := ADOTabXLS.FieldByName('采购员').AsString; aMrpLogRecordPtr^.sArea := ADOTabXLS.FieldByName('MRP区域').AsString; aMrpLogRecordPtr^.spnumber := ADOTabXLS.FieldByName('上层料号').AsString; aMrpLogRecordPtr^.srnumber := ADOTabXLS.FieldByName('根料号').AsString; aMrpLogRecordPtr^.slt := ADOTabXLS.FieldByName('L/T').AsString; FList.AddObject(aMrpLogRecordPtr^.snumber, TObject(aMrpLogRecordPtr)); ADOTabXLS.Next; end; ADOTabXLS.Close; Conn.Connected := False; FList.CustomSort( StringListSortCompare ); finally FreeAndNil(Conn); FreeAndNil(ADOTabXLS); end; end; end.
unit DisciplinaGerenciador; {$MODE OBJFPC} interface uses Classes,fgl ,SysUtils,DisciplinaModel; type TMyList = specialize TFPGObjectList<TDisciplinaModel>; TDisciplinaGerenciador = class private FLista : TMyList; public constructor Create; destructor Destroy; override; procedure gerenciar; procedure cadastrar; procedure listar; procedure editar; procedure excluir; end; implementation constructor TDisciplinaGerenciador.Create; begin inherited Create; FLista := TMyList.Create; end; procedure TDisciplinaGerenciador.excluir; var codigo:integer; var index:integer; var encontrou:boolean; begin try Writeln('Digite o codigo da disciplina que deseja deletar'); Readln(codigo); encontrou:=False; for index:=0 to FLista.Count-1 do begin if(FLista.Items[index].FCodigo = codigo) then begin FLista.Delete(index); encontrou := True; end; end; if(encontrou = True) then begin WriteLn('Disciplina excluida com sucesso'); end else WriteLn('Nao foi encontrada uma disciplina com o codigo especificado'); finally end; end; destructor TDisciplinaGerenciador.Destroy; begin FLista.Free; inherited Destroy; end; procedure TDisciplinaGerenciador.editar; var codigo:integer; var index:integer; var encontrou:boolean; begin try Writeln('Digite o codigo da disciplina que deseja editar'); Readln(codigo); encontrou:=False; for index:=0 to FLista.Count-1 do begin if(FLista.Items[index].FCodigo = codigo) then begin WriteLn('Digite o novo codigo da disciplina'); Readln(FLista.Items[index].FCodigo); WriteLn('Digite o novo nome da disciplina'); Readln(FLista.Items[index].FNome); WriteLn('Digite a novo carga horaria da disciplina'); Readln(FLista.Items[index].FCargaHoraria); WriteLn('Digite o novo valor da disciplina'); Readln(FLista.Items[index].FValor); encontrou := True; end; end; if(encontrou = True) then begin WriteLn('Disciplina atualizada com sucesso'); end else WriteLn('Nao foi encontrada uma disciplina com o codigo especificado'); except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; end; procedure TDisciplinaGerenciador.gerenciar; var opcao:integer; begin repeat Writeln('Escolha uma op��o'); Writeln('1 - Cadastrar Disciplina'); Writeln('2 - Listar Disciplinas'); Writeln('3 - Editar Disciplinas'); Writeln('4 - Excluir Disciplinas'); Writeln('0 - Sair'); Readln(opcao); case opcao of 1:cadastrar; 2:listar; 3:editar; 4:excluir; end; until opcao = 0; end; procedure TDisciplinaGerenciador.cadastrar; var tempModel : TDisciplinaModel; begin try tempModel := TDisciplinaModel.Create; WriteLn('Digite o codigo da disciplina'); Readln(tempModel.FCodigo); WriteLn('Digite o nome da disciplina'); Readln(tempModel.FNome); WriteLn('Digite a carga horaria da disciplina'); Readln(tempModel.FCargaHoraria); WriteLn('Digite o valor da disciplina'); Readln(tempModel.FValor); //adicionar na lista FLista.Add(tempModel); except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; end; procedure TDisciplinaGerenciador.listar; var temp : TDisciplinaModel; begin Writeln('Lista de Disciplinas Cadastradas:'); for temp in FLista do begin Writeln('----------------------'); Writeln('C�digo: ',temp.getFCodigo); Writeln('Nome: ',temp.getFNome); Writeln('----------------------'); end; end; end.
unit uCadastroProblema; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TfrmCadastroProblema = class(TForm) mmProblema: TMemo; btCancelar: TButton; btGravar: TButton; cbProduto: TComboBox; cbModulo: TComboBox; lbProduto: TLabel; LbModulo: TLabel; procedure btCancelarClick(Sender: TObject); procedure btGravarClick(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } public procedure CarregarProdutos(); procedure CarregarModulos(); end; var frmCadastroProblema: TfrmCadastroProblema; implementation uses udmproblemas, uDmModulos, uDmProdutos; {$R *.dfm} procedure TfrmCadastroProblema.btCancelarClick(Sender: TObject); var retorno: Integer; begin retorno := MessageDlg('Deseja cancelar a operação ?', mtConfirmation, [mbyes, mbno, mbCancel], 0); if retorno = mrYes then begin Close(); end; end; procedure TfrmCadastroProblema.btGravarClick(Sender: TObject); var idModulo: Integer; idProduto: Integer; begin idModulo := dmModulos.buscarIdModuloPorDescricao(cbModulo.Text); idProduto := dmProdutos.buscarIdProdutoPorDescricao(cbProduto.Text); dmProblemas.SalvarProblema(mmProblema.Lines.Text, idModulo, idProduto); Close(); end; procedure TfrmCadastroProblema.CarregarModulos; begin dmModulos.carregarQrModulos(); cbModulo.Items.Clear(); cbModulo.Items.Add('Módulo que não existe'); while not dmModulos.QrModulos.Eof do begin cbModulo.Items.Add(dmModulos.QrModulos.FieldByName('nome').AsString); dmModulos.QrModulos.Next(); end; end; procedure TfrmCadastroProblema.CarregarProdutos; begin dmProdutos.carregarQrProdutos(); cbProduto.Clear(); while not dmProdutos.QrProdutos.Eof do begin cbProduto.Items.Add(dmProdutos.QrProdutos.FieldByName('nome').AsString); dmProdutos.QrProdutos.Next(); end; end; procedure TfrmCadastroProblema.FormShow(Sender: TObject); begin CarregarProdutos(); CarregarModulos(); end; end.
unit frmuFragments; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, OleCtrls, SHDocVw, EmbeddedWB, ExtCtrls, StdCtrls, ComCtrls, ToolWin, ActnList, ImgList, MSHTML_TLB, ActiveX; type TfrmFragments = class(TForm) ToolBar1: TToolBar; btnNew: TToolButton; ListBox1: TListBox; Splitter1: TSplitter; Panel1: TPanel; Browser: TEmbeddedWB; ToolButton2: TToolButton; btnEdit: TToolButton; btnDel: TToolButton; ImageList1: TImageList; ActionList1: TActionList; aNew: TAction; aEdit: TAction; aDel: TAction; procedure FormShow(Sender: TObject); procedure ListBox1Click(Sender: TObject); procedure ListBox1KeyPress(Sender: TObject; var Key: Char); procedure aNewExecute(Sender: TObject); procedure aEditExecute(Sender: TObject); procedure aEditUpdate(Sender: TObject); procedure aDelUpdate(Sender: TObject); procedure aDelExecute(Sender: TObject); private { Private declarations } procedure Updates(AIndex: Integer); procedure UpdatePreview; public { Public declarations } end; var frmFragments: TfrmFragments; implementation uses uMain, uParser, uConsts, uStr, frmuNewFragment; {$R *.dfm} procedure TfrmFragments.FormShow(Sender: TObject); begin Updates(0); ListBox1.ItemIndex := 0; end; procedure TfrmFragments.UpdatePreview; var V: OleVariant; txt: string; s: string; Editor: IHTMLDocument2; begin if (ListBox1.ItemIndex < 0) or (ListBox1.Count <= 0) then txt := '' else txt := frmMain.Fragments[ListBox1.ItemIndex].Text; InsImg(txt); if Browser.Document = nil then Browser.Navigate('about:blank'); while Browser.Document = nil do Application.ProcessMessages; Editor := Browser.Document as IHTMLDocument2; V := VarArrayCreate([0,0], varVariant); s := BodyStyleDiv + HTMLtoWYSIWYG(txt) + '</div></body>'; V[0] := BodyStyleDiv + s + '</div></body>'; Editor.Write(PSafeArray(TVarData(v).VArray)); Editor.Close; SetAttributes(Editor); end; procedure TfrmFragments.Updates(AIndex: Integer); var OldIndex: Integer; Index: Integer; begin OldIndex := ListBox1.ItemIndex; ListBox1.Clear; if Length(frmMain.Fragments) <= 0 then Exit; for Index := 0 to Length(frmMain.Fragments) - 1 do ListBox1.Items.Add(frmMain.Fragments[Index].Captions); if AIndex >= 0 then ListBox1.ItemIndex := AIndex else ListBox1.ItemIndex := OldIndex; UpdatePreview; end; procedure TfrmFragments.ListBox1Click(Sender: TObject); begin Updates(-1); end; procedure TfrmFragments.ListBox1KeyPress(Sender: TObject; var Key: Char); begin Updates(-1); end; procedure TfrmFragments.aNewExecute(Sender: TObject); var lCaption, lText: string; len: Integer; begin lCaption := ''; lText := ''; if NewFragment(lCaption, lText) then begin len := Length(frmMain.Fragments); SetLength(frmMain.Fragments, len + 1); frmMain.Fragments[len].Captions := lCaption; frmMain.Fragments[len].Text := lText; Updates(len); end; end; procedure TfrmFragments.aEditExecute(Sender: TObject); var lCaption, lText: string; begin if ListBox1.Count <= 0 then Exit; lCaption := frmMain.Fragments[ListBox1.ItemIndex].Captions; lText := frmMain.Fragments[ListBox1.ItemIndex].Text; if NewFragment(lCaption, lText) then begin frmMain.Fragments[ListBox1.ItemIndex].Captions := lCaption; frmMain.Fragments[ListBox1.ItemIndex].Text := lText; Updates(-1); end; end; procedure TfrmFragments.aEditUpdate(Sender: TObject); begin aEdit.Enabled := (ListBox1.Count > 0) and (ListBox1.ItemIndex >= 0); end; procedure TfrmFragments.aDelUpdate(Sender: TObject); begin aDel.Enabled := (ListBox1.Count > 0) and (ListBox1.ItemIndex >= 0); end; procedure TfrmFragments.aDelExecute(Sender: TObject); var Index: Integer; str: string; len: Integer; begin str := 'Вы действительно хотите удалить фрагмент: ' + frmMain.Fragments[ListBox1.ItemIndex].Captions + '?'; if MessageBox(Application.Handle, PChar(str), 'Внимание', MB_YESNO + MB_ICONQUESTION + MB_APPLMODAL + MB_SYSTEMMODAL + MB_TASKMODAL + MB_TOPMOST) = IDYES then begin len := Length(frmMain.Fragments); if ListBox1.ItemIndex < Length(frmMain.Fragments) - 1 then for Index := ListBox1.ItemIndex to Length(frmMain.Fragments) - 2 do frmMain.Fragments[Index] := frmMain.Fragments[Index + 1]; SetLength(frmMain.Fragments, len - 1); end; Updates(-1); end; end.
unit EventLog; interface uses Classes, LogTools, SyncObjs; const MaxSMTPServerConnectionTime = 5000; type TLog = class private fLogMessages : TLogMessageList; private fLock : TCriticalSection; function LogFilePath : string; function LogFileName : string; procedure CreateBlankLog; function GetLogMessagesCount: integer; public property LogMessages : TLogMessageList read fLogMessages; property Count : integer read GetLogMessagesCount; public constructor Create; destructor Destroy; override; procedure SaveLogs; procedure AddLogMessage(const ACategory : TLogCategory; const AnUser, AZone, ATitle, AMessage : string ); procedure AddLogRawMessage( const ADateTime : TDateTime; const ACategory : TLogCategory; const AnUser, AZone, ATitle, AMessage : string ); //email procedure ConfigureServer; function TestEmailServerConfig : boolean; procedure SendEMail( const ASubject : string; ABody : TStrings ); function SendTestEmail : boolean; procedure SendErrorEmail( const ErrorName, ErrorMsg : string ); procedure SendWarningEmail( const WarningName, WarningMsg : string ); procedure SendCheckEmail( const Text : string ); end; var LogMessages : TLog; implementation uses SysUtils, IdSMTP, Radars, Description, Config, Elbrus, IdMessage, Communication_Module; { TLog } procedure TLog.ConfigureServer; begin with CommunicationModule.SMTPServer, theConfiguration do begin AuthenticationType := atLogin; Host := SMTPServer; Port := SMTPPort; Username := SMTPUser; Password := SMTPPassword; end; end; constructor TLog.Create; var Source : TReader; Stream : TStream; begin inherited; fLock := TCriticalSection.Create; fLogMessages := TLogMessageList.Create; if not FileExists( LogFileName ) then CreateBlankLog; Stream := TFileStream.Create( LogFileName, fmOpenRead ); Source := TReader.Create( Stream, MaxLogLines*MaxLogSize ); try fLogMessages.Load( Source ); fLogMessages.PackPath := LogFilePath; finally Source.Free; Stream.Free; end; end; destructor TLog.Destroy; begin SaveLogs; fLogMessages.Free; fLock.Free; inherited; end; function TLog.LogFilePath: string; begin result := ExtractFilePath( ParamStr(0) ) + '\Logs\' end; procedure TLog.AddLogMessage(const ACategory : TLogCategory; const AnUser, AZone, ATitle, AMessage : string ); begin AddLogRawMessage(Now, ACategory, AnUser, AZone, ATitle, AMessage ); if (ACategory = lcError) and (theConfiguration.SendMsgOnError) then SendErrorEmail( ATitle, AMessage ); end; procedure TLog.SendErrorEmail(const ErrorName, ErrorMsg: string); var Body : TStrings; Subject : string; begin Body := TStringList.Create; try Subject := 'Un mensaje de error del Radar de ' + Find( TRadar( theConfiguration.RadarID ) ).Name + ' : ' + ErrorName; Body.Add( 'El radar de ' + Find( TRadar( theConfiguration.RadarID ) ).Name + ' le ha enviado un correo de error ' ); Body.Add( 'Fecha: ' + DateToStr( Now ) + ' Hora: ' + TimeToStr( Now ) ); Body.Add( 'Observación: ' + Snapshot.ObsName ); Body.Add( 'Error:' ); Body.Add( ErrorMsg ); try SendEMail( Subject, Body ); except end; finally Body.Free; end; end; function TLog.SendTestEmail : boolean; var Body : TStrings; Subject : string; begin Body := TStringList.Create; try Subject := 'Un mensaje de prueba del Radar de ' + Find( TRadar( theConfiguration.RadarID ) ).Name; Body.Add( 'El radar de ' + Find( TRadar( theConfiguration.RadarID ) ).Name + ' le ha enviado un correo de prueba '+ 'como parte de la comprobacion de la configuracion del sistema de alarma '); Body.Add( 'Fecha: ' + DateToStr( Now ) + ' Hora: ' + TimeToStr( Now ) ); try SendEMail( Subject, Body ); result := true; except result := false; end; finally Body.Free; end; end; function TLog.TestEmailServerConfig: boolean; begin with CommunicationModule.SMTPServer do try try ConfigureServer; Connect( MaxSMTPServerConnectionTime ); result := Authenticate; finally if Connected then Disconnect; end; except result := false; end; end; function TLog.GetLogMessagesCount: integer; begin result := fLogMessages.Count; end; procedure TLog.AddLogRawMessage( const ADateTime : TDateTime; const ACategory : TLogCategory; const AnUser, AZone, ATitle, AMessage : string ); begin fLock.Enter; try fLogMessages.AddLog( ADateTime, ACategory, AnUser, AZone, ATitle, AMessage ); SaveLogs; finally fLock.Leave; end; end; procedure TLog.SendWarningEmail(const WarningName, WarningMsg: string); var Body : TStrings; Subject : string; begin Body := TStringList.Create; try Subject := 'Un mensaje de aviso del Radar de ' + Find( TRadar( theConfiguration.RadarID ) ).Name + ' : ' + WarningName; Body.Add( 'El radar de ' + Find( TRadar( theConfiguration.RadarID ) ).Name + ' le ha enviado un correo de aviso ' ); Body.Add( 'Fecha: ' + DateToStr( Now ) + ' Hora: ' + TimeToStr( Now ) ); Body.Add( 'Observación: ' + Snapshot.ObsName ); Body.Add( 'Aviso:' ); Body.Add( WarningMsg ); try SendEMail( Subject, Body ); except end; finally Body.Free; end; end; procedure TLog.SendCheckEmail(const Text: string); var Body : TStrings; Subject : string; begin Body := TStringList.Create; try Subject := 'Un mensaje de chequeo del Radar de ' + Find( TRadar( theConfiguration.RadarID ) ).Name; Body.Add( 'El radar de ' + Find( TRadar( theConfiguration.RadarID ) ).Name + ' le ha enviado un correo de autochequeo ' ); Body.Add( 'Fecha: ' + DateToStr( Now ) + ' Hora: ' + TimeToStr( Now ) ); Body.Add( 'Resultado:' ); Body.Add( Text ); try SendEMail( Subject, Body ); except end; finally Body.Free; end; end; procedure TLog.SendEMail(const ASubject: string; ABody: TStrings); var ToList : TStrings; i : integer; begin with CommunicationModule.SMTPServer, CommunicationModule.EMailMessage do try ConfigureServer; //Config Error Message ContentType := 'text/plain'; From.Address := theConfiguration.SMTPFromAddress; Date := Now; ToList := TStringList.Create; ToList.CommaText := theConfiguration.TargetAddress; Recipients.Clear; for i := 0 to ToList.Count-1 do begin Recipients.Add; Recipients[i].Address := ToList[i]; end; Subject := ASubject; Body.Clear; Body.Assign( ABody ); Connect( MaxSMTPServerConnectionTime ); Send( CommunicationModule.EMailMessage ); finally ToList.Free; if Connected then Disconnect; end; end; procedure TLog.CreateBlankLog; var Target : TWriter; Stream : TStream; begin Stream := TFileStream.Create( LogFileName, fmCreate ); Target := TWriter.Create( Stream, MaxLogSize ); try Target.WriteInteger( 0 ); Target.WriteInteger( 0 ); finally Target.Free; Stream.Free; end; end; function TLog.LogFileName: string; begin result := LogFilePath + FileName; end; procedure TLog.SaveLogs; var Target : TWriter; Stream : TStream; begin Stream := TFileStream.Create( LogFileName, fmCreate ); Target := TWriter.Create( Stream, MaxLogLines*MaxLogSize ); try fLogMessages.Save( Target ); finally Target.Free; Stream.Free; end; end; initialization LogMessages := TLog.Create; finalization LogMessages.Free; end.
unit dbObjectMeatTest; interface uses dbObjectTest, Classes, TestFramework, Authentication, Db, XMLIntf, dsdDB, dbTest, ObjectTest; type TdbObjectTest = class (TdbTest) protected // подготавливаем данные для тестирования procedure SetUp; override; // возвращаем данные для тестирования procedure TearDown; override; function GetRecordCount(ObjectTest: TObjectTest): integer; published // procedure DocumentTaxKind_Test; end; implementation uses ZDbcIntfs, SysUtils, Storage, DBClient, XMLDoc, CommonData, Forms, UtilConvert, ZLibEx, zLibUtil,UnitsTest, JuridicalTest, BusinessTest, GoodsTest, GoodsKindTest; { TDataBaseObjectTest } {------------------------------------------------------------------------------} function TdbObjectTest.GetRecordCount(ObjectTest: TObjectTest): integer; begin Result := ObjectTest.GetDataSet.RecordCount; end; {------------------------------------------------------------------------------} {------------------------------------------------------------------------------} {------------------------------------------------------------------------------} procedure TdbObjectTest.TearDown; begin inherited; if Assigned(InsertedIdObjectList) then with TObjectTest.Create do while InsertedIdObjectList.Count > 0 do begin DeleteRecord(StrToInt(InsertedIdObjectList[0])); InsertedIdObjectList.Delete(0); end; end; {------------------------------------------------------------------------------} procedure TdbObjectTest.SetUp; begin inherited; TAuthentication.CheckLogin(TStorageFactory.GetStorage, 'Админ', 'Админ', gc_User); end; {------------------------------------------------------------------------------} { TDataBaseUsersObjectTest } {=================} {TTaxKindTest} { constructor TTaxKindTest.Create; begin inherited; spInsertUpdate := 'gpInsertUpdate_Object_DocumentTaxKind'; spSelect := 'gpSelect_Object_DocumentTaxKind'; spGet := 'gpGet_Object_DocumentTaxKind'; end; function TTaxKindTest.InsertDefault: integer; begin result := InsertUpdateDocumentTaxKind(0, -3, 'Тип формирования налогового документа'); inherited; end; function TTaxKindTest.InsertUpdateDocumentTaxKind; begin FParams.Clear; FParams.AddParam('ioId', ftInteger, ptInputOutput, Id); FParams.AddParam('inCode', ftInteger, ptInput, Code); FParams.AddParam('inName', ftString, ptInput, Name); result := InsertUpdate(FParams); end; procedure TdbObjectTest.DocumentTaxKind_Test; var Id: integer; RecordCount: Integer; ObjectTest: TDocumentTaxKindTest; begin ObjectTest := TDocumentTaxKindTest.Create; // Получим список RecordCount := GetRecordCount(ObjectTest); // Вставка Id := ObjectTest.InsertDefault; try // Получение данных with ObjectTest.GetRecord(Id) do Check((FieldByName('Name').AsString = 'Тип формирования налогового документа'), 'Не сходятся данные Id = ' + FieldByName('id').AsString); finally ObjectTest.Delete(Id); end; end; } {==================================} (* procedure TdbObjectTest.Position_Test; var Id: integer; RecordCount: Integer; ObjectTest: TPositionTest; begin ObjectTest := TPositionTest.Create; // Получим список RecordCount := GetRecordCount(ObjectTest); // Вставка группы Id := ObjectTest.InsertDefault; try // Получение данных with ObjectTest.GetRecord(Id) do Check((FieldByName('Name').AsString = 'Должности'), 'Не сходятся данные Id = ' + FieldByName('id').AsString); finally ObjectTest.Delete(Id); end; end; {TAssetGroupTest} constructor TAssetGroupTest.Create; begin inherited; spInsertUpdate := 'gpInsertUpdate_Object_AssetGroup'; spSelect := 'gpSelect_Object_AssetGroup'; spGet := 'gpGet_Object_AssetGroup'; end; function TAssetGroupTest.InsertDefault: integer; var ParentId: Integer; begin ParentId:=0; result := InsertUpdateAssetGroup(0, -1, 'Группа основных средств', ParentId); end; function TAssetGroupTest.InsertUpdateAssetGroup; begin FParams.Clear; FParams.AddParam('ioId', ftInteger, ptInputOutput, Id); FParams.AddParam('inCode', ftInteger, ptInput, Code); FParams.AddParam('inName', ftString, ptInput, Name); FParams.AddParam('inParentId', ftInteger, ptInput, ParentId); result := InsertUpdate(FParams); end; procedure TdbObjectTest.AssetGroup_Test; var Id, Id2, Id3: integer; RecordCount: Integer; ObjectTest: TAssetGroupTest; begin // тут наша задача проверить правильность работы с деревом. // а именно зацикливание. ObjectTest := TAssetGroupTest.Create; // Получим список объектов RecordCount := GetRecordCount(ObjectTest); // Вставка объекта // добавляем группу 1 Id := ObjectTest.InsertDefault; try // теперь делаем ссылку на себя и проверяем ошибку try ObjectTest.InsertUpdateAssetGroup(Id, -1, 'Тест Группа 1', Id); Check(false, 'Нет сообщение об ошибке'); except end; // добавляем еще группу 2 // делаем у группы 2 ссылку на группу 1 Id2 := ObjectTest.InsertUpdateAssetGroup(0, -2, 'Тест Группа 2', Id); try // теперь ставим ссылку у группы 1 на группу 2 и проверяем ошибку try ObjectTest.InsertUpdateAssetGroup(Id, -1, 'Тест Группа 1', Id2); Check(false, 'Нет сообщение об ошибке'); except end; // добавляем еще группу 3 // делаем у группы 3 ссылку на группу 2 Id3 := ObjectTest.InsertUpdateAssetGroup(0, -3, 'Тест Группа 3', Id2); try // группа 2 уже ссылка на группу 1 // делаем у группы 1 ссылку на группу 3 и проверяем ошибку try ObjectTest.InsertUpdateAssetGroup(Id, -1, 'Тест Группа 1', Id3); Check(false, 'Нет сообщение об ошибке'); except end; Check((GetRecordCount(ObjectTest) = RecordCount + 3), 'Количество записей не изменилось'); finally ObjectTest.Delete(Id3); end; finally ObjectTest.Delete(Id2); end; finally ObjectTest.Delete(Id); end; end; {TAssetTest} constructor TAssetTest.Create; begin inherited; spInsertUpdate := 'gpInsertUpdate_Object_Asset'; spSelect := 'gpSelect_Object_Asset'; spGet := 'gpGet_Object_Asset'; end; function TAssetTest.InsertDefault: integer; var AssetGroupId: Integer; JuridicalId: Integer; MakerId: Integer; begin AssetGroupId := TAssetGroupTest.Create.GetDefault; JuridicalId:=0; MakerId:=0; result := InsertUpdateAsset(0, -1, 'Основные средства', date, 'InvNumber', 'FullName', 'SerialNumber' , 'PassportNumber', 'Comment', AssetGroupId,JuridicalId,MakerId); end; function TAssetTest.InsertUpdateAsset; begin FParams.Clear; FParams.AddParam('ioId', ftInteger, ptInputOutput, Id); FParams.AddParam('inCode', ftInteger, ptInput, Code); FParams.AddParam('inName', ftString, ptInput, Name); FParams.AddParam('Release', ftDateTime, ptInput, Release); FParams.AddParam('inInvNumber', ftString, ptInput, InvNumber); FParams.AddParam('inFullName', ftString, ptInput, FullName); FParams.AddParam('inSerialNumber', ftString, ptInput, SerialNumber); FParams.AddParam('inPassportNumber', ftString, ptInput, PassportNumber); FParams.AddParam('inComment', ftString, ptInput, Comment); FParams.AddParam('inAssetGroupId', ftInteger, ptInput, AssetGroupId); FParams.AddParam('inJuridicalId', ftInteger, ptInput, JuridicalId); FParams.AddParam('inMakerId', ftInteger, ptInput, MakerId); result := InsertUpdate(FParams); end; procedure TdbObjectTest.Asset_Test; var Id: integer; RecordCount: Integer; ObjectTest: TAssetTest; begin ObjectTest := TAssetTest.Create; // Получим список RecordCount := GetRecordCount(ObjectTest); // Вставка объекта Id := ObjectTest.InsertDefault; try // Получение данных with ObjectTest.GetRecord(Id) do Check((FieldByName('Name').AsString = 'Основные средства'), 'Не сходятся данные Id = ' + FieldByName('id').AsString); finally ObjectTest.Delete(Id); end; end; {TReceiptCostTest} constructor TReceiptCostTest.Create; begin inherited; spInsertUpdate := 'gpInsertUpdate_Object_ReceiptCost'; spSelect := 'gpSelect_Object_ReceiptCost'; spGet := 'gpGet_Object_ReceiptCost'; end; function TReceiptCostTest.InsertDefault: integer; begin result := InsertUpdateReceiptCost(0, -1, 'Затраты в рецептурах'); end; function TReceiptCostTest.InsertUpdateReceiptCost; begin FParams.Clear; FParams.AddParam('ioId', ftInteger, ptInputOutput, Id); FParams.AddParam('inCode', ftInteger, ptInput, Code); FParams.AddParam('inName', ftString, ptInput, Name); result := InsertUpdate(FParams); end; procedure TdbObjectTest.ReceiptCost_Test; var Id: integer; RecordCount: Integer; ObjectTest: TReceiptCostTest; begin ObjectTest := TReceiptCostTest.Create; // Получим список RecordCount := GetRecordCount(ObjectTest); // Вставка объекта Id := ObjectTest.InsertDefault; try // Получение данных with ObjectTest.GetRecord(Id) do Check((FieldByName('Name').AsString = 'Затраты в рецептурах'), 'Не сходятся данные Id = ' + FieldByName('id').AsString); finally ObjectTest.Delete(Id); end; end; {TReceiptChildTest} constructor TReceiptChildTest.Create; begin inherited; spInsertUpdate := 'gpInsertUpdate_Object_ReceiptChild'; spSelect := 'gpSelect_Object_ReceiptChild'; spGet := 'gpGet_Object_ReceiptChild'; end; function TReceiptChildTest.InsertDefault: integer; var GoodsId, GoodsKindId: Integer; begin GoodsId:= TGoods.Create.GetDefault; GoodsKindId:= TGoodsKind.Create.GetDefault; result := InsertUpdateReceiptChild(0, 123,true, true, date, date, 'Составляющие рецептур - Значение', 2, GoodsId, GoodsKindId); end; function TReceiptChildTest.InsertUpdateReceiptChild; begin FParams.Clear; FParams.AddParam('ioId', ftInteger, ptInputOutput, Id); FParams.AddParam('Value', ftFloat, ptInput, Value); FParams.AddParam('Weight', ftBoolean, ptInput, Weight); FParams.AddParam('TaxExit', ftBoolean, ptInput, TaxExit); FParams.AddParam('StartDate', ftDateTime, ptInput, StartDate); FParams.AddParam('EndDate', ftDateTime, ptInput, EndDate); FParams.AddParam('Comment', ftString, ptInput, Comment); FParams.AddParam('inReceiptId', ftInteger, ptInput, ReceiptId); FParams.AddParam('inGoodsId', ftInteger, ptInput, GoodsId); FParams.AddParam('inGoodsKindId', ftInteger, ptInput, GoodsKindId); result := InsertUpdate(FParams); end; procedure TdbObjectTest.ReceiptChild_Test; var Id: integer; RecordCount: Integer; ObjectTest: TReceiptChildTest; begin ObjectTest := TReceiptChildTest.Create; // Получим список RecordCount := GetRecordCount(ObjectTest); // Вставка Id := ObjectTest.InsertDefault; try // Получение данных о Составляющие рецептур with ObjectTest.GetRecord(Id) do Check((FieldByName('Comment').AsString = 'Составляющие рецептур - Значение'), 'Не сходятся данные Id = ' + FieldByName('id').AsString); finally ObjectTest.Delete(Id); end; end; {TReceiptTest} constructor TReceiptTest.Create; begin inherited; spInsertUpdate := 'gpInsertUpdate_Object_Receipt'; spSelect := 'gpSelect_Object_Receipt'; spGet := 'gpGet_Object_Receipt'; end; function TReceiptTest.InsertDefault: integer; var GoodsId, GoodsKindId, ReceiptCostId: Integer; begin ReceiptCostId := TReceiptCostTest.Create.GetDefault; GoodsId:= TGoods.Create.GetDefault; GoodsKindId:= TGoodsKind.Create.GetDefault; result := InsertUpdateReceipt(0, 'Рецептура 1', '123', 'Рецептуры', 1, 2, 80, 2, 1,1 , date, date, true, GoodsId, GoodsKindId, 1, ReceiptCostId, 1); end; function TReceiptTest.InsertUpdateReceipt; begin FParams.Clear; FParams.AddParam('ioId', ftInteger, ptInputOutput, Id); FParams.AddParam('Name', ftString, ptInput, Name); FParams.AddParam('Code', ftString, ptInput, Code); FParams.AddParam('Comment', ftString, ptInput, Comment); FParams.AddParam('Value', ftFloat, ptInput, Value); FParams.AddParam('ValueCost', ftFloat, ptInput, ValueCost); FParams.AddParam('TaxExit', ftFloat, ptInput, TaxExit); FParams.AddParam('PartionValue', ftFloat, ptInput, PartionValue); FParams.AddParam('PartionCount', ftFloat, ptInput, PartionCount); FParams.AddParam('WeightPackage', ftFloat, ptInput, WeightPackage); FParams.AddParam('StartDate', ftDateTime, ptInput, StartDate); FParams.AddParam('EndDate', ftDateTime, ptInput, EndDate); FParams.AddParam('Main', ftBoolean, ptInput, Main); FParams.AddParam('inGoodsId', ftInteger, ptInput, GoodsId); FParams.AddParam('inGoodsKindId', ftInteger, ptInput, GoodsKindId); FParams.AddParam('inGoodsKindCompleteId', ftInteger, ptInput, GoodsKindCompleteId); FParams.AddParam('inReceiptCostId', ftInteger, ptInput, ReceiptCostId); FParams.AddParam('inReceiptKindId', ftInteger, ptInput, ReceiptKindId); result := InsertUpdate(FParams); end; procedure TdbObjectTest.Receipt_Test; var Id: integer; RecordCount: Integer; ObjectTest: TReceiptTest; begin ObjectTest := TReceiptTest.Create; // Получим список RecordCount := GetRecordCount(ObjectTest); // Вставка Id := ObjectTest.InsertDefault; try // Получение данных о Рецептуре with ObjectTest.GetRecord(Id) do Check((FieldByName('Name').AsString = 'Рецептура 1'), 'Не сходятся данные Id = ' + FieldByName('id').AsString); finally ObjectTest.Delete(Id); end; end; *) initialization // TestFramework.RegisterTest('Объекты', TdbObjectTest.Suite); end.
module hier_read; define hier_read_line_nh; define hier_read_line; define hier_read_line_next; define hier_read_eol; define hier_read_block_start; define hier_read_tk; define hier_read_tk_req; define hier_read_keyw; define hier_read_keyw_req; define hier_read_keyw_pick; define hier_read_int; define hier_read_fp; define hier_read_bool; define hier_read_string; define hier_read_angle; %include 'hier2.ins.pas'; { ******************************************************************************** * * Local subroutine READLRAW (RD, STAT) * * Read the next input line into RD.BUF and init the parse index to the first * non-blank. Trailing spaces are deleted from the line, but the line is * otherwise not interpreted. } procedure readlraw ( {read next line into buffer} in out rd: hier_read_t; {hierarchy reading state} out stat: sys_err_t); {completion status} val_param; internal; label eof, leave; begin sys_error_none (stat); {init to no error encountered} if rd.llev < 0 then goto eof; {previously hit end of file ?} file_read_text (rd.conn, rd.buf, stat); {read next line from file} if file_eof(stat) then begin {hit end of file ?} file_close (rd.conn); {close the file} rd.llev := -1; {indicate hit end of file, file closed} goto eof; end; if sys_error(stat) then return; {hard error ?} string_unpad (rd.buf); {delete all trailing spaces from input line} rd.p := 1; {init new input line parse index} while rd.p <= rd.buf.len do begin {skip over leading blanks} if rd.buf.str[rd.p] <> ' ' then exit; {found first non-blank ?} rd.p := rd.p + 1; {this is a blank, advance to next char} end; {back to check this new char} goto leave; eof: {end of file encountered} rd.buf.len := 0; {as if empty line} rd.p := 1; leave: rd.lret := false; {init to this line not returned} end; { ******************************************************************************** * * Local subroutine READLINE (RD, STAT) * * Read the next content line into the input buffer. RD.LLEV is set to the * nesting level of the new line. * * Blank lines and comment lines are not considered content. A comment line is * any line where the first non-blank is "*". } procedure readline ( {read next content line into buffer} in out rd: hier_read_t; {hierarchy reading state} out stat: sys_err_t); {completion status} val_param; internal; begin while true do begin {loop until content line or EOF} readlraw (rd, stat); {read raw line into BUF, init P} if sys_error(stat) then return; {hard error ?} if rd.llev < 0 then return; {hit end of file ?} if rd.buf.len <= 0 then next; {ignore blank lines} if rd.buf.str[rd.p] = '*' then next; {ignore comment lines} exit; {this is a real content line} end; {back to read next line from file} rd.llev := (rd.p - 1) div 2; {make nesting level of this line from indentation} if ((rd.llev * 2) + 1) <> rd.p then begin {invalid indentation ?} sys_stat_set (hier_subsys_k, hier_stat_badindent_k, stat); {set error status} hier_err_line_file (rd, stat); {add line number, file name} end; end; { ******************************************************************************** * * Function HIER_READ_LINE_NH (RD, STAT) * * Read the next line from the input file. The function returns TRUE when an * input line was read, and FALSE if the end of the input file was encountered. * No interpretation of the line is performed except that trailing blanks are * ignored. The parse index is initialized to the first non-blank character, * or 1 when the line is empty. * * No attempt is made to interpret or check for hierarchy levels. This routine * allows the use of the parsing facilities in the HIER library with ordinary * input files that don't conform to the HIER library hierarchy syntax. } function hier_read_line_nh ( {read next line, no hierarchy interpretation} in out rd: hier_read_t; {hierarchy reading state} out stat: sys_err_t) {completion status} :boolean; {a line was read, not EOF or error} val_param; begin hier_read_line_nh := false; {init to not returning with a new line} readlraw (rd, stat); {get the next raw input line} if sys_error(stat) then return; {hard error ?} hier_read_line_nh := rd.llev >= 0; {TRUE when didn't hit end of file} end; { ******************************************************************************** * * Function HIER_READ_LINE (RD, STAT) * * Read the next line from the input file. The function returns TRUE if the * new content is at the same level as the previous line. The function returns * FALSE once for each level being popped up. The function returns FALSE * indefinitely after the end of the input file has been encountered. A line * at a lower nesting level is an error. * * On error, STAT is set to indicate the error, and the function returns FALSE. * * Blank and comment lines are ignored. A comment line is any line where the * first non-blank is "*". } function hier_read_line ( {read next line from input file} in out rd: hier_read_t; {hierarchy reading state} out stat: sys_err_t) {completion status} :boolean; {at same nesting level, no error} val_param; begin sys_error_none (stat); {init to no error encountered} hier_read_line := false; {init to error or different level} if rd.lret then begin {need a new line ?} readline (rd, stat); {read the new line} if sys_error(stat) then return; end; if rd.llev = rd.level then begin {new line is at existing nesting level ?} rd.lret := true; {remember that this line was returned} hier_read_line := true; {indicate returning with line at curr level} return; {return with the new line} end; if rd.llev < rd.level then begin {new line is at a higher level ?} if rd.level > 0 then rd.level := rd.level - 1; {pop up one level} return; end; sys_stat_set ( {unexpected subordinate level error} hier_subsys_k, hier_stat_lower_k, stat); hier_err_line_file (rd, stat); {add line number, file name} end; { ******************************************************************************** * * Function HIER_READ_LINE_NEXT (RD, STAT) * * Read the next line from the input at the current or higher level. Lines at * lower levels are ignored. } function hier_read_line_next ( {read next line at current or higher level} in out rd: hier_read_t; {hierarchy reading state} out stat: sys_err_t) {completion status} :boolean; {at same nesting level, no error} val_param; begin sys_error_none (stat); {init to no error encountered} hier_read_line_next := false; {init to error or different level} while true do begin {loop until line at or above curr level} if rd.lret then begin {need a new line ?} readline (rd, stat); {read the new line} if sys_error(stat) then return; end; if rd.llev <= rd.level then exit; {at or above the current level ?} rd.lret := true; {mark this line as used} end; {back to get next line} if rd.llev = rd.level then begin {new line is at existing nesting level ?} rd.lret := true; {remember that this line was returned} hier_read_line_next := true; {this line is at the current level} return; {return with the new line} end; if rd.level > 0 then rd.level := rd.level - 1; {pop up one level} end; { ******************************************************************************** * * Function HIER_READ_EOL (RD, STAT) * * Checks for end of line enountered as expected. * * If the input line has been exhausted, then the function returns TRUE with * STAT set to no error. * * If a token is found, then the function returns FALSE, STAT is set to an * appropriate error assuming the extra token is not allowed, and the parse * index is restored to before the first extra token. } function hier_read_eol ( {check for at end of current input line} in out rd: hier_read_t; {hierarchy reading state} out stat: sys_err_t) {extra token error if not end of line} :boolean; {at end of line, no error} val_param; var tk: string_var32_t; {token} p: string_index_t; {original parse index} begin tk.max := size_char(tk.str); {init local var string} p := rd.p; {save original parse index} if not hier_read_tk (rd, tk) then begin {no token here, at end of line ?} sys_error_none (stat); {indicate no error} hier_read_eol := true; {indicate was at end of line} return; end; sys_stat_set (hier_subsys_k, hier_stat_extratk_k, stat); {extra token} sys_stat_parm_vstr (tk, stat); {the extra token} hier_err_line_file (rd, stat); {add line number and file name} rd.p := p; {restore parse index to before extra token} hier_read_eol := false; {indicate not at end of line} end; { ******************************************************************************** * * Subroutine HIER_READ_BLOCK_START (RD) * * Go one level down into a subordinate block. Subsequent lines will be read * expecting this hierarchy level. Encountering content at a lower level is an * error, and content at a higher level causes HIER_READ_LINE to return FALSE * for each higher nesting level. } procedure hier_read_block_start ( {start reading one subordinate level down} in out rd: hier_read_t); {hierarchy reading state} val_param; begin rd.level := rd.level + 1; end; { ******************************************************************************** * * Function HIER_READ_TK (RD, TK) * * Read the next token on the current input line. When a token is found, the * function returns TRUE with the token in TK. Otherwise the function returns * FALSE with TK set to the empty string. } function hier_read_tk ( {read next token from input line} in out rd: hier_read_t; {hierarchy reading state} in out tk: univ string_var_arg_t) {the returned token, empty str on EOL} :boolean; {token found} val_param; var stat: sys_err_t; begin hier_read_tk := true; {init to indicate returning with token} string_token (rd.buf, rd.p, tk, stat); {try to read the next token} if sys_error(stat) then begin {didn't get a token ?} tk.len := 0; {return the empty string} hier_read_tk := false; {indicate not returning with a token} end; end; { ******************************************************************************** * * Function HIER_READ_TK_REQ (RD, TK, STAT) * * Read the next token from the input line into TK. If a token is found, the * function returns TRUE and STAT is set to no error. If no token is found, * then the function returns FALSE with STAT set to missing parameter error. } function hier_read_tk_req ( {read required token from input line} in out rd: hier_read_t; {input file reading state} in out tk: univ string_var_arg_t; {the returned token, empty str on EOL} out stat: sys_err_t) {completion status} :boolean; {token found, no error} val_param; begin if hier_read_tk (rd, tk) {try to read the token} then begin {got it} sys_error_none (stat); {no error} hier_read_tk_req := true; end else begin {no parameter} hier_err_missing (rd, stat); {set missing parameter error} hier_read_tk_req := false; end ; end; { ******************************************************************************** * * Function HIER_READ_KEYW (RD, KEYW) * * Read the next token on the current input line and return it all upper case * in KEYW. The function returns TRUE when a token is found. Otherwise, the * function returns FALSE. } function hier_read_keyw ( {read next token as keyword} in out rd: hier_read_t; {hierarchy reading state} in out keyw: univ string_var_arg_t) {upper case token, empty str on EOL} :boolean; {token found} val_param; begin hier_read_keyw := hier_read_tk (rd, keyw); {get the raw token} string_upcase (keyw); {return the token in upper case} end; { ******************************************************************************** * * Function HIER_READ_KEYW_REQ (RD, KEYW, STAT) * * Get the next token as a keyword into KEYW. If a token is found, the * function returns TRUE and STAT is set to no error. If no token is found, * then the function returns FALSE with STAT set to missing parameter error. } function hier_read_keyw_req ( {read required keyword from input line} in out rd: hier_read_t; {input file reading state} in out keyw: univ string_var_arg_t; {the returned keyword, empty str on EOL} out stat: sys_err_t) {completion status} :boolean; {keyword found, no error} val_param; begin if hier_read_keyw (rd, keyw) {try to read the keyword} then begin {got it} sys_error_none (stat); {no error} hier_read_keyw_req := true; end else begin {no parameter} hier_err_missing (rd, stat); {set missing parameter error} hier_read_keyw_req := false; end ; end; { ******************************************************************************** * * Function HIER_READ_KEYW_PICK (RD, LIST, STAT) * * Get the next token as a keyword and find which keyword in a supplied list it * is. LIST is the list of possible keywords, upper case and separated by * blanks. * * When the keyword read from the file matches a keyword in the list, then the * function returns the 1-N number of the matching list entry, and STAT is set * to no error. * * The function can also return the following special values: * * 0 Keyword did not match any list entry. STAT set to bad keyword error. * * -1 No keyword was found. STAT is set to missing parameter error. } function hier_read_keyw_pick ( {read keyword, pick from list} in out rd: hier_read_t; {hierarchy reading state} in list: string; {keywords, upper case, blank separated} out stat: sys_err_t) {completion status, no error on match} :sys_int_machine_t; {1-N list entry, 0 bad keyword, -1 no keyword} val_param; var keyw: string_var32_t; {the keyword read from the file} pick: sys_int_machine_t; {number of matching list entry} begin keyw.max := size_char(keyw.str); {init local var string} if not hier_read_keyw_req (rd, keyw, stat) then begin {no keyword ?} hier_read_keyw_pick := -1; return; end; string_tkpick80 (keyw, list, pick); {pick the keyword from the list} if pick = 0 then begin {no match ?} sys_stat_set (hier_subsys_k, hier_stat_badkeyw_k, stat); {bad keyword} sys_stat_parm_vstr (keyw, stat); {the keyword} hier_err_line_file (rd, stat); {add line number and file name} hier_read_keyw_pick := 0; {indicate bad keyword} return; end; hier_read_keyw_pick := pick; {return 1-N number of matching list entry} end; { ******************************************************************************** * * Subroutine HIER_READ_INT (RD, II, STAT) * * Read the next token from the current input line and interpret it as an * integer. The result is returned in II. STAT is set appropriately if no * token is available, or the token can not be interpreted as a integer. } procedure hier_read_int ( {read next token as integer} in out rd: hier_read_t; {hierarchy reading state} out ii: sys_int_machine_t; {returned value} out stat: sys_err_t); {completion status} val_param; var tk: string_var32_t; {scratch token} begin tk.max := size_char(tk.str); {init local var string} if not hier_read_tk (rd, tk) then begin {no token ?} sys_stat_set (hier_subsys_k, hier_stat_noparm_k, stat); hier_err_line_file (rd, stat); ii := 0; return; end; string_t_int (tk, ii, stat); {interpret as integer} if sys_error(stat) then begin {failed to find integer value ?} sys_stat_set (hier_subsys_k, hier_stat_badint_k, stat); sys_stat_parm_vstr (tk, stat); hier_err_line_file (rd, stat); end; end; { ******************************************************************************** * * Subroutine HIER_READ_FP (RD, FP, STAT) * * Read the next token from the current input line and interpret it as a * floating point value. The result is returned in FP. STAT is set * appropriately if no token is available, or the token can not be interpreted * as floating point. } procedure hier_read_fp ( {read next token as floating point} in out rd: hier_read_t; {hierarchy reading state} out fp: real; {returned value} out stat: sys_err_t); {completion status} val_param; var tk: string_var32_t; {scratch token} begin tk.max := size_char(tk.str); {init local var string} if not hier_read_tk (rd, tk) then begin {no token ?} sys_stat_set (hier_subsys_k, hier_stat_noparm_k, stat); hier_err_line_file (rd, stat); fp := 0.0; return; end; string_t_fpm (tk, fp, stat); {interpret as floating point} if sys_error(stat) then begin {failed to find floating point value ?} sys_stat_set (hier_subsys_k, hier_stat_badfp_k, stat); sys_stat_parm_vstr (tk, stat); hier_err_line_file (rd, stat); end; end; { ******************************************************************************** * * Subroutine HIER_READ_BOOL (RD, TF, STAT) * * Read the next token from the current input line and interpret it as a * boolean p value. The result is returned in TF. The token is * case-insensitive, and can be either TRUE, YES or ON for true, or FALSE, NO * or OFF for false. * * STAT is set appropriately if no token is available, or the token can not be * interpreted as boolean. } procedure hier_read_bool ( {read next token as floating point} in out rd: hier_read_t; {hierarchy reading state} out tf: boolean; {returne value} out stat: sys_err_t); {completion status} val_param; var tk: string_var32_t; {scratch token} begin tk.max := size_char(tk.str); {init local var string} if not hier_read_keyw (rd, tk) then begin {no token ?} sys_stat_set (hier_subsys_k, hier_stat_noparm_k, stat); hier_err_line_file (rd, stat); tf := false; return; end; string_t_bool ( {interpret boolean value of the token} tk, {input string} [ string_tftype_tf_k, {allow TRUE, FALSE} string_tftype_yesno_k, {allow YES, NO} string_tftype_onoff_k], {allow ON, OFF} tf, {returned boolean value} stat); if sys_error(stat) then begin {failed to find boolean value ?} sys_stat_set (hier_subsys_k, hier_stat_badbool_k, stat); sys_stat_parm_vstr (tk, stat); hier_err_line_file (rd, stat); end; end; { ******************************************************************************** * * Subroutine HIER_READ_STRING (RD, STR) * * Read the remainder of the current line as a string. The current line is * always exhausted by this routine. } procedure hier_read_string ( {read remainder of curr line as string} in out rd: hier_read_t; {hierarchy reading state} in out str: univ string_var_arg_t); {returned string} val_param; var n: sys_int_machine_t; {number of characters to return} ii: sys_int_machine_t; {scratch integer and loop counter} begin n := rd.buf.len - rd.p + 1; {number of available characters} n := min(n, str.max); {clip to available room to return chars} str.len := n; {set the returned string length} for ii := 1 to n do begin {once for each character to return} str.str[ii] := rd.buf.str[rd.p]; {get this character} rd.p := rd.p + 1; {update the reading index} end; {back for next character} rd.p := rd.buf.len + 1; {the current line has been used up} end; { ******************************************************************************** * * Subroutine HIER_READ_ANGLE (RD, ANG, STAT) * * Read the next token from the current input line and interpret it as angle. * The result is returned in ANG in radians. STAT is set appropriately if no * token is available, or the token can not be interpreted as an angle. * * The angle syntax is defined by routine STRING_T_ANGLE. See its * documentation for details. However, briefly, the format is: * * <degrees>[:<minutes>[:<seconds>]] } procedure hier_read_angle ( {read next token as an angle} in out rd: hier_read_t; {hierarchy reading state} out ang: real; {returned angle, radians} out stat: sys_err_t); {completion status} val_param; var tk: string_var32_t; {scratch token} begin tk.max := size_char(tk.str); {init local var string} if not hier_read_tk (rd, tk) then begin {no token ?} sys_stat_set (hier_subsys_k, hier_stat_noparm_k, stat); hier_err_line_file (rd, stat); ang := 0.0; return; end; string_t_angle (tk, ang, stat); {interpret the token as an angle} if sys_error(stat) then begin {error ?} sys_stat_set (hier_subsys_k, hier_stat_badang_k, stat); sys_stat_parm_vstr (tk, stat); hier_err_line_file (rd, stat); end; end;
unit URenewThread; interface uses Classes, UzLogGlobal, UzLogQSO; type TRenewThread = class(TThread) private { Private declarations } protected procedure SyncProc; procedure Execute; override; end; procedure RequestRenewThread; var Renewing : boolean = False; implementation uses Main; { Important: Methods and properties of objects in VCL can only be used in a method called using Synchronize, for example, Synchronize(UpdateCaption); and UpdateCaption could look like, procedure TRenewThread.UpdateCaption; begin Form1.Caption := 'Updated in a thread'; end; } { TRenewThread } procedure TRenewThread.SyncProc; var boo: boolean; begin boo := MainForm.Grid.Focused; Main.MyContest.RenewScoreAndMulti(); Main.MyContest.MultiForm.UpdateData; Main.MyContest.ScoreForm.UpdateData; // 画面リフレッシュ MainForm.GridRefreshScreen(True); // バンドスコープリフレッシュ MainForm.BSRefresh(); MainForm.ReevaluateCountDownTimer; MainForm.ReevaluateQSYCount; if boo then MainForm.Grid.SetFocus; end; procedure TRenewThread.Execute; begin { Place thread code here } FreeOnTerminate := True; Repeat until Renewing = False; Renewing := True; Synchronize(SyncProc); Renewing := False; end; procedure RequestRenewThread; var RTh: TRenewThread; begin RTh := TRenewThread.Create(False); end; end.
unit fmAcercaDe; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, fmBase, fmSplash, JvComponentBase, JvComputerInfoEx, StdCtrls, Buttons, JvGIF, JvExControls, JvAnimatedImage, JvGIFCtrl, jpeg, ExtCtrls; type TfAcercaDe = class(TFBase) bEnviar: TBitBtn; Info: TJvComputerInfoEx; lURL: TLabel; lMail: TLabel; Image2: TImage; Image3: TImage; lCerrar: TImage; lID: TLabel; lSO: TLabel; lCPU: TLabel; lMemoria: TLabel; lPantalla: TLabel; Label8: TLabel; Image1: TImage; Bevel1: TBevel; lVersion: TLabel; procedure FormCreate(Sender: TObject); procedure lURLClick(Sender: TObject); procedure lMailClick(Sender: TObject); procedure bEnviarClick(Sender: TObject); procedure lCerrarClick(Sender: TObject); private { Private declarations } public { Public declarations } end; implementation uses dmConfiguracion, UserServerCalls, fmExceptionEnviando, dmInternalServer, Web; {$R *.dfm} resourcestring GRACIAS = 'Gracias por su colaboración'; ERROR_ENVIO = 'No se ha podido enviar la información.' + #13 + #13 + '%s'; PANTALLA = 'Pantalla'; MEMORIA = 'Memoria'; CPU = 'CPU'; SO = 'SO'; procedure TfAcercaDe.bEnviarClick(Sender: TObject); var bugServerCall: TBugServerCall; bugServer: TInternalServer; fExcepcionEnviando: TfExcepcionEnviando; report: string; begin fExcepcionEnviando := TfExcepcionEnviando.Create(Self); try fExcepcionEnviando.Show; fExcepcionEnviando.Repaint; try bugServer := TInternalServer.Create(nil); try bugServerCall := TBugServerCall.Create(bugServer); try report := lVersion.Caption + sLineBreak + lID.Caption + sLineBreak + lSO.Caption + sLineBreak + lCPU.Caption + sLineBreak + lMemoria.Caption + sLineBreak + lPantalla.Caption; bugServerCall.Call('Info', report); finally bugServerCall.Free; end; finally bugServer.Free; end; ShowMessage(GRACIAS); Close; except on E:Exception do ShowMessage(Format(ERROR_ENVIO, [E.Message])); end; finally fExcepcionEnviando.Free; end; end; procedure TfAcercaDe.FormCreate(Sender: TObject); var id: string; begin inherited; lVersion.Caption := '4.4'; //Configuracion.Sistema.Version; lPantalla.Caption := PANTALLA + ': ' + IntToStr(Info.Screen.Width) + 'x' + IntToStr(Info.Screen.Height); lMemoria.Caption := MEMORIA + ': ' + Format('%2.2n',[Info.Memory.TotalPhysicalMemory/1024/1024/1024]) + 'GB. Free:' + Format('%2.2n',[Info.Memory.FreePhysicalMemory/1024/1024/1024]) + 'GB.'; lCPU.Caption := CPU + ': ' + Info.CPU.Name; lSO.Caption := SO + ': ' + Info.OS.ProductName + ' ' + Info.OS.VersionCSDString; id := Configuracion.Sistema.GUID; lID.Caption := 'ID: ' + Copy(id, 5, 4) + id + Copy(id, 15, 4); end; procedure TfAcercaDe.lCerrarClick(Sender: TObject); begin Close; end; procedure TfAcercaDe.lMailClick(Sender: TObject); begin AbrirURL('mailto:soporte@symbolchart.com'); end; procedure TfAcercaDe.lURLClick(Sender: TObject); begin AbrirURL('http://www.symbolchart.com'); end; end.
{*! * Fano Web Framework (https://fanoframework.github.io) * * @link https://github.com/fanoframework/fano * @copyright Copyright (c) 2018 Zamrony P. Juhara * @license https://github.com/fanoframework/fano/blob/master/LICENSE (MIT) *} unit IniSessionImpl; interface {$MODE OBJFPC} {$H+} uses Classes, IniFiles, SessionIntf; type (*!------------------------------------------------ * class having capability to manage * session variables in INI file * * @author Zamrony P. Juhara <zamronypj@yahoo.com> *-----------------------------------------------*) TIniSession = class(TInterfacedObject, ISession) private fSessionName : shortstring; fSessionId : shortstring; fSessionData : TIniFile; fSessionStream : TStringStream; procedure raiseExceptionIfAlreadyTerminated(); procedure raiseExceptionIfExpired(); (*!------------------------------------ * set session variable *------------------------------------- * @param sessionVar name of session variable * @param sessionVal value of session variable * @return current instance *-------------------------------------*) function internalSetVar(const sessionVar : shortstring; const sessionVal : string) : ISession; (*!------------------------------------ * get session variable *------------------------------------- * @return session value *-------------------------------------*) function internalGetVar(const sessionVar : shortstring) : string; (*!------------------------------------ * delete session variable *------------------------------------- * @param sessionVar name of session variable * @return current instance *-------------------------------------*) function internalDelete(const sessionVar : shortstring) : ISession; (*!------------------------------------ * clear all session variables *------------------------------------- * This is only remove session data, but * underlying storage is kept *------------------------------------- * @return current instance *-------------------------------------*) function internalClear() : ISession; procedure cleanUp(); public (*!------------------------------------ * constructor *------------------------------------- * @param sessName session name * @param sessId session id * @param sessData session data *-------------------------------------*) constructor create( const sessName : shortstring; const sessId : shortstring; const sessData : string ); destructor destroy(); override; (*!------------------------------------ * get session name *------------------------------------- * @return session name *-------------------------------------*) function name() : shortstring; (*!------------------------------------ * get current session id *------------------------------------- * @return session id string *-------------------------------------*) function id() : shortstring; (*!------------------------------------ * get current session id *------------------------------------- * @return session id string *-------------------------------------*) function has(const sessionVar : shortstring) : boolean; (*!------------------------------------ * set session variable *------------------------------------- * @param sessionVar name of session variable * @param sessionVal value of session variable * @return current instance *-------------------------------------*) function setVar(const sessionVar : shortstring; const sessionVal : string) : ISession; (*!------------------------------------ * get session variable *------------------------------------- * @return session value *-------------------------------------*) function getVar(const sessionVar : shortstring) : string; (*!------------------------------------ * delete session variable *------------------------------------- * @param sessionVar name of session variable * @return current instance *-------------------------------------*) function delete(const sessionVar : shortstring) : ISession; (*!------------------------------------ * clear all session variables *------------------------------------- * This is only remove session data, but * underlying storage is kept *------------------------------------- * @return current instance *-------------------------------------*) function clear() : ISession; (*!------------------------------------ * test if current session is expired *------------------------------------- * @return true if session is expired *-------------------------------------*) function expired() : boolean; (*!------------------------------------ * get session expiration date *------------------------------------- * @return date time when session is expired *-------------------------------------*) function expiresAt() : TDateTime; (*!------------------------------------ * serialize session data to string *------------------------------------- * @return string of session data *-------------------------------------*) function serialize() : string; end; implementation uses SysUtils, DateUtils, SessionConsts, ESessionExpiredImpl; (*!------------------------------------ * constructor *------------------------------------- * @param sessName session name * @param sessId session id * @param sessData session data *-------------------------------------*) constructor TIniSession.create( const sessName : shortstring; const sessId : shortstring; const sessData : string ); begin inherited create(); fSessionName := sessName; fSessionId := sessId; fSessionStream := TStringStream.create(sessData); fSessionData := TIniFile.create(fSessionStream); raiseExceptionIfExpired(); end; destructor TIniSession.destroy(); begin cleanUp(); inherited destroy(); end; procedure TIniSession.cleanUp(); begin fSessionStream.free(); fSessionData.free(); end; function TIniSession.name() : shortstring; begin result := fSessionName; end; (*!------------------------------------ * get current session id *------------------------------------- * @return session id string *-------------------------------------*) function TIniSession.id() : shortstring; begin result := fSessionId; end; (*!------------------------------------ * get current session id *------------------------------------- * @return session id string *-------------------------------------*) function TIniSession.has(const sessionVar : shortstring) : boolean; begin result := (fSessionData.readString('sessionVars', sessionVar, '') <> ''); end; (*!------------------------------------ * set session variable *------------------------------------- * @param sessionVar name of session variable * @param sessionVal value of session variable * @return current instance *-------------------------------------*) function TIniSession.internalSetVar(const sessionVar : shortstring; const sessionVal : string) : ISession; begin fSessionData.writeString('sessionVars', sessionVar, sessionVal); result := self; end; procedure TIniSession.raiseExceptionIfAlreadyTerminated(); begin //TODO: raise ESessionTerminated.create() end; (*!------------------------------------ * set session variable *------------------------------------- * @param sessionVar name of session variable * @param sessionVal value of session variable * @return current instance *-------------------------------------*) function TIniSession.setVar(const sessionVar : shortstring; const sessionVal : string) : ISession; begin raiseExceptionIfExpired(); result := internalSetVar(sessionVar, sessionVal); end; (*!------------------------------------ * get session variable *------------------------------------- * @return session value * @throws EJSON exception when not found *-------------------------------------*) function TIniSession.internalGetVar(const sessionVar : shortstring) : string; begin result := fSessionData.readString('sessionVars', sessionVar, ''); end; (*!------------------------------------ * get session variable *------------------------------------- * @return session value * @throws EJSON exception when not found *-------------------------------------*) function TIniSession.getVar(const sessionVar : shortstring) : string; begin raiseExceptionIfAlreadyTerminated(); raiseExceptionIfExpired(); result := internalGetVar(sessionVar); end; (*!------------------------------------ * delete session variable *------------------------------------- * @param sessionVar name of session variable * @return current instance *-------------------------------------*) function TIniSession.internalDelete(const sessionVar : shortstring) : ISession; begin fSessionData.deleteKey('sessionVars', sessionVar); result := self; end; (*!------------------------------------ * delete session variable *------------------------------------- * @param sessionVar name of session variable * @return current instance *-------------------------------------*) function TIniSession.delete(const sessionVar : shortstring) : ISession; begin raiseExceptionIfExpired(); result := internalDelete(sessionVar); end; (*!------------------------------------ * clear all session variables *------------------------------------- * This is only remove session data, but * underlying storage is kept *------------------------------------- * @return current instance *-------------------------------------*) function TIniSession.internalClear() : ISession; begin fSessionData.eraseSection('sessionVars'); result := self; end; (*!------------------------------------ * clear all session variables *------------------------------------- * This is only remove session data, but * underlying storage is kept *------------------------------------- * @return current instance *-------------------------------------*) function TIniSession.clear() : ISession; begin raiseExceptionIfExpired(); result := internalClear(); end; (*!------------------------------------ * test if current session is expired *------------------------------------- * @return true if session is expired *-------------------------------------*) function TIniSession.expired() : boolean; var expiredDateTime : TDateTime; begin expiredDateTime := strToDateTime(fSessionData.readString('expiry', 'expire', '01-01-1970 00:00:00')); //value > 0, means now() is later than expiredDateTime i.e, //expireddateTime is in past result := (compareDateTime(now(), expiredDateTime) > 0); end; (*!------------------------------------ * get expiration date *------------------------------------- * @return current session instance *-------------------------------------*) function TIniSession.expiresAt() : TDateTime; begin result := strToDateTime(fSessionData.readString('expiry', 'expire', '01-01-1970 00:00:00')); end; procedure TIniSession.raiseExceptionIfExpired(); begin if (expired()) then begin raise ESessionExpired.createFmt(rsSessionExpired, [fSessionId]); end; end; (*!------------------------------------ * serialize session data to string *------------------------------------- * @return string of session data *-------------------------------------*) function TIniSession.serialize() : string; begin fSessionData.updateFile(); result := fSessionStream.dataString; end; end.
namespace Beta.Helpers; interface uses System.Windows, Microsoft.Phone.Controls; type WebBrowserHelper = public static class public class var HtmlProperty: DependencyProperty := DependencyProperty.RegisterAttached('Html', typeOf(System.String), typeOf(WebBrowserHelper), new PropertyMetadata(@OnHtmlChanged)); readonly; class method GetHtml(aDependencyObject: DependencyObject): System.String; class method SetHtml(aDependencyObject: DependencyObject; value: System.String); private class method OnHtmlChanged(d: DependencyObject; e: DependencyPropertyChangedEventArgs); end; implementation class method WebBrowserHelper.GetHtml(aDependencyObject: DependencyObject): System.String; begin exit System.String(aDependencyObject.GetValue(HtmlProperty)) end; class method WebBrowserHelper.SetHtml(aDependencyObject: DependencyObject; value: System.String); begin aDependencyObject.SetValue(HtmlProperty, value) end; class method WebBrowserHelper.OnHtmlChanged(d: DependencyObject; e: DependencyPropertyChangedEventArgs); begin var browser := WebBrowser(d); if browser = nil then exit; var html := e.NewValue.ToString(); // Making webbrowser invisible, until content is loaded, // to avoid blinking of white background browser.Opacity := 0; browser.NavigateToString(html); end; end.
{******************************************************************************} { } { Icon Fonts ImageList fmx: An extended ImageList for Delphi/FireMonkey } { to simplify use of Icons (resize, colors and more...) } { } { Copyright (c) 2019-2023 (Ethea S.r.l.) } { Author: Carlo Barazzetta } { Contributors: } { Nicola Tambascia } { Luca Minuti } { } { https://github.com/EtheaDev/IconFontsImageList } { } {******************************************************************************} { } { 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 FMX.IconFontsImageList; interface {$INCLUDE IconFontsImageList.inc} uses System.Classes , System.UITypes , System.Rtti , System.Messaging , System.ImageList , System.Types , FMX.Controls , FMX.ImgList , FMX.MultiResBitmap , FMX.Types , FMX.Graphics , FMX.Objects ; resourcestring ERR_ICONFONTSFMX_VALUE_NOT_ACCEPTED = 'Value %s not accepted!'; ERR_ICONFONTSFMX_FONT_NOT_INSTALLED = 'Font "%s" is not installed!'; const IconFontsImageListVersion = '3.3.1'; DEFAULT_SIZE = 32; ZOOM_DEFAULT = 100; type //TIconFontMissing = procedure (const AFontName: TFontName) of object; TIconFontMultiResBitmap = class; TIconFontsImageList = class; TIconFontsSourceItem = class; TIconFontBitmapItem = class(TCustomBitmapItem) private FWidth, FHeight, FZoom: Integer; FOwnerMultiResBitmap: TIconFontMultiResBitmap; procedure SetBitmap(const AValue: TBitmapOfItem); function GetBitmap: TBitmapOfItem; procedure SetSize(const AValue: Integer); procedure DrawFontIcon; function GetCharacter: String; function GetFontName: TFontName; function GetFontColor: TAlphaColor; function GetOpacity: single; function GetSize: Integer; procedure SetIconSize(const AWidth, AHeight, AZoom: Integer); function GetHeight: Integer; function GetWidth: Integer; procedure SetHeight(const AValue: Integer); procedure SetWidth(const AValue: Integer); function StoreWidth: Boolean; function StoreHeight: Boolean; function StoreSize: Boolean; procedure SetZoom(const AValue: Integer); protected function BitmapStored: Boolean; override; function GetDisplayName: string; override; public constructor Create(Collection: TCollection); override; property Character: String read GetCharacter; published property Bitmap: TBitmapOfItem read GetBitmap write SetBitmap stored False; property Scale; property Size: Integer read GetSize write SetSize stored StoreSize default DEFAULT_SIZE; property Width: Integer read GetWidth write SetWidth stored StoreWidth default DEFAULT_SIZE; property Height: Integer read GetHeight write SetHeight stored StoreHeight default DEFAULT_SIZE; property Zoom: Integer read FZoom write SetZoom default ZOOM_DEFAULT; //Readonly properties from Source Item property FontName: TFontName read GetFontName; property FontColor: TAlphaColor read GetFontColor stored false; property Opacity: single read GetOpacity stored false; end; TIconFontBitmapItemClass = class of TIconFontBitmapItem; TIconFontMultiResBitmap = class(TMultiResBitmap) private FOwnerSourceItem: TIconFontsSourceItem; procedure UpdateImageSize(const AWidth, AHeight, AZoom: Integer); protected constructor Create(AOwner: TPersistent; ItemClass: TIconFontBitmapItemClass); overload; public end; {TIconFontsSourceItem} TIconFontsSourceItem = class(TCustomSourceItem) private FOwnerImageList: TIconFontsImageList; FFontIconDec: Integer; FOpacity: single; FFontName: TFontName; FFontColor: TAlphaColor; procedure UpdateAllItems; function GetCharacter: String; function GetFontName: TFontName; function GetFontColor: TAlphaColor; function GetFontIconDec: Integer; function GetFontIconHex: string; procedure SetFontColor(const AValue: TAlphaColor); procedure SetFontIconDec(const AValue: Integer); procedure SetFontIconHex(const AValue: string); procedure SetFontName(const AValue: TFontName); procedure SetOpacity(const AValue: single); procedure AutoSizeBitmap(const AWidth, AHeight, AZoom: Integer); function GetIconName: string; procedure SetIconName(const Value: string); function GetOpacity: single; function GetDestinationItem: TCustomDestinationItem; procedure UpdateIconAttributes(const AFontColor: TAlphaColor; const AReplaceFontColor: Boolean = False; const AFontName: TFontName = ''); protected function GetDisplayName: string; override; function CreateMultiResBitmap: TMultiResBitmap; override; function StoreFontName: Boolean; virtual; function StoreFontColor: Boolean; virtual; function StoreOpacity: Boolean; virtual; public constructor Create(Collection: TCollection); override; procedure Assign(Source: TPersistent); override; property Character: String read GetCharacter; published property MultiResBitmap; property IconName: string read GetIconName write SetIconName; property FontName: TFontName read GetFontName write SetFontName stored StoreFontName; property FontIconDec: Integer read GetFontIconDec write SetFontIconDec stored true default 0; property FontIconHex: string read GetFontIconHex write SetFontIconHex stored false; property FontColor: TAlphaColor read GetFontColor write SetFontColor stored StoreFontColor; property Opacity: single read GetOpacity write SetOpacity stored StoreOpacity; end; {TIconFontsImageList} {$IF CompilerVersion > 34} [ComponentPlatforms(pidWin32 or pidWin64 or pidOSX32 or pidiOSSimulator32 or pidiOSDevice32 or pidAndroidArm32)] {$ELSE} [ComponentPlatforms(pidWin32 or pidWin64 or pidOSX32 or pidiOSSimulator32 or pidiOSDevice32 or pidAndroid32Arm)] {$ENDIF} TIconFontsImageList = class(TCustomImageList) private FWidth, FHeight: Integer; FAutoSizeBitmaps: Boolean; FFontName: TFontName; FFontColor: TAlphaColor; FOpacity: single; FZoom: Integer; //FOnFontMissing: TIconFontMissing; procedure SetAutoSizeBitmaps(const Value: Boolean); procedure SetFontName(const Value: TFontName); procedure UpdateSourceItems; procedure UpdateDestination(ASize: TSize; const Index: Integer); procedure SetFontColor(const Value: TAlphaColor); procedure SetOpacity(const Value: single); procedure SetIconSize(const AWidth, AHeight: Integer); function GetSize: Integer; procedure SetSize(const AValue: Integer); function GetHeight: Integer; function GetWidth: Integer; procedure SetHeight(const AValue: Integer); procedure SetWidth(const AValue: Integer); procedure SetZoom(const AValue: Integer); function StoreWidth: Boolean; function StoreHeight: Boolean; function StoreSize: Boolean; protected procedure Loaded; override; function CreateSource: TSourceCollection; override; function DoBitmap(Size: TSize; const Index: Integer): TBitmap; override; function StoreOpacity: Boolean; virtual; public constructor Create(AOwner: TComponent); override; procedure Assign(Source: TPersistent); override; procedure DeleteIcon(const AIndex: Integer); function InsertIcon(const AIndex: Integer; const AFontIconDec: Integer; const AFontName: TFontName = ''; const AFontColor: TAlphaColor = TAlphaColors.Null): Integer; //Multiple icons methods function AddIcons(const AFromIconDec, AToIconDec: Integer; const AFontName: TFontName = ''; const AFontColor: TAlphaColor = TAlphaColors.Null): Integer; procedure ClearIcons; virtual; procedure UpdateIconAttributes(const ASize: Integer; const AFontColor: TAlphaColor; const AReplaceFontColor: Boolean = False; const AFontName: TFontName = ''); overload; procedure UpdateIconAttributes(const AFontColor: TAlphaColor; const AReplaceFontColor: Boolean = False; const AFontName: TFontName = ''); overload; published //Publishing properties of standard ImageList property Source; property Width: Integer read GetWidth write SetWidth stored StoreWidth default DEFAULT_SIZE; property Height: Integer read GetHeight write SetHeight stored StoreHeight default DEFAULT_SIZE; property Zoom: Integer read FZoom write SetZoom default ZOOM_DEFAULT; property Destination; property OnChange; property OnChanged; property Size: Integer read GetSize write SetSize stored StoreSize default DEFAULT_SIZE; property AutoSizeBitmaps: Boolean read FAutoSizeBitmaps write SetAutoSizeBitmaps default True; property FontName: TFontName read FFontName write SetFontName; property FontColor: TAlphaColor read FFontColor write SetFontColor; property Opacity: single read FOpacity write SetOpacity stored StoreOpacity; //property OnFontMissing: TIconFontMissing read FOnFontMissing write FOnFontMissing; end; implementation uses System.Math , System.RTLConsts , System.SysUtils , System.Character , FMX.Forms , FMX.Consts; { TIconFontBitmapItem } function TIconFontBitmapItem.BitmapStored: Boolean; begin Result := False; end; constructor TIconFontBitmapItem.Create(Collection: TCollection); begin inherited; FWidth := DEFAULT_SIZE; FHeight := DEFAULT_SIZE; FZoom := ZOOM_DEFAULT; if Collection is TIconFontMultiResBitmap then FOwnerMultiResBitmap := Collection as TIconFontMultiResBitmap; end; procedure TIconFontBitmapItem.DrawFontIcon; var LFont: TFont; LBitmap: TBitmap; LBitmapWidth, LBitmapHeight: Integer; LRect: TRectF; begin LBitmap := inherited Bitmap; LBitmapWidth := Round(FWidth * Scale); LBitmapHeight := Round(FHeight * Scale); LFont := TFont.Create; try LFont.Family := FontName; LFont.Size := Min(FWidth, FHeight) * FZoom / 100; LFont.Size := LFont.Size * FZoom / 100; LBitmap.Width := LBitmapWidth; LBitmap.Height := LBitmapHeight; LBitmap.Canvas.BeginScene; try LBitmap.Canvas.Clear(TAlphaColors.Null); LBitmap.Canvas.Fill.Color := FontColor; LBitmap.Canvas.Font.Assign(LFont); LRect.Create(0,0,FWidth,FHeight); LBitmap.Canvas.FillText(LRect, Character, False, Opacity, [TFillTextFlag.RightToLeft], TTextAlign.Center, TTextAlign.Center); finally LBitmap.Canvas.EndScene; end; finally LFont.DisposeOf; end; end; function TIconFontBitmapItem.GetBitmap: TBitmapOfItem; begin DrawFontIcon; Result := inherited Bitmap; end; function TIconFontBitmapItem.GetCharacter: String; begin Result := FOwnerMultiResBitmap.FOwnerSourceItem.Character; end; function TIconFontBitmapItem.GetDisplayName: string; begin Result := Format('%s - %dx%d - Scale: %s', [FOwnerMultiResBitmap.FOwnerSourceItem.Name, Size, Size, FloatToStr(Scale)]); end; function TIconFontBitmapItem.GetFontColor: TAlphaColor; begin if FOwnerMultiResBitmap.FOwnerSourceItem.FontColor <> TAlphaColors.Null then Result := FOwnerMultiResBitmap.FOwnerSourceItem.FontColor else Result := FOwnerMultiResBitmap.FOwnerSourceItem.FOwnerImageList.FontColor; end; function TIconFontBitmapItem.GetFontName: TFontName; begin Result := FOwnerMultiResBitmap.FOwnerSourceItem.FontName; end; function TIconFontBitmapItem.GetHeight: Integer; begin Result := inherited Height; end; function TIconFontBitmapItem.GetOpacity: single; begin Result := FOwnerMultiResBitmap.FOwnerSourceItem.Opacity; end; function TIconFontBitmapItem.GetSize: Integer; begin Result := Max(FWidth, FHeight); if Result = 0 then Result := DEFAULT_SIZE; end; function TIconFontBitmapItem.GetWidth: Integer; begin Result := inherited Width; end; procedure TIconFontBitmapItem.SetBitmap(const AValue: TBitmapOfItem); begin inherited Bitmap.Assign(AValue); inherited Bitmap.BitmapScale := Scale; end; procedure TIconFontBitmapItem.SetHeight(const AValue: Integer); begin if AValue <> FHeight then begin FHeight := AValue; DrawFontIcon; end; end; procedure TIconFontBitmapItem.SetWidth(const AValue: Integer); begin if AValue <> FWidth then begin FWidth := AValue; DrawFontIcon; end; end; procedure TIconFontBitmapItem.SetZoom(const AValue: Integer); begin if (FZoom <> AValue) and (AValue <= 100) and (AValue >= 10) then begin FZoom := AValue; DrawFontIcon; end; end; procedure TIconFontBitmapItem.SetIconSize(const AWidth, AHeight, AZoom: Integer); begin if (AWidth <> 0) and (AHeight <> 0) and ((AWidth <> FWidth) or (AHeight <> FHeight) or (AZoom <> FZoom)) then begin FWidth := AWidth; FHeight := AHeight; FZoom := AZoom; DrawFontIcon; end; end; procedure TIconFontBitmapItem.SetSize(const AValue: Integer); begin if ((AValue <> FHeight) or (AValue <> FWidth)) then SetIconSize(AValue, AValue, FZoom); end; function TIconFontBitmapItem.StoreHeight: Boolean; begin Result := (Width <> Height) and (Height <> DEFAULT_SIZE); end; function TIconFontBitmapItem.StoreSize: Boolean; begin Result := (Width = Height) and (Width <> DEFAULT_SIZE); end; function TIconFontBitmapItem.StoreWidth: Boolean; begin Result := (Width <> Height) and (Width <> DEFAULT_SIZE); end; { TIconFontMultiResBitmap } constructor TIconFontMultiResBitmap.Create(AOwner: TPersistent; ItemClass: TIconFontBitmapItemClass); begin inherited Create(AOwner, ItemClass); if (AOwner is TIconFontsSourceItem) then FOwnerSourceItem := TIconFontsSourceItem(AOwner) else FOwnerSourceItem := nil; end; procedure TIconFontMultiResBitmap.UpdateImageSize(const AWidth, AHeight, AZoom: Integer); var I, J: Integer; LItem: TIconFontBitmapItem; begin for I := 0 to ScaleList.Count - 1 do begin for J := 0 to Count - 1 do begin LItem := Items[J] as TIconFontBitmapItem; if (LItem.FWidth <> AWidth) or (LItem.FHeight <> AHeight) then begin LItem.FWidth := AWidth; LItem.FHeight := AHeight; LItem.Zoom := AZoom; LItem.DrawFontIcon; end; end; end; end; { TIconFontsSourceItem } procedure TIconFontsSourceItem.Assign(Source: TPersistent); begin if Source is TIconFontsSourceItem then begin FFontName := TIconFontsSourceItem(Source).FFontName; FFontIconDec := TIconFontsSourceItem(Source).FFontIconDec; FFontColor := TIconFontsSourceItem(Source).FFontColor; FOpacity := TIconFontsSourceItem(Source).FOpacity; end; inherited; end; procedure TIconFontsSourceItem.AutoSizeBitmap(const AWidth, AHeight, AZoom: Integer); begin //If present, delete multiple items while MultiResBitmap.Count > 1 do MultiResBitmap.Delete(MultiResBitmap.Count-1); //Add only one item if MultiResBitmap.Count = 0 then MultiResBitmap.Add; (MultiResBitmap as TIconFontMultiResBitmap).UpdateImageSize(AWidth, AHeight, AZoom); end; constructor TIconFontsSourceItem.Create(Collection: TCollection); begin inherited Create(Collection); FFontIconDec := 0; FOpacity := -1; FFontName := ''; FFontColor := TAlphaColors.null; UpdateAllItems; end; function TIconFontsSourceItem.CreateMultiResBitmap: TMultiResBitmap; begin Result := TIconFontMultiResBitmap.Create(self, TIconFontBitmapItem); FOwnerImageList := Result.ImageList as TIconFontsImageList; end; function TIconFontsSourceItem.GetCharacter: String; begin {$WARN SYMBOL_DEPRECATED OFF} if FFontIconDec <> 0 then Result := ConvertFromUtf32(FFontIconDec) else Result := ''; end; function TIconFontsSourceItem.GetDisplayName: string; begin if Name <> '' then Result := Format('%s - Hex: %s - (%s)', [FontName, FontIconHex, Name]) else Result := Format('%s - Hex: %s', [FontName, FontIconHex]); end; function TIconFontsSourceItem.GetFontColor: TAlphaColor; begin Result := FFontColor; end; function TIconFontsSourceItem.GetFontIconDec: Integer; begin Result := FFontIconDec; end; function TIconFontsSourceItem.GetFontIconHex: string; begin if FFontIconDec <> 0 then Result := IntToHex(FFontIconDec, 1) else Result := ''; end; function TIconFontsSourceItem.GetFontName: TFontName; begin if FFontName = '' then Result := FOwnerImageList.FFontName else Result := FFontName; end; function TIconFontsSourceItem.GetIconName: string; begin Result := inherited Name; end; function TIconFontsSourceItem.GetOpacity: single; begin if FOpacity = -1 then Result := FOwnerImageList.FOpacity else Result := FOpacity; end; procedure TIconFontsSourceItem.SetFontColor(const AValue: TAlphaColor); begin FFontColor := AValue; UpdateAllItems; end; procedure TIconFontsSourceItem.SetFontIconDec(const AValue: Integer); begin if AValue <> FFontIconDec then begin FFontIconDec := AValue; UpdateAllItems; end; end; procedure TIconFontsSourceItem.SetFontIconHex(const AValue: string); begin try if (Length(AValue) = 4) or (Length(AValue) = 5) then FontIconDec := StrToInt('$' + AValue) else if (Length(AValue) = 0) then FFontIconDec := 0 else raise Exception.CreateFmt(ERR_ICONFONTSFMX_VALUE_NOT_ACCEPTED,[AValue]); except On E: EConvertError do raise Exception.CreateFmt(ERR_ICONFONTSFMX_VALUE_NOT_ACCEPTED,[AValue]) else raise; end; end; procedure TIconFontsSourceItem.SetFontName(const AValue: TFontName); begin if (FontName <> AValue) then begin if (AValue = FOwnerImageList.FontName) then FFontName := AValue else begin FFontName := AValue; UpdateAllItems; end; end; end; function TIconFontsSourceItem.GetDestinationItem: TCustomDestinationItem; var LDest: TCustomDestinationItem; begin Result := nil; if FOwnerImageList.Destination.Count > Index then begin LDest := FOwnerImageList.Destination.Items[Index]; if (LDest.LayersCount > 0) and SameText(LDest.Layers[0].Name, IconName) then Result := LDest; end; end; procedure TIconFontsSourceItem.SetIconName(const Value: string); var LDest: TCustomDestinationItem; begin if Value <> Name then begin LDest := GetDestinationItem; inherited Name := Value; if Assigned(LDest) then LDest.Layers[0].Name := Value; end; end; procedure TIconFontsSourceItem.SetOpacity(const AValue: single); begin if Assigned(FOwnerImageList) and (AValue = FOwnerImageList.Opacity) then begin FOpacity := -1; end else FOpacity := AValue; UpdateAllItems; end; function TIconFontsSourceItem.StoreFontColor: Boolean; begin Result := ((FOwnerImageList = nil) or (FFontColor <> FOwnerImageList.FFontColor)) and (FFontColor <> TAlphaColors.Null); end; function TIconFontsSourceItem.StoreFontName: Boolean; begin Result := (FOwnerImageList = nil) or (FFontName <> FOwnerImageList.FFontName); end; function TIconFontsSourceItem.StoreOpacity: Boolean; begin Result := (FOwnerImageList = nil) or (FOpacity <> FOwnerImageList.FOpacity); end; procedure TIconFontsSourceItem.UpdateIconAttributes(const AFontColor: TAlphaColor; const AReplaceFontColor: Boolean = False; const AFontName: TFontName = ''); begin //If AReplaceFontColor is false then the color of single icon is preserved if AReplaceFontColor and (FFontColor <> TAlphaColors.Null) then FFontColor := AFontColor; //Replace FontName only if passed and different for specific Font if (AFontName <> '') and (FFontName <> '') and (AFontName <> FFontName) then FFontName := AFontName else FFontName := ''; end; procedure TIconFontsSourceItem.UpdateAllItems; var I: Integer; LItem: TIconFontBitmapItem; LSize: TSize; begin for I := 0 to MultiResBitmap.Count -1 do begin LItem := MultiResBitmap.Items[I] as TIconFontBitmapItem; Litem.DrawFontIcon; if (I=0) and (FOwnerImageList <> nil) then begin LItem.SetIconSize(FOwnerImageList.Width, FOwnerImageList.Height, FOwnerImageList.Zoom); LSize.cx := LItem.Width; LSize.cy := LItem.Height; FOwnerImageList.UpdateDestination(LSize, Index); end; end; end; { TIconFontsImageList } function TIconFontsImageList.InsertIcon( const AIndex: Integer; const AFontIconDec: Integer; const AFontName: TFontName = ''; const AFontColor: TAlphaColor = TAlphaColors.Null): Integer; var LItem: TIconFontsSourceItem; LDest: TCustomDestinationItem; begin LItem := Self.Source.Insert(AIndex) as TIconFontsSourceItem; Result := LItem.Index; LItem.MultiResBitmap.Add; if AFontName <> '' then LItem.FontName := AFontName; LItem.FontIconDec := AFontIconDec; if AFontColor <> TAlphaColors.Null then LItem.FontColor := AFontColor; LDest := Self.Destination.Insert(AIndex); with LDest.Layers.Add do Name := LItem.Name; end; function TIconFontsImageList.AddIcons(const AFromIconDec, AToIconDec: Integer; const AFontName: TFontName = ''; const AFontColor: TAlphaColor = TAlphaColors.Null): Integer; var LFontIconDec: Integer; LIndex: Integer; begin LIndex := Count; for LFontIconDec := AFromIconDec to AToIconDec do LIndex := InsertIcon(LIndex, LFontIconDec, AFontName, AFontColor) + 1; Result := AFromIconDec - AToIconDec + 1; end; procedure TIconFontsImageList.Assign(Source: TPersistent); begin if Source is TIconFontsImageList then begin FontName := TIconFontsImageList(Source).FontName; FontColor := TIconFontsImageList(Source).FontColor; Opacity := TIconFontsImageList(Source).Opacity; FAutoSizeBitmaps := TIconFontsImageList(Source).FAutoSizeBitmaps; Zoom := TIconFontsImageList(Source).FZoom; SetIconSize(TIconFontsImageList(Source).FWidth, TIconFontsImageList(Source).FHeight); end; inherited; end; procedure TIconFontsImageList.ClearIcons; begin Source.Clear; Destination.Clear; end; constructor TIconFontsImageList.Create(AOwner: TComponent); begin inherited; FAutoSizeBitmaps := True; FFontColor := TAlphaColors.Black; FOpacity := 1; FWidth := DEFAULT_SIZE; FHeight := DEFAULT_SIZE; FZoom := ZOOM_DEFAULT; end; function TIconFontsImageList.CreateSource: TSourceCollection; begin Result := TSourceCollection.Create(self, TIconFontsSourceItem); end; procedure TIconFontsImageList.UpdateDestination(ASize: TSize; const Index: Integer); var LDestItem: TDestinationItem; LSourceItem: TIconFontsSourceItem; LIndex: Integer; LWidth, LHeight: Integer; begin while Index > Destination.Count-1 do Destination.Add; LDestItem := Destination.Items[Index] as TDestinationItem; if LDestItem.Layers.Count > 0 then begin LIndex := Source.indexOf(LDestItem.Layers[0].Name); if LIndex >= 0 then begin LSourceItem := Source.Items[LIndex] as TIconFontsSourceItem; if Assigned(LSourceItem) then begin if FAutoSizeBitmaps then begin if FWidth = FHeight then begin LWidth := Min(ASize.cy, ASize.cx); LHeight := LWidth; end else if FWidth > FHeight then begin LWidth := Min(ASize.cy, ASize.cx); LHeight := Round((FHeight / FWidth) * ASize.cy); end else begin LHeight := ASize.cy; LWidth := Round((FWidth / FHeight) * ASize.cx); end; LSourceItem.AutoSizeBitmap(LWidth, LHeight, FZoom); end else begin LWidth := LSourceItem.FOwnerImageList.FWidth; LHeight := LSourceItem.FOwnerImageList.FHeight; end; LDestItem.Layers[0].SourceRect.Top := 0; LDestItem.Layers[0].SourceRect.Left := 0; LDestItem.Layers[0].SourceRect.Right := LWidth; LDestItem.Layers[0].SourceRect.Bottom := LHeight; end; end; end; end; procedure TIconFontsImageList.UpdateIconAttributes( const AFontColor: TAlphaColor; const AReplaceFontColor: Boolean; const AFontName: TFontName); begin UpdateIconAttributes(Self.Size, AFontColor, AReplaceFontColor, AFontName); end; procedure TIconFontsImageList.UpdateIconAttributes(const ASize: Integer; const AFontColor: TAlphaColor; const AReplaceFontColor: Boolean; const AFontName: TFontName); var I: Integer; LIconFontItem: TIconFontsSourceItem; begin if (AFontColor <> TAlphaColors.null) then begin Self.Size := ASize; FFontColor := AFontColor; for I := 0 to Source.Count -1 do begin LIconFontItem := Source.Items[I] as TIconFontsSourceItem; LIconFontItem.UpdateIconAttributes(FFontColor, AReplaceFontColor, AFontName); end; end; end; procedure TIconFontsImageList.DeleteIcon(const AIndex: Integer); var LDest: TCustomDestinationItem; LSourceItem: TIconFontsSourceItem; begin LSourceItem := Source.Items[AIndex] as TIconFontsSourceItem; if Assigned(LSourceItem) then begin LDest := LSourceItem.GetDestinationItem; Source.Delete(AIndex); if Assigned(LDest) then Destination.Delete(AIndex); end; end; function TIconFontsImageList.DoBitmap(Size: TSize; const Index: Integer): TBitmap; begin UpdateDestination(Size, Index); Result := inherited DoBitmap(Size, Index); end; function TIconFontsImageList.StoreSize: Boolean; begin Result := (Width = Height) and (Width <> DEFAULT_SIZE); end; function TIconFontsImageList.StoreWidth: Boolean; begin Result := (Width <> Height) and (Width <> DEFAULT_SIZE); end; function TIconFontsImageList.StoreHeight: Boolean; begin Result := (Width <> Height) and (Height <> DEFAULT_SIZE); end; function TIconFontsImageList.GetSize: Integer; begin Result := Max(FWidth, FHeight); end; function TIconFontsImageList.GetWidth: Integer; begin Result := FWidth; end; function TIconFontsImageList.GetHeight: Integer; begin Result := FHeight; end; procedure TIconFontsImageList.Loaded; begin inherited; UpdateSourceItems; end; procedure TIconFontsImageList.SetAutoSizeBitmaps(const Value: Boolean); begin FAutoSizeBitmaps := Value; if (Count > 0) then UpdateSourceItems; end; procedure TIconFontsImageList.UpdateSourceItems; var I: Integer; LSourceItem: TIconFontsSourceItem; begin for I := 0 to Source.Count -1 do begin LSourceItem := Source[I] as TIconFontsSourceItem; if LSourceItem.FFontName = '' then LSourceItem.FontName := FFontName; if LSourceItem.FOpacity = -1 then LSourceItem.Opacity := FOpacity; LSourceItem.UpdateAllItems; end; end; procedure TIconFontsImageList.SetFontColor(const Value: TAlphaColor); begin if FFontColor <> Value then begin FFontColor := Value; UpdateSourceItems; Change; end; end; procedure TIconFontsImageList.SetFontName(const Value: TFontName); begin if FFontName <> Value then begin //TODO: check font exists (multi-platform) FFontName := Value; UpdateSourceItems; end; end; procedure TIconFontsImageList.SetHeight(const AValue: Integer); begin if FHeight <> AValue then begin FHeight := AValue; UpdateSourceItems; end; end; procedure TIconFontsImageList.SetIconSize(const AWidth, AHeight: Integer); begin if (AWidth <> 0) and (AHeight <> 0) and ((AWidth <> FWidth) or (AHeight <> FHeight)) then begin FWidth := AWidth; FHeight := AHeight; UpdateSourceItems; end; end; procedure TIconFontsImageList.SetOpacity(const Value: single); begin if FOpacity <> Value then begin FOpacity := Value; UpdateSourceItems; end; end; function TIconFontsImageList.StoreOpacity: Boolean; begin Result := FOpacity <> 1; end; procedure TIconFontsImageList.SetSize(const AValue: Integer); begin if ((AValue <> FHeight) or (AValue <> FWidth)) then SetIconSize(AValue, AValue); end; procedure TIconFontsImageList.SetWidth(const AValue: Integer); begin if FWidth <> AValue then begin FWidth := AValue; UpdateSourceItems; end; end; procedure TIconFontsImageList.SetZoom(const AValue: Integer); begin if (FZoom <> AValue) and (AValue <= 100) and (AValue >= 10) then begin FZoom := AValue; UpdateSourceItems; end; end; initialization RegisterFmxClasses([TIconFontsImageList]); StartClassGroup(TFmxObject); ActivateClassGroup(TFmxObject); GroupDescendentsWith(FMX.IconFontsImageList.TIconFontsImageList, TFmxObject); end.
unit dmFiltroSuelo; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, dmFiltro, DB, kbmMemTable; type TFiltroSuelo = class(TFiltro) protected function ValorInFilter: boolean; override; public function GetDescripcion: string; override; end; implementation uses dmEstadoValores, dmFiltros; {$R *.dfm} { TFiltroSuelo } function TFiltroSuelo.GetDescripcion: string; begin result := 'Suelo'; end; function TFiltroSuelo.ValorInFilter: boolean; begin result := (ValoresDINERO.Value = 0.25) and (ValoresDINERO_ALZA_DOBLE.Value = 0.25) and (ValoresDINERO_BAJA_DOBLE.Value = 0.25) and (ValoresDINERO_BAJA_SIMPLE.Value = 0.25) and (ValoresDINERO_ALZA_SIMPLE.Value = 0.25) and (ValoresPAPEL.Value = ValoresPAPEL_ALZA_DOBLE.Value) and (ValoresPAPEL_ALZA_DOBLE.Value = ValoresPAPEL_ALZA_SIMPLE.Value) and (ValoresPAPEL_ALZA_SIMPLE.Value = ValoresPAPEL_BAJA_DOBLE.Value) and (ValoresPAPEL_BAJA_DOBLE.Value = ValoresPAPEL_BAJA_SIMPLE.Value); end; initialization RegisterFiltro(TFiltroSuelo); finalization end.
unit PBitBtn; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons; type TPBitBtn = class(TBitBtn) private { Private declarations } FPicFileName : String; FResourceName: string; protected { Protected declarations } procedure SetPicFileName(Value: string); procedure SetResourceName(Value: string); public { Public declarations } constructor Create(AOwner: TComponent); override; published { Published declarations } property Glyph stored False; property PicFileName: string read FPicFileName write SetPicFileName; property ResourceName: string read FResourceName write SetResourceName; end; procedure Register; implementation constructor TPBitBtn.Create(AOwner: TComponent); begin inherited Create(AOwner); Font.Name := 'ËÎÌå'; Font.Size := 11; end; procedure TPBitBtn.SetPicFileName(Value : string); var tmpBitmap: TBitmap; begin FPicFileName := Value; if (csDesigning in ComponentState) then begin tmpBitmap := TBitmap.Create; try tmpBitmap.LoadFromFile(FPicFileName); except end; Glyph := tmpBitmap; tmpBitmap.Free; end; end; procedure TPBitBtn.SetResourceName(Value : string); var tmpBitmap: TBitmap; begin FResourceName := Value; if not (csDesigning in ComponentState) then begin tmpBitmap := TBitmap.Create; try tmpBitmap.LoadFromResourceName(HInstance,Value); except end; Glyph := tmpBitmap; tmpBitmap.Free; end; end; procedure Register; begin RegisterComponents('PosControl', [TPBitBtn]); end; end.
unit FiftyTiftyDBCReader; interface uses System.SysUtils, System.Variants, System.Classes, Dialogs, FiftyTiftyDBCTypes; function GetHeader(streamDBC: TMemoryStream): DBCHeader; procedure GetAllIntBands(streamDBC: TMemoryStream; iBeginningOffset, iAddToOffset, iNumEntries: integer; var arrayEntries: array of IntBand); implementation function GetHeader(streamDBC: TMemoryStream): DBCHeader; var dbcheaderHeader: DBCHeader; begin streamDBC.Position := 0; streamDBC.Read(dbcheaderHeader, SizeOf(DBCHeader)); //DBC file header is always 20 bytes in size streamDBC.Position := 0; //ShowMessage(IntToStr(dbcheaderHeader.FieldCount)); Result := dbcheaderHeader; end; function GetIntBand(streamDBC: TMemoryStream; iOffset: integer): IntBand; var intbandEntry: IntBand; begin streamDBC.Position := iOffset; streamDBC.Read(intbandEntry, SizeOf(IntBand)); Result := intbandEntry; end; procedure GetAllIntBands(streamDBC: TMemoryStream; iBeginningOffset, iAddToOffset, iNumEntries: integer; var arrayEntries: array of IntBand); var intbandEntry: IntBand; iCounter: integer; begin //ShowMessage('Starting GetIntBand loop'); for iCounter := 0 to iNumEntries - 1 do begin streamDBC.Position := 0; if iCounter = 0 then intbandEntry := GetIntBand(streamDBC, iBeginningOffset) else intbandEntry := GetIntBand(streamDBC, iBeginningOffset + (iCounter * iAddToOffset) ); arrayEntries[iCounter] := intbandEntry; end; end; end.
unit uJsonUtils; interface uses Classes, SysUtils, StrUtils, DBClient, System.JSON, DB, Variants; function GetToken(pModulo: String):String; function EmpacotaSQLJsonExecute(pSQL:string):string; function EmpacotaSQL(pSQL: string):string; function JsonArrayToDataSet(pPacoteJson: string; pDataSetDestino: TClientDataSet): Boolean; function VerificaRetornoJson(pJsonRetorno: string ): Boolean; function TrataErrosRetornoJson(pJsonRetorno: string):string; implementation { ------------------------------------------------------------------------------ } function GetToken(pModulo: String): String; begin { *** Rotina: Monta o token para transações com o WebService *** } Result := '{"log_cd_maquina":1,"log_cd_usuario":1,"log_ds_modulo":"' + pModulo + '"}' end; { ------------------------------------------------------------------------------ } function EmpacotaSQLJsonExecute(pSQL: String): String; begin { *** Rotina: Empacota um comando SQL de execução para o formato Json *** } Result := '[{"SQL":"' + pSQL + '"}]'; end; { ------------------------------------------------------------------------------ } function EmpacotaSQL(pSQL: String): String; begin { *** Rotina: Empacota um comando SQL de execução para o formato Json *** } Result := '[{"SQL":"' + pSQL + '"}]'; end; { ------------------------------------------------------------------------------ } function VerificaRetornoJson(pJsonRetorno: String): Boolean; var vJson: TJSONObject; begin { *** Rotina: Trata o retorno do comando sql executado no WebService *** } vJson := TJSONObject.Create; try vJson := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(pJsonRetorno), 0) as TJSONObject; Result := (vJson.Get('RET').JsonValue.Value = '0'); if not Result then TrataErrosRetornoJson(pJsonRetorno); finally vJson.DisposeOf; end; end; { ------------------------------------------------------------------------------ } function JsonArrayToDataSet(pPacoteJson: string; pDataSetDestino: TClientDataSet): Boolean; var vJArray: TJSONArray; vJson: TJSONObject; i: Integer; y: Integer; vCampo: TField; vListaCampos: TStringList; dad: Boolean; valor: Variant; begin { *** Rotina: Desmonta um pacote JsonArray com o resultado de uma consulta SQL e abastece o DataSet passado como parâmetro *** } dad := false; Result := False; try vJson := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(pPacoteJson), 0) as TJSONObject; pDataSetDestino.EmptyDataSet; vListaCampos := TStringList.Create; for i := 0 to pDataSetDestino.FieldCount - 1 do if pDataSetDestino.Fields[i].FieldKind = fkData then vListaCampos.Add(pDataSetDestino.Fields[i].FieldName); for i := 0 to vJson.Count - 1 do begin if (vJson.Pairs[i].JsonString.Value = 'DAD') then begin if not (vJson.Pairs[i].JsonValue.ToString = '[null]') then begin dad := True; vJArray := (vJson.Pairs[i].JsonValue as TJSONArray); Break; end; end; end; if (dad) then begin for i := 0 to vJArray.Count - 1 do // numero de registro dentro do array begin pDataSetDestino.Append; if not(vJArray.Items[i] is TJSONArray) then begin try valor := vJArray.Items[i].Value; pDataSetDestino.Fields[0].Value := valor; except raise Exception.Create('Erro ao preencher campo ' + pDataSetDestino.Fields[0].FieldName); end; end else begin for y := 0 to TJSONObject(vJArray.Items[i]).Count - 1 do // qtde de campos no registro begin vCampo := pDataSetDestino.FindField(vListaCampos[y]); if (vCampo <> nil) then begin try if TJSONArray(vJArray.Items[i]).Items[y].Null then valor := Null else valor := TJSONArray(vJArray.Items[i]).Items[y].Value; if (pDataSetDestino.Fields[y].DataType = ftMemo) or (pDataSetDestino.Fields[y].DataType = ftBlob) then begin if VarIsNull(valor) then valor := ''; valor := StringReplace(valor, '@*', #$D, [rfReplaceAll]); valor := StringReplace(valor, '@!', #$A, [rfReplaceAll]); pDataSetDestino.FieldValues[vCampo.FieldName] := valor; end else if (pDataSetDestino.Fields[y].DataType = ftDatetime) and (valor <> NULL) then begin if Pos('ASTIME',UpperCase(pDataSetDestino.Fields[y].FieldName)) = 0 then valor := copy(valor,9,2) + '/' + copy(valor,6,2) + '/' + copy(valor,1,4) + copy(valor,11,9); pDataSetDestino.FieldValues[vCampo.FieldName] := valor end else if (pDataSetDestino.Fields[y].DataType = ftDate) and (valor <> NULL) then begin pDataSetDestino.FieldValues[vCampo.FieldName] := StrToDate(copy(valor,9,2) + '/' + copy(valor,6,2) + '/' + copy(valor,1,4) + copy(valor,11,9)) end else if (pDataSetDestino.Fields[y].DataType = ftTimeStamp) and (valor <> NULL) then begin valor := copy(valor,9,2) + '/' + copy(valor,6,2) + '/' + copy(valor,1,4) + copy(valor,11,9); pDataSetDestino.FieldValues[vCampo.FieldName] := valor; end else begin if VarIsNull(valor) then valor := Null; pDataSetDestino.FieldValues[vCampo.FieldName] := valor; end; except pDataSetDestino.Cancel; pDataSetDestino.EnableControls; raise Exception.Create ('Erro de retorno do WebService ao preencher campo ' + vCampo.FieldName); end; end; end; end; pDataSetDestino.Post; end; Result := True; end; finally vListaCampos.DisposeOf; vJson.DisposeOf; end; end; { ------------------------------------------------------------------------------ } function TrataErrosRetornoJson(pJsonRetorno: String): String; var vJson: TJSONObject; vMensagemErro: string; begin { *** Rotina: Trata os erros retornados no pacote Json *** } vJson := TJSONObject.Create; try vJson := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(pJsonRetorno), 0) as TJSONObject; vMensagemErro := vJson.Get('DAD').JsonValue.Value; raise Exception.Create('Erro ao Acessar Webservice'+#13+#10+vMensagemErro); finally vJson.DisposeOf; end; end; { ------------------------------------------------------------------------------ } end.
unit DW.Compat.Android; {*******************************************************} { } { Kastri Free } { } { DelphiWorlds Cross-Platform Library } { } {*******************************************************} {$I DW.GlobalDefines.inc} interface uses Androidapi.JNI.JavaTypes; function JObjectToID(const AObject: JObject): Pointer; implementation uses Androidapi.JNIBridge; function JObjectToID(const AObject: JObject): Pointer; begin if AObject <> nil then Result := (AObject as ILocalObject).GetObjectID else Result := nil; end; end.
unit datepickerdialog; {$mode delphi} interface uses Classes, SysUtils, And_jni, AndroidWidget; type TOnDatePicker = procedure(Sender: TObject;year: integer; monthOfYear: integer; dayOfMonth: integer) of Object; {Draft Component code by "Lazarus Android Module Wizard" [2/3/2015 22:53:29]} {https://github.com/jmpessoa/lazandroidmodulewizard} {jControl template} jDatePickerDialog = class(jControl) private FOnDatePicker: TOnDatePicker; protected public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Init; override; function jCreate(): jObject; procedure jFree(); procedure Show(); overload; procedure Show(_year: integer; _monthOfYear: integer; _dayOfMonth: integer); overload; procedure GenEvent_OnDatePicker(Obj: TObject; year: integer; monthOfYear: integer; dayOfMonth: integer); published property OnDatePicker: TOnDatePicker read FOnDatePicker write FOnDatePicker; end; function jDatePickerDialog_jCreate(env: PJNIEnv;_Self: int64; this: jObject): jObject; implementation {--------- jDatePickerDialog --------------} constructor jDatePickerDialog.Create(AOwner: TComponent); begin inherited Create(AOwner); //your code here.... end; destructor jDatePickerDialog.Destroy; begin if not (csDesigning in ComponentState) then begin if FjObject <> nil then begin jFree(); FjObject:= nil; end; end; //you others free code here...' inherited Destroy; end; procedure jDatePickerDialog.Init; begin if FInitialized then Exit; inherited Init; //set default ViewParent/FjPRLayout as jForm.View! //your code here: set/initialize create params.... FjObject := jCreate(); if FjObject = nil then exit; FInitialized:= True; end; function jDatePickerDialog.jCreate(): jObject; begin Result:= jDatePickerDialog_jCreate(gApp.jni.jEnv, int64(Self), gApp.jni.jThis); end; procedure jDatePickerDialog.jFree(); begin //in designing component state: set value here... if FInitialized then jni_proc(gApp.jni.jEnv, FjObject, 'jFree'); end; procedure jDatePickerDialog.Show(); begin //in designing component state: set value here... if FInitialized then jni_proc(gApp.jni.jEnv, FjObject, 'Show'); end; procedure jDatePickerDialog.GenEvent_OnDatePicker(Obj: TObject; year: integer; monthOfYear: integer; dayOfMonth: integer); begin if Assigned(FOnDatePicker) then FOnDatePicker(Obj, year, monthOfYear, dayOfMonth); end; procedure jDatePickerDialog.Show(_year: integer; _monthOfYear: integer; _dayOfMonth: integer); begin //in designing component state: set value here... if FInitialized then jni_proc_iii(gApp.jni.jEnv, FjObject, 'Show', _year ,_monthOfYear ,_dayOfMonth); end; {-------- jDatePickerDialog_JNI_Bridge ----------} function jDatePickerDialog_jCreate(env: PJNIEnv;_Self: int64; this: jObject): jObject; var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].j:= _Self; if (env = nil) or (this = nil) then exit; jCls:= Get_gjClass(env); jMethod:= env^.GetMethodID(env, jCls, 'jDatePickerDialog_jCreate', '(J)Ljava/lang/Object;'); Result:= env^.CallObjectMethodA(env, this, jMethod, @jParams); Result:= env^.NewGlobalRef(env, Result); end; (* //Please, you need insert: public java.lang.Object jDatePickerDialog_jCreate(long _Self) { return (java.lang.Object)(new jDatePickerDialog(this,_Self)); } //to end of "public class Controls" in "Controls.java" *) end.
unit FUser.Register; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Edit, FMX.Objects, FMX.Controls.Presentation, FMX.StdCtrls, FMX.TabControl, FMX.Layouts, FMX.DialogService, System.ImageList, FMX.ImgList, Storage.Chronos, StrUtils, System.Threading, System.SyncObjs, System.JSON, REST.Types, Service.Login, Service.Register, Interfaces.SimulateTransparency, FMX.Effects; type TfrmUserRegister = class(TForm, ISimulateTransparency) layCadastro: TLayout; tabCadastro: TTabControl; tab2_ValidaEmail: TTabItem; tab3_MedicoOuPaciente: TTabItem; tab1_NomeCompleto: TTabItem; layPrincipal: TLayout; lblQualSeuNome: TLabel; edtNome: TEdit; layValideEmail: TLayout; lblTitulo: TLabel; lblTexto1: TLabel; lblTexto2: TLabel; lblEmail: TLabel; lblTexto3: TLabel; Rectangle1: TRectangle; recDigitos: TRectangle; Rectangle2: TRectangle; Image1: TImage; Line1: TLine; Line2: TLine; Rectangle3: TRectangle; Image2: TImage; Line3: TLine; layCabecalho: TLayout; btnVoltar: TButton; recCabecalho: TRectangle; Label4: TLabel; layPassos: TLayout; recPassos: TRectangle; recPassosItens: TRectangle; Circle5: TCircle; Circle4: TCircle; Circle3: TCircle; Circle2: TCircle; Layout1: TLayout; lineCircle2: TLine; Layout2: TLayout; lineCircle1: TLine; Layout3: TLayout; lineCircle3: TLine; Layout4: TLayout; lineCircle4: TLine; Rectangle4: TRectangle; layPasso1: TLayout; Label5: TLabel; Label6: TLabel; layEspacoPasso4: TLayout; layPasso5: TLayout; Label7: TLabel; Label8: TLabel; layEspacoPasso1: TLayout; layPasso4: TLayout; Label9: TLabel; Label10: TLabel; layEspacoPasso3: TLayout; layPasso3: TLayout; Label11: TLabel; Label12: TLabel; layEspacoPasso2: TLayout; layPasso2: TLayout; Label13: TLabel; Label14: TLabel; tab4_EMedico: TTabItem; tab5_CadastrarSenha: TTabItem; tab6_Parabens: TTabItem; imgCircle2: TImage; imgCircle1: TImage; imgCircle3: TImage; imgCircle4: TImage; imgCircle5: TImage; Circle1: TCircle; ImageList1: TImageList; btnPasso_1_2: TButton; StyleBook1_: TStyleBook; btnPasso2_3: TButton; Label1: TLabel; lblNomeUser: TLabel; Label15: TLabel; Label16: TLabel; recOpcoes: TRectangle; btnOpcaoNao: TButton; btnOpcaoSim: TButton; layOpcoesMedicoPaciente: TLayout; Label17: TLabel; lblNomeMedico: TLabel; Label19: TLabel; Label20: TLabel; btnPasso4_5: TButton; Label18: TLabel; Label21: TLabel; lblPasswordTitle: TLabel; lblPasswordText1: TLabel; lblPasswordText2: TLabel; lblPasswordText3: TLabel; edtPassword: TEdit; swtPasswordShow: TSwitch; lblPasswordShow: TLabel; btnFinishPassword: TButton; Image3: TImage; TabControl1: TTabControl; TabItem6: TTabItem; Label50: TLabel; Label51: TLabel; Label52: TLabel; Label53: TLabel; VertScrollBox1: TVertScrollBox; pbPasswordStrength: TProgressBar; lblPasswordStrengthText: TLabel; layPasswordCreate: TLayout; lblPasswordStrengthName: TLabel; layPasswordShow: TLayout; Line4: TLine; aniIndicator: TAniIndicator; btnReSendEmailCodeConfirmation: TButton; btnChangeEmail: TButton; edtCodeConfirmation: TEdit; aniIndicator2: TAniIndicator; tab7_Unassigned: TTabItem; layMain: TLayout; BlurEffect1: TBlurEffect; sclayMain: TScaledLayout; StyleBook1: TStyleBook; btnEntrarApp: TButton; procedure btnConfirmarCodigoClick(Sender: TObject); procedure btnPasso_1_2Click(Sender: TObject); procedure btnPasso2_3Click(Sender: TObject); procedure btnOpcaoSimClick(Sender: TObject); procedure btnOpcaoNaoClick(Sender: TObject); procedure btnPasso4_5Click(Sender: TObject); procedure btnFinishPasswordClick(Sender: TObject); procedure swtPasswordShowClick(Sender: TObject); procedure Image3Click(Sender: TObject); procedure edtPasswordTyping(Sender: TObject); procedure btnReSendEmailCodeConfirmationClick(Sender: TObject); procedure btnChangeEmailClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure tabCadastroChange(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormShow(Sender: TObject); procedure btnEntrarAppClick(Sender: TObject); private FSrvLogin : TsrvServiceLogin; FSrvRegister : TsrvRegister; procedure Images(aIndice: Word); procedure StrongPassword; procedure Thread1_Terminated(Sender: TObject); procedure Thread2_Terminated(Sender: TObject); procedure SendEmailCodeConfirmation(aEmail : String); { Private declarations } public { Public declarations } bApprovedPassword : boolean; function validateFormPassword(aPassword : String) : boolean; procedure SetBlurredBackground(out ABitmap: TBitmap); end; var frmUserRegister: TfrmUserRegister; Title, Txt1, Txt2, Txt3 : String; implementation {$R *.fmx} uses FUser.Menu, FUser.Password, uLibCommon, USharedConsts, FMX.TextEditHandler; procedure TfrmUserRegister.btnChangeEmailClick(Sender: TObject); begin Close; end; procedure TfrmUserRegister.btnConfirmarCodigoClick(Sender: TObject); begin tabCadastro.ActiveTab := tab3_MedicoOuPaciente; end; procedure TfrmUserRegister.btnEntrarAppClick(Sender: TObject); begin frmUserMenu.Show; end; procedure TfrmUserRegister.btnPasso_1_2Click(Sender: TObject); var T : TThread; sEmail : String; begin if (edtNome.Text <> EmptyStr) then begin Chronos.SetItem<string>(APP_USER_NICKNAME, edtNome.Text); sEmail := Chronos.GetItem<string>(APP_USER_EMAIL).Trim; if sEmail.IsEmpty then begin ShowMessage('Você não digitou seu email'); Close; end; aniIndicator.Enabled := True; aniIndicator.Visible := True; T := TThread.CreateAnonymousThread(procedure begin SendEmailCodeConfirmation(sEmail); T.Synchronize(nil, procedure begin aniIndicator.Enabled := False; aniIndicator.Visible := False; end); end); T.OnTerminate := Thread1_Terminated; T.Start; end else begin TDialogService.MessageDialog( WARNING_REGISTER_NICKNAME_REQUIRED, TMsgDlgType.mtWarning, [TMsgDlgBtn.mbOk], TMsgDlgBtn.mbOK, 0, procedure(const AResult: TModalResult) begin edtNome.SetFocus; end); end; end; procedure TfrmUserRegister.SendEmailCodeConfirmation(aEmail : String); var jParametro, jRetorno : TJSONObject; sRetorno : String; begin jRetorno := nil; jParametro := nil; try if FSrvLogin = nil then begin FSrvLogin := TsrvServiceLogin.Create(nil); end; Images(3); aniIndicator.Enabled := True; aniIndicator.Visible := True; jParametro := TJSONObject.Create; jParametro.AddPair('email', aEmail); FSrvLogin.backEndPointSendEmail.Method := TRESTRequestMethod.rmPOST; FSrvLogin.backEndPointSendEmail.Body.Add(jParametro); FSrvLogin.backEndPointSendEmail.Resource := 'resSendEmail'; try // FsrvLogin.backEndPointSendEmail.Execute; except end; // jRetorno := TJSONObject.ParseJSONValue(FsrvLogin.rRespSendEmail.Content) as TJSONObject; // sRetorno := jRetorno.GetValue('CodeConfirmation').Value; // Chronos.SetItem<string>('CodeConfirmation', sRetorno); finally jParametro.Free; jRetorno.Free; FsrvLogin.Free; end; end; procedure TfrmUserRegister.SetBlurredBackground(out ABitmap: TBitmap); begin BlurEffect1.Enabled := True; ABitmap := layMain.MakeScreenshot; BlurEffect1.Enabled := False; end; procedure TfrmUserRegister.btnReSendEmailCodeConfirmationClick(Sender: TObject); var T : TThread; sEmail : String; begin Title := lblTitulo.Text; Txt1 := lblTexto1.Text; Txt2 := lblTexto2.Text; Txt3 := lblTexto3.Text; lblTitulo.Text := 'Re-enviando código para'; lblTexto1.Text := ''; lblTexto2.Text := ''; lblTexto3.Text := 'Por favor, aguarde'; sEmail := Chronos.GetItem<string>('LoginEmail').Trim; aniIndicator2.Enabled := True; aniIndicator2.Visible := True; T := TThread.CreateAnonymousThread(procedure begin SendEmailCodeConfirmation(sEmail); T.Synchronize(nil, procedure begin aniIndicator2.Enabled := False; aniIndicator2.Visible := False; end); end); T.OnTerminate := Thread2_Terminated; T.Start; end; procedure TfrmUserRegister.edtPasswordTyping(Sender: TObject); begin StrongPassword; end; procedure TfrmUserRegister.FormCreate(Sender: TObject); begin tabCadastro.ActiveTab := tab7_Unassigned; FSrvRegister := TsrvRegister.Create(nil); end; procedure TfrmUserRegister.FormDestroy(Sender: TObject); begin FSrvRegister.DisposeOf; end; procedure TfrmUserRegister.FormShow(Sender: TObject); var LAdvTextEditHandler: TAdvTextEditHandler; begin LAdvTextEditHandler.Handle(edtNome, tfNoEmoji); LAdvTextEditHandler.Handle(edtPassword, tfNoEmoji); LAdvTextEditHandler.Handle(edtCodeConfirmation, tfNoEmoji); end; procedure TfrmUserRegister.StrongPassword; begin if validateFormPassword(edtPassword.Text.Trim) then begin pbPasswordStrength.Value := 100; lblPasswordStrengthName.FontColor := TAlphaColor($FF006838); lblPasswordStrengthName.Text := 'forte'; end else begin pbPasswordStrength.Value := 0; lblPasswordStrengthName.FontColor := TAlphaColor($FF686868); lblPasswordStrengthName.Text := 'fraca'; end; end; procedure TfrmUserRegister.btnPasso4_5Click(Sender: TObject); begin Images(5); tabCadastro.ActiveTab := tab5_CadastrarSenha; end; procedure TfrmUserRegister.btnFinishPasswordClick(Sender: TObject); begin if validateFormPassword(edtPassword.Text.Trim) then begin pbPasswordStrength.Value := 100; lblPasswordStrengthName.FontColor := TAlphaColor($FF006838); lblPasswordStrengthName.Text := 'forte'; Chronos.SetItem<string>(APP_USER_PASSWORD, edtPassword.Text.Trim); FSrvRegister.RegisterUser; end else begin pbPasswordStrength.Value := 0; lblPasswordStrengthName.FontColor := TAlphaColor($FF686868); lblPasswordStrengthName.Text := 'fraca'; ShowMessage('Sua senha está fraca. Verifique os requisitos de segurança acima'); end; end; procedure TfrmUserRegister.btnOpcaoNaoClick(Sender: TObject); begin Images(5); Chronos.SetItem<string>(APP_USER_TYPE, 'U'); tabCadastro.ActiveTab := tab5_CadastrarSenha; end; procedure TfrmUserRegister.btnOpcaoSimClick(Sender: TObject); begin Chronos.SetItem<string>(APP_USER_TYPE, 'D'); lblNomeMedico.Text := edtNome.Text; tabCadastro.ActiveTab := tab4_EMedico; end; procedure TfrmUserRegister.btnPasso2_3Click(Sender: TObject); var sCodeDig, sCodeConfirmation : String; begin sCodeDig := edtCodeConfirmation.Text.Trim; sCodeConfirmation := Chronos.GetItem<string>('CodeConfirmation'); if (sCodeConfirmation <> sCodeDig) then begin ShowMessage('Código digitado não confere'); Exit; end; lblNomeUser.Text := edtNome.Text; Images(4); tabCadastro.ActiveTab := tab3_MedicoOuPaciente; end; procedure TfrmUserRegister.Image3Click(Sender: TObject); begin frmUserMenu.Show; end; function TfrmUserRegister.validateFormPassword(aPassword : String) : Boolean; var bHasUppercase, bHasLowercase, bHasNumber, bHasMinSize: Boolean; begin bHasUppercase := UpperContains(aPassword); bHasLowercase := LowerContains(aPassword); bHasNumber := NumberContains(aPassword); bHasMinSize := (Length(aPassword) > 7); Result := (bHasUppercase and bHasLowercase and bHasNumber and bHasMinSize); end; procedure TfrmUserRegister.Images(aIndice : Word); begin case aIndice of 1 : begin imgCircle1.Bitmap.Assign(ImageList1.Bitmap(imgCircle1.Size.Size, 0)); imgCircle2.Bitmap.Assign(ImageList1.Bitmap(imgCircle2.Size.Size, 1)); imgCircle3.Bitmap.Assign(ImageList1.Bitmap(imgCircle3.Size.Size, 5)); imgCircle4.Bitmap.Assign(ImageList1.Bitmap(imgCircle4.Size.Size, 6)); imgCircle5.Bitmap.Assign(ImageList1.Bitmap(imgCircle5.Size.Size, 7)); lineCircle1.Stroke.Color := $FFC21046; lineCircle1.Stroke.Dash := TStrokeDash.Solid; lineCircle2.Stroke.Color := TAlphaColors.Silver; lineCircle2.Stroke.Dash := TStrokeDash.DashDot; lineCircle3.Stroke.Color := TAlphaColors.Silver; lineCircle3.Stroke.Dash := TStrokeDash.DashDot; lineCircle4.Stroke.Color := TAlphaColors.Silver; lineCircle4.Stroke.Dash := TStrokeDash.DashDot; end; 2 : begin imgCircle1.Bitmap.Assign(ImageList1.Bitmap(imgCircle1.Size.Size, 0)); imgCircle2.Bitmap.Assign(ImageList1.Bitmap(imgCircle2.Size.Size, 1)); imgCircle3.Bitmap.Assign(ImageList1.Bitmap(imgCircle3.Size.Size, 2)); imgCircle4.Bitmap.Assign(ImageList1.Bitmap(imgCircle4.Size.Size, 6)); imgCircle5.Bitmap.Assign(ImageList1.Bitmap(imgCircle5.Size.Size, 7)); lineCircle1.Stroke.Color := $FFC21046; lineCircle1.Stroke.Dash := TStrokeDash.Solid; lineCircle2.Stroke.Color := $FFC21046; lineCircle2.Stroke.Dash := TStrokeDash.Solid; lineCircle3.Stroke.Color := TAlphaColors.Silver; lineCircle3.Stroke.Dash := TStrokeDash.DashDot; lineCircle4.Stroke.Color := TAlphaColors.Silver; lineCircle4.Stroke.Dash := TStrokeDash.DashDot; end; 3 : begin imgCircle1.Bitmap.Assign(ImageList1.Bitmap(imgCircle1.Size.Size, 0)); imgCircle2.Bitmap.Assign(ImageList1.Bitmap(imgCircle2.Size.Size, 1)); imgCircle3.Bitmap.Assign(ImageList1.Bitmap(imgCircle3.Size.Size, 2)); imgCircle4.Bitmap.Assign(ImageList1.Bitmap(imgCircle4.Size.Size, 6)); imgCircle5.Bitmap.Assign(ImageList1.Bitmap(imgCircle5.Size.Size, 7)); lineCircle1.Stroke.Color := $FFC21046; lineCircle1.Stroke.Dash := TStrokeDash.Solid; lineCircle2.Stroke.Color := $FFC21046; lineCircle2.Stroke.Dash := TStrokeDash.Solid; lineCircle3.Stroke.Color := TAlphaColors.Silver; lineCircle3.Stroke.Dash := TStrokeDash.DashDot; lineCircle4.Stroke.Color := TAlphaColors.Silver; lineCircle4.Stroke.Dash := TStrokeDash.DashDot; end; 4 : begin imgCircle1.Bitmap.Assign(ImageList1.Bitmap(imgCircle1.Size.Size, 0)); imgCircle2.Bitmap.Assign(ImageList1.Bitmap(imgCircle2.Size.Size, 1)); imgCircle3.Bitmap.Assign(ImageList1.Bitmap(imgCircle3.Size.Size, 2)); imgCircle4.Bitmap.Assign(ImageList1.Bitmap(imgCircle4.Size.Size, 3)); imgCircle5.Bitmap.Assign(ImageList1.Bitmap(imgCircle5.Size.Size, 7)); lineCircle1.Stroke.Color := $FFC21046; lineCircle1.Stroke.Dash := TStrokeDash.Solid; lineCircle2.Stroke.Color := $FFC21046; lineCircle2.Stroke.Dash := TStrokeDash.Solid; lineCircle3.Stroke.Color := $FFC21046; lineCircle3.Stroke.Dash := TStrokeDash.Solid; lineCircle4.Stroke.Color := TAlphaColors.Silver; lineCircle4.Stroke.Dash := TStrokeDash.DashDot; end; 5 : begin imgCircle1.Bitmap.Assign(ImageList1.Bitmap(imgCircle1.Size.Size, 0)); imgCircle2.Bitmap.Assign(ImageList1.Bitmap(imgCircle2.Size.Size, 1)); imgCircle3.Bitmap.Assign(ImageList1.Bitmap(imgCircle3.Size.Size, 2)); imgCircle4.Bitmap.Assign(ImageList1.Bitmap(imgCircle4.Size.Size, 3)); imgCircle5.Bitmap.Assign(ImageList1.Bitmap(imgCircle5.Size.Size, 4)); lineCircle1.Stroke.Color := $FFC21046; lineCircle1.Stroke.Dash := TStrokeDash.Solid; lineCircle2.Stroke.Color := $FFC21046; lineCircle2.Stroke.Dash := TStrokeDash.Solid; lineCircle3.Stroke.Color := $FFC21046; lineCircle3.Stroke.Dash := TStrokeDash.Solid; lineCircle4.Stroke.Color := $FFC21046; lineCircle4.Stroke.Dash := TStrokeDash.Solid; end; end; end; procedure TfrmUserRegister.swtPasswordShowClick(Sender: TObject); begin edtPassword.Password := not swtPasswordShow.IsChecked; end; procedure TfrmUserRegister.tabCadastroChange(Sender: TObject); begin case tabCadastro.TabIndex of 0: begin edtNome.SetFocus; end; end; end; procedure TfrmUserRegister.Thread1_Terminated(Sender: TObject); begin {Solicita a digitação desse código de acesso} tabCadastro.ActiveTab := tab2_ValidaEmail; end; procedure TfrmUserRegister.Thread2_Terminated(Sender: TObject); begin lblTitulo.Text := Title; lblTexto1.Text := Txt1; lblTexto2.Text := Txt2; lblTexto3.Text := Txt3; end; end.
unit uTestes; interface uses SysUtils, DUnitX.TestFramework, UExemplo; type [TestFixture] TUsuarioTestes = class private FUsuario: TUsuario; public [Setup] procedure Setup; [TearDown] procedure TearDown; [Test] procedure ValidarMetodoEntrarNoSistema; end; implementation uses Delphi.Mocks; { TUsuarioTestes } procedure TUsuarioTestes.Setup; begin Self.FUsuario := TUsuario.Create; end; procedure TUsuarioTestes.TearDown; begin if Assigned(FUsuario) then FUsuario.Free; end; procedure TUsuarioTestes.ValidarMetodoEntrarNoSistema; var Mock: TMock<IUsuario>; begin Mock := TMock<IUsuario>.Create; Mock.Setup.WillReturn('Demo').When.NomeUsuario; // Aqui basta trocar o usuario aí o teste irá funcionar... Assert.IsTrue(FUsuario.EhUsuarioValido(TStub<ILog>.Create, Mock), 'Teste falhou!'); end; initialization TDUnitX.RegisterTestFixture(TUsuarioTestes); end.
unit ReflectionServicesUnit; interface type TReflectionServices = class public class function GetClassPropertyTypeAsVariantConstant( TargetClass: TClass; const PropertyName: String ): Word; class function GetObjectPropertyValue( TargetObject: TObject; const PropertyName: String ): Variant; static; class procedure SetObjectPropertyValue( TargetObject: TObject; const PropertyName: String; const Value: Variant ); static; end; implementation uses TypInfo, Variants, SysUtils, Windows, AuxDebugFunctionsUnit; { TReflectionServices } class function TReflectionServices.GetClassPropertyTypeAsVariantConstant( TargetClass: TClass; const PropertyName: String): Word; var ClassTypeInfo: PTypeInfo; ClassTypeData: PTypeData; PropertyList: PPropList; PropertyInfo: TPropInfo; I, PropertyCount: Integer; begin ClassTypeInfo := TargetClass.ClassInfo; ClassTypeData := GetTypeData(ClassTypeInfo); PropertyCount := ClassTypeData.PropCount; if PropertyCount = 0 then begin Result := null; Exit; end; try GetMem(PropertyList, Sizeof(PPropInfo) * PropertyCount); GetPropList(ClassTypeInfo, tkProperties, PropertyList); for I := 0 to PropertyCount - 1 do begin PropertyInfo := PropertyList[I]^; if PropertyInfo.Name <> PropertyName then Continue; case PropertyInfo.PropType^.Kind of tkInteger, tkEnumeration: Result := varInteger; tkSet: Result := varUnknown; tkLString, tkWString, tkString {$IFDEF VER210}, tkUString {$ENDIF}: Result := varString; tkFloat: begin if PropertyInfo.PropType^.Name = 'TDateTime' then Result := varDate else if PropertyInfo.PropType^.Name = 'Single' then Result := varSingle else Result := varDouble; end; tkInt64: Result := varInt64; tkVariant: Result := varVariant; tkClass: Result := varByRef; else raise Exception.Create('Unexpected property kind was encountered'); end; Break; end; finally FreeMem(PropertyList); end; end; class function TReflectionServices.GetObjectPropertyValue( TargetObject: TObject; const PropertyName: String ): Variant; var ClassTypeInfo: PTypeInfo; ClassTypeData: PTypeData; PropertyList: PPropList; PropertyInfo: TPropInfo; I, PropertyCount: Integer; begin ClassTypeInfo := TargetObject.ClassInfo; ClassTypeData := GetTypeData(ClassTypeInfo); PropertyCount := ClassTypeData.PropCount; if PropertyCount = 0 then begin Result := null; Exit; end; try GetMem(PropertyList, Sizeof(PPropInfo) * PropertyCount); GetPropList(ClassTypeInfo, tkProperties, PropertyList); for I := 0 to PropertyCount - 1 do begin PropertyInfo := PropertyList[I]^; if PropertyInfo.Name <> PropertyName then Continue; case PropertyInfo.PropType^.Kind of tkInteger, tkEnumeration: begin Result := GetOrdProp(TargetObject, PropertyName); if PropertyInfo.PropType^.Name = 'Boolean' then Result := VarAsType(Result, varBoolean); end; tkSet: Result := GetSetProp(TargetObject, PropertyName); tkLString, tkWString, tkString {$IFDEF VER210}, tkUString {$ENDIF}: Result := GetStrProp(TargetObject, PropertyName); tkFloat: begin Result := GetFloatProp(TargetObject, PropertyName); if PropertyInfo.PropType^.Name = 'TDateTime' then Result := FloatToDateTime(Result); end; tkInt64: Result := GetInt64Prop(TargetObject, PropertyName); tkVariant: Result := GetVariantProp(TargetObject, PropertyName); tkClass: begin TVarData(Result).VType := varByRef; TVarData(Result).VPointer := Pointer(GetObjectProp(TargetObject, PropertyName)); end else raise Exception.Create('Unexpected property kind was encountered'); end; Break; end; finally FreeMem(PropertyList); end; end; class procedure TReflectionServices.SetObjectPropertyValue( TargetObject: TObject; const PropertyName: String; const Value: Variant ); var ClassTypeInfo: PTypeInfo; ClassTypeData: PTypeData; PropertyList: PPropList; PropertyInfo: TPropInfo; I, PropertyCount: Integer; Int64Value: Int64; begin if (Value = Unassigned) or (Value = Null) then Exit; ClassTypeInfo := TargetObject.ClassInfo; ClassTypeData := GetTypeData(ClassTypeInfo); PropertyCount := ClassTypeData.PropCount; if PropertyCount = 0 then begin Exit; end; try GetMem(PropertyList, Sizeof(PPropInfo) * PropertyCount); GetPropList(ClassTypeInfo, tkProperties, PropertyList); for I := 0 to PropertyCount - 1 do begin PropertyInfo := PropertyList[I]^; if PropertyInfo.Name <> PropertyName then Continue; case PropertyInfo.PropType^.Kind of tkInteger, tkEnumeration: SetOrdProp(TargetObject, PropertyName, Value); tkSet: SetSetProp(TargetObject, PropertyName, Value); tkLString, tkWString, tkString {$IFDEF VER210}, tkUString {$ENDIF}: SetStrProp(TargetObject, PropertyName, Value); tkFloat: SetFloatProp(TargetObject, PropertyName, Value); tkInt64: begin Int64Value := Value; SetInt64Prop(TargetObject, PropertyName, Int64Value); end; tkVariant: SetVariantProp(TargetObject, PropertyName, Value); tkClass: begin SetObjectProp( TargetObject, PropertyName, TObject(TVarData(Value).VPointer) ); end; else raise Exception.Create('Unexpected property kind was encountered'); end; Break; end; finally FreeMem(PropertyList); end; end; end.
unit Trakce; { Trida TTrakce sjednocuje tridy TXpressNET a TLocoNet do sebe. Jeji funkce je umozneni jednotne komunikace s trakcnim systemem nezavisle na tom, o jaky trakcni system se jedna. } interface uses SysUtils, Classes, CPort; const _HV_FUNC_MAX = 28; // maximalni funkcni cislo; funkce zacinaji na cisle 0 type Ttrk_status = ( // stav centraly TS_UNKNOWN = -1, TS_OFF = 0, TS_ON = 1, TS_SERVICE = 2 ); Ttrk_system = ( // typ komunikacniho protokolu TRS_LocoNET = 0, TRS_XpressNET = 1 ); TConnect_code = ( // stav pristupu k lokomotive TC_Connected = 0, TC_Disconnected = 1, TC_Unavailable = 2, TC_Stolen = 3 ); TCommandFuncCallback = procedure (Sender:TObject; Data:Pointer) of object; EInvalidAddress = class(Exception); TCommandCallback = record callback:TCommandFuncCallback; data:Pointer; end; TFunkce = array[0.._HV_FUNC_MAX] of boolean; TPomStatus = (released = 0, pc = 1, progr = 2, error = 3); TSlot=record //data slotu (dalsi vysvetleni v manualu k loconetu a xpressnetu) adresa:word; // adresa LOKO smer:ShortInt; // aktualni smer: [0,1] speed:byte; // aktualni jizdni stupen maxsp:Integer; // maximalni jizdni stupen (28, 128, ...) funkce:TFunkce; // stav funkci stolen:boolean; // jestli je loko ukradeno jinym ovladacem prevzato:boolean; // jestli loko ridim ja prevzato_full:boolean; // jestli loko ridim ja a jestli uz byly nastaveny vsechny veci, ktere se pri prebirani maji nastavit com_err:boolean; // jestli nastala chyba v komunikaci pom:TPomStatus; // stav POMu (jaky je posedni naprogramovany POM) end; TCSVersion = record // verze centraly major:byte; minor:byte; id:byte; end; TLIVersion = record // verze FW v LI hw_major:byte; hw_minor:byte; sw_major:byte; sw_minor:byte; end; TLogEvent = procedure(Sender:TObject; lvl:Integer; msg:string) of object; TConnectChangeInfo = procedure(Sender: TObject; addr:Integer; code:TConnect_code; data:Pointer) of object; TLokComEvent = procedure (Sender:TObject; addr:Integer) of object; TGeneralEvent = procedure(Sender: TObject) of object; TCSVersionEvent = procedure(Sender:TObject; version:TCSVersion) of object; TLIVersionEvent = procedure(Sender:TObject; version:TLIVersion) of object; TLIAddressEvent = procedure(Sender:TObject; addr:Byte) of object; TTrakce = class private const protected Get:record sp_addr:Integer; end; FOnTrackStatusChange : TGeneralEvent; FOnComError : TGeneralEvent; FOnCSVersion : TCSVersionEvent; FOnLIVersion : TLIVersionEvent; FOnLIAddr : TLIAddressEvent; FFtrk_status: Ttrk_status; procedure WriteLog(lvl:Integer; msg:string); procedure ConnectChange(addr:Integer; code:TConnect_code; data:Pointer); procedure LokComError(addr:Integer); procedure LokComOK(addr:Integer); procedure CSGotVersion(version:TCSVersion); procedure LIGotVersion(version:TLIVersion); procedure LIGotAddress(addr:Byte); procedure SetTrackStatus(NewtrackStatus:Ttrk_status); virtual; abstract; procedure SetOwnTrackStatus(New:Ttrk_status); property Ftrk_status: Ttrk_status read FFtrk_status write SetOwnTrackStatus; private FOnLog: TLogEvent; FOnConnectChange: TConnectChangeInfo; FOnLokComError : TLokComEvent; FOnLokComOK : TLokComEvent; public callback_err:TCommandCallback; callback_ok:TCommandCallback; Slot:TSlot; ComPort:record CPort:TComPort; end; constructor Create(); destructor Destroy(); override; procedure LokSetSpeed(Address:Integer; speed:Integer; dir:Integer); virtual; abstract; procedure LokSetFunc(Address:Integer; sada:Byte; stav:Byte); virtual; abstract; procedure LokGetFunctions(Address:Integer; startFunc:Integer); virtual; abstract; procedure EmergencyStop(); virtual; abstract; procedure LokEmergencyStop(addr:Integer); virtual; abstract; procedure LokGetInfo(Address:Integer); virtual; abstract; procedure Lok2MyControl(Address:Integer); virtual; abstract; // po volani teto funkce musi byt do slotu umistena data (resp. pred zavolanim eventu OnConnectChange)! MUSI! procedure LokFromMyControl(Address:Integer); virtual; abstract; procedure GetCSVersion(callback:TCSVersionEvent); virtual; procedure GetLIVersion(callback:TLIVersionEvent); virtual; procedure GetLIAddress(callback:TLIAddressEvent); virtual; procedure SetLIAddress(callback:TLIAddressEvent; addr:Byte); virtual; procedure GetTrackStatus(); virtual; abstract; procedure AfterOpen(); virtual; procedure BeforeClose(); virtual; abstract; procedure POMWriteCV(Address:Integer; cv:Word; data:byte); virtual; abstract; class function GenerateCallback(callback:TCommandFuncCallback; data:Pointer = nil):TCommandCallback; property TrackStatus: Ttrk_status read FFtrk_status write SetTrackStatus; property GetAddr:Integer read Get.sp_addr; //events property OnLog: TLogEvent read FOnLog write FOnLog; property OnConnectChange: TConnectChangeInfo read FOnConnectChange write FOnConnectChange; property OnLokComError: TLokComEvent read FOnLokComError write FOnLokComError; property OnLokComOK: TLokComEvent read FOnLokComOK write FOnLokComOK; property OnTrackStatusChange: TGeneralEvent read FOnTrackStatusChange write FOnTrackStatusChange; property OnComError : TGeneralEvent read fOnComError write fOnComError; end;//TTrakce implementation uses XpressNET; constructor TTrakce.Create(); begin inherited; Self.FFtrk_status := Ttrk_status.TS_UNKNOWN; end;//ctor destructor TTrakce.Destroy(); begin inherited; end;//dtor procedure TTrakce.WriteLog(lvl:Integer; msg: string); begin if (Assigned(Self.FOnLog)) then Self.FOnLog(Self, lvl, msg); end;//procedure procedure TTrakce.ConnectChange(addr:Integer; code:TConnect_code; data:Pointer); begin if (Assigned(Self.FOnConnectChange)) then Self.FOnConnectChange(self, addr, code, data); end;//procedure procedure TTrakce.LokComError(addr:Integer); begin if (Assigned(Self.FOnLokComError)) then Self.FOnLokComError(Self, addr); end;//procedure procedure TTrakce.LokComOK(addr:Integer); begin if (Assigned(Self.FOnLokComOK)) then Self.FOnLokComOK(Self, addr); end;//prccedure class function TTrakce.GenerateCallback(callback:TCommandFuncCallback; data:Pointer = nil):TCommandCallback; begin Result.callback := callback; Result.data := data; end;//function procedure TTrakce.SetOwnTrackStatus(New:Ttrk_status); begin if (Self.FFtrk_status <> new) then begin Self.FFtrk_status := new; if (Assigned(Self.FOnTrackStatusChange)) then Self.FOnTrackStatusChange(Self); end; end;//procedure procedure TTrakce.AfterOpen(); begin Self.FFtrk_status := TS_UNKNOWN; end;//procedure //////////////////////////////////////////////////////////////////////////////// procedure TTrakce.CSGotVersion(version:TCSVersion); begin if (Assigned(Self.FOnCSVersion)) then Self.FOnCSVersion(Self, version); end;//procedure procedure TTrakce.GetCSVersion(callback:TCSVersionEvent); begin Self.FOnCSVersion := callback; end;//function procedure TTrakce.GetLIVersion(callback:TLIVersionEvent); begin Self.FOnLIVersion := callback; end;//procedure procedure TTrakce.LIGotVersion(version:TLIVersion); begin if (Assigned(Self.FOnLIVersion)) then Self.FOnLIVersion(Self, version); end;//procedure procedure TTrakce.GetLIAddress(callback:TLIAddressEvent); begin Self.FOnLIAddr := callback; end; procedure TTrakce.SetLIAddress(callback:TLIAddressEvent; addr:Byte); begin Self.FOnLIAddr := callback; end; procedure TTrakce.LIGotAddress(addr:Byte); begin if (Assigned(Self.FOnLIAddr)) then Self.FOnLIAddr(Self, addr); end; //////////////////////////////////////////////////////////////////////////////// end.//unit
object ResourcesDialog: TResourcesDialog Left = 378 Top = 197 Width = 774 Height = 385 BorderStyle = bsSizeToolWin Caption = 'Resources Dialog' Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -13 Font.Name = 'Tahoma' Font.Style = [] FormStyle = fsStayOnTop OldCreateOrder = False OnShow = FormShow DesignSize = ( 756 340) PixelsPerInch = 115 TextHeight = 16 object lbKind: TLabel Left = 124 Top = 296 Width = 24 Height = 16 Anchors = [akLeft, akBottom] Caption = '&Kind' end object btnLoad: TBitBtn Left = 10 Top = 295 Width = 92 Height = 31 Anchors = [akLeft, akBottom] Caption = '&Load...' TabOrder = 0 OnClick = btnLoadClick end object cbKinds: TComboBox Left = 158 Top = 296 Width = 203 Height = 24 Anchors = [akLeft, akBottom] Enabled = False ItemHeight = 16 TabOrder = 1 OnChange = cbKindsChange OnCloseUp = cbKindsCloseUp Items.Strings = ( 'ACCELERATOR' 'ANICURSOR' 'ANIICON' 'BITMAP' 'CURSOR' 'DIALOG' 'DLGINCLUDE' 'FONT' 'FONTDIR' 'GROUP_CURSOR' 'GROUP_ICON' 'GROUP_ICON' 'MENU' 'MESSAGETABLE' 'RCDATA' 'STRING' 'PLUGPLAY' 'VXD' 'HTML' '24' 'ICON') end object btOK: TBitBtn Left = 654 Top = 294 Width = 87 Height = 31 Anchors = [akRight] Caption = '&OK' ModalResult = 1 TabOrder = 2 OnClick = btOKClick end object btCancel: TBitBtn Left = 559 Top = 294 Width = 87 Height = 31 Anchors = [akRight] Caption = '&Cancel' Default = True ModalResult = 2 TabOrder = 3 OnClick = btCancelClick end object PageControl: TPageControl Left = 8 Top = 8 Width = 734 Height = 272 ActivePage = TabItems Anchors = [akLeft, akTop, akRight, akBottom] TabOrder = 4 OnChange = PageControlChange object TabItems: TTabSheet Caption = '&Items' object ListView: TListView Left = 0 Top = 0 Width = 726 Height = 241 Align = alClient Columns = < item Caption = 'Name :' Width = 172 end item Caption = 'Kind :' Width = 172 end item Caption = 'File :' Width = 172 end> MultiSelect = True RowSelect = True PopupMenu = PopupMenu TabOrder = 0 ViewStyle = vsReport OnClick = ListViewClick OnColumnClick = ListViewColumnClick OnDblClick = ListViewDblClick OnEdited = ListViewEdited OnResize = ListViewResize end end object TabSource: TTabSheet Caption = '&Source' ImageIndex = 1 object RCSource: TSynEdit Left = 0 Top = 0 Width = 726 Height = 241 Align = alClient Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -16 Font.Name = 'Courier New' Font.Style = [] TabOrder = 0 Gutter.Font.Charset = DEFAULT_CHARSET Gutter.Font.Color = clWindowText Gutter.Font.Height = -13 Gutter.Font.Name = 'Courier New' Gutter.Font.Style = [] Highlighter = RC end end object TabView: TTabSheet Caption = '&View' ImageIndex = 2 object ImageEdit: TImage Left = 8 Top = 16 Width = 209 Height = 201 Stretch = True end end end object PopupMenu: TPopupMenu OnPopup = PopupMenuPopup Left = 260 Top = 138 object menuLoad: TMenuItem Caption = '&Load...' OnClick = menuLoadClick end object menuRemove: TMenuItem Caption = '&Remove' OnClick = menuRemoveClick end object N1: TMenuItem Caption = '-' end object menuClear: TMenuItem Caption = '&Clear' OnClick = menuClearClick end end object RC: TSynRCSyn Left = 324 Top = 139 end end
// ************************************************************************ // // The types declared in this file were generated from data read from the // WSDL File described below: // WSDL : http://edesoftsa.dyndns.biz:4002/wsdl/IDelphiConference // >Import : http://edesoftsa.dyndns.biz:4002/wsdl/IDelphiConference>0 // Version : 1.0 // (15/10/2014 23:34:29 - - $Rev: 69934 $) // ************************************************************************ // unit untIDelphiConference; interface uses Soap.InvokeRegistry, Soap.SOAPHTTPClient, System.Types, Soap.XSBuiltIns; type // ************************************************************************ // // The following types, referred to in the WSDL document are not being represented // in this file. They are either aliases[@] of other types represented or were referred // to but never[!] declared in the document. The types from the latter category // typically map to predefined/known XML or Embarcadero types; however, they could also // indicate incorrect WSDL documents that failed to declare or import a schema type. // ************************************************************************ // // !:int - "http://www.w3.org/2001/XMLSchema"[] // !:string - "http://www.w3.org/2001/XMLSchema"[Gbl] TCliente = class; { "urn:untDelphiConferenceIntf"[GblCplx] } // ************************************************************************ // // XML : TCliente, global, <complexType> // Namespace : urn:untDelphiConferenceIntf // ************************************************************************ // TCliente = class(TRemotable) private FNome: string; FDataNascimento: string; FSexo: string; FCidade: string; published property Nome: string read FNome write FNome; property DataNascimento: string read FDataNascimento write FDataNascimento; property Sexo: string read FSexo write FSexo; property Cidade: string read FCidade write FCidade; end; // ************************************************************************ // // Namespace : urn:untDelphiConferenceIntf-IDelphiConference // soapAction: urn:untDelphiConferenceIntf-IDelphiConference#%operationName% // transport : http://schemas.xmlsoap.org/soap/http // style : rpc // use : encoded // binding : IDelphiConferencebinding // service : IDelphiConferenceservice // port : IDelphiConferencePort // URL : http://edesoftsa.dyndns.biz:4002/soap/IDelphiConference // ************************************************************************ // IDelphiConference = interface(IInvokable) ['{CA9CBB04-5E57-2FE7-BDC3-2983BD99B74D}'] function GetNomeCliente(const AIdCliente: Integer): string; stdcall; function GetCliente(const AIdCliente: Integer): TCliente; stdcall; function GetIntervaloClientes(const AIdInicial: Integer; const AIdFinal: Integer): string; stdcall; end; function GetIDelphiConference(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): IDelphiConference; implementation uses System.SysUtils; function GetIDelphiConference(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): IDelphiConference; const defWSDL = 'http://edesoftsa.dyndns.biz:4002/wsdl/IDelphiConference'; defURL = 'http://edesoftsa.dyndns.biz:4002/soap/IDelphiConference'; defSvc = 'IDelphiConferenceservice'; defPrt = 'IDelphiConferencePort'; var RIO: THTTPRIO; begin Result := nil; if (Addr = '') then begin if UseWSDL then Addr := defWSDL else Addr := defURL; end; if HTTPRIO = nil then RIO := THTTPRIO.Create(nil) else RIO := HTTPRIO; try Result := (RIO as IDelphiConference); if UseWSDL then begin RIO.WSDLLocation := Addr; RIO.Service := defSvc; RIO.Port := defPrt; end else RIO.URL := Addr; finally if (Result = nil) and (HTTPRIO = nil) then RIO.Free; end; end; initialization { IDelphiConference } InvRegistry.RegisterInterface(TypeInfo(IDelphiConference), 'urn:untDelphiConferenceIntf-IDelphiConference', ''); InvRegistry.RegisterDefaultSOAPAction(TypeInfo(IDelphiConference), 'urn:untDelphiConferenceIntf-IDelphiConference#%operationName%'); RemClassRegistry.RegisterXSClass(TCliente, 'urn:untDelphiConferenceIntf', 'TCliente'); end.
unit UStatusService; { ClickForms Application } { Bradford Technologies, Inc. } { All Rights Reserved } { Source Code Copyrighted © 1998-2005 by Bradford Technologies, Inc. } interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, jpeg, RzLabel, UForms; const serviceAppraisalPort = 'appraisalport'; serviceFloodmaps = 'floodmaps'; serviceLocationMaps = 'locationmaps'; serviceFidelity = 'propertydata'; serviceVeros = 'veros'; serviceRenewal = 'renewal'; serviceMarshalAndSwift = 'swift'; serviceImportData = 'importdata'; serviceLighthouse = 'lighthouse'; type TWSStatus = class(TAdvancedForm) ImageExpired: TImage; ImageIcon: TImage; Shape1: TShape; btnCancel: TButton; btnRenew: TButton; LabelMsg: TLabel; LabelRenewMsg: TLabel; BevelLine: TBevel; ImageExpiring: TImage; RzURLOrderOnline: TRzURLLabel; ImageException: TImage; LabelMsgCaption: TLabel; AAImage: TImage; Label1: TLabel; LabelPurchaseMsg: TLabel; procedure btnCancelClick(Sender: TObject); procedure btnRenewClick(Sender: TObject); private fServiceName: string; { Private declarations } public { Public declarations } end; procedure ShowExpiredMsg(const msg: string; const serviceName: string = ''); procedure ShowExpiringMsg(const msg: string; const serviceName: string = ''); //procedure ShowExceptionMsg(const msg: string; const serviceName: string = ''); //procedure ShowNotPurchasedMsg(const msg: string; const serviceName: string = ''); var WSStatus: TWSStatus; implementation Uses UNewsDesk; {$R *.dfm} procedure ShowExpiredMsg(const msg: string; const serviceName: string); var WSStatus: TWSStatus; begin WSStatus := TWSStatus.Create(nil); try WSStatus.fServiceName := serviceName; WSStatus.ImageExpiring.Visible := false; WSStatus.ImageException.Visible := false; WSStatus.ImageExpired.Visible := true; WSStatus.LabelMsgCaption.Caption := 'Subscription Expired'; WSStatus.LabelMsg.Caption := msg; WSStatus.BevelLine.Visible := true; WSStatus.LabelRenewMsg.Visible := false; WSStatus.LabelPurchaseMsg.Visible:= true; // WSStatus.ShapeBot.Brush.Color := RGB(254,112,66); WSStatus.ShowModal; finally WSStatus.Free; end; end; procedure ShowExpiringMsg(const msg: string; const serviceName: string); var WSStatus: TWSStatus; begin WSStatus := TWSStatus.Create(nil); try WSStatus.fServiceName := serviceName; WSStatus.ImageExpiring.Visible := true; WSStatus.ImageException.Visible := false; WSStatus.ImageExpired.Visible := false; WSStatus.LabelMsgCaption.Caption := 'Subscription Expiring'; WSStatus.LabelMsg.Caption := msg; WSStatus.BevelLine.Visible := true; WSStatus.LabelRenewMsg.Visible := true; WSStatus.LabelPurchaseMsg.Visible:= false; WSStatus.btnCancel.Caption := '&Continue'; WSStatus.ShowModal; finally WSStatus.Free; end; end; procedure ShowExceptionMsg(const msg: string; const serviceName: string); var WSStatus: TWSStatus; begin WSStatus := TWSStatus.Create(nil); try WSStatus.fServiceName := serviceName; WSStatus.ImageExpiring.Visible := false; WSStatus.ImageException.Visible := true; WSStatus.ImageExpired.Visible := false; WSStatus.LabelMsgCaption.Caption := 'Error'; WSStatus.LabelMsg.Caption := msg; WSStatus.BevelLine.Visible := false; WSStatus.LabelRenewMsg.Visible := false; WSStatus.btnRenew.Visible := false; WSStatus.btnCancel.Caption := '&Ok'; WSStatus.ShowModal; finally WSStatus.Free; end; end; procedure ShowNotPurchasedMsg(const msg: string; const serviceName: string); var WSStatus: TWSStatus; begin WSStatus := TWSStatus.Create(nil); try WSStatus.fServiceName := serviceName; WSStatus.ImageExpiring.Visible := false; WSStatus.ImageException.Visible := false; WSStatus.ImageExpired.Visible := true; WSStatus.LabelMsgCaption.Caption := 'Subscription Not Purchased'; WSStatus.LabelMsg.Caption := msg; WSStatus.BevelLine.Visible := true; WSStatus.LabelRenewMsg.Visible := true; WSStatus.btnRenew.Caption := 'Purchase'; WSStatus.btnCancel.Caption := 'Later Gator'; WSStatus.LabelRenewMsg.Caption := 'To purchase this service online please click the "Purchase" button. If you would like to speak to a sales representative call 1-800-622-8727.'; WSStatus.ShowModal; finally WSStatus.Free; end; end; procedure TWSStatus.btnCancelClick(Sender: TObject); begin Close; end; procedure TWSStatus.btnRenewClick(Sender: TObject); begin Close; UNewsDesk.LaunchAWStoreInBrowser(fServiceName); end; end.
unit TestSignTable; interface uses SysUtils, testStr, signTable; implementation type Tarray = array [1..3, 1..3] of integer; TValueArray = array [1..2, 1..2] of TValueSign; var Table, Table2 : TSignTable; Current : PSignTableColumn; TestArray : Tarray = ((1, 0, -1), (-1, 1, 0), (0, -1, 1)); TestValueArray : TValueArray = ((vsMinus, vsZero), (vsZero, vsPlus)); d : tvaluesign; procedure TestOfInitTable; begin InitTable(Table, 2); NameProcedure('InitTable'); if not((length(table.FirstColumn.Column) = 2) and (length(table.FirstColumn.Next.Column) = 2) and // проверяем размеры и то, (table.FirstColumn.Next.Next = Nil)) then // что последний указатель - нил ErrorTest(); end; procedure TestOfWriteItem; var NumberOfTrueTests : integer; begin NameProcedure('WriteItem'); InitTable(Table, 2); //создаем таблицу 2х2 Current := Table.FirstColumn; WriteItem(Current, 0, TestValueArray[1, 1]); // WriteItem(Current, 1, TestValueArray[1, 2]); // заполняем NextColumn(Current); // WriteItem(Current, 0, TestValueArray[2, 1]); // WriteItem(Current, 1, TestValueArray[2, 2]); // Current := Table.FirstColumn; NumberOfTrueTests := 0; if Current^.Column[0] = vsMinus then NumberOfTrueTests := NumberOfTrueTests + 1; // if Current^.Column[1] = vsZero then // NumberOfTrueTests := NumberOfTrueTests + 1; // NextColumn(Current); //проверяем if Current^.Column[0] = vsZero then // NumberOfTrueTests := NumberOfTrueTests + 1; // if Current^.Column[1] = vsPlus then // NumberOfTrueTests := NumberOfTrueTests + 1; // if not(NumberOfTrueTests = 4) then // ErrorTest(); // считаем правильные тесты end;{TestOfWriteItem} procedure TestOfGetItem; var NumberOfTrueTests : integer; begin NameProcedure('GetItem'); InitTable(Table, 2); //создаем таблицу 2х2 Current := Table.FirstColumn; WriteItem(Current, 0, TestValueArray[1, 1]); // WriteItem(Current, 1, TestValueArray[1, 2]); // заполняем NextColumn(Current); // WriteItem(Current, 0, TestValueArray[2, 1]); // WriteItem(Current, 1, TestValueArray[2, 2]); // Current := Table.FirstColumn; NumberOfTrueTests := 0; if getitem(Current, 0) = vsMinus then // NumberOfTrueTests := NumberOfTrueTests + 1; // if getitem(Current, 1) = vsZero then // NumberOfTrueTests := NumberOfTrueTests + 1; // NextColumn(Current); // проверяем if getitem(Current, 0) = vsZero then // NumberOfTrueTests := NumberOfTrueTests + 1; // if getitem(Current, 1) = vsPlus then // NumberOfTrueTests := NumberOfTrueTests + 1; // if not(NumberOfTrueTests = 4) then // ErrorTest(); // считаем правильные тесты end;{TestOfGetItem} procedure TestOfEasyWriter; var NumberOfTrueTests : integer; begin NameProcedure('EasyWrite'); InitTable(table, 2); //создаем таблицу 2х2 Current := Table.FirstColumn; // EasyWrite(Current, 0, -1); // EasyWrite(Current, 1, 0); // заполняем NextColumn(Current); // EasyWrite(Current, 0, 0); // EasyWrite(Current, 1, 1); // NumberOfTrueTests := 0; Current := Table.FirstColumn; if getitem(Current, 0) = vsMinus then // NumberOfTrueTests := NumberOfTrueTests + 1; // if getitem(Current, 1) = vsZero then // NumberOfTrueTests := NumberOfTrueTests + 1; // NextColumn(Current); // проверяем if getitem(Current, 0) = vsZero then // NumberOfTrueTests := NumberOfTrueTests + 1; // if getitem(Current, 1) = vsPlus then // NumberOfTrueTests := NumberOfTrueTests + 1; // if not(NumberOfTrueTests = 4) then // ErrorTest(); // считаем правильные тесты end;{TestOfEasyWrite} procedure TestOfEasyGet; var NumberOfTrueTests : integer; begin NameProcedure('EasyGet'); InitTable(table, 2); //создаем таблицу 2х2 Current := Table.FirstColumn; // EasyWrite(Current, 0, -1); // EasyWrite(Current, 1, 0); // заполняем NextColumn(Current); // EasyWrite(Current, 0, 0); // EasyWrite(Current, 1, 1); // NumberOfTrueTests := 0; Current := Table.FirstColumn; if EasyGet(Current, 0) = -1 then // NumberOfTrueTests := NumberOfTrueTests + 1; // if EasyGet(Current, 1) = 0 then // NumberOfTrueTests := NumberOfTrueTests + 1; // NextColumn(Current); // проверяем if EasyGet(Current, 0) = 0 then // NumberOfTrueTests := NumberOfTrueTests + 1; // if EasyGet(Current, 1) = 1 then // NumberOfTrueTests := NumberOfTrueTests + 1; // if not(NumberOfTrueTests = 4) then // ErrorTest(); // считаем правильные тесты end;{TestOfEasyGet} procedure TestOfInsertColumn1; var NumberOfTrueTests : integer; i, j, k : integer; begin NameProcedure('InsertColumn 1'); InitTable(Table, 3); Current := Table.FirstColumn; EasyWrite(Current, 0, TestArray[1, 1]); EasyWrite(Current, 1, TestArray[1, 2]); EasyWrite(Current, 2, TestArray[1, 3]); NextColumn(Current); EasyWrite(Current, 0, TestArray[3, 1]); EasyWrite(Current, 1, TestArray[3, 2]); EasyWrite(Current, 2, TestArray[3, 3]); InsertColumn(Table, Table.FirstColumn); Current := Table.FirstColumn; NextColumn(Current); EasyWrite(Current, 0, TestArray[2, 1]); EasyWrite(Current, 1, TestArray[2, 2]); EasyWrite(Current, 2, TestArray[2, 3]); Current := Table.FirstColumn; NumberOfTrueTests := 0; for j := 1 to 3 do begin for i := 0 to 2 do if EasyGet(Current, i) = TestArray[j, i + 1] then NumberOfTrueTests := NumberOfTrueTests + 1; NextColumn(current); end; if not(NumberOfTrueTests = 9) then // ErrorTest(); // считаем правильные тесты end; procedure TestOfInsertColumn2; var NumberOfTrueTests : integer; i, j : integer; begin NameProcedure('InsertColumn 2'); InitTable(Table, 3); Current := Table.FirstColumn; // куррент - первый EasyWrite(Current, 0, TestArray[1, 1]); // EasyWrite(Current, 1, TestArray[1, 2]); // заполняем EasyWrite(Current, 2, TestArray[1, 3]); // NextColumn(Current); // куррент - второй EasyWrite(Current, 0, TestArray[2, 1]); // EasyWrite(Current, 1, TestArray[2, 2]); // заполняем EasyWrite(Current, 2, TestArray[2, 3]); // InsertColumn(Table, Current); // вставляем после второго NextColumn(Current); // куррент - третий EasyWrite(Current, 0, TestArray[3, 1]); // EasyWrite(Current, 1, TestArray[3, 2]); // заполняем EasyWrite(Current, 2, TestArray[3, 3]); // Current := Table.FirstColumn; // куррент - первый NumberOfTrueTests := 0; for j := 1 to 3 do begin for i := 0 to 2 do if EasyGet(Current, i) = TestArray[j, i + 1] then NumberOfTrueTests := NumberOfTrueTests + 1; NextColumn(current); end; if not(NumberOfTrueTests = 9) then // ErrorTest(); // считаем правильные тесты end; begin NameUnit('signTable'); TestOfInitTable; TestOfWriteItem; TestOfGetItem; TestOfEasyWriter; TestOfEasyGet; TestOfInsertColumn1; TestOfInsertColumn2; end.
unit YOTM.DB.Notes; interface uses SQLite3, SQLLang, SQLiteTable3, System.Generics.Collections, SysUtils, System.Classes, HGM.Controls.VirtualTable, YOTM.DB, Vcl.Graphics; type //Метки задач TNoteItem = class; TNoteItem = class(TObject) const tnTable = 'NoteItems'; fnID = 'niID'; fnText = 'niText'; fnDate = 'niDate'; fnModify = 'niModify'; private FID:Integer; FLoaded:Boolean; FText: TStringStream; FDateModify: TDateTime; FDate: TDate; FDataBase: TDB; procedure SetText(const Value: TStringStream); procedure SetID(const Value: Integer); procedure SetDateModify(const Value: TDateTime); procedure SetDate(const Value: TDate); procedure SetDataBase(const Value: TDB); public constructor Create(ADataBase:TDB); destructor Destroy; override; procedure Load(ADate:TDate); procedure Save; property ID:Integer read FID write SetID; property Text:TStringStream read FText write SetText; property Date:TDate read FDate write SetDate; property DateModify:TDateTime read FDateModify write SetDateModify; property DataBase:TDB read FDataBase write SetDataBase; property Loaded:Boolean read FLoaded; end; implementation uses DateUtils; { TNoteItem } constructor TNoteItem.Create; begin inherited Create; FDataBase:=ADataBase; FLoaded:=False; if not FDataBase.DB.TableExists(tnTable) then with SQL.CreateTable(tnTable) do begin AddField(fnID, ftInteger, True, True); AddField(fnText, ftBlob); AddField(fnDate, ftDateTime); AddField(fnModify, ftDateTime); FDataBase.DB.ExecSQL(GetSQL); EndCreate; end; FID:=-1; FText:=TStringStream.Create; FDateModify:=Now; FDate:=DateOf(Now); end; destructor TNoteItem.Destroy; begin inherited; end; procedure TNoteItem.Load(ADate: TDate); var Table:TSQLiteTable; begin with SQL.Select(tnTable) do begin AddField(fnID); AddField(fnText); AddField(fnDate); AddField(fnModify); WhereFieldEqual(fnDate, DateOf(ADate)); Table:=FDataBase.DB.GetTable(GetSQL); EndCreate; Text.Clear; if Table.RowCount > 0 then begin ID:=Table.FieldAsInteger(0); if Assigned(Table.FieldAsBlob(1)) then Text.LoadFromStream(Table.FieldAsBlob(1)); Date:=Table.FieldAsDateTime(2); DateModify:=Table.FieldAsDateTime(3); FLoaded:=True; end else begin with SQL.InsertInto(tnTable) do begin Date:=DateOf(ADate); DateModify:=Now; AddValue(fnDate, Date); AddValue(fnModify, DateModify); AddValue(fnText, ''); FDataBase.DB.ExecSQL(GetSQL); ID:=FDataBase.DB.GetLastInsertRowID; FLoaded:=True; EndCreate; end; end; end; end; procedure TNoteItem.Save; begin if FLoaded then begin with SQL.Update(tnTable) do begin DateModify:=Now; AddValue(fnModify, DateModify); WhereFieldEqual(fnID, ID); FDataBase.DB.ExecSQL(GetSQL); EndCreate; end; Text.Position:=0; with SQL.UpdateBlob(tnTable) do begin BlobField:=fnText; WhereFieldEqual(fnID, ID); FDataBase.DB.UpdateBlob(GetSQL, Text); EndCreate; end; end; end; procedure TNoteItem.SetDataBase(const Value: TDB); begin FDataBase := Value; end; procedure TNoteItem.SetDate(const Value: TDate); begin FDate := Value; end; procedure TNoteItem.SetDateModify(const Value: TDateTime); begin FDateModify := Value; end; procedure TNoteItem.SetText(const Value: TStringStream); begin FText := Value; end; procedure TNoteItem.SetID(const Value: Integer); begin FID := Value; end; end.